Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/catalog/loader/loader.go
2843 views
1
package loader
2
3
import (
4
"fmt"
5
"io"
6
"net/url"
7
"os"
8
"sort"
9
"strings"
10
"sync"
11
12
"github.com/logrusorgru/aurora"
13
"github.com/pkg/errors"
14
"github.com/projectdiscovery/gologger"
15
"github.com/projectdiscovery/nuclei/v3/pkg/catalog"
16
"github.com/projectdiscovery/nuclei/v3/pkg/catalog/config"
17
"github.com/projectdiscovery/nuclei/v3/pkg/catalog/index"
18
"github.com/projectdiscovery/nuclei/v3/pkg/keys"
19
"github.com/projectdiscovery/nuclei/v3/pkg/model/types/severity"
20
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
21
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/protocolstate"
22
"github.com/projectdiscovery/nuclei/v3/pkg/templates"
23
templateTypes "github.com/projectdiscovery/nuclei/v3/pkg/templates/types"
24
"github.com/projectdiscovery/nuclei/v3/pkg/types"
25
"github.com/projectdiscovery/nuclei/v3/pkg/utils/stats"
26
"github.com/projectdiscovery/nuclei/v3/pkg/workflows"
27
"github.com/projectdiscovery/retryablehttp-go"
28
"github.com/projectdiscovery/utils/errkit"
29
mapsutil "github.com/projectdiscovery/utils/maps"
30
sliceutil "github.com/projectdiscovery/utils/slice"
31
stringsutil "github.com/projectdiscovery/utils/strings"
32
syncutil "github.com/projectdiscovery/utils/sync"
33
urlutil "github.com/projectdiscovery/utils/url"
34
"github.com/rs/xid"
35
)
36
37
const (
38
httpPrefix = "http://"
39
httpsPrefix = "https://"
40
AuthStoreId = "auth_store"
41
)
42
43
var (
44
TrustedTemplateDomains = []string{"cloud.projectdiscovery.io"}
45
)
46
47
// Config contains the configuration options for the loader
48
type Config struct {
49
StoreId string // used to set store id (optional)
50
Templates []string
51
TemplateURLs []string
52
Workflows []string
53
WorkflowURLs []string
54
ExcludeTemplates []string
55
IncludeTemplates []string
56
RemoteTemplateDomainList []string
57
AITemplatePrompt string
58
59
Tags []string
60
ExcludeTags []string
61
Protocols templateTypes.ProtocolTypes
62
ExcludeProtocols templateTypes.ProtocolTypes
63
Authors []string
64
Severities severity.Severities
65
ExcludeSeverities severity.Severities
66
IncludeTags []string
67
IncludeIds []string
68
ExcludeIds []string
69
IncludeConditions []string
70
71
Catalog catalog.Catalog
72
ExecutorOptions *protocols.ExecutorOptions
73
Logger *gologger.Logger
74
}
75
76
// Store is a storage for loaded nuclei templates
77
type Store struct {
78
id string // id of the store (optional)
79
tagFilter *templates.TagFilter
80
config *Config
81
finalTemplates []string
82
finalWorkflows []string
83
84
templates []*templates.Template
85
workflows []*templates.Template
86
87
preprocessor templates.Preprocessor
88
89
logger *gologger.Logger
90
91
// parserCacheOnce is used to cache the parser cache result
92
parserCacheOnce func() *templates.Cache
93
94
// metadataIndex is the template metadata cache
95
metadataIndex *index.Index
96
97
// indexFilter is the cached filter for metadata matching
98
indexFilter *index.Filter
99
100
// saveTemplatesIndexOnce is used to ensure we only save the metadata index
101
// once
102
saveMetadataIndexOnce func()
103
104
// NotFoundCallback is called for each not found template
105
// This overrides error handling for not found templates
106
NotFoundCallback func(template string) bool
107
}
108
109
// NewConfig returns a new loader config
110
func NewConfig(options *types.Options, catalog catalog.Catalog, executerOpts *protocols.ExecutorOptions) *Config {
111
loaderConfig := Config{
112
Templates: options.Templates,
113
Workflows: options.Workflows,
114
RemoteTemplateDomainList: options.RemoteTemplateDomainList,
115
TemplateURLs: options.TemplateURLs,
116
WorkflowURLs: options.WorkflowURLs,
117
ExcludeTemplates: options.ExcludedTemplates,
118
Tags: options.Tags,
119
ExcludeTags: options.ExcludeTags,
120
IncludeTemplates: options.IncludeTemplates,
121
Authors: options.Authors,
122
Severities: options.Severities,
123
ExcludeSeverities: options.ExcludeSeverities,
124
IncludeTags: options.IncludeTags,
125
IncludeIds: options.IncludeIds,
126
ExcludeIds: options.ExcludeIds,
127
Protocols: options.Protocols,
128
ExcludeProtocols: options.ExcludeProtocols,
129
IncludeConditions: options.IncludeConditions,
130
Catalog: catalog,
131
ExecutorOptions: executerOpts,
132
AITemplatePrompt: options.AITemplatePrompt,
133
Logger: options.Logger,
134
}
135
loaderConfig.RemoteTemplateDomainList = append(loaderConfig.RemoteTemplateDomainList, TrustedTemplateDomains...)
136
return &loaderConfig
137
}
138
139
// New creates a new template store based on provided configuration
140
func New(cfg *Config) (*Store, error) {
141
// tagFilter only for IncludeConditions (advanced filtering).
142
// All other filtering (tags, authors, severities, IDs, protocols, paths) is
143
// handled by [index.Filter].
144
tagFilter, err := templates.NewTagFilter(&templates.TagFilterConfig{
145
IncludeConditions: cfg.IncludeConditions,
146
})
147
if err != nil {
148
return nil, err
149
}
150
151
store := &Store{
152
id: cfg.StoreId,
153
config: cfg,
154
tagFilter: tagFilter,
155
finalTemplates: cfg.Templates,
156
finalWorkflows: cfg.Workflows,
157
logger: cfg.Logger,
158
}
159
160
store.parserCacheOnce = sync.OnceValue(func() *templates.Cache {
161
if cfg.ExecutorOptions == nil || cfg.ExecutorOptions.Parser == nil {
162
return nil
163
}
164
165
if parser, ok := cfg.ExecutorOptions.Parser.(*templates.Parser); ok {
166
return parser.Cache()
167
}
168
169
return nil
170
})
171
172
// Initialize metadata index and filter (load from disk & cache for reuse)
173
store.metadataIndex = store.loadTemplatesIndex()
174
store.indexFilter = store.buildIndexFilter()
175
if cfg.ExecutorOptions != nil {
176
cfg.ExecutorOptions.TemplateVerificationCallback = store.getTemplateVerification
177
}
178
store.saveMetadataIndexOnce = sync.OnceFunc(func() {
179
if store.metadataIndex == nil {
180
return
181
}
182
183
if err := store.metadataIndex.Save(); err != nil {
184
store.logger.Warning().Msgf("Could not save metadata cache: %v", err)
185
} else {
186
store.logger.Verbose().Msgf("Saved %d templates to metadata cache", store.metadataIndex.Size())
187
}
188
})
189
190
// Do a check to see if we have URLs in templates flag, if so
191
// we need to process them separately and remove them from the initial list
192
var templatesFinal []string
193
for _, template := range cfg.Templates {
194
// TODO: Add and replace this with urlutil.IsURL() helper
195
if stringsutil.HasPrefixAny(template, httpPrefix, httpsPrefix) {
196
cfg.TemplateURLs = append(cfg.TemplateURLs, template)
197
} else {
198
templatesFinal = append(templatesFinal, template)
199
}
200
}
201
202
// fix editor paths
203
remoteTemplates := []string{}
204
for _, v := range cfg.TemplateURLs {
205
if _, err := urlutil.Parse(v); err == nil {
206
remoteTemplates = append(remoteTemplates, handleTemplatesEditorURLs(v))
207
} else {
208
templatesFinal = append(templatesFinal, v) // something went wrong, treat it as a file
209
}
210
}
211
212
cfg.TemplateURLs = remoteTemplates
213
store.finalTemplates = templatesFinal
214
215
urlBasedTemplatesProvided := len(cfg.TemplateURLs) > 0 || len(cfg.WorkflowURLs) > 0
216
if urlBasedTemplatesProvided {
217
remoteTemplates, remoteWorkflows, err := getRemoteTemplatesAndWorkflows(cfg.TemplateURLs, cfg.WorkflowURLs, cfg.RemoteTemplateDomainList)
218
if err != nil {
219
return store, err
220
}
221
222
store.finalTemplates = append(store.finalTemplates, remoteTemplates...)
223
store.finalWorkflows = append(store.finalWorkflows, remoteWorkflows...)
224
}
225
226
// Handle AI template generation if prompt is provided
227
if len(cfg.AITemplatePrompt) > 0 {
228
aiTemplates, err := getAIGeneratedTemplates(cfg.AITemplatePrompt, cfg.ExecutorOptions.Options)
229
if err != nil {
230
return nil, err
231
}
232
store.finalTemplates = append(store.finalTemplates, aiTemplates...)
233
}
234
235
// Handle a dot as the current working directory
236
if len(store.finalTemplates) == 1 && store.finalTemplates[0] == "." {
237
currentDirectory, err := os.Getwd()
238
if err != nil {
239
return nil, errors.Wrap(err, "could not get current directory")
240
}
241
store.finalTemplates = []string{currentDirectory}
242
}
243
244
// Handle a case with no templates or workflows, where we use base directory
245
if len(store.finalTemplates) == 0 && len(store.finalWorkflows) == 0 && !urlBasedTemplatesProvided {
246
store.finalTemplates = []string{config.DefaultConfig.TemplatesDirectory}
247
}
248
249
return store, nil
250
}
251
252
func (store *Store) getTemplateVerification(templatePath string) *protocols.TemplateVerification {
253
if store.metadataIndex == nil {
254
return nil
255
}
256
257
metadata, found := store.metadataIndex.Get(templatePath)
258
if !found {
259
return nil
260
}
261
262
return &protocols.TemplateVerification{
263
Verified: metadata.Verified,
264
Verifier: metadata.TemplateVerifier,
265
}
266
}
267
268
func handleTemplatesEditorURLs(input string) string {
269
parsed, err := url.Parse(input)
270
if err != nil {
271
return input
272
}
273
274
if !strings.HasSuffix(parsed.Hostname(), "cloud.projectdiscovery.io") {
275
return input
276
}
277
278
if strings.HasSuffix(parsed.Path, ".yaml") {
279
return input
280
}
281
282
parsed.Path = fmt.Sprintf("%s.yaml", parsed.Path)
283
finalURL := parsed.String()
284
285
return finalURL
286
}
287
288
// ReadTemplateFromURI should only be used for viewing templates
289
// and should not be used anywhere else like loading and executing templates
290
// there is no sandbox restriction here
291
func (store *Store) ReadTemplateFromURI(uri string, remote bool) ([]byte, error) {
292
if stringsutil.HasPrefixAny(uri, httpPrefix, httpsPrefix) && remote {
293
uri = handleTemplatesEditorURLs(uri)
294
295
remoteTemplates, _, err := getRemoteTemplatesAndWorkflows([]string{uri}, nil, store.config.RemoteTemplateDomainList)
296
if err != nil || len(remoteTemplates) == 0 {
297
return nil, errkit.Wrapf(err, "Could not load template %s: got %v", uri, remoteTemplates)
298
}
299
300
resp, err := retryablehttp.Get(remoteTemplates[0])
301
if err != nil {
302
return nil, err
303
}
304
305
defer func() {
306
_ = resp.Body.Close()
307
}()
308
309
return io.ReadAll(resp.Body)
310
} else {
311
return os.ReadFile(uri)
312
}
313
}
314
315
func (store *Store) ID() string {
316
return store.id
317
}
318
319
// Templates returns all the templates in the store
320
func (store *Store) Templates() []*templates.Template {
321
return store.templates
322
}
323
324
// Workflows returns all the workflows in the store
325
func (store *Store) Workflows() []*templates.Template {
326
return store.workflows
327
}
328
329
// RegisterPreprocessor allows a custom preprocessor to be passed to the store to run against templates
330
func (store *Store) RegisterPreprocessor(preprocessor templates.Preprocessor) {
331
store.preprocessor = preprocessor
332
}
333
334
// Load loads all the templates from a store, performs filtering and returns
335
// the complete compiled templates for a nuclei execution configuration.
336
func (store *Store) Load() {
337
store.templates = store.LoadTemplates(store.finalTemplates)
338
store.workflows = store.LoadWorkflows(store.finalWorkflows)
339
}
340
341
var templateIDPathMap map[string]string
342
343
func init() {
344
templateIDPathMap = make(map[string]string)
345
}
346
347
// buildIndexFilter creates an [index.Filter] from the store configuration.
348
// This filter handles all basic filtering (paths, tags, authors, severities,
349
// IDs, protocols). Advanced IncludeConditions filtering is handled separately
350
// by tagFilter.
351
func (store *Store) buildIndexFilter() *index.Filter {
352
includeTemplates, _ := store.config.Catalog.GetTemplatesPath(store.config.IncludeTemplates)
353
excludeTemplates, _ := store.config.Catalog.GetTemplatesPath(store.config.ExcludeTemplates)
354
355
return &index.Filter{
356
Authors: store.config.Authors,
357
Tags: store.config.Tags,
358
ExcludeTags: store.config.ExcludeTags,
359
IncludeTags: store.config.IncludeTags,
360
IDs: store.config.IncludeIds,
361
ExcludeIDs: store.config.ExcludeIds,
362
IncludeTemplates: includeTemplates,
363
ExcludeTemplates: excludeTemplates,
364
Severities: []severity.Severity(store.config.Severities),
365
ExcludeSeverities: []severity.Severity(store.config.ExcludeSeverities),
366
ProtocolTypes: []templateTypes.ProtocolType(store.config.Protocols),
367
ExcludeProtocolTypes: []templateTypes.ProtocolType(store.config.ExcludeProtocols),
368
}
369
}
370
371
func (store *Store) loadTemplatesIndex() *index.Index {
372
var metadataIdx *index.Index
373
374
idx, err := index.NewDefaultIndex()
375
if err != nil {
376
store.logger.Warning().Msgf("Could not create metadata cache: %v", err)
377
} else {
378
metadataIdx = idx
379
if err := metadataIdx.Load(); err != nil {
380
store.logger.Warning().Msgf("Could not load metadata cache: %v", err)
381
}
382
}
383
384
return metadataIdx
385
}
386
387
// LoadTemplatesOnlyMetadata loads only the metadata of the templates
388
func (store *Store) LoadTemplatesOnlyMetadata() error {
389
defer store.saveMetadataIndexOnce()
390
391
templatePaths, errs := store.config.Catalog.GetTemplatesPath(store.finalTemplates)
392
store.logErroredTemplates(errs)
393
394
indexFilter := store.indexFilter
395
validPaths := make(map[string]struct{})
396
397
for _, templatePath := range templatePaths {
398
if store.metadataIndex != nil {
399
if metadata, found := store.metadataIndex.Get(templatePath); found {
400
if !indexFilter.Matches(metadata) {
401
continue
402
}
403
404
if store.tagFilter != nil {
405
loaded, err := store.config.ExecutorOptions.Parser.LoadTemplate(templatePath, store.tagFilter, nil, store.config.Catalog)
406
if !loaded {
407
if err != nil && strings.Contains(err.Error(), templates.ErrExcluded.Error()) {
408
stats.Increment(templates.TemplatesExcludedStats)
409
if config.DefaultConfig.LogAllEvents {
410
store.logger.Print().Msgf("[%v] %v\n", aurora.Yellow("WRN").String(), err.Error())
411
}
412
}
413
continue
414
}
415
}
416
417
validPaths[templatePath] = struct{}{}
418
continue
419
}
420
}
421
422
loaded, err := store.config.ExecutorOptions.Parser.LoadTemplate(templatePath, store.tagFilter, nil, store.config.Catalog)
423
if loaded {
424
templatesCache := store.parserCacheOnce()
425
if templatesCache != nil {
426
if template, _, _ := templatesCache.Has(templatePath); template != nil {
427
var metadata *index.Metadata
428
429
if store.metadataIndex != nil {
430
metadata, _ = store.metadataIndex.SetFromTemplate(templatePath, template)
431
} else {
432
metadata = index.NewMetadataFromTemplate(templatePath, template)
433
}
434
435
if !indexFilter.Matches(metadata) {
436
continue
437
}
438
439
validPaths[templatePath] = struct{}{}
440
continue
441
}
442
}
443
444
validPaths[templatePath] = struct{}{}
445
}
446
447
if err != nil {
448
if strings.Contains(err.Error(), templates.ErrExcluded.Error()) {
449
stats.Increment(templates.TemplatesExcludedStats)
450
if config.DefaultConfig.LogAllEvents {
451
store.logger.Print().Msgf("[%v] %v\n", aurora.Yellow("WRN").String(), err.Error())
452
}
453
continue
454
}
455
456
store.logger.Warning().Msg(err.Error())
457
}
458
}
459
460
templatesCache := store.parserCacheOnce()
461
if templatesCache == nil {
462
return errors.New("invalid parser")
463
}
464
465
loadedTemplateIDs := mapsutil.NewSyncLockMap[string, struct{}]()
466
caps := templates.Capabilities{
467
Headless: store.config.ExecutorOptions.Options.Headless,
468
Code: store.config.ExecutorOptions.Options.EnableCodeTemplates,
469
DAST: store.config.ExecutorOptions.Options.DAST,
470
SelfContained: store.config.ExecutorOptions.Options.EnableSelfContainedTemplates,
471
File: store.config.ExecutorOptions.Options.EnableFileTemplates,
472
}
473
isListOrDisplay := store.config.ExecutorOptions.Options.TemplateList ||
474
store.config.ExecutorOptions.Options.TemplateDisplay
475
476
for templatePath := range validPaths {
477
template, _, _ := templatesCache.Has(templatePath)
478
if template == nil {
479
continue
480
}
481
482
if !isListOrDisplay && !template.IsEnabledFor(caps) {
483
continue
484
}
485
486
if loadedTemplateIDs.Has(template.ID) {
487
store.logger.Debug().Msgf("Skipping duplicate template ID '%s' from path '%s'", template.ID, templatePath)
488
continue
489
}
490
491
_ = loadedTemplateIDs.Set(template.ID, struct{}{})
492
template.Path = templatePath
493
store.templates = append(store.templates, template)
494
}
495
496
return nil
497
}
498
499
// ValidateTemplates takes a list of templates and validates them
500
// erroring out on discovering any faulty templates.
501
func (store *Store) ValidateTemplates() error {
502
templatePaths, errs := store.config.Catalog.GetTemplatesPath(store.finalTemplates)
503
store.logErroredTemplates(errs)
504
505
workflowPaths, errs := store.config.Catalog.GetTemplatesPath(store.finalWorkflows)
506
store.logErroredTemplates(errs)
507
508
templatePathsMap := make(map[string]struct{}, len(templatePaths))
509
for _, path := range templatePaths {
510
templatePathsMap[path] = struct{}{}
511
}
512
513
workflowPathsMap := make(map[string]struct{}, len(workflowPaths))
514
for _, path := range workflowPaths {
515
workflowPathsMap[path] = struct{}{}
516
}
517
518
if store.areTemplatesValid(templatePathsMap) && store.areWorkflowsValid(workflowPathsMap) {
519
return nil
520
}
521
522
return errors.New("errors occurred during template validation")
523
}
524
525
func (store *Store) areWorkflowsValid(filteredWorkflowPaths map[string]struct{}) bool {
526
return store.areWorkflowOrTemplatesValid(filteredWorkflowPaths, true, func(templatePath string, tagFilter *templates.TagFilter) (bool, error) {
527
return store.config.ExecutorOptions.Parser.LoadWorkflow(templatePath, store.config.Catalog)
528
})
529
}
530
531
func (store *Store) areTemplatesValid(filteredTemplatePaths map[string]struct{}) bool {
532
return store.areWorkflowOrTemplatesValid(filteredTemplatePaths, false, func(templatePath string, tagFilter *templates.TagFilter) (bool, error) {
533
return store.config.ExecutorOptions.Parser.LoadTemplate(templatePath, store.tagFilter, nil, store.config.Catalog)
534
})
535
}
536
537
func (store *Store) areWorkflowOrTemplatesValid(filteredTemplatePaths map[string]struct{}, isWorkflow bool, load func(templatePath string, tagFilter *templates.TagFilter) (bool, error)) bool {
538
areTemplatesValid := true
539
parsedCache := store.parserCacheOnce()
540
541
for templatePath := range filteredTemplatePaths {
542
if _, err := load(templatePath, store.tagFilter); err != nil {
543
if isParsingError(store, "Error occurred loading template %s: %s\n", templatePath, err) {
544
areTemplatesValid = false
545
continue
546
}
547
}
548
549
var template *templates.Template
550
var err error
551
552
if parsedCache != nil {
553
if cachedTemplate, _, cacheErr := parsedCache.Has(templatePath); cacheErr == nil && cachedTemplate != nil {
554
template = cachedTemplate
555
}
556
}
557
558
if template == nil {
559
template, err = templates.Parse(templatePath, store.preprocessor, store.config.ExecutorOptions)
560
if err != nil {
561
if isParsingError(store, "Error occurred parsing template %s: %s\n", templatePath, err) {
562
areTemplatesValid = false
563
continue
564
}
565
}
566
}
567
568
if template == nil {
569
// NOTE(dwisiswant0): possibly global matchers template.
570
// This could definitely be handled better, for example by returning an
571
// `ErrGlobalMatchersTemplate` during `templates.Parse` and checking it
572
// with `errors.Is`.
573
//
574
// However, I'm not sure if every reference to it should be handled
575
// that way. Returning a `templates.Template` pointer would mean it's
576
// an active template (sending requests), and adding a specific field
577
// like `isGlobalMatchers` in `templates.Template` (then checking it
578
// with a `*templates.Template.IsGlobalMatchersEnabled` method) would
579
// just introduce more unknown issues - like during template
580
// clustering, AFAIK.
581
continue
582
} else {
583
if existingTemplatePath, found := templateIDPathMap[template.ID]; !found {
584
templateIDPathMap[template.ID] = templatePath
585
} else {
586
// TODO: until https://github.com/projectdiscovery/nuclei-templates/issues/11324 is deployed
587
// disable strict validation to allow GH actions to run
588
// areTemplatesValid = false
589
store.logger.Warning().Msgf("Found duplicate template ID during validation '%s' => '%s': %s\n", templatePath, existingTemplatePath, template.ID)
590
}
591
592
if !isWorkflow && template.HasWorkflows() {
593
continue
594
}
595
}
596
597
if isWorkflow {
598
if !areWorkflowTemplatesValid(store, template.Workflows) {
599
areTemplatesValid = false
600
continue
601
}
602
}
603
}
604
605
return areTemplatesValid
606
}
607
608
func areWorkflowTemplatesValid(store *Store, workflows []*workflows.WorkflowTemplate) bool {
609
for _, workflow := range workflows {
610
if !areWorkflowTemplatesValid(store, workflow.Subtemplates) {
611
return false
612
}
613
614
_, err := store.config.Catalog.GetTemplatePath(workflow.Template)
615
if err != nil {
616
if isParsingError(store, "Error occurred loading template %s: %s\n", workflow.Template, err) {
617
return false
618
}
619
}
620
}
621
622
return true
623
}
624
625
func isParsingError(store *Store, message string, template string, err error) bool {
626
if errors.Is(err, templates.ErrExcluded) {
627
return false
628
}
629
630
if errors.Is(err, templates.ErrCreateTemplateExecutor) {
631
return false
632
}
633
634
store.logger.Error().Msgf(message, template, err)
635
636
return true
637
}
638
639
// LoadTemplates takes a list of templates and returns paths for them
640
func (store *Store) LoadTemplates(templatesList []string) []*templates.Template {
641
return store.LoadTemplatesWithTags(templatesList, nil)
642
}
643
644
// LoadWorkflows takes a list of workflows and returns paths for them
645
func (store *Store) LoadWorkflows(workflowsList []string) []*templates.Template {
646
includedWorkflows, errs := store.config.Catalog.GetTemplatesPath(workflowsList)
647
store.logErroredTemplates(errs)
648
649
loadedWorkflows := make([]*templates.Template, 0, len(includedWorkflows))
650
for _, workflowPath := range includedWorkflows {
651
loaded, err := store.config.ExecutorOptions.Parser.LoadWorkflow(workflowPath, store.config.Catalog)
652
if err != nil {
653
store.logger.Warning().Msgf("Could not load workflow %s: %s\n", workflowPath, err)
654
}
655
656
if loaded {
657
parsed, err := templates.Parse(workflowPath, store.preprocessor, store.config.ExecutorOptions)
658
if err != nil {
659
store.logger.Warning().Msgf("Could not parse workflow %s: %s\n", workflowPath, err)
660
} else if parsed != nil {
661
loadedWorkflows = append(loadedWorkflows, parsed)
662
}
663
}
664
}
665
666
return loadedWorkflows
667
}
668
669
// LoadTemplatesWithTags takes a list of templates and extra tags
670
// returning templates that match.
671
func (store *Store) LoadTemplatesWithTags(templatesList, tags []string) []*templates.Template {
672
defer store.saveMetadataIndexOnce()
673
674
indexFilter := store.indexFilter
675
676
includedTemplates, errs := store.config.Catalog.GetTemplatesPath(templatesList)
677
store.logErroredTemplates(errs)
678
679
loadedTemplates := sliceutil.NewSyncSlice[*templates.Template]()
680
loadedTemplateIDs := mapsutil.NewSyncLockMap[string, struct{}]()
681
682
loadTemplate := func(tmpl *templates.Template) {
683
if loadedTemplateIDs.Has(tmpl.ID) {
684
store.logger.Debug().Msgf("Skipping duplicate template ID '%s' from path '%s'", tmpl.ID, tmpl.Path)
685
return
686
}
687
688
_ = loadedTemplateIDs.Set(tmpl.ID, struct{}{})
689
690
loadedTemplates.Append(tmpl)
691
// increment signed/unsigned counters
692
if tmpl.Verified {
693
if tmpl.TemplateVerifier == "" {
694
templates.SignatureStats[keys.PDVerifier].Add(1)
695
} else {
696
templates.SignatureStats[tmpl.TemplateVerifier].Add(1)
697
}
698
} else {
699
templates.SignatureStats[templates.Unsigned].Add(1)
700
}
701
}
702
703
typesOpts := store.config.ExecutorOptions.Options
704
concurrency := typesOpts.TemplateLoadingConcurrency
705
if concurrency <= 0 {
706
concurrency = types.DefaultTemplateLoadingConcurrency
707
}
708
709
wgLoadTemplates, errWg := syncutil.New(syncutil.WithSize(concurrency))
710
if errWg != nil {
711
panic("could not create wait group")
712
}
713
714
if typesOpts.ExecutionId == "" {
715
typesOpts.ExecutionId = xid.New().String()
716
}
717
718
dialers := protocolstate.GetDialersWithId(typesOpts.ExecutionId)
719
if dialers == nil {
720
panic("dialers with executionId " + typesOpts.ExecutionId + " not found")
721
}
722
723
for _, templatePath := range includedTemplates {
724
wgLoadTemplates.Add()
725
go func(templatePath string) {
726
defer wgLoadTemplates.Done()
727
728
var (
729
metadata *index.Metadata
730
metadataCached bool
731
)
732
733
if store.metadataIndex != nil {
734
if cachedMetadata, found := store.metadataIndex.Get(templatePath); found {
735
metadata = cachedMetadata
736
if !indexFilter.Matches(metadata) {
737
return
738
}
739
// NOTE(dwisiswant0): else, tagFilter probably exists (for
740
// IncludeConditions), which still need to check via
741
// LoadTemplate.
742
743
metadataCached = true
744
}
745
}
746
747
loaded, err := store.config.ExecutorOptions.Parser.LoadTemplate(templatePath, store.tagFilter, tags, store.config.Catalog)
748
if loaded {
749
parsed, err := templates.Parse(templatePath, store.preprocessor, store.config.ExecutorOptions)
750
751
if parsed != nil && !metadataCached {
752
if store.metadataIndex != nil {
753
metadata, _ = store.metadataIndex.SetFromTemplate(templatePath, parsed)
754
} else {
755
metadata = index.NewMetadataFromTemplate(templatePath, parsed)
756
}
757
758
if metadata != nil && !indexFilter.Matches(metadata) {
759
return
760
}
761
}
762
763
if err != nil {
764
// exclude templates not compatible with offline matching from total runtime warning stats
765
if !errors.Is(err, templates.ErrIncompatibleWithOfflineMatching) {
766
stats.Increment(templates.RuntimeWarningsStats)
767
}
768
store.logger.Warning().Msgf("Could not parse template %s: %s\n", templatePath, err)
769
} else if parsed != nil {
770
if !parsed.Verified && typesOpts.DisableUnsignedTemplates {
771
// skip unverified templates when prompted to
772
stats.Increment(templates.SkippedUnsignedStats)
773
return
774
}
775
776
if parsed.SelfContained && !typesOpts.EnableSelfContainedTemplates {
777
stats.Increment(templates.ExcludedSelfContainedStats)
778
return
779
}
780
781
if parsed.HasFileRequest() && !typesOpts.EnableFileTemplates {
782
stats.Increment(templates.ExcludedFileStats)
783
return
784
}
785
786
// if template has request signature like aws then only signed and verified templates are allowed
787
if parsed.UsesRequestSignature() && !parsed.Verified {
788
stats.Increment(templates.SkippedRequestSignatureStats)
789
return
790
}
791
// DAST only templates
792
// Skip DAST filter when loading auth templates
793
if store.ID() != AuthStoreId && typesOpts.DAST {
794
// check if the template is a DAST template
795
// also allow global matchers template to be loaded
796
if parsed.IsFuzzableRequest() || parsed.IsGlobalMatchersTemplate() {
797
if parsed.HasHeadlessRequest() && !typesOpts.Headless {
798
stats.Increment(templates.ExcludedHeadlessTmplStats)
799
if config.DefaultConfig.LogAllEvents {
800
store.logger.Print().Msgf("[%v] Headless flag is required for headless template '%s'.\n", aurora.Yellow("WRN").String(), templatePath)
801
}
802
} else {
803
loadTemplate(parsed)
804
}
805
}
806
} else if parsed.HasHeadlessRequest() && !typesOpts.Headless {
807
// donot include headless template in final list if headless flag is not set
808
stats.Increment(templates.ExcludedHeadlessTmplStats)
809
if config.DefaultConfig.LogAllEvents {
810
store.logger.Print().Msgf("[%v] Headless flag is required for headless template '%s'.\n", aurora.Yellow("WRN").String(), templatePath)
811
}
812
} else if parsed.HasCodeRequest() && !typesOpts.EnableCodeTemplates {
813
// donot include 'Code' protocol custom template in final list if code flag is not set
814
stats.Increment(templates.ExcludedCodeTmplStats)
815
if config.DefaultConfig.LogAllEvents {
816
store.logger.Print().Msgf("[%v] Code flag is required for code protocol template '%s'.\n", aurora.Yellow("WRN").String(), templatePath)
817
}
818
} else if parsed.HasCodeRequest() && !parsed.Verified && !parsed.HasWorkflows() {
819
// donot include unverified 'Code' protocol custom template in final list
820
stats.Increment(templates.SkippedCodeTmplTamperedStats)
821
// these will be skipped so increment skip counter
822
stats.Increment(templates.SkippedUnsignedStats)
823
if config.DefaultConfig.LogAllEvents {
824
store.logger.Print().Msgf("[%v] Tampered/Unsigned template at %v.\n", aurora.Yellow("WRN").String(), templatePath)
825
}
826
} else if parsed.IsFuzzableRequest() && !typesOpts.DAST {
827
stats.Increment(templates.ExludedDastTmplStats)
828
if config.DefaultConfig.LogAllEvents {
829
store.logger.Print().Msgf("[%v] -dast flag is required for DAST template '%s'.\n", aurora.Yellow("WRN").String(), templatePath)
830
}
831
} else {
832
loadTemplate(parsed)
833
}
834
}
835
}
836
if err != nil {
837
if strings.Contains(err.Error(), templates.ErrExcluded.Error()) {
838
stats.Increment(templates.TemplatesExcludedStats)
839
if config.DefaultConfig.LogAllEvents {
840
store.logger.Print().Msgf("[%v] %v\n", aurora.Yellow("WRN").String(), err.Error())
841
}
842
return
843
}
844
store.logger.Warning().Msg(err.Error())
845
}
846
}(templatePath)
847
}
848
849
wgLoadTemplates.Wait()
850
851
sort.SliceStable(loadedTemplates.Slice, func(i, j int) bool {
852
return loadedTemplates.Slice[i].Path < loadedTemplates.Slice[j].Path
853
})
854
855
return loadedTemplates.Slice
856
}
857
858
// IsHTTPBasedProtocolUsed returns true if http/headless protocol is being used for
859
// any templates.
860
func IsHTTPBasedProtocolUsed(store *Store) bool {
861
templates := append(store.Templates(), store.Workflows()...)
862
863
for _, template := range templates {
864
if template.HasHTTPRequest() || template.HasHeadlessRequest() {
865
return true
866
}
867
868
if template.HasWorkflows() {
869
if workflowContainsProtocol(template.Workflows) {
870
return true
871
}
872
}
873
}
874
return false
875
}
876
877
func workflowContainsProtocol(workflow []*workflows.WorkflowTemplate) bool {
878
for _, workflow := range workflow {
879
for _, template := range workflow.Matchers {
880
if workflowContainsProtocol(template.Subtemplates) {
881
return true
882
}
883
}
884
for _, template := range workflow.Subtemplates {
885
if workflowContainsProtocol(template.Subtemplates) {
886
return true
887
}
888
}
889
for _, executer := range workflow.Executers {
890
if executer.TemplateType == templateTypes.HTTPProtocol || executer.TemplateType == templateTypes.HeadlessProtocol {
891
return true
892
}
893
}
894
}
895
return false
896
}
897
898
func (s *Store) logErroredTemplates(erred map[string]error) {
899
for template, err := range erred {
900
if s.NotFoundCallback == nil || !s.NotFoundCallback(template) {
901
s.logger.Error().Msgf("Could not find template '%s': %s", template, err)
902
}
903
}
904
}
905
906