Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/fuzz/execute.go
2070 views
1
package fuzz
2
3
import (
4
"fmt"
5
"io"
6
"regexp"
7
"strings"
8
9
"github.com/pkg/errors"
10
"github.com/projectdiscovery/gologger"
11
"github.com/projectdiscovery/nuclei/v3/pkg/fuzz/component"
12
fuzzStats "github.com/projectdiscovery/nuclei/v3/pkg/fuzz/stats"
13
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
14
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/contextargs"
15
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/expressions"
16
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/generators"
17
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/marker"
18
"github.com/projectdiscovery/nuclei/v3/pkg/utils/json"
19
"github.com/projectdiscovery/retryablehttp-go"
20
"github.com/projectdiscovery/utils/errkit"
21
mapsutil "github.com/projectdiscovery/utils/maps"
22
sliceutil "github.com/projectdiscovery/utils/slice"
23
urlutil "github.com/projectdiscovery/utils/url"
24
)
25
26
var (
27
ErrRuleNotApplicable = errkit.New("rule not applicable")
28
)
29
30
// IsErrRuleNotApplicable checks if an error is due to rule not applicable
31
func IsErrRuleNotApplicable(err error) bool {
32
if err == nil {
33
return false
34
}
35
if strings.Contains(err.Error(), "rule not applicable") {
36
return true
37
}
38
return false
39
}
40
41
// ExecuteRuleInput is the input for rule Execute function
42
type ExecuteRuleInput struct {
43
// Input is the context args input
44
Input *contextargs.Context
45
// Callback is the callback for generated rule requests
46
Callback func(GeneratedRequest) bool
47
// InteractURLs contains interact urls for execute call
48
InteractURLs []string
49
// Values contains dynamic values for the rule
50
Values map[string]interface{}
51
// BaseRequest is the base http request for fuzzing rule
52
BaseRequest *retryablehttp.Request
53
// DisplayFuzzPoints is a flag to display fuzz points
54
DisplayFuzzPoints bool
55
56
// ApplyPayloadInitialTransformation is an optional function
57
// to transform the payload initially based on analyzer rules
58
ApplyPayloadInitialTransformation func(string, map[string]interface{}) string
59
AnalyzerParams map[string]interface{}
60
}
61
62
// GeneratedRequest is a single generated request for rule
63
type GeneratedRequest struct {
64
// Request is the http request for rule
65
Request *retryablehttp.Request
66
// InteractURLs is the list of interactsh urls
67
InteractURLs []string
68
// DynamicValues contains dynamic values map
69
DynamicValues map[string]interface{}
70
// Component is the component for the request
71
Component component.Component
72
// Parameter being fuzzed
73
Parameter string
74
75
// Key is the key for the request
76
Key string
77
// Value is the value for the request
78
Value string
79
// OriginalValue is the original value for the request
80
OriginalValue string
81
// OriginalPayload is the original payload for the request
82
OriginalPayload string
83
}
84
85
// Execute executes a fuzzing rule accepting a callback on which
86
// generated requests are returned.
87
//
88
// Input is not thread safe and should not be shared between concurrent
89
// goroutines.
90
func (rule *Rule) Execute(input *ExecuteRuleInput) (err error) {
91
if !rule.isInputURLValid(input.Input) {
92
return errkit.Newf("rule not applicable: invalid input url: %v", input.Input.MetaInput.Input)
93
}
94
if input.BaseRequest == nil && input.Input.MetaInput.ReqResp == nil {
95
return errkit.Newf("rule not applicable: both base request and reqresp are nil for %v", input.Input.MetaInput.Input)
96
}
97
98
var finalComponentList []component.Component
99
// match rule part with component name
100
displayDebugFuzzPoints := make(map[string]map[string]string)
101
for _, componentName := range component.Components {
102
if rule.Part != componentName && !sliceutil.Contains(rule.Parts, componentName) && rule.partType != requestPartType {
103
continue
104
}
105
component := component.New(componentName)
106
discovered, err := component.Parse(input.BaseRequest)
107
if err != nil {
108
gologger.Verbose().Msgf("Could not parse component %s: %s\n", componentName, err)
109
continue
110
}
111
if !discovered {
112
continue
113
}
114
115
// check rule applicable on this component
116
if !rule.checkRuleApplicableOnComponent(component) {
117
continue
118
}
119
// Debugging display for fuzz points
120
if input.DisplayFuzzPoints {
121
displayDebugFuzzPoints[componentName] = make(map[string]string)
122
_ = component.Iterate(func(key string, value interface{}) error {
123
displayDebugFuzzPoints[componentName][key] = fmt.Sprintf("%v", value)
124
return nil
125
})
126
}
127
128
if rule.options.FuzzStatsDB != nil {
129
_ = component.Iterate(func(key string, value interface{}) error {
130
rule.options.FuzzStatsDB.RecordComponentEvent(fuzzStats.ComponentEvent{
131
URL: input.Input.MetaInput.Target(),
132
ComponentType: componentName,
133
ComponentName: fmt.Sprintf("%v", value),
134
})
135
return nil
136
})
137
}
138
139
finalComponentList = append(finalComponentList, component)
140
}
141
if len(displayDebugFuzzPoints) > 0 {
142
marshalled, _ := json.MarshalIndent(displayDebugFuzzPoints, "", " ")
143
gologger.Info().Msgf("[%s] Fuzz points for %s [%s]\n%s\n", rule.options.TemplateID, input.Input.MetaInput.Input, input.BaseRequest.Method, string(marshalled))
144
}
145
146
if len(finalComponentList) == 0 {
147
return errkit.Newf("rule not applicable: no component matched on this rule")
148
}
149
150
baseValues := input.Values
151
if rule.generator == nil {
152
for _, component := range finalComponentList {
153
// get vars from variables while replacing interactsh urls
154
evaluatedValues, interactURLs := rule.options.Variables.EvaluateWithInteractsh(baseValues, rule.options.Interactsh)
155
input.Values = generators.MergeMaps(evaluatedValues, baseValues, rule.options.Options.Vars.AsMap(), rule.options.Constants)
156
// evaluate all vars with interactsh
157
input.Values, interactURLs = rule.evaluateVarsWithInteractsh(input.Values, interactURLs)
158
input.InteractURLs = interactURLs
159
err := rule.executeRuleValues(input, component)
160
if err != nil {
161
return err
162
}
163
}
164
return nil
165
}
166
mainLoop:
167
for _, component := range finalComponentList {
168
iterator := rule.generator.NewIterator()
169
for {
170
values, next := iterator.Value()
171
if !next {
172
continue mainLoop
173
}
174
// get vars from variables while replacing interactsh urls
175
evaluatedValues, interactURLs := rule.options.Variables.EvaluateWithInteractsh(generators.MergeMaps(values, baseValues), rule.options.Interactsh)
176
input.Values = generators.MergeMaps(values, evaluatedValues, baseValues, rule.options.Options.Vars.AsMap(), rule.options.Constants)
177
// evaluate all vars with interactsh
178
input.Values, interactURLs = rule.evaluateVarsWithInteractsh(input.Values, interactURLs)
179
input.InteractURLs = interactURLs
180
181
if err := rule.executeRuleValues(input, component); err != nil {
182
if err == io.EOF {
183
return nil
184
}
185
gologger.Warning().Msgf("[%s] Could not execute rule: %s\n", rule.options.TemplateID, err)
186
return err
187
}
188
}
189
}
190
return nil
191
}
192
193
// evaluateVars evaluates variables in a string using available executor options
194
func (rule *Rule) evaluateVars(input string) (string, error) {
195
if rule.options == nil {
196
return input, nil
197
}
198
199
data := generators.MergeMaps(
200
rule.options.Variables.GetAll(),
201
rule.options.Constants,
202
rule.options.Options.Vars.AsMap(),
203
)
204
205
exprs := expressions.FindExpressions(input, marker.ParenthesisOpen, marker.ParenthesisClose, data)
206
207
err := expressions.ContainsUnresolvedVariables(exprs...)
208
if err != nil {
209
return input, err
210
}
211
212
eval, err := expressions.Evaluate(input, data)
213
if err != nil {
214
return input, err
215
}
216
217
return eval, nil
218
}
219
220
// evaluateVarsWithInteractsh evaluates the variables with Interactsh URLs and updates them accordingly.
221
func (rule *Rule) evaluateVarsWithInteractsh(data map[string]interface{}, interactshUrls []string) (map[string]interface{}, []string) {
222
// Check if Interactsh options are configured
223
if rule.options.Interactsh != nil {
224
interactshUrlsMap := make(map[string]struct{})
225
for _, url := range interactshUrls {
226
interactshUrlsMap[url] = struct{}{}
227
}
228
interactshUrls = mapsutil.GetKeys(interactshUrlsMap)
229
// Iterate through the data to replace and evaluate variables with Interactsh URLs
230
for k, v := range data {
231
value := fmt.Sprint(v)
232
// Replace variables with Interactsh URLs and collect new URLs
233
got, oastUrls := rule.options.Interactsh.Replace(value, interactshUrls)
234
if got != value {
235
data[k] = got
236
}
237
// Append new OAST URLs if any
238
if len(oastUrls) > 0 {
239
for _, url := range oastUrls {
240
if _, ok := interactshUrlsMap[url]; !ok {
241
interactshUrlsMap[url] = struct{}{}
242
interactshUrls = append(interactshUrls, url)
243
}
244
}
245
}
246
// Evaluate the replaced data
247
evaluatedData, err := expressions.Evaluate(got, data)
248
if err == nil {
249
// Update the data if there is a change after evaluation
250
if evaluatedData != got {
251
data[k] = evaluatedData
252
}
253
}
254
}
255
}
256
// Return the updated data and Interactsh URLs without any error
257
return data, interactshUrls
258
}
259
260
// isInputURLValid returns true if url is valid after parsing it
261
func (rule *Rule) isInputURLValid(input *contextargs.Context) bool {
262
if input == nil || input.MetaInput == nil || input.MetaInput.Input == "" {
263
return false
264
}
265
_, err := urlutil.Parse(input.MetaInput.Input)
266
return err == nil
267
}
268
269
// executeRuleValues executes a rule with a set of values
270
func (rule *Rule) executeRuleValues(input *ExecuteRuleInput, ruleComponent component.Component) error {
271
// if we are only fuzzing values
272
if len(rule.Fuzz.Value) > 0 {
273
for _, value := range rule.Fuzz.Value {
274
originalPayload := value
275
276
if err := rule.executePartRule(input, ValueOrKeyValue{Value: value, OriginalPayload: originalPayload}, ruleComponent); err != nil {
277
if component.IsErrSetValue(err) {
278
// this are errors due to format restrictions
279
// ex: fuzzing string value in a json int field
280
continue
281
}
282
return err
283
}
284
}
285
return nil
286
}
287
288
// if we are fuzzing both keys and values
289
if rule.Fuzz.KV != nil {
290
var gotErr error
291
rule.Fuzz.KV.Iterate(func(key, value string) bool {
292
if err := rule.executePartRule(input, ValueOrKeyValue{Key: key, Value: value}, ruleComponent); err != nil {
293
if component.IsErrSetValue(err) {
294
// this are errors due to format restrictions
295
// ex: fuzzing string value in a json int field
296
return true
297
}
298
gotErr = err
299
return false
300
}
301
return true
302
})
303
// if mode is multiple now build and execute it
304
if rule.modeType == multipleModeType {
305
rule.Fuzz.KV.Iterate(func(key, value string) bool {
306
var evaluated string
307
evaluated, input.InteractURLs = rule.executeEvaluate(input, key, "", value, input.InteractURLs)
308
if err := ruleComponent.SetValue(key, evaluated); err != nil {
309
return true
310
}
311
return true
312
})
313
req, err := ruleComponent.Rebuild()
314
if err != nil {
315
return err
316
}
317
if gotErr := rule.execWithInput(input, req, input.InteractURLs, ruleComponent, "", "", "", "", "", ""); gotErr != nil {
318
return gotErr
319
}
320
}
321
return gotErr
322
}
323
324
// something else is wrong
325
return fmt.Errorf("no fuzz values specified")
326
}
327
328
// Compile compiles a fuzzing rule and initializes it for operation
329
func (rule *Rule) Compile(generator *generators.PayloadGenerator, options *protocols.ExecutorOptions) error {
330
// If a payload generator is specified from base request, use it
331
// for payload values.
332
if generator != nil {
333
rule.generator = generator
334
}
335
rule.options = options
336
337
// Resolve the default enums
338
if rule.Mode != "" {
339
if valueType, ok := stringToModeType[rule.Mode]; !ok {
340
return errors.Errorf("invalid mode value specified: %s", rule.Mode)
341
} else {
342
rule.modeType = valueType
343
}
344
} else {
345
rule.modeType = multipleModeType
346
}
347
if rule.Part != "" {
348
if valueType, ok := stringToPartType[rule.Part]; !ok {
349
return errors.Errorf("invalid part value specified: %s", rule.Part)
350
} else {
351
rule.partType = valueType
352
}
353
}
354
if rule.Part == "" && len(rule.Parts) == 0 {
355
return errors.Errorf("no part specified for rule")
356
}
357
358
if rule.Type != "" {
359
if valueType, ok := stringToRuleType[rule.Type]; !ok {
360
return errors.Errorf("invalid type value specified: %s", rule.Type)
361
} else {
362
rule.ruleType = valueType
363
}
364
} else {
365
rule.ruleType = replaceRuleType
366
}
367
368
// Initialize other required regexes and maps
369
if len(rule.Keys) > 0 {
370
rule.keysMap = make(map[string]struct{})
371
}
372
373
// eval vars in "keys"
374
for _, key := range rule.Keys {
375
evaluatedKey, err := rule.evaluateVars(key)
376
if err != nil {
377
return errors.Wrap(err, "could not evaluate key")
378
}
379
380
rule.keysMap[strings.ToLower(evaluatedKey)] = struct{}{}
381
}
382
383
// eval vars in "values"
384
for _, value := range rule.ValuesRegex {
385
evaluatedValue, err := rule.evaluateVars(value)
386
if err != nil {
387
return errors.Wrap(err, "could not evaluate value regex")
388
}
389
390
compiled, err := regexp.Compile(evaluatedValue)
391
if err != nil {
392
return errors.Wrap(err, "could not compile value regex")
393
}
394
395
rule.valuesRegex = append(rule.valuesRegex, compiled)
396
}
397
398
// eval vars in "keys-regex"
399
for _, value := range rule.KeysRegex {
400
evaluatedValue, err := rule.evaluateVars(value)
401
if err != nil {
402
return errors.Wrap(err, "could not evaluate key regex")
403
}
404
405
compiled, err := regexp.Compile(evaluatedValue)
406
if err != nil {
407
return errors.Wrap(err, "could not compile key regex")
408
}
409
410
rule.keysRegex = append(rule.keysRegex, compiled)
411
}
412
413
if rule.ruleType != replaceRegexRuleType {
414
if rule.ReplaceRegex != "" {
415
return errors.Errorf("replace-regex is only applicable for replace and replace-regex rule types")
416
}
417
} else {
418
if rule.ReplaceRegex == "" {
419
return errors.Errorf("replace-regex is required for replace-regex rule type")
420
}
421
422
evalReplaceRegex, err := rule.evaluateVars(rule.ReplaceRegex)
423
if err != nil {
424
return errors.Wrap(err, "could not evaluate replace regex")
425
}
426
427
compiled, err := regexp.Compile(evalReplaceRegex)
428
if err != nil {
429
return errors.Wrap(err, "could not compile replace regex")
430
}
431
432
rule.replaceRegex = compiled
433
}
434
435
return nil
436
}
437
438