-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathscan.go
376 lines (320 loc) · 9.4 KB
/
scan.go
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package gbounty
import (
"context"
"errors"
stdurl "net/url"
"strings"
"sync"
"time"
"github.com/BountySecurity/gbounty/entrypoint"
"github.com/BountySecurity/gbounty/internal/platform/metrics"
"github.com/BountySecurity/gbounty/kit/logger"
"github.com/BountySecurity/gbounty/kit/panics"
"github.com/BountySecurity/gbounty/kit/syncutil"
"github.com/BountySecurity/gbounty/profile"
"github.com/BountySecurity/gbounty/request"
"github.com/BountySecurity/gbounty/response"
)
var ErrManuallyInterrupted = errors.New("scan interrupted manually")
// LineOfWork is the aggregation for all the Task, for a given Template.
// In other words:
// - There is a LineOfWork for each request to be scanned:
// - For which we identify all the Entrypoints,
// - and combine with profile.Profile, to generate all starting possible combinations:
// - For every combination of entrypoint.Entrypoint (see Task.EntrypointIdx)
// - with every payload (see Task.PayloadIdx).
// [Rough estimate: #profiles x #payloads x #entrypoints]
//
// =
// - Then, during the execution of the scan, more Task can be created, because
// one Task can be forked into more than one (for each step). So, every Task
// represents a path of steps, where every other step (except the current)
// did match.
type LineOfWork struct {
Template Template
Entrypoints []entrypoint.Entrypoint
Tasks []*Task
sync.RWMutex
Matches map[string]struct{}
}
func (low *LineOfWork) appendEntrypoints(entrypoints []entrypoint.Entrypoint) {
low.Entrypoints = append(low.Entrypoints, entrypoints...)
}
func (low *LineOfWork) registerMatch(matchId string) bool {
low.Lock()
defer low.Unlock()
if _, ok := low.Matches[matchId]; ok {
return false
}
low.Matches[matchId] = struct{}{}
return true
}
func (low *LineOfWork) isThereAnyEquivalentMatch(matchId string) bool {
low.RLock()
defer low.RUnlock()
_, ok := low.Matches[matchId]
return ok
}
// Consider: Moving these labels to the `scan` package (entrypoints might be independent of the label itself).
const (
bhLabel = "{BH}"
emailLabel = "{EMAIL}"
)
func (low *LineOfWork) prepareTasks(
ctx context.Context,
prof *profile.Active,
blindHostDefined bool,
emailAddressDefined bool,
) (totalTasks int, skipped bool) {
// We first check if the profile should be skipped.
// For instance, in case any of its steps is a raw request that contains an undefined label.
if profileShouldBeSkipped(ctx, prof, blindHostDefined, emailAddressDefined) {
return 0, true
}
// At this point, there must always be at least one step.
// Otherwise, the profile is invalid. So, it should be validated before reaching this point.
const sIdx = 0
step := prof.Steps[sIdx]
// If it is a raw request, then we just add one task.
if step.RequestType.RawRequest() {
low.Tasks = append(low.Tasks, &Task{Profile: prof, StepIdx: sIdx, PayloadIdx: -1, LoW: low})
return 1, false
}
// Otherwise, there'll be one for each payload in the first step of the profile,
// and for each LineOfWork entrypoint, plus the ones entrypoint.From step.
stepEntrypoints := entrypoint.From(step)
for pIdx := range step.Payloads {
enabled, payload, err := step.PayloadAt(pIdx)
if err != nil {
logger.For(ctx).Errorf(
"Error while parsing payload (idx=%d) from step (idx=%d) from profile (name=%s): %s",
pIdx, sIdx, prof.Name, err.Error(),
)
continue
}
if !enabled {
logger.For(ctx).Debugf(
"Payload (idx=%d) from step (idx=%d) from profile (name=%s) is disabled",
pIdx, sIdx, prof.Name,
)
continue
}
if (strings.Contains(payload, bhLabel) && !blindHostDefined) ||
(strings.Contains(payload, emailLabel) && !emailAddressDefined) {
skipped = true
continue // Skipping
}
for idx, ep := range low.Entrypoints {
if step.InsertionPointEnabled(ep.InsertionPointType(), low.Template.Method) {
totalTasks++
low.Tasks = append(low.Tasks, &Task{Profile: prof, StepIdx: sIdx, PayloadIdx: pIdx, LoW: low, EntrypointIdx: idx})
}
}
for _, ep := range stepEntrypoints {
totalTasks++
low.Tasks = append(low.Tasks, &Task{Profile: prof, StepIdx: sIdx, PayloadIdx: pIdx, LoW: low, Entrypoint: ep})
}
}
return totalTasks, skipped
}
// profileShouldBeSkipped checks if the profile should be skipped.
// Conditions checked:
// - Any step is a raw request that contains an undefined label ({BH}, {EMAIL}).
func profileShouldBeSkipped(
_ context.Context,
prof *profile.Active,
blindHostDefined bool,
emailAddressDefined bool,
) bool {
// Any step is a raw request that contains an undefined label ({BH}, {EMAIL}).
for _, step := range prof.Steps {
if step.RequestType.RawRequest() {
if (strings.Contains(step.RawRequest, bhLabel) && !blindHostDefined) ||
(strings.Contains(step.RawRequest, emailLabel) && !emailAddressDefined) {
return true // Skipping
}
}
}
return false
}
//nolint:nolintlint,gocyclo
func (low *LineOfWork) executeTasks(
ctx context.Context,
reqBuilder RequesterBuilder,
bhPoller BlindHostPoller,
onRequestsScheduled, onRequestsSkipped func(int),
onUpdate func(bool, bool, bool),
onErrorFn onErrorFunc,
onMatchFn onMatchFunc,
onTaskFn onTaskFunc,
rps int,
saveAllRequests, saveResponses, saveAllResponses bool,
baseModifiers []Modifier,
passiveReqProfiles []*profile.Request,
passiveResProfiles []*profile.Response,
customTokens CustomTokens,
payloadStrategy PayloadStrategy,
) {
// We set the throttle to the desired rate of requests per second.
// It is important to prevent flooding the endpoint.
throttle := time.NewTicker(time.Duration(1e6/(rps)) * time.Microsecond) //nolint:mnd
defer throttle.Stop()
var (
wg = syncutil.NewWaitGroupWithCount()
from int
)
for {
if from > len(low.Tasks) {
panic("How is it possible?")
}
// If we reached the end of the list of tasks
// and no one is running, we can stop.
// Otherwise, we need to pause for a bit.
if from == len(low.Tasks) {
if wg.Count() == 0 {
break
}
const shortPause = 10 * time.Millisecond
time.Sleep(shortPause)
continue
}
task := low.Tasks[from]
wg.Add(1)
from++
go func() {
// Prevent any panic caused during the task execution
// from escalating outside the goroutine.
defer panics.Log(ctx)
// Make sure that the task is marked as done,
// whatever that causes it to finish.
defer wg.Done()
// Before starting the task execution,
// we double-check the context cancellation.
// If the context has already been cancelled,
// then we prevent the execution even from starting.
select {
case <-ctx.Done():
return
default:
}
// Wait for the throttle to allow the task to be executed.
// This is a blocking operation, and what ensure an approximate
// rate of max(rps) requests per second.
//
// If the context is cancelled while waiting, then again
// we prevent the task execution even from starting.
select {
case <-throttle.C:
case <-ctx.Done():
return
}
// Account the number of concurrent tasks.
// We only account them once reached the throttle.
metrics.OngoingTasks.Inc()
defer func() { metrics.OngoingTasks.Dec() }()
// Finally, we actually trigger the task execution.
// Which might be either a base request, or an injected request.
task.run(
ctx,
low.Template,
reqBuilder,
bhPoller,
onRequestsScheduled,
onRequestsSkipped,
onMatchFn,
onErrorFn,
onTaskFn,
onUpdate,
saveAllRequests,
saveResponses,
saveAllResponses,
baseModifiers,
passiveReqProfiles,
passiveResProfiles,
customTokens,
payloadStrategy,
)
}()
}
wg.Wait()
}
func (low *LineOfWork) reset() {
for _, task := range low.Tasks {
task.reset()
}
}
func (low *LineOfWork) numOfMatches() (n int) {
for _, t := range low.Tasks {
if t.Match {
n++
}
}
return
}
func (low *LineOfWork) numOfFailedTasks() (n int) {
for _, t := range low.Tasks {
if t.Error != nil && t.Performed {
n++
}
}
return
}
func (low *LineOfWork) numOfSucceedTasks() (n int) {
for _, t := range low.Tasks {
if t.Error == nil && t.Performed {
n++
}
}
return
}
func shouldFollowRedirect(ctx context.Context, req *request.Request, res *response.Response) bool {
if ctx.Err() != nil {
return false
}
// Initial request is always true
if req.FollowedRedirects == 0 {
req.FollowedRedirects++
return true
}
loc := res.Location()
// Three conditions needs to be satisfied
shouldFollowRedirect := statusCodeRedirect(res.Code) &&
req.FollowedRedirects < req.MaxRedirects &&
redirectTypeActive(req.RedirectType, loc)
if !shouldFollowRedirect {
return false
}
req.FollowedRedirects++
if strings.HasPrefix(loc, "/") {
req.Path = loc
return true
}
if !strings.Contains(loc, "://") {
loc = "http://" + loc
}
req.URL = loc
req.Path = ""
u, err := stdurl.ParseRequestURI(loc)
if err != nil {
logger.For(ctx).Errorf("Error while parsing request uri: %s", err)
}
if u != nil {
req.Headers["Host"] = []string{u.Host}
}
return true
}
func statusCodeRedirect(statusCode int) bool {
return statusCode >= 300 && statusCode < 400
}
func redirectTypeActive(redirectType profile.Redirect, location string) bool {
return redirectType.Always() ||
(redirectType.OnSite() && strings.HasPrefix(location, "/"))
}
func rawRequestFromStep(tpl Template, step profile.Step) request.Request {
req, err := request.ParseRequest([]byte(step.RawRequest), tpl.URL)
if err != nil {
return request.Request{}
}
req.URL = tpl.URL
return req
}