Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/protocols/http/http.go
2070 views
1
package http
2
3
import (
4
"bytes"
5
"fmt"
6
"math"
7
"strings"
8
"time"
9
10
"github.com/invopop/jsonschema"
11
json "github.com/json-iterator/go"
12
"github.com/pkg/errors"
13
14
"github.com/projectdiscovery/fastdialer/fastdialer"
15
_ "github.com/projectdiscovery/nuclei/v3/pkg/fuzz/analyzers/time"
16
17
"github.com/projectdiscovery/nuclei/v3/pkg/fuzz"
18
"github.com/projectdiscovery/nuclei/v3/pkg/fuzz/analyzers"
19
"github.com/projectdiscovery/nuclei/v3/pkg/operators"
20
"github.com/projectdiscovery/nuclei/v3/pkg/operators/matchers"
21
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
22
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/expressions"
23
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/generators"
24
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/protocolstate"
25
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/http/httpclientpool"
26
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/network/networkclientpool"
27
httputil "github.com/projectdiscovery/nuclei/v3/pkg/protocols/utils/http"
28
"github.com/projectdiscovery/nuclei/v3/pkg/utils/stats"
29
"github.com/projectdiscovery/rawhttp"
30
"github.com/projectdiscovery/retryablehttp-go"
31
fileutil "github.com/projectdiscovery/utils/file"
32
)
33
34
// Request contains a http request to be made from a template
35
type Request struct {
36
// Operators for the current request go here.
37
operators.Operators `yaml:",inline" json:",inline"`
38
// description: |
39
// Path contains the path/s for the HTTP requests. It supports variables
40
// as placeholders.
41
// examples:
42
// - name: Some example path values
43
// value: >
44
// []string{"{{BaseURL}}", "{{BaseURL}}/+CSCOU+/../+CSCOE+/files/file_list.json?path=/sessions"}
45
Path []string `yaml:"path,omitempty" json:"path,omitempty" jsonschema:"title=path(s) for the http request,description=Path(s) to send http requests to"`
46
// description: |
47
// Raw contains HTTP Requests in Raw format.
48
// examples:
49
// - name: Some example raw requests
50
// value: |
51
// []string{"GET /etc/passwd HTTP/1.1\nHost:\nContent-Length: 4", "POST /.%0d./.%0d./.%0d./.%0d./bin/sh HTTP/1.1\nHost: {{Hostname}}\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0\nContent-Length: 1\nConnection: close\n\necho\necho\ncat /etc/passwd 2>&1"}
52
Raw []string `yaml:"raw,omitempty" json:"raw,omitempty" jsonschema:"http requests in raw format,description=HTTP Requests in Raw Format"`
53
// ID is the optional id of the request
54
ID string `yaml:"id,omitempty" json:"id,omitempty" jsonschema:"title=id for the http request,description=ID for the HTTP Request"`
55
// description: |
56
// Name is the optional name of the request.
57
//
58
// If a name is specified, all the named request in a template can be matched upon
59
// in a combined manner allowing multi-request based matchers.
60
Name string `yaml:"name,omitempty" json:"name,omitempty" jsonschema:"title=name for the http request,description=Optional name for the HTTP Request"`
61
// description: |
62
// Attack is the type of payload combinations to perform.
63
//
64
// batteringram is inserts the same payload into all defined payload positions at once, pitchfork combines multiple payload sets and clusterbomb generates
65
// permutations and combinations for all payloads.
66
// values:
67
// - "batteringram"
68
// - "pitchfork"
69
// - "clusterbomb"
70
AttackType generators.AttackTypeHolder `yaml:"attack,omitempty" json:"attack,omitempty" jsonschema:"title=attack is the payload combination,description=Attack is the type of payload combinations to perform,enum=batteringram,enum=pitchfork,enum=clusterbomb"`
71
// description: |
72
// Method is the HTTP Request Method.
73
Method HTTPMethodTypeHolder `yaml:"method,omitempty" json:"method,omitempty" jsonschema:"title=method is the http request method,description=Method is the HTTP Request Method,enum=GET,enum=HEAD,enum=POST,enum=PUT,enum=DELETE,enum=CONNECT,enum=OPTIONS,enum=TRACE,enum=PATCH,enum=PURGE"`
74
// description: |
75
// Body is an optional parameter which contains HTTP Request body.
76
// examples:
77
// - name: Same Body for a Login POST request
78
// value: "\"username=test&password=test\""
79
Body string `yaml:"body,omitempty" json:"body,omitempty" jsonschema:"title=body is the http request body,description=Body is an optional parameter which contains HTTP Request body"`
80
// description: |
81
// Payloads contains any payloads for the current request.
82
//
83
// Payloads support both key-values combinations where a list
84
// of payloads is provided, or optionally a single file can also
85
// be provided as payload which will be read on run-time.
86
Payloads map[string]interface{} `yaml:"payloads,omitempty" json:"payloads,omitempty" jsonschema:"title=payloads for the http request,description=Payloads contains any payloads for the current request"`
87
88
// description: |
89
// Headers contains HTTP Headers to send with the request.
90
// examples:
91
// - value: |
92
// map[string]string{"Content-Type": "application/x-www-form-urlencoded", "Content-Length": "1", "Any-Header": "Any-Value"}
93
Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty" jsonschema:"title=headers to send with the http request,description=Headers contains HTTP Headers to send with the request"`
94
// description: |
95
// RaceCount is the number of times to send a request in Race Condition Attack.
96
// examples:
97
// - name: Send a request 5 times
98
// value: "5"
99
RaceNumberRequests int `yaml:"race_count,omitempty" json:"race_count,omitempty" jsonschema:"title=number of times to repeat request in race condition,description=Number of times to send a request in Race Condition Attack"`
100
// description: |
101
// MaxRedirects is the maximum number of redirects that should be followed.
102
// examples:
103
// - name: Follow up to 5 redirects
104
// value: "5"
105
MaxRedirects int `yaml:"max-redirects,omitempty" json:"max-redirects,omitempty" jsonschema:"title=maximum number of redirects to follow,description=Maximum number of redirects that should be followed"`
106
// description: |
107
// PipelineConcurrentConnections is number of connections to create during pipelining.
108
// examples:
109
// - name: Create 40 concurrent connections
110
// value: 40
111
PipelineConcurrentConnections int `yaml:"pipeline-concurrent-connections,omitempty" json:"pipeline-concurrent-connections,omitempty" jsonschema:"title=number of pipelining connections,description=Number of connections to create during pipelining"`
112
// description: |
113
// PipelineRequestsPerConnection is number of requests to send per connection when pipelining.
114
// examples:
115
// - name: Send 100 requests per pipeline connection
116
// value: 100
117
PipelineRequestsPerConnection int `yaml:"pipeline-requests-per-connection,omitempty" json:"pipeline-requests-per-connection,omitempty" jsonschema:"title=number of requests to send per pipelining connections,description=Number of requests to send per connection when pipelining"`
118
// description: |
119
// Threads specifies number of threads to use sending requests. This enables Connection Pooling.
120
//
121
// Connection: Close attribute must not be used in request while using threads flag, otherwise
122
// pooling will fail and engine will continue to close connections after requests.
123
// examples:
124
// - name: Send requests using 10 concurrent threads
125
// value: 10
126
Threads int `yaml:"threads,omitempty" json:"threads,omitempty" jsonschema:"title=threads for sending requests,description=Threads specifies number of threads to use sending requests. This enables Connection Pooling"`
127
// description: |
128
// MaxSize is the maximum size of http response body to read in bytes.
129
// examples:
130
// - name: Read max 2048 bytes of the response
131
// value: 2048
132
MaxSize int `yaml:"max-size,omitempty" json:"max-size,omitempty" jsonschema:"title=maximum http response body size,description=Maximum size of http response body to read in bytes"`
133
134
// Fuzzing describes schema to fuzz http requests
135
Fuzzing []*fuzz.Rule `yaml:"fuzzing,omitempty" json:"fuzzing,omitempty" jsonschema:"title=fuzzin rules for http fuzzing,description=Fuzzing describes rule schema to fuzz http requests"`
136
// description: |
137
// Analyzer is an analyzer to use for matching the response.
138
Analyzer *analyzers.AnalyzerTemplate `yaml:"analyzer,omitempty" json:"analyzer,omitempty" jsonschema:"title=analyzer for http request,description=Analyzer for HTTP Request"`
139
140
CompiledOperators *operators.Operators `yaml:"-" json:"-"`
141
142
options *protocols.ExecutorOptions
143
connConfiguration *httpclientpool.Configuration
144
totalRequests int
145
customHeaders map[string]string
146
generator *generators.PayloadGenerator // optional, only enabled when using payloads
147
httpClient *retryablehttp.Client
148
rawhttpClient *rawhttp.Client
149
dialer *fastdialer.Dialer
150
151
// description: |
152
// SelfContained specifies if the request is self-contained.
153
SelfContained bool `yaml:"self-contained,omitempty" json:"self-contained,omitempty"`
154
155
// description: |
156
// Signature is the request signature method
157
// values:
158
// - "AWS"
159
Signature SignatureTypeHolder `yaml:"signature,omitempty" json:"signature,omitempty" jsonschema:"title=signature is the http request signature method,description=Signature is the HTTP Request signature Method,enum=AWS"`
160
161
// description: |
162
// SkipSecretFile skips the authentication or authorization configured in the secret file.
163
SkipSecretFile bool `yaml:"skip-secret-file,omitempty" json:"skip-secret-file,omitempty" jsonschema:"title=bypass secret file,description=Skips the authentication or authorization configured in the secret file"`
164
165
// description: |
166
// CookieReuse is an optional setting that enables cookie reuse for
167
// all requests defined in raw section.
168
// Deprecated: This is default now. Use disable-cookie to disable cookie reuse. cookie-reuse will be removed in future releases.
169
CookieReuse bool `yaml:"cookie-reuse,omitempty" json:"cookie-reuse,omitempty" jsonschema:"title=optional cookie reuse enable,description=Optional setting that enables cookie reuse"`
170
171
// description: |
172
// DisableCookie is an optional setting that disables cookie reuse
173
DisableCookie bool `yaml:"disable-cookie,omitempty" json:"disable-cookie,omitempty" jsonschema:"title=optional disable cookie reuse,description=Optional setting that disables cookie reuse"`
174
175
// description: |
176
// Enables force reading of the entire raw unsafe request body ignoring
177
// any specified content length headers.
178
ForceReadAllBody bool `yaml:"read-all,omitempty" json:"read-all,omitempty" jsonschema:"title=force read all body,description=Enables force reading of entire unsafe http request body"`
179
// description: |
180
// Redirects specifies whether redirects should be followed by the HTTP Client.
181
//
182
// This can be used in conjunction with `max-redirects` to control the HTTP request redirects.
183
Redirects bool `yaml:"redirects,omitempty" json:"redirects,omitempty" jsonschema:"title=follow http redirects,description=Specifies whether redirects should be followed by the HTTP Client"`
184
// description: |
185
// Redirects specifies whether only redirects to the same host should be followed by the HTTP Client.
186
//
187
// This can be used in conjunction with `max-redirects` to control the HTTP request redirects.
188
HostRedirects bool `yaml:"host-redirects,omitempty" json:"host-redirects,omitempty" jsonschema:"title=follow same host http redirects,description=Specifies whether redirects to the same host should be followed by the HTTP Client"`
189
// description: |
190
// Pipeline defines if the attack should be performed with HTTP 1.1 Pipelining
191
//
192
// All requests must be idempotent (GET/POST). This can be used for race conditions/billions requests.
193
Pipeline bool `yaml:"pipeline,omitempty" json:"pipeline,omitempty" jsonschema:"title=perform HTTP 1.1 pipelining,description=Pipeline defines if the attack should be performed with HTTP 1.1 Pipelining"`
194
// description: |
195
// Unsafe specifies whether to use rawhttp engine for sending Non RFC-Compliant requests.
196
//
197
// This uses the [rawhttp](https://github.com/projectdiscovery/rawhttp) engine to achieve complete
198
// control over the request, with no normalization performed by the client.
199
Unsafe bool `yaml:"unsafe,omitempty" json:"unsafe,omitempty" jsonschema:"title=use rawhttp non-strict-rfc client,description=Unsafe specifies whether to use rawhttp engine for sending Non RFC-Compliant requests"`
200
// description: |
201
// Race determines if all the request have to be attempted at the same time (Race Condition)
202
//
203
// The actual number of requests that will be sent is determined by the `race_count` field.
204
Race bool `yaml:"race,omitempty" json:"race,omitempty" jsonschema:"title=perform race-http request coordination attack,description=Race determines if all the request have to be attempted at the same time (Race Condition)"`
205
// description: |
206
// ReqCondition automatically assigns numbers to requests and preserves their history.
207
//
208
// This allows matching on them later for multi-request conditions.
209
// Deprecated: request condition will be detected automatically (https://github.com/projectdiscovery/nuclei/issues/2393)
210
ReqCondition bool `yaml:"req-condition,omitempty" json:"req-condition,omitempty" jsonschema:"title=preserve request history,description=Automatically assigns numbers to requests and preserves their history"`
211
// description: |
212
// StopAtFirstMatch stops the execution of the requests and template as soon as a match is found.
213
StopAtFirstMatch bool `yaml:"stop-at-first-match,omitempty" json:"stop-at-first-match,omitempty" jsonschema:"title=stop at first match,description=Stop the execution after a match is found"`
214
// description: |
215
// SkipVariablesCheck skips the check for unresolved variables in request
216
SkipVariablesCheck bool `yaml:"skip-variables-check,omitempty" json:"skip-variables-check,omitempty" jsonschema:"title=skip variable checks,description=Skips the check for unresolved variables in request"`
217
// description: |
218
// IterateAll iterates all the values extracted from internal extractors
219
// Deprecated: Use flow instead . iterate-all will be removed in future releases
220
IterateAll bool `yaml:"iterate-all,omitempty" json:"iterate-all,omitempty" jsonschema:"title=iterate all the values,description=Iterates all the values extracted from internal extractors"`
221
// description: |
222
// DigestAuthUsername specifies the username for digest authentication
223
DigestAuthUsername string `yaml:"digest-username,omitempty" json:"digest-username,omitempty" jsonschema:"title=specifies the username for digest authentication,description=Optional parameter which specifies the username for digest auth"`
224
// description: |
225
// DigestAuthPassword specifies the password for digest authentication
226
DigestAuthPassword string `yaml:"digest-password,omitempty" json:"digest-password,omitempty" jsonschema:"title=specifies the password for digest authentication,description=Optional parameter which specifies the password for digest auth"`
227
// description: |
228
// DisablePathAutomerge disables merging target url path with raw request path
229
DisablePathAutomerge bool `yaml:"disable-path-automerge,omitempty" json:"disable-path-automerge,omitempty" jsonschema:"title=disable auto merging of path,description=Disable merging target url path with raw request path"`
230
// description: |
231
// Fuzz PreCondition is matcher-like field to check if fuzzing should be performed on this request or not
232
FuzzPreCondition []*matchers.Matcher `yaml:"pre-condition,omitempty" json:"pre-condition,omitempty" jsonschema:"title=pre-condition for fuzzing/dast,description=PreCondition is matcher-like field to check if fuzzing should be performed on this request or not"`
233
// description: |
234
// FuzzPreConditionOperator is the operator between multiple PreConditions for fuzzing Default is OR
235
FuzzPreConditionOperator string `yaml:"pre-condition-operator,omitempty" json:"pre-condition-operator,omitempty" jsonschema:"title=condition between the filters,description=Operator to use between multiple per-conditions,enum=and,enum=or"`
236
fuzzPreConditionOperator matchers.ConditionType `yaml:"-" json:"-"`
237
// description: |
238
// GlobalMatchers marks matchers as static and applies globally to all result events from other templates
239
GlobalMatchers bool `yaml:"global-matchers,omitempty" json:"global-matchers,omitempty" jsonschema:"title=global matchers,description=marks matchers as static and applies globally to all result events from other templates"`
240
}
241
242
func (e Request) JSONSchemaExtend(schema *jsonschema.Schema) {
243
headersSchema, ok := schema.Properties.Get("headers")
244
if !ok {
245
return
246
}
247
headersSchema.PatternProperties = map[string]*jsonschema.Schema{
248
".*": {
249
OneOf: []*jsonschema.Schema{
250
{
251
Type: "string",
252
},
253
{
254
Type: "integer",
255
},
256
{
257
Type: "boolean",
258
},
259
},
260
},
261
}
262
headersSchema.Ref = ""
263
}
264
265
// Options returns executer options for http request
266
func (r *Request) Options() *protocols.ExecutorOptions {
267
return r.options
268
}
269
270
// RequestPartDefinitions contains a mapping of request part definitions and their
271
// description. Multiple definitions are separated by commas.
272
// Definitions not having a name (generated on runtime) are prefixed & suffixed by <>.
273
var RequestPartDefinitions = map[string]string{
274
"template-id": "ID of the template executed",
275
"template-info": "Info Block of the template executed",
276
"template-path": "Path of the template executed",
277
"host": "Host is the input to the template",
278
"matched": "Matched is the input which was matched upon",
279
"type": "Type is the type of request made",
280
"request": "HTTP request made from the client",
281
"response": "HTTP response received from server",
282
"status_code": "Status Code received from the Server",
283
"body": "HTTP response body received from server (default)",
284
"content_length": "HTTP Response content length",
285
"header,all_headers": "HTTP response headers",
286
"duration": "HTTP request time duration",
287
"all": "HTTP response body + headers",
288
"cookies_from_response": "HTTP response cookies in name:value format",
289
"headers_from_response": "HTTP response headers in name:value format",
290
}
291
292
// GetID returns the unique ID of the request if any.
293
func (request *Request) GetID() string {
294
return request.ID
295
}
296
297
func (request *Request) isRaw() bool {
298
return len(request.Raw) > 0
299
}
300
301
// Compile compiles the protocol request for further execution.
302
func (request *Request) Compile(options *protocols.ExecutorOptions) error {
303
if err := request.validate(); err != nil {
304
return errors.Wrap(err, "validation error")
305
}
306
307
connectionConfiguration := &httpclientpool.Configuration{
308
Threads: request.Threads,
309
MaxRedirects: request.MaxRedirects,
310
NoTimeout: false,
311
DisableCookie: request.DisableCookie,
312
Connection: &httpclientpool.ConnectionConfiguration{
313
DisableKeepAlive: httputil.ShouldDisableKeepAlive(options.Options),
314
},
315
RedirectFlow: httpclientpool.DontFollowRedirect,
316
}
317
var customTimeout int
318
if request.Analyzer != nil && request.Analyzer.Name == "time_delay" {
319
var timeoutVal int
320
if timeout, ok := request.Analyzer.Parameters["sleep_duration"]; ok {
321
timeoutVal, _ = timeout.(int)
322
} else {
323
timeoutVal = 5
324
}
325
326
// Add 5x buffer to the timeout
327
customTimeout = int(math.Ceil(float64(timeoutVal) * 5))
328
}
329
if customTimeout > 0 {
330
connectionConfiguration.Connection.CustomMaxTimeout = time.Duration(customTimeout) * time.Second
331
}
332
333
if request.Redirects || options.Options.FollowRedirects {
334
connectionConfiguration.RedirectFlow = httpclientpool.FollowAllRedirect
335
}
336
if request.HostRedirects || options.Options.FollowHostRedirects {
337
connectionConfiguration.RedirectFlow = httpclientpool.FollowSameHostRedirect
338
}
339
340
// If we have request level timeout, ignore http client timeouts
341
for _, req := range request.Raw {
342
if reTimeoutAnnotation.MatchString(req) {
343
connectionConfiguration.NoTimeout = true
344
}
345
}
346
request.connConfiguration = connectionConfiguration
347
348
client, err := httpclientpool.Get(options.Options, connectionConfiguration)
349
if err != nil {
350
return errors.Wrap(err, "could not get dns client")
351
}
352
request.customHeaders = make(map[string]string)
353
request.httpClient = client
354
355
dialer, err := networkclientpool.Get(options.Options, &networkclientpool.Configuration{
356
CustomDialer: options.CustomFastdialer,
357
})
358
if err != nil {
359
return errors.Wrap(err, "could not get dialer")
360
}
361
request.dialer = dialer
362
363
request.options = options
364
for _, option := range request.options.Options.CustomHeaders {
365
parts := strings.SplitN(option, ":", 2)
366
if len(parts) != 2 {
367
continue
368
}
369
request.customHeaders[parts[0]] = strings.TrimSpace(parts[1])
370
}
371
372
if request.Body != "" && !strings.Contains(request.Body, "\r\n") {
373
request.Body = strings.ReplaceAll(request.Body, "\n", "\r\n")
374
}
375
if len(request.Raw) > 0 {
376
for i, raw := range request.Raw {
377
if !strings.Contains(raw, "\r\n") {
378
request.Raw[i] = strings.ReplaceAll(raw, "\n", "\r\n")
379
}
380
}
381
request.rawhttpClient = httpclientpool.GetRawHTTP(options)
382
}
383
if len(request.Matchers) > 0 || len(request.Extractors) > 0 {
384
compiled := &request.Operators
385
compiled.ExcludeMatchers = options.ExcludeMatchers
386
compiled.TemplateID = options.TemplateID
387
if compileErr := compiled.Compile(); compileErr != nil {
388
return errors.Wrap(compileErr, "could not compile operators")
389
}
390
request.CompiledOperators = compiled
391
}
392
393
// === fuzzing filters ===== //
394
395
if request.FuzzPreConditionOperator != "" {
396
request.fuzzPreConditionOperator = matchers.ConditionTypes[request.FuzzPreConditionOperator]
397
} else {
398
request.fuzzPreConditionOperator = matchers.ORCondition
399
}
400
401
for _, filter := range request.FuzzPreCondition {
402
if err := filter.CompileMatchers(); err != nil {
403
return errors.Wrap(err, "could not compile matcher")
404
}
405
}
406
407
if request.Analyzer != nil {
408
if analyzer := analyzers.GetAnalyzer(request.Analyzer.Name); analyzer == nil {
409
return errors.Errorf("analyzer %s not found", request.Analyzer.Name)
410
}
411
}
412
413
// Resolve payload paths from vars if they exists
414
for name, payload := range request.options.Options.Vars.AsMap() {
415
payloadStr, ok := payload.(string)
416
// check if inputs contains the payload
417
var hasPayloadName bool
418
// search for markers in all request parts
419
var inputs []string
420
inputs = append(inputs, request.Method.String(), request.Body)
421
inputs = append(inputs, request.Raw...)
422
for k, v := range request.customHeaders {
423
inputs = append(inputs, fmt.Sprintf("%s: %s", k, v))
424
}
425
for k, v := range request.Headers {
426
inputs = append(inputs, fmt.Sprintf("%s: %s", k, v))
427
}
428
429
for _, input := range inputs {
430
if expressions.ContainsVariablesWithNames(map[string]interface{}{name: payload}, input) == nil {
431
hasPayloadName = true
432
break
433
}
434
}
435
if ok && hasPayloadName && fileutil.FileExists(payloadStr) {
436
if request.Payloads == nil {
437
request.Payloads = make(map[string]interface{})
438
}
439
request.Payloads[name] = payloadStr
440
}
441
}
442
443
// tries to drop unused payloads - by marshaling sections that might contain the payload
444
unusedPayloads := make(map[string]struct{})
445
requestSectionsToCheck := []interface{}{
446
request.customHeaders, request.Headers, request.Matchers,
447
request.Extractors, request.Body, request.Path, request.Raw, request.Fuzzing,
448
}
449
if requestSectionsToCheckData, err := json.Marshal(requestSectionsToCheck); err == nil {
450
for payload := range request.Payloads {
451
if bytes.Contains(requestSectionsToCheckData, []byte(payload)) {
452
continue
453
}
454
unusedPayloads[payload] = struct{}{}
455
}
456
}
457
for payload := range unusedPayloads {
458
delete(request.Payloads, payload)
459
}
460
461
if len(request.Payloads) > 0 {
462
request.generator, err = generators.New(request.Payloads, request.AttackType.Value, request.options.TemplatePath, request.options.Catalog, request.options.Options.AttackType, request.options.Options)
463
if err != nil {
464
return errors.Wrap(err, "could not parse payloads")
465
}
466
}
467
request.options = options
468
request.totalRequests = request.Requests()
469
470
if len(request.Fuzzing) > 0 {
471
if request.Unsafe {
472
return errors.New("cannot use unsafe with http fuzzing templates")
473
}
474
for _, rule := range request.Fuzzing {
475
if fuzzingMode := options.Options.FuzzingMode; fuzzingMode != "" {
476
rule.Mode = fuzzingMode
477
}
478
if fuzzingType := options.Options.FuzzingType; fuzzingType != "" {
479
rule.Type = fuzzingType
480
}
481
if err := rule.Compile(request.generator, request.options); err != nil {
482
return errors.Wrap(err, "could not compile fuzzing rule")
483
}
484
}
485
}
486
if len(request.Payloads) > 0 {
487
// Due to a known issue (https://github.com/projectdiscovery/nuclei/issues/5015),
488
// dynamic extractors cannot be used with payloads. To address this,
489
// execution is handled by the standard engine without concurrency,
490
// achieved by setting the thread count to 0.
491
492
// this limitation will be removed once we have a better way to handle dynamic extractors with payloads
493
hasMultipleRequests := false
494
if len(request.Raw)+len(request.Path) > 1 {
495
hasMultipleRequests = true
496
}
497
// look for dynamic extractor ( internal: true with named extractor)
498
hasNamedInternalExtractor := false
499
for _, extractor := range request.Extractors {
500
if extractor.Internal && extractor.Name != "" {
501
hasNamedInternalExtractor = true
502
break
503
}
504
}
505
if hasNamedInternalExtractor && hasMultipleRequests {
506
stats.Increment(SetThreadToCountZero)
507
request.Threads = 0
508
} else {
509
// specifically for http requests high concurrency and and threads will lead to memory exausthion, hence reduce the maximum parallelism
510
if protocolstate.IsLowOnMemory() {
511
request.Threads = protocolstate.GuardThreadsOrDefault(request.Threads)
512
}
513
request.Threads = options.GetThreadsForNPayloadRequests(request.Requests(), request.Threads)
514
}
515
}
516
return nil
517
}
518
519
// RebuildGenerator rebuilds the generator for the request
520
func (request *Request) RebuildGenerator() error {
521
generator, err := generators.New(request.Payloads, request.AttackType.Value, request.options.TemplatePath, request.options.Catalog, request.options.Options.AttackType, request.options.Options)
522
if err != nil {
523
return errors.Wrap(err, "could not parse payloads")
524
}
525
request.generator = generator
526
return nil
527
}
528
529
// Requests returns the total number of requests the YAML rule will perform
530
func (request *Request) Requests() int {
531
generator := request.newGenerator(false)
532
return generator.Total()
533
}
534
535
const (
536
SetThreadToCountZero = "set-thread-count-to-zero"
537
)
538
539
func init() {
540
stats.NewEntry(SetThreadToCountZero, "Setting thread count to 0 for %d templates, dynamic extractors are not supported with payloads yet")
541
}
542
543
// UpdateOptions replaces this request's options with a new copy
544
func (r *Request) UpdateOptions(opts *protocols.ExecutorOptions) {
545
r.options.ApplyNewEngineOptions(opts)
546
}
547
548