forked from projectdiscovery/nuclei
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompile.go
More file actions
686 lines (596 loc) · 21 KB
/
compile.go
File metadata and controls
686 lines (596 loc) · 21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
package templates
import (
"fmt"
"io"
"reflect"
"sync"
"sync/atomic"
"github.com/logrusorgru/aurora"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
"github.com/projectdiscovery/gologger"
"github.com/projectdiscovery/nuclei/v3/pkg/catalog/config"
"github.com/projectdiscovery/nuclei/v3/pkg/js/compiler"
"github.com/projectdiscovery/nuclei/v3/pkg/model/types/severity"
"github.com/projectdiscovery/nuclei/v3/pkg/operators"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/generators"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/globalmatchers"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/offlinehttp"
"github.com/projectdiscovery/nuclei/v3/pkg/templates/signer"
"github.com/projectdiscovery/nuclei/v3/pkg/tmplexec"
"github.com/projectdiscovery/nuclei/v3/pkg/utils"
"github.com/projectdiscovery/nuclei/v3/pkg/utils/json"
"github.com/projectdiscovery/utils/errkit"
stringsutil "github.com/projectdiscovery/utils/strings"
)
var (
ErrCreateTemplateExecutor = errors.New("cannot create template executer")
ErrIncompatibleWithOfflineMatching = errors.New("template can't be used for offline matching")
// track how many templates are verified and by which signer
SignatureStats = map[string]*atomic.Uint64{}
)
const (
Unsigned = "unsigned"
)
func init() {
for _, verifier := range signer.DefaultTemplateVerifiers {
SignatureStats[verifier.Identifier()] = &atomic.Uint64{}
}
SignatureStats[Unsigned] = &atomic.Uint64{}
}
// updateRequestOptions updates options for all request types in a template
func updateRequestOptions(template *Template) {
for i, r := range template.RequestsDNS {
rCopy := *r
rCopy.UpdateOptions(template.Options)
template.RequestsDNS[i] = &rCopy
}
for i, r := range template.RequestsHTTP {
rCopy := *r
rCopy.UpdateOptions(template.Options)
template.RequestsHTTP[i] = &rCopy
}
for i, r := range template.RequestsCode {
rCopy := *r
rCopy.UpdateOptions(template.Options)
template.RequestsCode[i] = &rCopy
}
for i, r := range template.RequestsFile {
rCopy := *r
rCopy.UpdateOptions(template.Options)
template.RequestsFile[i] = &rCopy
}
for i, r := range template.RequestsHeadless {
rCopy := *r
rCopy.UpdateOptions(template.Options)
template.RequestsHeadless[i] = &rCopy
}
for i, r := range template.RequestsNetwork {
rCopy := *r
rCopy.UpdateOptions(template.Options)
template.RequestsNetwork[i] = &rCopy
}
for i, r := range template.RequestsJavascript {
rCopy := *r
rCopy.UpdateOptions(template.Options)
template.RequestsJavascript[i] = &rCopy
}
for i, r := range template.RequestsSSL {
rCopy := *r
rCopy.UpdateOptions(template.Options)
template.RequestsSSL[i] = &rCopy
}
for i, r := range template.RequestsWHOIS {
rCopy := *r
rCopy.UpdateOptions(template.Options)
template.RequestsWHOIS[i] = &rCopy
}
for i, r := range template.RequestsWebsocket {
rCopy := *r
rCopy.UpdateOptions(template.Options)
template.RequestsWebsocket[i] = &rCopy
}
}
// parseFromSource parses a template from source with caching support
func parseFromSource(filePath string, preprocessor Preprocessor, options *protocols.ExecutorOptions, parser *Parser) (*Template, error) {
reader, err := utils.ReaderFromPathOrURL(filePath, options.Catalog)
if err != nil {
return nil, err
}
defer func() {
_ = reader.Close()
}()
options = options.Copy()
options.TemplatePath = filePath
template, err := ParseTemplateFromReader(reader, preprocessor, options)
if err != nil {
return nil, err
}
if template.isGlobalMatchersEnabled() {
item := &globalmatchers.Item{
TemplateID: template.ID,
TemplatePath: filePath,
TemplateInfo: template.Info,
}
for _, request := range template.RequestsHTTP {
item.Operators = append(item.Operators, request.CompiledOperators)
}
options.GlobalMatchers.AddOperator(item)
return nil, nil
}
// Compile the workflow request
if len(template.Workflows) > 0 {
compiled := &template.Workflow
compileWorkflow(filePath, preprocessor, options, compiled, options.WorkflowLoader)
template.CompiledWorkflow = compiled
template.CompiledWorkflow.Options = options
}
template.Path = filePath
if !options.DoNotCache {
parser.compiledTemplatesCache.StoreWithoutRaw(filePath, template, err)
}
return template, nil
}
// getParser returns a cached parser instance
func getParser(options *protocols.ExecutorOptions) *Parser {
parser, ok := options.Parser.(*Parser)
if !ok || parser == nil {
panic("invalid parser")
}
return parser
}
// Parse parses a yaml request template file
// TODO make sure reading from the disk the template parsing happens once: see parsers.ParseTemplate vs templates.Parse
func Parse(filePath string, preprocessor Preprocessor, options *protocols.ExecutorOptions) (*Template, error) {
parser := getParser(options)
if !options.DoNotCache {
if value, _, _ := parser.compiledTemplatesCache.Has(filePath); value != nil {
// Copy the template, apply new options, and recompile requests
tplCopy := *value
newBase := options.Copy()
newBase.TemplateID = tplCopy.Options.TemplateID
newBase.TemplatePath = tplCopy.Options.TemplatePath
newBase.TemplateInfo = tplCopy.Options.TemplateInfo
newBase.TemplateVerifier = tplCopy.Options.TemplateVerifier
newBase.RawTemplate = tplCopy.Options.RawTemplate
if tplCopy.Options.Variables.Len() > 0 {
newBase.Variables = tplCopy.Options.Variables
}
if len(tplCopy.Options.Constants) > 0 {
newBase.Constants = tplCopy.Options.Constants
}
tplCopy.Options = newBase
tplCopy.Options.ApplyNewEngineOptions(options)
if tplCopy.CompiledWorkflow != nil {
tplCopy.CompiledWorkflow.Options.ApplyNewEngineOptions(options)
for _, w := range tplCopy.CompiledWorkflow.Workflows {
for _, ex := range w.Executers {
ex.Options.ApplyNewEngineOptions(options)
}
}
}
// Update options for all request types
updateRequestOptions(&tplCopy)
template := &tplCopy
if template.isGlobalMatchersEnabled() {
item := &globalmatchers.Item{
TemplateID: template.ID,
TemplatePath: filePath,
TemplateInfo: template.Info,
}
for _, request := range template.RequestsHTTP {
item.Operators = append(item.Operators, request.CompiledOperators)
}
options.GlobalMatchers.AddOperator(item)
return nil, nil
}
// Compile the workflow request
if len(template.Workflows) > 0 {
compiled := &template.Workflow
compileWorkflow(filePath, preprocessor, tplCopy.Options, compiled, tplCopy.Options.WorkflowLoader)
template.CompiledWorkflow = compiled
template.CompiledWorkflow.Options = tplCopy.Options
}
if isCachedTemplateValid(template) {
// options.Logger.Error().Msgf("returning cached template %s after recompiling %d requests", tplCopy.Options.TemplateID, tplCopy.Requests())
return template, nil
}
// else: fallthrough to re-parse template from scratch
}
}
return parseFromSource(filePath, preprocessor, options, parser)
}
// isGlobalMatchersEnabled checks if any of requests in the template
// have global matchers enabled. It iterates through all requests and
// returns true if at least one request has global matchers enabled;
// otherwise, it returns false. If global matchers templates are not
// enabled in the options, the method will immediately return false.
//
// Note: This method only checks the `RequestsHTTP`
// field of the template, which is specific to http-protocol-based
// templates.
//
// TODO: support all protocols.
func (template *Template) isGlobalMatchersEnabled() bool {
if !template.Options.Options.EnableGlobalMatchersTemplates {
return false
}
for _, request := range template.RequestsHTTP {
if request.GlobalMatchers {
return true
}
}
return false
}
// parseSelfContainedRequests parses the self contained template requests.
func (template *Template) parseSelfContainedRequests() {
if template.Signature.Value.String() != "" {
for _, request := range template.RequestsHTTP {
request.Signature = template.Signature
}
}
if !template.SelfContained {
return
}
for _, request := range template.RequestsHTTP {
request.SelfContained = true
}
for _, request := range template.RequestsNetwork {
request.SelfContained = true
}
for _, request := range template.RequestsHeadless {
request.SelfContained = true
}
}
// Requests returns the total request count for the template
func (template *Template) Requests() int {
return len(template.RequestsDNS) +
len(template.RequestsHTTP) +
len(template.RequestsFile) +
len(template.RequestsNetwork) +
len(template.RequestsHeadless) +
len(template.Workflows) +
len(template.RequestsSSL) +
len(template.RequestsWebsocket) +
len(template.RequestsWHOIS) +
len(template.RequestsCode) +
len(template.RequestsJavascript)
}
// compileProtocolRequests compiles all the protocol requests for the template
func (template *Template) compileProtocolRequests(options *protocols.ExecutorOptions) error {
templateRequests := template.Requests()
if templateRequests == 0 {
return fmt.Errorf("no requests defined for %s", template.ID)
}
if options.Options.OfflineHTTP {
return template.compileOfflineHTTPRequest(options)
}
var requests []protocols.Request
if template.hasMultipleRequests() {
// when multiple requests are present preserve the order of requests and protocols
// which is already done during unmarshalling
requests = template.RequestsQueue
if options.Flow == "" {
options.IsMultiProtocol = true
}
} else {
if template.HasDNSRequest() {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsDNS)...)
}
if template.HasFileRequest() {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsFile)...)
}
if template.HasNetworkRequest() {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsNetwork)...)
}
if template.HasHTTPRequest() {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsHTTP)...)
}
if template.HasHeadlessRequest() && options.Options.Headless {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsHeadless)...)
}
if template.HasSSLRequest() {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsSSL)...)
}
if template.HasWebsocketRequest() {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsWebsocket)...)
}
if template.HasWHOISRequest() {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsWHOIS)...)
}
if template.HasCodeRequest() && options.Options.EnableCodeTemplates {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsCode)...)
}
if template.HasJavascriptRequest() {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsJavascript)...)
}
}
var err error
template.Executer, err = tmplexec.NewTemplateExecuter(requests, options)
return err
}
// convertRequestToProtocolsRequest is a convenience wrapper to convert
// arbitrary interfaces which are slices of requests from the template to a
// slice of protocols.Request interface items.
func (template *Template) convertRequestToProtocolsRequest(requests interface{}) []protocols.Request {
switch reflect.TypeOf(requests).Kind() {
case reflect.Slice:
s := reflect.ValueOf(requests)
requestSlice := make([]protocols.Request, s.Len())
for i := 0; i < s.Len(); i++ {
value := s.Index(i)
valueInterface := value.Interface()
requestSlice[i] = valueInterface.(protocols.Request)
}
return requestSlice
}
return nil
}
// compileOfflineHTTPRequest iterates all requests if offline http mode is
// specified and collects all matchers for all the base request templates
// (those with URL {{BaseURL}} and it's slash variation.)
func (template *Template) compileOfflineHTTPRequest(options *protocols.ExecutorOptions) error {
operatorsList := []*operators.Operators{}
mainLoop:
for _, req := range template.RequestsHTTP {
hasPaths := len(req.Path) > 0
if !hasPaths {
break mainLoop
}
for _, path := range req.Path {
pathIsBaseURL := stringsutil.EqualFoldAny(path, "{{BaseURL}}", "{{BaseURL}}/", "/")
if !pathIsBaseURL {
break mainLoop
}
}
operatorsList = append(operatorsList, &req.Operators)
}
if len(operatorsList) > 0 {
options.Operators = operatorsList
var err error
template.Executer, err = tmplexec.NewTemplateExecuter([]protocols.Request{&offlinehttp.Request{}}, options)
if err != nil {
// it seems like flow executor cannot be used for offline http matching (ex:http(1) && http(2))
return ErrIncompatibleWithOfflineMatching
}
return err
}
return ErrIncompatibleWithOfflineMatching
}
// ParseTemplateFromReader parses a template from an [io.Reader] with optional
// preprocessing.
func ParseTemplateFromReader(reader io.Reader, preprocessor Preprocessor, options *protocols.ExecutorOptions) (*Template, error) {
data, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
// a preprocessor is a variable like
// {{randstr}} which is replaced before unmarshalling
// as it is known to be a random static value per template
hasPreprocessor := false
allPreprocessors := getPreprocessors(preprocessor)
for _, preprocessor := range allPreprocessors {
if preprocessor.Exists(data) {
hasPreprocessor = true
break
}
}
if !hasPreprocessor {
// if no preprocessors exists parse template and exit
template, err := parseTemplate(data, options)
if err != nil {
return nil, err
}
if !template.Verified && len(template.Workflows) == 0 {
if config.DefaultConfig.LogAllEvents {
gologger.DefaultLogger.Print().Msgf("[%v] Template %s is not signed or tampered\n", aurora.Yellow("WRN").String(), template.ID)
}
}
return template, nil
}
// if preprocessor is required / exists in this template
// expand all preprocessors, parse once, then verify against original data
generatedConstants := map[string]interface{}{}
// ==== execute preprocessors ======
processedData := data
for _, v := range allPreprocessors {
var replaced map[string]interface{}
processedData, replaced = v.ProcessNReturnData(processedData)
// preprocess kind of act like a constant and are generated while loading
// and stay constant for the template lifecycle
generatedConstants = generators.MergeMaps(generatedConstants, replaced)
}
template, err := parseTemplateNoVerify(processedData, options)
if err != nil {
return nil, err
}
// add generated constants to constants map and executer options
template.Constants = generators.MergeMaps(template.Constants, generatedConstants)
template.Options.Constants = template.Constants
applyTemplateVerification(template, data)
if !template.Verified && len(template.Workflows) == 0 {
// workflows are not signed by default
if config.DefaultConfig.LogAllEvents {
gologger.DefaultLogger.Print().Msgf("[%v] Template %s is not signed or tampered\n", aurora.Yellow("WRN").String(), template.ID)
}
}
return template, nil
}
// parseTemplate parses the template and applies verification.
func parseTemplate(data []byte, srcOptions *protocols.ExecutorOptions) (*Template, error) {
template, err := parseTemplateNoVerify(data, srcOptions)
if err != nil {
return nil, err
}
applyTemplateVerification(template, data)
return template, nil
}
// parseTemplateNoVerify parses the template without applying any verification.
func parseTemplateNoVerify(data []byte, srcOptions *protocols.ExecutorOptions) (*Template, error) {
// Create a copy of the options specifically for this template
options := srcOptions.Copy()
template := &Template{}
var err error
switch config.GetTemplateFormatFromExt(template.Path) {
case config.JSON:
err = json.Unmarshal(data, template)
case config.YAML:
err = yaml.Unmarshal(data, template)
default:
// assume its yaml
if err = yaml.Unmarshal(data, template); err != nil {
return nil, err
}
}
if err != nil {
return nil, errkit.Wrapf(err, "failed to parse %s", template.Path)
}
if utils.IsBlank(template.Info.Name) {
return nil, errors.New("no template name field provided")
}
if template.Info.Authors.IsEmpty() {
return nil, errors.New("no template author field provided")
}
numberOfWorkflows := len(template.Workflows)
if numberOfWorkflows > 0 && numberOfWorkflows != template.Requests() {
return nil, errors.New("workflows cannot have other protocols")
}
// use default unknown severity
if len(template.Workflows) == 0 {
if template.Info.SeverityHolder.Severity == severity.Undefined {
// set unknown severity with counter and forced warning
template.Info.SeverityHolder.Severity = severity.Unknown
if options.Options.Validate {
// when validating return error
return nil, errors.New("no template severity field provided")
}
}
}
// Setting up variables regarding template metadata
options.TemplateID = template.ID
options.TemplateInfo = template.Info
options.StopAtFirstMatch = template.StopAtFirstMatch
if template.Variables.Len() > 0 {
options.Variables = template.Variables
}
// if more than 1 request per protocol exist we add request id to protocol request
// since in template context we have proto_prefix for each protocol it is overwritten
// if request id is not present
template.validateAllRequestIDs()
// create empty context args for template scope
options.CreateTemplateCtxStore()
options.ProtocolType = template.Type()
options.Constants = template.Constants
// initialize the js compiler if missing
if options.JsCompiler == nil {
options.JsCompiler = GetJsCompiler() // this is a singleton
}
template.Options = options
// If no requests, and it is also not a workflow, return error.
if template.Requests() == 0 {
return nil, fmt.Errorf("no requests defined for %s", template.ID)
}
// load `flow` and `source` in code protocol from file
// if file is referenced instead of actual source code
if err := template.ImportFileRefs(template.Options); err != nil {
return nil, errkit.Wrapf(err, "failed to load file refs for %s", template.ID)
}
if err := template.compileProtocolRequests(template.Options); err != nil {
return nil, err
}
if template.Executer != nil {
if err := template.Executer.Compile(); err != nil {
return nil, errors.Wrap(err, "could not compile request")
}
template.TotalRequests = template.Executer.Requests()
}
if template.Executer == nil && template.CompiledWorkflow == nil {
return nil, ErrCreateTemplateExecutor
}
template.parseSelfContainedRequests()
return template, nil
}
// applyTemplateVerification verifies a parsed template against the provided data.
func applyTemplateVerification(template *Template, data []byte) {
if template == nil || template.Options == nil {
return
}
options := template.Options
// check if the template is verified
// only valid templates can be verified or signed
if options.TemplateVerificationCallback != nil && options.TemplatePath != "" {
if cached := options.TemplateVerificationCallback(options.TemplatePath); cached != nil {
template.Verified = cached.Verified
template.TemplateVerifier = cached.Verifier
options.TemplateVerifier = cached.Verifier
//nolint
if !(template.Verified && template.TemplateVerifier == "projectdiscovery/nuclei-templates") {
template.Options.RawTemplate = data
}
return
}
}
var verifier *signer.TemplateSigner
for _, verifier = range signer.DefaultTemplateVerifiers {
template.Verified, _ = verifier.Verify(data, template)
if config.DefaultConfig.LogAllEvents {
gologger.Verbose().Msgf("template %v verified by %s : %v", template.ID, verifier.Identifier(), template.Verified)
}
if template.Verified {
template.TemplateVerifier = verifier.Identifier()
break
}
}
options.TemplateVerifier = template.TemplateVerifier
//nolint
if !(template.Verified && verifier.Identifier() == "projectdiscovery/nuclei-templates") {
template.Options.RawTemplate = data
}
}
// isCachedTemplateValid validates that a cached template is still usable after
// option updates
func isCachedTemplateValid(template *Template) bool {
// no requests or workflows
if template.Requests() == 0 && len(template.Workflows) == 0 {
return false
}
// options not initialized
if template.Options == nil {
return false
}
// executer not available for non-workflow template
if len(template.Workflows) == 0 && template.Executer == nil {
return false
}
// compiled workflow not available
if len(template.Workflows) > 0 && template.CompiledWorkflow == nil {
return false
}
// template ID mismatch
if template.Options.TemplateID != template.ID {
return false
}
// executer exists but no requests or flow available
if template.Executer != nil {
// NOTE(dwisiswant0): This is a basic sanity check since we can't access
// private fields, but we can check requests tho
if template.Requests() == 0 && template.Options.Flow == "" {
return false
}
}
if template.Options.Options == nil {
return false
}
return true
}
var (
jsCompiler *compiler.Compiler
jsCompilerOnce = sync.OnceFunc(func() {
jsCompiler = compiler.New()
})
)
func GetJsCompiler() *compiler.Compiler {
jsCompilerOnce()
return jsCompiler
}