Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/protocols/ssl/ssl.go
2070 views
1
package ssl
2
3
import (
4
"fmt"
5
"maps"
6
"net"
7
"strings"
8
"time"
9
10
"github.com/cespare/xxhash"
11
"github.com/fatih/structs"
12
jsoniter "github.com/json-iterator/go"
13
"github.com/pkg/errors"
14
15
"github.com/projectdiscovery/fastdialer/fastdialer"
16
"github.com/projectdiscovery/gologger"
17
"github.com/projectdiscovery/nuclei/v3/pkg/model"
18
"github.com/projectdiscovery/nuclei/v3/pkg/operators"
19
"github.com/projectdiscovery/nuclei/v3/pkg/operators/extractors"
20
"github.com/projectdiscovery/nuclei/v3/pkg/operators/matchers"
21
"github.com/projectdiscovery/nuclei/v3/pkg/output"
22
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
23
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/contextargs"
24
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/expressions"
25
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/generators"
26
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/helpers/eventcreator"
27
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/helpers/responsehighlighter"
28
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/utils/vardump"
29
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/network/networkclientpool"
30
protocolutils "github.com/projectdiscovery/nuclei/v3/pkg/protocols/utils"
31
templateTypes "github.com/projectdiscovery/nuclei/v3/pkg/templates/types"
32
"github.com/projectdiscovery/nuclei/v3/pkg/types"
33
"github.com/projectdiscovery/tlsx/pkg/tlsx"
34
"github.com/projectdiscovery/tlsx/pkg/tlsx/clients"
35
"github.com/projectdiscovery/tlsx/pkg/tlsx/openssl"
36
"github.com/projectdiscovery/utils/errkit"
37
stringsutil "github.com/projectdiscovery/utils/strings"
38
)
39
40
// Request is a request for the SSL protocol
41
type Request struct {
42
// Operators for the current request go here.
43
operators.Operators `yaml:",inline,omitempty" json:",inline,omitempty"`
44
CompiledOperators *operators.Operators `yaml:"-" json:"-"`
45
46
// ID is the optional id of the request
47
ID string `yaml:"id,omitempty" json:"id,omitempty" jsonschema:"title=id of the request,description=ID of the request"`
48
49
// description: |
50
// Address contains address for the request
51
Address string `yaml:"address,omitempty" json:"address,omitempty" jsonschema:"title=address for the ssl request,description=Address contains address for the request"`
52
// description: |
53
// Minimum tls version - auto if not specified.
54
// values:
55
// - "sslv3"
56
// - "tls10"
57
// - "tls11"
58
// - "tls12"
59
// - "tls13"
60
MinVersion string `yaml:"min_version,omitempty" json:"min_version,omitempty" jsonschema:"title=Min. TLS version,description=Minimum tls version - automatic if not specified.,enum=sslv3,enum=tls10,enum=tls11,enum=tls12,enum=tls13"`
61
// description: |
62
// Max tls version - auto if not specified.
63
// values:
64
// - "sslv3"
65
// - "tls10"
66
// - "tls11"
67
// - "tls12"
68
// - "tls13"
69
MaxVersion string `yaml:"max_version,omitempty" json:"max_version,omitempty" jsonschema:"title=Max. TLS version,description=Max tls version - automatic if not specified.,enum=sslv3,enum=tls10,enum=tls11,enum=tls12,enum=tls13"`
70
// description: |
71
// Client Cipher Suites - auto if not specified.
72
CipherSuites []string `yaml:"cipher_suites,omitempty" json:"cipher_suites,omitempty"`
73
// description: |
74
// Tls Scan Mode - auto if not specified
75
// values:
76
// - "ctls"
77
// - "ztls"
78
// - "auto"
79
// - "openssl" # reverts to "auto" is openssl is not installed
80
ScanMode string `yaml:"scan_mode,omitempty" json:"scan_mode,omitempty" jsonschema:"title=Scan Mode,description=Scan Mode - auto if not specified.,enum=ctls,enum=ztls,enum=auto"`
81
// description: |
82
// TLS Versions Enum - false if not specified
83
// Enumerates supported TLS versions
84
TLSVersionsEnum bool `yaml:"tls_version_enum,omitempty" json:"tls_version_enum,omitempty" jsonschema:"title=Enumerate Versions,description=Enumerate Version - false if not specified"`
85
// description: |
86
// TLS Ciphers Enum - false if not specified
87
// Enumerates supported TLS ciphers
88
TLSCiphersEnum bool `yaml:"tls_cipher_enum,omitempty" json:"tls_cipher_enum,omitempty" jsonschema:"title=Enumerate Ciphers,description=Enumerate Ciphers - false if not specified"`
89
// description: |
90
// TLS Cipher types to enumerate
91
// values:
92
// - "insecure" (default)
93
// - "weak"
94
// - "secure"
95
// - "all"
96
TLSCipherTypes []string `yaml:"tls_cipher_types,omitempty" json:"tls_cipher_types,omitempty" jsonschema:"title=TLS Cipher Types,description=TLS Cipher Types to enumerate,enum=weak,enum=secure,enum=insecure,enum=all"`
97
98
// cache any variables that may be needed for operation.
99
dialer *fastdialer.Dialer
100
tlsx *tlsx.Service
101
options *protocols.ExecutorOptions
102
}
103
104
// TmplClusterKey generates a unique key for the request
105
// to be used in the clustering process.
106
func (request *Request) TmplClusterKey() uint64 {
107
inp := fmt.Sprintf("%s-%s-%t-%t-%s", request.Address, request.ScanMode, request.TLSCiphersEnum, request.TLSVersionsEnum, strings.Join(request.TLSCipherTypes, ","))
108
return xxhash.Sum64String(inp)
109
}
110
111
func (request *Request) IsClusterable() bool {
112
// nolint
113
return !(len(request.CipherSuites) > 0 || request.MinVersion != "" || request.MaxVersion != "")
114
}
115
116
// Compile compiles the request generators preparing any requests possible.
117
func (request *Request) Compile(options *protocols.ExecutorOptions) error {
118
request.options = options
119
120
client, err := networkclientpool.Get(options.Options, &networkclientpool.Configuration{
121
CustomDialer: options.CustomFastdialer,
122
})
123
if err != nil {
124
return errkit.Wrap(err, "could not get network client")
125
}
126
request.dialer = client
127
switch {
128
//validate scanmode
129
case request.ScanMode == "":
130
request.ScanMode = "auto"
131
132
case !stringsutil.EqualFoldAny(request.ScanMode, "auto", "openssl", "ztls", "ctls"):
133
return errkit.Newf("template %v does not contain valid scan-mode", request.TemplateID)
134
135
case request.ScanMode == "openssl" && !openssl.IsAvailable():
136
// if openssl is not installed instead of failing "auto" scanmode is used
137
request.ScanMode = "auto"
138
}
139
if request.TLSCiphersEnum {
140
// cipher enumeration requires tls version enumeration first
141
request.TLSVersionsEnum = true
142
}
143
if request.TLSCiphersEnum && len(request.TLSCipherTypes) == 0 {
144
// by default only look for insecure ciphers
145
request.TLSCipherTypes = []string{"insecure"}
146
}
147
148
tlsxOptions := &clients.Options{
149
AllCiphers: true,
150
ScanMode: request.ScanMode,
151
Expired: true,
152
SelfSigned: true,
153
Revoked: true,
154
MisMatched: true,
155
MinVersion: request.MinVersion,
156
MaxVersion: request.MaxVersion,
157
Ciphers: request.CipherSuites,
158
WildcardCertCheck: true,
159
Retries: request.options.Options.Retries,
160
Timeout: request.options.Options.Timeout,
161
Fastdialer: client,
162
ClientHello: true,
163
ServerHello: true,
164
DisplayDns: true,
165
TlsVersionsEnum: request.TLSVersionsEnum,
166
TlsCiphersEnum: request.TLSCiphersEnum,
167
TLsCipherLevel: request.TLSCipherTypes,
168
}
169
170
tlsxService, err := tlsx.New(tlsxOptions)
171
if err != nil {
172
return errkit.New("could not create tlsx service")
173
}
174
request.tlsx = tlsxService
175
176
if len(request.Matchers) > 0 || len(request.Extractors) > 0 {
177
compiled := &request.Operators
178
compiled.ExcludeMatchers = options.ExcludeMatchers
179
compiled.TemplateID = options.TemplateID
180
if err := compiled.Compile(); err != nil {
181
return errkit.Newf("could not compile operators got %v", err)
182
}
183
request.CompiledOperators = compiled
184
}
185
return nil
186
}
187
188
// Options returns executer options for http request
189
func (r *Request) Options() *protocols.ExecutorOptions {
190
return r.options
191
}
192
193
// Requests returns the total number of requests the rule will perform
194
func (request *Request) Requests() int {
195
return 1
196
}
197
198
// GetID returns the ID for the request if any.
199
func (request *Request) GetID() string {
200
return ""
201
}
202
203
// ExecuteWithResults executes the protocol requests and returns results instead of writing them.
204
func (request *Request) ExecuteWithResults(input *contextargs.Context, dynamicValues, previous output.InternalEvent, callback protocols.OutputEventCallback) error {
205
hostPort := input.MetaInput.Input
206
hostname, port, _ := net.SplitHostPort(hostPort)
207
208
requestOptions := request.options
209
payloadValues := generators.BuildPayloadFromOptions(request.options.Options)
210
maps.Copy(payloadValues, dynamicValues)
211
212
payloadValues["Hostname"] = hostPort
213
payloadValues["Host"] = hostname
214
payloadValues["Port"] = port
215
216
hostnameVariables := protocolutils.GenerateDNSVariables(hostname)
217
// add template context variables to varMap
218
values := generators.MergeMaps(payloadValues, hostnameVariables)
219
if request.options.HasTemplateCtx(input.MetaInput) {
220
values = generators.MergeMaps(values, request.options.GetTemplateCtx(input.MetaInput).GetAll())
221
}
222
223
variablesMap := request.options.Variables.Evaluate(values)
224
payloadValues = generators.MergeMaps(variablesMap, payloadValues, request.options.Constants)
225
226
if vardump.EnableVarDump {
227
gologger.Debug().Msgf("SSL Protocol request variables: %s\n", vardump.DumpVariables(payloadValues))
228
}
229
230
finalAddress, dataErr := expressions.EvaluateByte([]byte(request.Address), payloadValues)
231
if dataErr != nil {
232
requestOptions.Output.Request(requestOptions.TemplateID, input.MetaInput.Input, request.Type().String(), dataErr)
233
requestOptions.Progress.IncrementFailedRequestsBy(1)
234
return errors.Wrap(dataErr, "could not evaluate template expressions")
235
}
236
addressToDial := string(finalAddress)
237
host, port, err := net.SplitHostPort(addressToDial)
238
if err != nil {
239
return errkit.Wrap(err, "could not split input host port")
240
}
241
242
var hostIp string
243
if input.MetaInput.CustomIP != "" {
244
hostIp = input.MetaInput.CustomIP
245
} else {
246
hostIp = host
247
}
248
249
response, err := request.tlsx.Connect(host, hostIp, port)
250
if err != nil {
251
requestOptions.Output.Request(requestOptions.TemplateID, input.MetaInput.Input, request.Type().String(), err)
252
requestOptions.Progress.IncrementFailedRequestsBy(1)
253
return errkit.Wrap(err, "could not connect to server")
254
}
255
256
requestOptions.Output.Request(requestOptions.TemplateID, hostPort, request.Type().String(), err)
257
gologger.Verbose().Msgf("[%s] Sent SSL request to %s", request.options.TemplateID, hostPort)
258
259
if requestOptions.Options.Debug || requestOptions.Options.DebugRequests || requestOptions.Options.StoreResponse {
260
msg := fmt.Sprintf("[%s] Dumped SSL request for %s", requestOptions.TemplateID, input.MetaInput.Input)
261
if requestOptions.Options.Debug || requestOptions.Options.DebugRequests {
262
gologger.Debug().Str("address", input.MetaInput.Input).Msg(msg)
263
}
264
if requestOptions.Options.StoreResponse {
265
request.options.Output.WriteStoreDebugData(input.MetaInput.Input, request.options.TemplateID, request.Type().String(), msg)
266
}
267
}
268
269
jsonData, _ := jsoniter.Marshal(response)
270
jsonDataString := string(jsonData)
271
272
data := make(map[string]interface{})
273
maps.Copy(data, payloadValues)
274
data["type"] = request.Type().String()
275
data["response"] = jsonDataString
276
data["host"] = input.MetaInput.Input
277
data["matched"] = addressToDial
278
if input.MetaInput.CustomIP != "" {
279
data["ip"] = hostIp
280
} else {
281
data["ip"] = request.dialer.GetDialedIP(hostname)
282
}
283
data["Port"] = port
284
data["template-path"] = requestOptions.TemplatePath
285
data["template-id"] = requestOptions.TemplateID
286
data["template-info"] = requestOptions.TemplateInfo
287
288
// if response is not struct compatible, error out
289
if !structs.IsStruct(response) {
290
return errkit.Newf("response cannot be parsed into a struct: %v", response)
291
}
292
293
// Convert response to key value pairs and first cert chain item as well
294
responseParsed := structs.New(response)
295
for _, f := range responseParsed.Fields() {
296
if !f.IsExported() {
297
// if field is not exported f.IsZero() , f.Value() will panic
298
continue
299
}
300
tag := protocolutils.CleanStructFieldJSONTag(f.Tag("json"))
301
if tag == "" || f.IsZero() {
302
continue
303
}
304
request.options.AddTemplateVar(input.MetaInput, request.Type(), request.ID, tag, f.Value())
305
data[tag] = f.Value()
306
}
307
308
// if certificate response is not struct compatible, error out
309
if !structs.IsStruct(response.CertificateResponse) {
310
return errkit.Newf("certificate response cannot be parsed into a struct: %v", response.CertificateResponse)
311
}
312
313
responseParsed = structs.New(response.CertificateResponse)
314
for _, f := range responseParsed.Fields() {
315
if !f.IsExported() {
316
// if field is not exported f.IsZero() , f.Value() will panic
317
continue
318
}
319
tag := protocolutils.CleanStructFieldJSONTag(f.Tag("json"))
320
if tag == "" || f.IsZero() {
321
continue
322
}
323
request.options.AddTemplateVar(input.MetaInput, request.Type(), request.ID, tag, f.Value())
324
data[tag] = f.Value()
325
}
326
327
// add response fields ^ to template context and merge templatectx variables to output event
328
if request.options.HasTemplateCtx(input.MetaInput) {
329
data = generators.MergeMaps(data, request.options.GetTemplateCtx(input.MetaInput).GetAll())
330
}
331
event := eventcreator.CreateEvent(request, data, requestOptions.Options.Debug || requestOptions.Options.DebugResponse)
332
if requestOptions.Options.Debug || requestOptions.Options.DebugResponse || requestOptions.Options.StoreResponse {
333
msg := fmt.Sprintf("[%s] Dumped SSL response for %s", requestOptions.TemplateID, input.MetaInput.Input)
334
if requestOptions.Options.Debug || requestOptions.Options.DebugResponse {
335
gologger.Debug().Msg(msg)
336
gologger.Print().Msgf("%s", responsehighlighter.Highlight(event.OperatorsResult, jsonDataString, requestOptions.Options.NoColor, false))
337
}
338
if requestOptions.Options.StoreResponse {
339
request.options.Output.WriteStoreDebugData(input.MetaInput.Input, request.options.TemplateID, request.Type().String(), fmt.Sprintf("%s\n%s", msg, jsonDataString))
340
}
341
}
342
callback(event)
343
return nil
344
}
345
346
// RequestPartDefinitions contains a mapping of request part definitions and their
347
// description. Multiple definitions are separated by commas.
348
// Definitions not having a name (generated on runtime) are prefixed & suffixed by <>.
349
var RequestPartDefinitions = map[string]string{
350
"template-id": "ID of the template executed",
351
"template-info": "Info Block of the template executed",
352
"template-path": "Path of the template executed",
353
"host": "Host is the input to the template",
354
"port": "Port is the port of the host",
355
"matched": "Matched is the input which was matched upon",
356
"type": "Type is the type of request made",
357
"timestamp": "Timestamp is the time when the request was made",
358
"response": "JSON SSL protocol handshake details",
359
"cipher": "Cipher is the encryption algorithm used",
360
"domains": "Domains are the list of domain names in the certificate",
361
"fingerprint_hash": "Fingerprint hash is the unique identifier of the certificate",
362
"ip": "IP is the IP address of the server",
363
"issuer_cn": "Issuer CN is the common name of the certificate issuer",
364
"issuer_dn": "Issuer DN is the distinguished name of the certificate issuer",
365
"issuer_org": "Issuer organization is the organization of the certificate issuer",
366
"not_after": "Timestamp after which the remote cert expires",
367
"not_before": "Timestamp before which the certificate is not valid",
368
"probe_status": "Probe status indicates if the probe was successful",
369
"serial": "Serial is the serial number of the certificate",
370
"sni": "SNI is the server name indication used in the handshake",
371
"subject_an": "Subject AN is the list of subject alternative names",
372
"subject_cn": "Subject CN is the common name of the certificate subject",
373
"subject_dn": "Subject DN is the distinguished name of the certificate subject",
374
"subject_org": "Subject organization is the organization of the certificate subject",
375
"tls_connection": "TLS connection is the type of TLS connection used",
376
"tls_version": "TLS version is the version of the TLS protocol used",
377
}
378
379
// Match performs matching operation for a matcher on model and returns:
380
// true and a list of matched snippets if the matcher type is supports it
381
// otherwise false and an empty string slice
382
func (request *Request) Match(data map[string]interface{}, matcher *matchers.Matcher) (bool, []string) {
383
return protocols.MakeDefaultMatchFunc(data, matcher)
384
}
385
386
// Extract performs extracting operation for an extractor on model and returns true or false.
387
func (request *Request) Extract(data map[string]interface{}, matcher *extractors.Extractor) map[string]struct{} {
388
return protocols.MakeDefaultExtractFunc(data, matcher)
389
}
390
391
// MakeResultEvent creates a result event from internal wrapped event
392
func (request *Request) MakeResultEvent(wrapped *output.InternalWrappedEvent) []*output.ResultEvent {
393
return protocols.MakeDefaultResultEvent(request, wrapped)
394
}
395
396
// GetCompiledOperators returns a list of the compiled operators
397
func (request *Request) GetCompiledOperators() []*operators.Operators {
398
return []*operators.Operators{request.CompiledOperators}
399
}
400
401
// Type returns the type of the protocol request
402
func (request *Request) Type() templateTypes.ProtocolType {
403
return templateTypes.SSLProtocol
404
}
405
406
func (request *Request) MakeResultEventItem(wrapped *output.InternalWrappedEvent) *output.ResultEvent {
407
fields := protocolutils.GetJsonFieldsFromURL(types.ToString(wrapped.InternalEvent["host"]))
408
if types.ToString(wrapped.InternalEvent["ip"]) != "" {
409
fields.Ip = types.ToString(wrapped.InternalEvent["ip"])
410
}
411
// in case scheme is not specified , we only connect to port 443 unless custom https port was specified
412
// like 8443 etc
413
if fields.Port == "80" {
414
fields.Port = "443"
415
}
416
if types.ToString(wrapped.InternalEvent["Port"]) != "" {
417
fields.Port = types.ToString(wrapped.InternalEvent["Port"])
418
}
419
data := &output.ResultEvent{
420
TemplateID: types.ToString(wrapped.InternalEvent["template-id"]),
421
TemplatePath: types.ToString(wrapped.InternalEvent["template-path"]),
422
Info: wrapped.InternalEvent["template-info"].(model.Info),
423
TemplateVerifier: request.options.TemplateVerifier,
424
Type: types.ToString(wrapped.InternalEvent["type"]),
425
Host: fields.Host,
426
Port: fields.Port,
427
Matched: types.ToString(wrapped.InternalEvent["matched"]),
428
Metadata: wrapped.OperatorsResult.PayloadValues,
429
ExtractedResults: wrapped.OperatorsResult.OutputExtracts,
430
Timestamp: time.Now(),
431
MatcherStatus: true,
432
IP: fields.Ip,
433
TemplateEncoded: request.options.EncodeTemplate(),
434
Error: types.ToString(wrapped.InternalEvent["error"]),
435
}
436
return data
437
}
438
439
// UpdateOptions replaces this request's options with a new copy
440
func (r *Request) UpdateOptions(opts *protocols.ExecutorOptions) {
441
r.options.ApplyNewEngineOptions(opts)
442
}
443
444