forked from projectdiscovery/nuclei
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplates.go
More file actions
647 lines (577 loc) · 24.1 KB
/
templates.go
File metadata and controls
647 lines (577 loc) · 24.1 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
//go:generate dstdocgen -path "" -structure Template -output templates_doc.go -package templates
package templates
import (
"io"
"path/filepath"
"strconv"
"strings"
"github.com/projectdiscovery/nuclei/v3/pkg/model"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/code"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/variables"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/dns"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/file"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/headless"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/http"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/javascript"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/network"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/ssl"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/websocket"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/whois"
"github.com/projectdiscovery/nuclei/v3/pkg/templates/types"
"github.com/projectdiscovery/nuclei/v3/pkg/utils"
"github.com/projectdiscovery/nuclei/v3/pkg/utils/json"
"github.com/projectdiscovery/nuclei/v3/pkg/workflows"
"github.com/projectdiscovery/utils/errkit"
fileutil "github.com/projectdiscovery/utils/file"
"go.uber.org/multierr"
"gopkg.in/yaml.v2"
)
// Template is a YAML input file which defines all the requests and
// other metadata for a template.
type Template struct {
// description: |
// ID is the unique id for the template.
//
// #### Good IDs
//
// A good ID uniquely identifies what the requests in the template
// are doing. Let's say you have a template that identifies a git-config
// file on the webservers, a good name would be `git-config-exposure`. Another
// example name is `azure-apps-nxdomain-takeover`.
// examples:
// - name: ID Example
// value: "\"CVE-2021-19520\""
ID string `yaml:"id" json:"id" jsonschema:"title=id of the template,description=The Unique ID for the template,required,example=cve-2021-19520,pattern=^([a-zA-Z0-9]+[-_])*[a-zA-Z0-9]+$"`
// description: |
// Info contains metadata information about the template.
// examples:
// - value: exampleInfoStructure
Info model.Info `yaml:"info" json:"info" jsonschema:"title=info for the template,description=Info contains metadata for the template,required,type=object"`
// description: |
// Flow contains the execution flow for the template.
// examples:
// - flow: |
// for region in regions {
// http(0)
// }
// for vpc in vpcs {
// http(1)
// }
//
Flow string `yaml:"flow,omitempty" json:"flow,omitempty" jsonschema:"title=template execution flow in js,description=Flow contains js code which defines how the template should be executed,type=string,example='flow: http(0) && http(1)'"`
// description: |
// Requests contains the http request to make in the template.
// WARNING: 'requests' will be deprecated and will be removed in a future release. Please use 'http' instead.
// examples:
// - value: exampleNormalHTTPRequest
RequestsHTTP []*http.Request `yaml:"requests,omitempty" json:"requests,omitempty" jsonschema:"title=http requests to make,description=HTTP requests to make for the template,deprecated=true"`
// description: |
// HTTP contains the http request to make in the template.
// examples:
// - value: exampleNormalHTTPRequest
// RequestsWithHTTP is placeholder(internal) only, and should not be used instead use RequestsHTTP
// Deprecated: Use RequestsHTTP instead.
RequestsWithHTTP []*http.Request `yaml:"http,omitempty" json:"http,omitempty" jsonschema:"title=http requests to make,description=HTTP requests to make for the template"`
// description: |
// DNS contains the dns request to make in the template
// examples:
// - value: exampleNormalDNSRequest
RequestsDNS []*dns.Request `yaml:"dns,omitempty" json:"dns,omitempty" jsonschema:"title=dns requests to make,description=DNS requests to make for the template"`
// description: |
// File contains the file request to make in the template
// examples:
// - value: exampleNormalFileRequest
RequestsFile []*file.Request `yaml:"file,omitempty" json:"file,omitempty" jsonschema:"title=file requests to make,description=File requests to make for the template"`
// description: |
// Network contains the network request to make in the template
// WARNING: 'network' will be deprecated and will be removed in a future release. Please use 'tcp' instead.
// examples:
// - value: exampleNormalNetworkRequest
RequestsNetwork []*network.Request `yaml:"network,omitempty" json:"network,omitempty" jsonschema:"title=network requests to make,description=Network requests to make for the template,deprecated=true"`
// description: |
// TCP contains the network request to make in the template
// examples:
// - value: exampleNormalNetworkRequest
// RequestsWithTCP is placeholder(internal) only, and should not be used instead use RequestsNetwork
// Deprecated: Use RequestsNetwork instead.
RequestsWithTCP []*network.Request `yaml:"tcp,omitempty" json:"tcp,omitempty" jsonschema:"title=network(tcp) requests to make,description=Network requests to make for the template"`
// description: |
// Headless contains the headless request to make in the template.
RequestsHeadless []*headless.Request `yaml:"headless,omitempty" json:"headless,omitempty" jsonschema:"title=headless requests to make,description=Headless requests to make for the template"`
// description: |
// SSL contains the SSL request to make in the template.
RequestsSSL []*ssl.Request `yaml:"ssl,omitempty" json:"ssl,omitempty" jsonschema:"title=ssl requests to make,description=SSL requests to make for the template"`
// description: |
// Websocket contains the Websocket request to make in the template.
RequestsWebsocket []*websocket.Request `yaml:"websocket,omitempty" json:"websocket,omitempty" jsonschema:"title=websocket requests to make,description=Websocket requests to make for the template"`
// description: |
// WHOIS contains the WHOIS request to make in the template.
RequestsWHOIS []*whois.Request `yaml:"whois,omitempty" json:"whois,omitempty" jsonschema:"title=whois requests to make,description=WHOIS requests to make for the template"`
// description: |
// Code contains code snippets.
RequestsCode []*code.Request `yaml:"code,omitempty" json:"code,omitempty" jsonschema:"title=code snippets to make,description=Code snippets"`
// description: |
// Javascript contains the javascript request to make in the template.
RequestsJavascript []*javascript.Request `yaml:"javascript,omitempty" json:"javascript,omitempty" jsonschema:"title=javascript requests to make,description=Javascript requests to make for the template"`
// description: |
// Workflows is a yaml based workflow declaration code.
workflows.Workflow `yaml:",inline,omitempty" jsonschema:"title=workflows to run,description=Workflows to run for the template"`
CompiledWorkflow *workflows.Workflow `yaml:"-" json:"-" jsonschema:"-"`
// description: |
// Self Contained marks Requests for the template as self-contained
SelfContained bool `yaml:"self-contained,omitempty" json:"self-contained,omitempty" jsonschema:"title=mark requests as self-contained,description=Mark Requests for the template as self-contained"`
// description: |
// Stop execution once first match is found
StopAtFirstMatch bool `yaml:"stop-at-first-match,omitempty" json:"stop-at-first-match,omitempty" jsonschema:"title=stop at first match,description=Stop at first match for the template"`
// description: |
// Signature is the request signature method
// WARNING: 'signature' will be deprecated and will be removed in a future release. Prefer using 'code' protocol for writing cloud checks
// values:
// - "AWS"
Signature http.SignatureTypeHolder `yaml:"signature,omitempty" json:"signature,omitempty" jsonschema:"title=signature is the http request signature method,description=Signature is the HTTP Request signature Method,enum=AWS,deprecated=true"`
// description: |
// Variables contains any variables for the current request.
Variables variables.Variable `yaml:"variables,omitempty" json:"variables,omitempty" jsonschema:"title=variables for the http request,description=Variables contains any variables for the current request,type=object"`
// description: |
// Constants contains any scalar constant for the current template
Constants map[string]interface{} `yaml:"constants,omitempty" json:"constants,omitempty" jsonschema:"title=constant for the template,description=constants contains any constant for the template,type=object"`
// TotalRequests is the total number of requests for the template.
TotalRequests int `yaml:"-" json:"-"`
// Executer is the actual template executor for running template requests
Executer protocols.Executer `yaml:"-" json:"-"`
Path string `yaml:"-" json:"-"`
// Verified defines if the template signature is digitally verified
Verified bool `yaml:"-" json:"-"`
// TemplateVerifier is identifier verifier used to verify the template (default nuclei-templates have projectdiscovery/nuclei-templates)
TemplateVerifier string `yaml:"-" json:"-"`
// RequestsQueue contains all template requests in order (both protocol & request order)
RequestsQueue []protocols.Request `yaml:"-" json:"-"`
// ImportedFiles contains list of files whose contents are imported after template was compiled
ImportedFiles []string `yaml:"-" json:"-"`
}
// HasCodeProtocol returns true if the template has a code protocol section
//
// Deprecated: Use [HasCodeRequest] instead.
func (template *Template) HasCodeProtocol() bool {
return len(template.RequestsCode) > 0
}
// HasFileProtocol returns true if the template has a file protocol section.
//
// Deprecated: Use [HasFileRequest] instead.
func (template *Template) HasFileProtocol() bool {
return len(template.RequestsFile) > 0
}
// Type returns the type of the template
func (template *Template) Type() types.ProtocolType {
switch {
case template.HasDNSRequest():
return types.DNSProtocol
case template.HasFileRequest():
return types.FileProtocol
case template.HasHTTPRequest():
return types.HTTPProtocol
case template.HasHeadlessRequest():
return types.HeadlessProtocol
case template.HasNetworkRequest():
return types.NetworkProtocol
case template.HasSSLRequest():
return types.SSLProtocol
case template.HasWebsocketRequest():
return types.WebsocketProtocol
case template.HasWHOISRequest():
return types.WHOISProtocol
case template.HasCodeRequest():
return types.CodeProtocol
case template.HasJavascriptRequest():
return types.JavascriptProtocol
case template.HasWorkflows():
return types.WorkflowProtocol
default:
return types.InvalidProtocol
}
}
// IsFuzzing returns true if the template is a fuzzing template
//
// Deprecated: Use [IsFuzzableRequest] instead.
func (template *Template) IsFuzzing() bool {
if len(template.RequestsHTTP) == 0 && len(template.RequestsHeadless) == 0 {
// fuzzing is only supported for http and headless protocols
return false
}
if len(template.RequestsHTTP) > 0 {
for _, request := range template.RequestsHTTP {
if len(request.Fuzzing) > 0 {
return true
}
}
}
if len(template.RequestsHeadless) > 0 {
for _, request := range template.RequestsHeadless {
if len(request.Fuzzing) > 0 {
return true
}
}
}
return false
}
// UsesRequestSignature returns true if the template uses a request signature like AWS
func (template *Template) UsesRequestSignature() bool {
return template.Signature.Value.String() != ""
}
// validateAllRequestIDs check if that protocol already has given id if not
// then is is manually set to proto_index
func (template *Template) validateAllRequestIDs() {
// this is required in multiprotocol and flow where we save response variables
// and all other data in template context if template as two requests in a protocol
// then it is overwritten to avoid this we use proto_index as request ID
if template.HasCodeRequest(1) {
for i, req := range template.RequestsCode {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if template.HasDNSRequest(1) {
for i, req := range template.RequestsDNS {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if template.HasFileRequest(1) {
for i, req := range template.RequestsFile {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if template.HasHTTPRequest(1) {
for i, req := range template.RequestsHTTP {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if template.HasHeadlessRequest(1) {
for i, req := range template.RequestsHeadless {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if template.HasNetworkRequest(1) {
for i, req := range template.RequestsNetwork {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if template.HasSSLRequest(1) {
for i, req := range template.RequestsSSL {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if template.HasWebsocketRequest(1) {
for i, req := range template.RequestsWebsocket {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if template.HasWHOISRequest(1) {
for i, req := range template.RequestsWHOIS {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if template.HasJavascriptRequest(1) {
for i, req := range template.RequestsJavascript {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
}
// MarshalYAML forces recursive struct validation during marshal operation
func (template *Template) MarshalYAML() ([]byte, error) {
out, marshalErr := yaml.Marshal(template)
// Use shared validator to avoid rebuilding struct cache for every template marshal
errValidate := tplValidator.Struct(template)
return out, multierr.Append(marshalErr, errValidate)
}
// UnmarshalYAML forces recursive struct validation after unmarshal operation
func (template *Template) UnmarshalYAML(unmarshal func(interface{}) error) error {
type Alias Template
alias := &Alias{}
err := unmarshal(alias)
if err != nil {
return err
}
*template = Template(*alias)
if !ReTemplateID.MatchString(template.ID) {
return errkit.New("template id must match expression %v", ReTemplateID, "tag", "invalid_template")
}
info := template.Info
if utils.IsBlank(info.Name) {
return errkit.New("no template name field provided", "tag", "invalid_template")
}
if info.Authors.IsEmpty() {
return errkit.New("no template author field provided", "tag", "invalid_template")
}
if template.HasHTTPRequest() || template.HasNetworkRequest() {
_ = deprecatedProtocolNameTemplates.Set(template.ID, true)
}
if HasRequest(alias.RequestsHTTP) && HasRequest(alias.RequestsWithHTTP) {
return errkit.New("use http or requests, both are not supported", "tag", "invalid_template")
}
if HasRequest(alias.RequestsNetwork) && HasRequest(alias.RequestsWithTCP) {
return errkit.New("use tcp or network, both are not supported", "tag", "invalid_template")
}
if HasRequest(alias.RequestsWithHTTP) {
template.RequestsHTTP = alias.RequestsWithHTTP
}
if HasRequest(alias.RequestsWithTCP) {
template.RequestsNetwork = alias.RequestsWithTCP
}
err = tplValidator.Struct(template)
if err != nil {
return err
}
// check if the template contains more than 1 protocol request
// if so preserve the order of the protocols and requests
if template.hasMultipleRequests() {
var tempmap yaml.MapSlice
err = unmarshal(&tempmap)
if err != nil {
return errkit.Wrapf(err, "failed to unmarshal multi protocol template %s", template.ID)
}
arr := []string{}
for _, v := range tempmap {
key, ok := v.Key.(string)
if !ok {
continue
}
arr = append(arr, key)
}
// add protocols to the protocol stack (the idea is to preserve the order of the protocols)
template.addRequestsToQueue(arr...)
}
return nil
}
// ImportFileRefs checks if sensitive fields like `flow` , `source` in code protocol are referencing files
// instead of actual javascript / engine code if so it loads the file contents and replaces the reference
func (template *Template) ImportFileRefs(options *protocols.ExecutorOptions) error {
var errs []error
loadFile := func(source string) (string, bool) {
// load file respecting sandbox
data, err := options.Options.LoadHelperFile(source, options.TemplatePath, options.Catalog)
if err == nil {
defer func() {
_ = data.Close()
}()
bin, err := io.ReadAll(data)
if err == nil {
return string(bin), true
} else {
errs = append(errs, err)
}
} else {
errs = append(errs, err)
}
return "", false
}
// for code protocol requests
for _, request := range template.RequestsCode {
// simple test to check if source is a file or a snippet
if !strings.ContainsRune(request.Source, '\n') && fileutil.FileExists(request.Source) {
if val, ok := loadFile(request.Source); ok {
template.ImportedFiles = append(template.ImportedFiles, request.Source)
request.Source = val
}
}
}
// for javascript protocol code references
for _, request := range template.RequestsJavascript {
// simple test to check if source is a file or a snippet
if !strings.ContainsRune(request.Code, '\n') && fileutil.FileExists(request.Code) {
if val, ok := loadFile(request.Code); ok {
template.ImportedFiles = append(template.ImportedFiles, request.Code)
request.Code = val
}
}
}
// flow code references
if template.IsFlowTemplate() {
if filepath.Ext(template.Flow) == ".js" && fileutil.FileExists(template.Flow) {
if val, ok := loadFile(template.Flow); ok {
template.ImportedFiles = append(template.ImportedFiles, template.Flow)
template.Flow = val
}
}
options.Flow = template.Flow
}
// for multiprotocol requests
// mutually exclusive with flow
if HasRequest(template.RequestsQueue) && template.Flow == "" {
// this is most likely a multiprotocol template
for _, req := range template.RequestsQueue {
if req.Type() == types.CodeProtocol {
request := req.(*code.Request)
// simple test to check if source is a file or a snippet
if !strings.ContainsRune(request.Source, '\n') && fileutil.FileExists(request.Source) {
if val, ok := loadFile(request.Source); ok {
template.ImportedFiles = append(template.ImportedFiles, request.Source)
request.Source = val
}
}
}
}
// for javascript protocol code references
for _, req := range template.RequestsQueue {
if req.Type() == types.JavascriptProtocol {
request := req.(*javascript.Request)
// simple test to check if source is a file or a snippet
if !strings.ContainsRune(request.Code, '\n') && fileutil.FileExists(request.Code) {
if val, ok := loadFile(request.Code); ok {
template.ImportedFiles = append(template.ImportedFiles, request.Code)
request.Code = val
}
}
}
}
}
return multierr.Combine(errs...)
}
// GetFileImports returns a list of files that are imported by the template
func (template *Template) GetFileImports() []string {
return template.ImportedFiles
}
// addRequestsToQueue adds protocol requests to the queue and preserves order of the protocols and requests
func (template *Template) addRequestsToQueue(keys ...string) {
for _, key := range keys {
switch key {
case types.DNSProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsDNS)...)
case types.FileProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsFile)...)
case types.HTTPProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsHTTP)...)
case types.HeadlessProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsHeadless)...)
case types.NetworkProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsNetwork)...)
case types.SSLProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsSSL)...)
case types.WebsocketProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsWebsocket)...)
case types.WHOISProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsWHOIS)...)
case types.CodeProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsCode)...)
case types.JavascriptProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsJavascript)...)
// for deprecated protocols
case "requests":
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsHTTP)...)
case "network":
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsNetwork)...)
}
}
}
// hasMultipleRequests checks if the template has multiple requests
// if so it preserves the order of the request during compile and execution
func (template *Template) hasMultipleRequests() bool {
counter := len(template.RequestsDNS) + len(template.RequestsFile) +
len(template.RequestsHTTP) + len(template.RequestsHeadless) +
len(template.RequestsNetwork) + len(template.RequestsSSL) +
len(template.RequestsWebsocket) + len(template.RequestsWHOIS) +
len(template.RequestsCode) + len(template.RequestsJavascript)
return counter > 1
}
// MarshalJSON forces recursive struct validation during marshal operation
func (template *Template) MarshalJSON() ([]byte, error) {
type TemplateAlias Template //avoid recursion
out, marshalErr := json.Marshal((*TemplateAlias)(template))
errValidate := tplValidator.Struct(template)
return out, multierr.Append(marshalErr, errValidate)
}
// UnmarshalJSON forces recursive struct validation after unmarshal operation
func (template *Template) UnmarshalJSON(data []byte) error {
type Alias Template
alias := &Alias{}
err := json.Unmarshal(data, alias)
if err != nil {
return err
}
*template = Template(*alias)
err = tplValidator.Struct(template)
if err != nil {
return err
}
// check if the template contains more than 1 protocol request
// if so preserve the order of the protocols and requests
if template.hasMultipleRequests() {
var tempMap map[string]interface{}
err = json.Unmarshal(data, &tempMap)
if err != nil {
return errkit.Wrapf(err, "failed to unmarshal multi protocol template %s", template.ID)
}
arr := []string{}
for k := range tempMap {
arr = append(arr, k)
}
template.addRequestsToQueue(arr...)
}
return nil
}
// Requirements holds the required options for a template to be enabled.
type Requirements struct {
Headless bool
Code bool
DAST bool
SelfContained bool
File bool
}
// Requirements returns what options must be enabled for the template to run.
func (template *Template) Requirements() Requirements {
return Requirements{
Headless: template.HasHeadlessRequest(),
Code: template.HasCodeRequest(),
DAST: template.IsFuzzableRequest(),
SelfContained: template.SelfContained,
File: template.HasFileRequest(),
}
}
// Capabilities represents the enabled options/capabilities.
type Capabilities struct {
Headless bool
Code bool
DAST bool
SelfContained bool
File bool
}
// IsEnabledFor checks if all template requirements are satisfied by the given
// capabilities.
func (template *Template) IsEnabledFor(caps Capabilities) bool {
reqs := template.Requirements()
if reqs.Headless && !caps.Headless {
return false
}
if reqs.Code && !caps.Code {
return false
}
if reqs.DAST && !caps.DAST {
return false
}
if reqs.SelfContained && !caps.SelfContained {
return false
}
if reqs.File && !caps.File {
return false
}
return true
}