Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/protocols/network/network.go
2843 views
1
package network
2
3
import (
4
"strconv"
5
"strings"
6
7
"github.com/pkg/errors"
8
9
"github.com/projectdiscovery/fastdialer/fastdialer"
10
"github.com/projectdiscovery/nuclei/v3/pkg/operators"
11
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
12
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/expressions"
13
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/generators"
14
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/network/networkclientpool"
15
"github.com/projectdiscovery/utils/errkit"
16
fileutil "github.com/projectdiscovery/utils/file"
17
)
18
19
// Request contains a Network protocol request to be made from a template
20
type Request struct {
21
// ID is the optional id of the request
22
ID string `yaml:"id,omitempty" json:"id,omitempty" jsonschema:"title=id of the request,description=ID of the network request"`
23
24
// description: |
25
// Host to send network requests to.
26
//
27
// Usually it's set to `{{Hostname}}`. If you want to enable TLS for
28
// TCP Connection, you can use `tls://{{Hostname}}`.
29
// examples:
30
// - value: |
31
// []string{"{{Hostname}}"}
32
Address []string `yaml:"host,omitempty" json:"host,omitempty" jsonschema:"title=host to send requests to,description=Host to send network requests to"`
33
addresses []addressKV
34
35
// description: |
36
// Attack is the type of payload combinations to perform.
37
//
38
// Batteringram is inserts the same payload into all defined payload positions at once, pitchfork combines multiple payload sets and clusterbomb generates
39
// permutations and combinations for all payloads.
40
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"`
41
// description: |
42
// Payloads contains any payloads for the current request.
43
//
44
// Payloads support both key-values combinations where a list
45
// of payloads is provided, or optionally a single file can also
46
// be provided as payload which will be read on run-time.
47
Payloads map[string]interface{} `yaml:"payloads,omitempty" json:"payloads,omitempty" jsonschema:"title=payloads for the network request,description=Payloads contains any payloads for the current request"`
48
// description: |
49
// Threads specifies number of threads to use sending requests. This enables Connection Pooling.
50
//
51
// Connection: Close attribute must not be used in request while using threads flag, otherwise
52
// pooling will fail and engine will continue to close connections after requests.
53
// examples:
54
// - name: Send requests using 10 concurrent threads
55
// value: 10
56
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"`
57
58
// description: |
59
// Inputs contains inputs for the network socket
60
Inputs []*Input `yaml:"inputs,omitempty" json:"inputs,omitempty" jsonschema:"title=inputs for the network request,description=Inputs contains any input/output for the current request"`
61
// description: |
62
// Port is the port to send network requests to. this acts as default port but is overridden if target/input contains
63
// non-http(s) ports like 80,8080,8081 etc
64
Port string `yaml:"port,omitempty" json:"port,omitempty" jsonschema:"title=port to send requests to,description=Port to send network requests to,oneof_type=string;integer"`
65
66
// description: |
67
// ExcludePorts is the list of ports to exclude from being scanned . It is intended to be used with `Port` field and contains a list of ports which are ignored/skipped
68
ExcludePorts string `yaml:"exclude-ports,omitempty" json:"exclude-ports,omitempty" jsonschema:"title=exclude ports from being scanned,description=Exclude ports from being scanned"`
69
// description: |
70
// ReadSize is the size of response to read at the end
71
//
72
// Default value for read-size is 1024.
73
// examples:
74
// - value: "2048"
75
ReadSize int `yaml:"read-size,omitempty" json:"read-size,omitempty" jsonschema:"title=size of network response to read,description=Size of response to read at the end. Default is 1024 bytes"`
76
// description: |
77
// ReadAll determines if the data stream should be read till the end regardless of the size
78
//
79
// Default value for read-all is false.
80
// examples:
81
// - value: false
82
ReadAll bool `yaml:"read-all,omitempty" json:"read-all,omitempty" jsonschema:"title=read all response stream,description=Read all response stream till the server stops sending"`
83
84
// description: |
85
// SelfContained specifies if the request is self-contained.
86
SelfContained bool `yaml:"-" json:"-"`
87
88
// description: |
89
// StopAtFirstMatch stops the execution of the requests and template as soon as a match is found.
90
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"`
91
92
// description: |
93
// ports is post processed list of ports to scan (obtained from Port)
94
ports []string `yaml:"-" json:"-"`
95
96
// Operators for the current request go here.
97
operators.Operators `yaml:",inline,omitempty"`
98
CompiledOperators *operators.Operators `yaml:"-" json:"-"`
99
100
generator *generators.PayloadGenerator
101
// cache any variables that may be needed for operation.
102
dialer *fastdialer.Dialer
103
options *protocols.ExecutorOptions
104
}
105
106
// RequestPartDefinitions contains a mapping of request part definitions and their
107
// description. Multiple definitions are separated by commas.
108
// Definitions not having a name (generated on runtime) are prefixed & suffixed by <>.
109
var RequestPartDefinitions = map[string]string{
110
"template-id": "ID of the template executed",
111
"template-info": "Info Block of the template executed",
112
"template-path": "Path of the template executed",
113
"host": "Host is the input to the template",
114
"matched": "Matched is the input which was matched upon",
115
"type": "Type is the type of request made",
116
"request": "Network request made from the client",
117
"body,all,data": "Network response received from server (default)",
118
"raw": "Full Network protocol data",
119
}
120
121
type addressKV struct {
122
address string
123
tls bool
124
}
125
126
// Input is the input to send on the network
127
type Input struct {
128
// description: |
129
// Data is the data to send as the input.
130
//
131
// It supports DSL Helper Functions as well as normal expressions.
132
// examples:
133
// - value: "\"TEST\""
134
// - value: "\"hex_decode('50494e47')\""
135
Data string `yaml:"data,omitempty" json:"data,omitempty" jsonschema:"title=data to send as input,description=Data is the data to send as the input,oneof_type=string;integer"`
136
// description: |
137
// Type is the type of input specified in `data` field.
138
//
139
// Default value is text, but hex can be used for hex formatted data.
140
// values:
141
// - "hex"
142
// - "text"
143
Type NetworkInputTypeHolder `yaml:"type,omitempty" json:"type,omitempty" jsonschema:"title=type is the type of input data,description=Type of input specified in data field,enum=hex,enum=text"`
144
// description: |
145
// Read is the number of bytes to read from socket.
146
//
147
// This can be used for protocols which expect an immediate response. You can
148
// read and write responses one after another and eventually perform matching
149
// on every data captured with `name` attribute.
150
//
151
// The [network docs](https://nuclei.projectdiscovery.io/templating-guide/protocols/network/) highlight more on how to do this.
152
// examples:
153
// - value: "1024"
154
Read int `yaml:"read,omitempty" json:"read,omitempty" jsonschema:"title=bytes to read from socket,description=Number of bytes to read from socket"`
155
// description: |
156
// Name is the optional name of the data read to provide matching on.
157
// examples:
158
// - value: "\"prefix\""
159
Name string `yaml:"name,omitempty" json:"name,omitempty" jsonschema:"title=optional name for data read,description=Optional name of the data read to provide matching on"`
160
}
161
162
// GetID returns the unique ID of the request if any.
163
func (request *Request) GetID() string {
164
return request.ID
165
}
166
167
// Compile compiles the protocol request for further execution.
168
func (request *Request) Compile(options *protocols.ExecutorOptions) error {
169
var shouldUseTLS bool
170
var err error
171
172
request.options = options
173
for _, address := range request.Address {
174
// check if the connection should be encrypted
175
if strings.HasPrefix(address, "tls://") {
176
shouldUseTLS = true
177
address = strings.TrimPrefix(address, "tls://")
178
}
179
request.addresses = append(request.addresses, addressKV{address: address, tls: shouldUseTLS})
180
}
181
// Pre-compile any input dsl functions before executing the request.
182
// Build a map with template variables and -var flag values for pre-compilation
183
preCompileVars := request.options.Variables.GetAll()
184
// Merge in -var flag values
185
if request.options.Options != nil {
186
generators.MergeMapsInto(preCompileVars, request.options.Options.Vars.AsMap())
187
}
188
// Also merge in constants
189
generators.MergeMapsInto(preCompileVars, request.options.Constants)
190
191
for _, input := range request.Inputs {
192
if input.Type.String() != "" {
193
continue
194
}
195
if compiled, evalErr := expressions.Evaluate(input.Data, preCompileVars); evalErr == nil {
196
input.Data = compiled
197
}
198
}
199
200
// parse ports and validate
201
if request.Port != "" {
202
for _, port := range strings.Split(request.Port, ",") {
203
if port == "" {
204
continue
205
}
206
portInt, err := strconv.Atoi(port)
207
if err != nil {
208
return errkit.Wrapf(err, "could not parse port %v from '%s'", port, request.Port)
209
}
210
if portInt < 1 || portInt > 65535 {
211
return errkit.Newf("port %v is not in valid range", portInt)
212
}
213
request.ports = append(request.ports, port)
214
}
215
}
216
217
// Resolve payload paths from vars if they exists
218
for name, payload := range request.options.Options.Vars.AsMap() {
219
payloadStr, ok := payload.(string)
220
// check if inputs contains the payload
221
var hasPayloadName bool
222
for _, input := range request.Inputs {
223
if input.Type.String() != "" {
224
continue
225
}
226
if expressions.ContainsVariablesWithNames(map[string]interface{}{name: payload}, input.Data) == nil {
227
hasPayloadName = true
228
break
229
}
230
}
231
if ok && hasPayloadName && fileutil.FileExists(payloadStr) {
232
if request.Payloads == nil {
233
request.Payloads = make(map[string]interface{})
234
}
235
request.Payloads[name] = payloadStr
236
}
237
}
238
239
if len(request.Payloads) > 0 {
240
request.generator, err = generators.New(request.Payloads, request.AttackType.Value, request.options.TemplatePath, request.options.Catalog, request.options.Options.AttackType, request.options.Options)
241
if err != nil {
242
return errors.Wrap(err, "could not parse payloads")
243
}
244
// if we have payloads, adjust threads if none specified
245
request.Threads = options.GetThreadsForNPayloadRequests(request.Requests(), request.Threads)
246
}
247
248
// Create a client for the class
249
client, err := networkclientpool.Get(options.Options, &networkclientpool.Configuration{
250
CustomDialer: options.CustomFastdialer,
251
})
252
if err != nil {
253
return errors.Wrap(err, "could not get network client")
254
}
255
request.dialer = client
256
257
if len(request.Matchers) > 0 || len(request.Extractors) > 0 {
258
compiled := &request.Operators
259
compiled.ExcludeMatchers = options.ExcludeMatchers
260
compiled.TemplateID = options.TemplateID
261
if err := compiled.Compile(); err != nil {
262
return errors.Wrap(err, "could not compile operators")
263
}
264
request.CompiledOperators = compiled
265
}
266
return nil
267
}
268
269
// Requests returns the total number of requests the YAML rule will perform
270
func (request *Request) Requests() int {
271
return len(request.Address)
272
}
273
274
func (request *Request) SetDialer(dialer *fastdialer.Dialer) {
275
request.dialer = dialer
276
}
277
278
// UpdateOptions replaces this request's options with a new copy
279
func (r *Request) UpdateOptions(opts *protocols.ExecutorOptions) {
280
r.options.ApplyNewEngineOptions(opts)
281
}
282
283