Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/protocols/network/network.go
2070 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 overriden 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
for _, input := range request.Inputs {
183
if input.Type.String() != "" {
184
continue
185
}
186
if compiled, evalErr := expressions.Evaluate(input.Data, map[string]interface{}{}); evalErr == nil {
187
input.Data = compiled
188
}
189
}
190
191
// parse ports and validate
192
if request.Port != "" {
193
for _, port := range strings.Split(request.Port, ",") {
194
if port == "" {
195
continue
196
}
197
portInt, err := strconv.Atoi(port)
198
if err != nil {
199
return errkit.Wrapf(err, "could not parse port %v from '%s'", port, request.Port)
200
}
201
if portInt < 1 || portInt > 65535 {
202
return errkit.Newf("port %v is not in valid range", portInt)
203
}
204
request.ports = append(request.ports, port)
205
}
206
}
207
208
// Resolve payload paths from vars if they exists
209
for name, payload := range request.options.Options.Vars.AsMap() {
210
payloadStr, ok := payload.(string)
211
// check if inputs contains the payload
212
var hasPayloadName bool
213
for _, input := range request.Inputs {
214
if input.Type.String() != "" {
215
continue
216
}
217
if expressions.ContainsVariablesWithNames(map[string]interface{}{name: payload}, input.Data) == nil {
218
hasPayloadName = true
219
break
220
}
221
}
222
if ok && hasPayloadName && fileutil.FileExists(payloadStr) {
223
if request.Payloads == nil {
224
request.Payloads = make(map[string]interface{})
225
}
226
request.Payloads[name] = payloadStr
227
}
228
}
229
230
if len(request.Payloads) > 0 {
231
request.generator, err = generators.New(request.Payloads, request.AttackType.Value, request.options.TemplatePath, request.options.Catalog, request.options.Options.AttackType, request.options.Options)
232
if err != nil {
233
return errors.Wrap(err, "could not parse payloads")
234
}
235
// if we have payloads, adjust threads if none specified
236
request.Threads = options.GetThreadsForNPayloadRequests(request.Requests(), request.Threads)
237
}
238
239
// Create a client for the class
240
client, err := networkclientpool.Get(options.Options, &networkclientpool.Configuration{
241
CustomDialer: options.CustomFastdialer,
242
})
243
if err != nil {
244
return errors.Wrap(err, "could not get network client")
245
}
246
request.dialer = client
247
248
if len(request.Matchers) > 0 || len(request.Extractors) > 0 {
249
compiled := &request.Operators
250
compiled.ExcludeMatchers = options.ExcludeMatchers
251
compiled.TemplateID = options.TemplateID
252
if err := compiled.Compile(); err != nil {
253
return errors.Wrap(err, "could not compile operators")
254
}
255
request.CompiledOperators = compiled
256
}
257
return nil
258
}
259
260
// Requests returns the total number of requests the YAML rule will perform
261
func (request *Request) Requests() int {
262
return len(request.Address)
263
}
264
265
func (request *Request) SetDialer(dialer *fastdialer.Dialer) {
266
request.dialer = dialer
267
}
268
269
// UpdateOptions replaces this request's options with a new copy
270
func (r *Request) UpdateOptions(opts *protocols.ExecutorOptions) {
271
r.options.ApplyNewEngineOptions(opts)
272
}
273
274