forked from projectdiscovery/tlsx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwriter.go
More file actions
291 lines (270 loc) · 7.93 KB
/
writer.go
File metadata and controls
291 lines (270 loc) · 7.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package pdcp
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"sync"
"sync/atomic"
"time"
"github.com/projectdiscovery/gologger"
"github.com/projectdiscovery/retryablehttp-go"
"github.com/projectdiscovery/tlsx/pkg/tlsx/clients"
pdcpauth "github.com/projectdiscovery/utils/auth/pdcp"
"github.com/projectdiscovery/utils/conversion"
"github.com/projectdiscovery/utils/env"
errkit "github.com/projectdiscovery/utils/errkit"
unitutils "github.com/projectdiscovery/utils/unit"
updateutils "github.com/projectdiscovery/utils/update"
urlutil "github.com/projectdiscovery/utils/url"
)
const (
uploadEndpoint = "/v1/assets"
appendEndpoint = "/v1/assets/%s/contents"
flushTimer = time.Minute
MaxChunkSize = 4 * unitutils.Mega // 4 MB
xidRe = `^[a-z0-9]{20}$`
teamIDHeader = "X-Team-Id"
NoneTeamID = "none"
)
var (
xidRegex = regexp.MustCompile(xidRe)
// EnableeUpload if set to true enables the upload feature
HideAutoSaveMsg = env.GetEnvOrDefault("DISABLE_CLOUD_UPLOAD_WRN", false)
EnableCloudUpload = env.GetEnvOrDefault("ENABLE_CLOUD_UPLOAD", false)
)
// UploadWriter is a writer that uploads its output to pdcp
// server to enable web dashboard and more
type UploadWriter struct {
creds *pdcpauth.PDCPCredentials
uploadURL *url.URL
client *retryablehttp.Client
done chan struct{}
data chan *clients.Response
mu sync.RWMutex
assetGroupID string
assetGroupName string
counter atomic.Int32
closed atomic.Bool
TeamID string
}
// NewUploadWriterCallback creates a new upload writer callback
// which when enabled periodically uploads the results to pdcp assets dashboard
func NewUploadWriterCallback(ctx context.Context, creds *pdcpauth.PDCPCredentials) (*UploadWriter, error) {
if creds == nil {
return nil, fmt.Errorf("no credentials provided")
}
u := &UploadWriter{
creds: creds,
done: make(chan struct{}, 1),
data: make(chan *clients.Response, 8), // default buffer size
TeamID: "",
}
var err error
tmp, err := urlutil.Parse(creds.Server)
if err != nil {
return nil, errkit.Wrap(err, "could not parse server url")
}
tmp.Path = uploadEndpoint
tmp.Update()
u.uploadURL = tmp.URL
// create http client
opts := retryablehttp.DefaultOptionsSingle
opts.NoAdjustTimeout = true
opts.Timeout = time.Duration(3) * time.Minute
u.client = retryablehttp.NewClient(opts)
// start auto commit
// upload every 1 minute or when buffer is full
go u.autoCommit(ctx)
return u, nil
}
// GetWriterCallback returns the writer callback
func (u *UploadWriter) GetWriterCallback() func(*clients.Response) {
return func(resp *clients.Response) {
u.data <- resp
}
}
// SetAssetID sets the scan id for the upload writer
func (u *UploadWriter) SetAssetID(id string) error {
if !xidRegex.MatchString(id) {
gologger.Warning().Msgf("invalid asset id provided (unknown xid format): %s", id)
}
u.mu.Lock()
defer u.mu.Unlock()
u.assetGroupID = id
return nil
}
// SetAssetGroupName sets the scan name for the upload writer
func (u *UploadWriter) SetAssetGroupName(name string) {
u.mu.Lock()
defer u.mu.Unlock()
u.assetGroupName = name
}
// SetTeamID sets the team id for the upload writer
func (u *UploadWriter) SetTeamID(id string) {
u.mu.Lock()
defer u.mu.Unlock()
u.TeamID = id
}
func (u *UploadWriter) autoCommit(ctx context.Context) {
// wait for context to be done
defer func() {
u.done <- struct{}{}
close(u.done)
// if no scanid is generated no results were uploaded
u.mu.RLock()
assetGroupID := u.assetGroupID
teamID := u.TeamID
u.mu.RUnlock()
if assetGroupID == "" {
gologger.Verbose().Msgf("UI dashboard setup skipped, no results found to upload")
} else {
gologger.Info().Msgf("Found %v results, View found results in dashboard : %v", u.counter.Load(), getAssetsDashBoardURL(assetGroupID, teamID))
}
}()
// temporary buffer to store the results
buff := &bytes.Buffer{}
ticker := time.NewTicker(flushTimer)
for {
select {
case <-ctx.Done():
// flush before exit
if buff.Len() > 0 {
if err := u.uploadChunk(buff); err != nil {
gologger.Error().Msgf("Failed to upload scan results on cloud: %v", err)
}
}
return
case <-ticker.C:
// flush the buffer
if buff.Len() > 0 {
if err := u.uploadChunk(buff); err != nil {
gologger.Error().Msgf("Failed to upload scan results on cloud: %v", err)
}
}
case res, ok := <-u.data:
if !ok {
if buff.Len() > 0 {
if err := u.uploadChunk(buff); err != nil {
gologger.Error().Msgf("Failed to upload scan results on cloud: %v", err)
}
}
return
}
lineBytes, err := json.Marshal(res)
if err != nil {
gologger.Error().Msgf("Failed to marshal result: %v", err)
continue
}
u.counter.Add(1)
line := conversion.String(lineBytes)
if buff.Len()+len(line) > MaxChunkSize {
// flush existing buffer
if err := u.uploadChunk(buff); err != nil {
gologger.Error().Msgf("Failed to upload asset results on cloud: %v", err)
}
} else {
buff.WriteString(line)
buff.WriteString("\n")
}
}
}
}
// uploadChunk uploads a chunk of data to the server
func (u *UploadWriter) uploadChunk(buff *bytes.Buffer) error {
if err := u.upload(buff.Bytes()); err != nil {
return errkit.Wrap(err, "could not upload chunk")
}
// if successful, reset the buffer
buff.Reset()
// log in verbose mode
u.mu.RLock()
assetGroupID := u.assetGroupID
teamID := u.TeamID
u.mu.RUnlock()
gologger.Warning().Msgf("Uploaded results chunk, you can view assets at %v", getAssetsDashBoardURL(assetGroupID, teamID))
return nil
}
func (u *UploadWriter) upload(data []byte) error {
req, err := u.getRequest(data)
if err != nil {
return errkit.Wrap(err, "could not create upload request")
}
resp, err := u.client.Do(req)
if err != nil {
return errkit.Wrap(err, "could not upload results")
}
defer func() {
_ = resp.Body.Close()
}()
bin, err := io.ReadAll(resp.Body)
if err != nil {
return errkit.Wrap(err, "could not get id from response")
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("could not upload results got status code %v on %v", resp.StatusCode, resp.Request.URL.String())
}
var uploadResp uploadResponse
if err := json.Unmarshal(bin, &uploadResp); err != nil {
return errkit.Wrapf(err, "could not unmarshal response got %v", string(bin))
}
if uploadResp.ID != "" {
u.mu.Lock()
if u.assetGroupID == "" {
u.assetGroupID = uploadResp.ID
}
u.mu.Unlock()
}
return nil
}
// getRequest returns a new request for upload
// if scanID is not provided create new scan by uploading the data
// if scanID is provided append the data to existing scan
func (u *UploadWriter) getRequest(bin []byte) (*retryablehttp.Request, error) {
var method, url string
u.mu.RLock()
assetID := u.assetGroupID
assetName := u.assetGroupName
teamID := u.TeamID
u.mu.RUnlock()
if assetID == "" {
u.uploadURL.Path = uploadEndpoint
method = http.MethodPost
url = u.uploadURL.String()
} else {
u.uploadURL.Path = fmt.Sprintf(appendEndpoint, assetID)
method = http.MethodPatch
url = u.uploadURL.String()
}
req, err := retryablehttp.NewRequest(method, url, bytes.NewReader(bin))
if err != nil {
return nil, errkit.Wrap(err, "could not create cloud upload request")
}
// add pdtm meta params - version will be set by updateutils
req.Params.Merge(updateutils.GetpdtmParams("tlsx"))
// if it is upload endpoint also include name if it exists
if assetName != "" && req.Path == uploadEndpoint {
req.Params.Add("name", assetName)
}
req.Update()
req.Header.Set(pdcpauth.ApiKeyHeaderName, u.creds.APIKey)
if teamID != "" {
req.Header.Set(teamIDHeader, teamID)
}
req.Header.Set("Content-Type", "application/octet-stream")
req.Header.Set("Accept", "application/json")
return req, nil
}
// Close closes the upload writer
func (u *UploadWriter) Close() {
if !u.closed.Load() {
// protect to avoid channel closed twice error
close(u.data)
u.closed.Store(true)
}
<-u.done
}