Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/templates/preprocessors.go
2070 views
1
package templates
2
3
import (
4
"bytes"
5
"regexp"
6
"strings"
7
8
stringsutil "github.com/projectdiscovery/utils/strings"
9
"github.com/segmentio/ksuid"
10
)
11
12
type Preprocessor interface {
13
// Process processes the data and returns the processed data.
14
ProcessNReturnData(data []byte) ([]byte, map[string]interface{})
15
// Exists check if the preprocessor exists in the data.
16
Exists(data []byte) bool
17
}
18
19
var (
20
preprocessorRegex = regexp.MustCompile(`{{([a-z0-9_]+)}}`)
21
defaultPreprocessors = []Preprocessor{
22
&randStrPreprocessor{},
23
}
24
)
25
26
func getPreprocessors(preprocessor Preprocessor) []Preprocessor {
27
if preprocessor != nil {
28
// append() function adds the elements to existing slice if space is available
29
// else it creates a new slice and copies the elements to new slice
30
// this may cause race-conditions hence we do it explicitly
31
tmp := make([]Preprocessor, 0, len(defaultPreprocessors)+1)
32
tmp = append(tmp, preprocessor)
33
tmp = append(tmp, defaultPreprocessors...)
34
return tmp
35
}
36
return defaultPreprocessors
37
}
38
39
var _ Preprocessor = &randStrPreprocessor{}
40
41
type randStrPreprocessor struct{}
42
43
// ProcessNReturnData processes the data and returns the key-value pairs of generated/replaced data.
44
func (r *randStrPreprocessor) ProcessNReturnData(data []byte) ([]byte, map[string]interface{}) {
45
foundMap := make(map[string]struct{})
46
dataMap := make(map[string]interface{})
47
for _, expression := range preprocessorRegex.FindAllStringSubmatch(string(data), -1) {
48
if len(expression) != 2 {
49
continue
50
}
51
value := expression[1]
52
if stringsutil.ContainsAny(value, "(", ")") {
53
continue
54
}
55
56
if _, ok := foundMap[value]; ok {
57
continue
58
}
59
foundMap[value] = struct{}{}
60
if strings.EqualFold(value, "randstr") || strings.HasPrefix(value, "randstr_") {
61
randStr := ksuid.New().String()
62
data = bytes.ReplaceAll(data, []byte(expression[0]), []byte(randStr))
63
dataMap[expression[0]] = randStr
64
}
65
}
66
return data, dataMap
67
}
68
69
// Exists check if the preprocessor exists in the data.
70
func (r *randStrPreprocessor) Exists(data []byte) bool {
71
return bytes.Contains(data, []byte("randstr"))
72
}
73
74