Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/types/types.go
2070 views
1
package types
2
3
import (
4
"io"
5
"os"
6
"path/filepath"
7
"strings"
8
"sync"
9
"time"
10
11
"github.com/projectdiscovery/goflags"
12
"github.com/projectdiscovery/gologger"
13
"github.com/projectdiscovery/nuclei/v3/pkg/catalog"
14
"github.com/projectdiscovery/nuclei/v3/pkg/catalog/config"
15
"github.com/projectdiscovery/nuclei/v3/pkg/model/types/severity"
16
"github.com/projectdiscovery/nuclei/v3/pkg/templates/types"
17
"github.com/projectdiscovery/utils/errkit"
18
fileutil "github.com/projectdiscovery/utils/file"
19
folderutil "github.com/projectdiscovery/utils/folder"
20
unitutils "github.com/projectdiscovery/utils/unit"
21
)
22
23
var (
24
// ErrNoMoreRequests is internal error to indicate that generator has no more requests to generate
25
ErrNoMoreRequests = io.EOF
26
)
27
28
// LoadHelperFileFunction can be used to load a helper file.
29
type LoadHelperFileFunction func(helperFile, templatePath string, catalog catalog.Catalog) (io.ReadCloser, error)
30
31
// Options contains the configuration options for nuclei scanner.
32
type Options struct {
33
// Tags contains a list of tags to execute templates for. Multiple paths
34
// can be specified with -l flag and -tags can be used in combination with
35
// the -l flag.
36
Tags goflags.StringSlice
37
// ExcludeTags is the list of tags to exclude
38
ExcludeTags goflags.StringSlice
39
// Workflows specifies any workflows to run by nuclei
40
Workflows goflags.StringSlice
41
// WorkflowURLs specifies URLs to a list of workflows to use
42
WorkflowURLs goflags.StringSlice
43
// Templates specifies the template/templates to use
44
Templates goflags.StringSlice
45
// TemplateURLs specifies URLs to a list of templates to use
46
TemplateURLs goflags.StringSlice
47
// AITemplatePrompt specifies prompt to generate template using AI
48
AITemplatePrompt string
49
// RemoteTemplates specifies list of allowed URLs to load remote templates from
50
RemoteTemplateDomainList goflags.StringSlice
51
// ExcludedTemplates specifies the template/templates to exclude
52
ExcludedTemplates goflags.StringSlice
53
// ExcludeMatchers is a list of matchers to exclude processing
54
ExcludeMatchers goflags.StringSlice
55
// CustomHeaders is the list of custom global headers to send with each request.
56
CustomHeaders goflags.StringSlice
57
// Vars is the list of custom global vars
58
Vars goflags.RuntimeMap
59
// Severities filters templates based on their severity and only run the matching ones.
60
Severities severity.Severities
61
// ExcludeSeverities specifies severities to exclude
62
ExcludeSeverities severity.Severities
63
// Authors filters templates based on their author and only run the matching ones.
64
Authors goflags.StringSlice
65
// Protocols contains the protocols to be allowed executed
66
Protocols types.ProtocolTypes
67
// ExcludeProtocols contains protocols to not be executed
68
ExcludeProtocols types.ProtocolTypes
69
// IncludeTags includes specified tags to be run even while being in denylist
70
IncludeTags goflags.StringSlice
71
// IncludeTemplates includes specified templates to be run even while being in denylist
72
IncludeTemplates goflags.StringSlice
73
// IncludeIds includes specified ids to be run even while being in denylist
74
IncludeIds goflags.StringSlice
75
// ExcludeIds contains templates ids to not be executed
76
ExcludeIds goflags.StringSlice
77
// InternalResolversList is the list of internal resolvers to use
78
InternalResolversList []string
79
// ProjectPath allows nuclei to use a user defined project folder
80
ProjectPath string
81
// InteractshURL is the URL for the interactsh server.
82
InteractshURL string
83
// Interactsh Authorization header value for self-hosted servers
84
InteractshToken string
85
// Target URLs/Domains to scan using a template
86
Targets goflags.StringSlice
87
// ExcludeTargets URLs/Domains to exclude from scanning
88
ExcludeTargets goflags.StringSlice
89
// TargetsFilePath specifies the targets from a file to scan using templates.
90
TargetsFilePath string
91
// Resume the scan from the state stored in the resume config file
92
Resume string
93
// Output is the file to write found results to.
94
Output string
95
// ProxyInternal requests
96
ProxyInternal bool
97
// Show all supported DSL signatures
98
ListDslSignatures bool
99
// List of HTTP(s)/SOCKS5 proxy to use (comma separated or file input)
100
Proxy goflags.StringSlice
101
// AliveProxy is the alive proxy to use
102
AliveHttpProxy string
103
// AliveSocksProxy is the alive socks proxy to use
104
AliveSocksProxy string
105
// TemplatesDirectory is the directory to use for storing templates
106
NewTemplatesDirectory string
107
// TraceLogFile specifies a file to write with the trace of all requests
108
TraceLogFile string
109
// ErrorLogFile specifies a file to write with the errors of all requests
110
ErrorLogFile string
111
// ReportingDB is the db for report storage as well as deduplication
112
ReportingDB string
113
// ReportingConfig is the config file for nuclei reporting module
114
ReportingConfig string
115
// MarkdownExportDirectory is the directory to export reports in Markdown format
116
MarkdownExportDirectory string
117
// MarkdownExportSortMode is the method to sort the markdown reports (options: severity, template, host, none)
118
MarkdownExportSortMode string
119
// SarifExport is the file to export sarif output format to
120
SarifExport string
121
// ResolversFile is a file containing resolvers for nuclei.
122
ResolversFile string
123
// StatsInterval is the number of seconds to display stats after
124
StatsInterval int
125
// MetricsPort is the port to show metrics on
126
MetricsPort int
127
// MaxHostError is the maximum number of errors allowed for a host
128
MaxHostError int
129
// TrackError contains additional error messages that count towards the maximum number of errors allowed for a host
130
TrackError goflags.StringSlice
131
// NoHostErrors disables host skipping after maximum number of errors
132
NoHostErrors bool
133
// BulkSize is the of targets analyzed in parallel for each template
134
BulkSize int
135
// TemplateThreads is the number of templates executed in parallel
136
TemplateThreads int
137
// HeadlessBulkSize is the of targets analyzed in parallel for each headless template
138
HeadlessBulkSize int
139
// HeadlessTemplateThreads is the number of headless templates executed in parallel
140
HeadlessTemplateThreads int
141
// Timeout is the seconds to wait for a response from the server.
142
Timeout int
143
// Retries is the number of times to retry the request
144
Retries int
145
// Rate-Limit is the maximum number of requests per specified target
146
RateLimit int
147
// Rate Limit Duration interval between burst resets
148
RateLimitDuration time.Duration
149
// Rate-Limit is the maximum number of requests per minute for specified target
150
// Deprecated: Use RateLimitDuration - automatically set Rate Limit Duration to 60 seconds
151
RateLimitMinute int
152
// PageTimeout is the maximum time to wait for a page in seconds
153
PageTimeout int
154
// InteractionsCacheSize is the number of interaction-url->req to keep in cache at a time.
155
InteractionsCacheSize int
156
// InteractionsPollDuration is the number of seconds to wait before each interaction poll
157
InteractionsPollDuration int
158
// Eviction is the number of seconds after which to automatically discard
159
// interaction requests.
160
InteractionsEviction int
161
// InteractionsCoolDownPeriod is additional seconds to wait for interactions after closing
162
// of the poller.
163
InteractionsCoolDownPeriod int
164
// MaxRedirects is the maximum numbers of redirects to be followed.
165
MaxRedirects int
166
// FollowRedirects enables following redirects for http request module
167
FollowRedirects bool
168
// FollowRedirects enables following redirects for http request module only on the same host
169
FollowHostRedirects bool
170
// OfflineHTTP is a flag that specific offline processing of http response
171
// using same matchers/extractors from http protocol without the need
172
// to send a new request, reading responses from a file.
173
OfflineHTTP bool
174
// Force HTTP2 requests
175
ForceAttemptHTTP2 bool
176
// StatsJSON writes stats output in JSON format
177
StatsJSON bool
178
// Headless specifies whether to allow headless mode templates
179
Headless bool
180
// ShowBrowser specifies whether the show the browser in headless mode
181
ShowBrowser bool
182
// HeadlessOptionalArguments specifies optional arguments to pass to Chrome
183
HeadlessOptionalArguments goflags.StringSlice
184
// DisableClustering disables clustering of templates
185
DisableClustering bool
186
// UseInstalledChrome skips chrome install and use local instance
187
UseInstalledChrome bool
188
// SystemResolvers enables override of nuclei's DNS client opting to use system resolver stack.
189
SystemResolvers bool
190
// ShowActions displays a list of all headless actions
191
ShowActions bool
192
// Deprecated: Enabled by default through clistats . Metrics enables display of metrics via an http endpoint
193
Metrics bool
194
// Debug mode allows debugging request/responses for the engine
195
Debug bool
196
// DebugRequests mode allows debugging request for the engine
197
DebugRequests bool
198
// DebugResponse mode allows debugging response for the engine
199
DebugResponse bool
200
// DisableHTTPProbe disables http probing feature of input normalization
201
DisableHTTPProbe bool
202
// LeaveDefaultPorts skips normalization of default ports
203
LeaveDefaultPorts bool
204
// AutomaticScan enables automatic tech based template execution
205
AutomaticScan bool
206
// Silent suppresses any extra text and only writes found URLs on screen.
207
Silent bool
208
// Validate validates the templates passed to nuclei.
209
Validate bool
210
// NoStrictSyntax disables strict syntax check on nuclei templates (allows custom key-value pairs).
211
NoStrictSyntax bool
212
// Verbose flag indicates whether to show verbose output or not
213
Verbose bool
214
VerboseVerbose bool
215
// ShowVarDump displays variable dump
216
ShowVarDump bool
217
// VarDumpLimit limits the number of characters displayed in var dump
218
VarDumpLimit int
219
// No-Color disables the colored output.
220
NoColor bool
221
// UpdateTemplates updates the templates installed at startup (also used by cloud to update datasources)
222
UpdateTemplates bool
223
// JSON writes json line output to files
224
JSONL bool
225
// JSONRequests writes requests/responses for matches in JSON output
226
// Deprecated: use OmitRawRequests instead as of now JSONRequests(include raw requests) is always true
227
JSONRequests bool
228
// OmitRawRequests omits requests/responses for matches in JSON output
229
OmitRawRequests bool
230
// HTTPStats enables http statistics tracking and display.
231
HTTPStats bool
232
// OmitTemplate omits encoded template from JSON output
233
OmitTemplate bool
234
// JSONExport is the file to export JSON output format to
235
JSONExport string
236
// JSONLExport is the file to export JSONL output format to
237
JSONLExport string
238
// Redact redacts given keys in
239
Redact goflags.StringSlice
240
// EnableProgressBar enables progress bar
241
EnableProgressBar bool
242
// TemplateDisplay displays the template contents
243
TemplateDisplay bool
244
// TemplateList lists available templates
245
TemplateList bool
246
// TemplateList lists available tags
247
TagList bool
248
// HangMonitor enables nuclei hang monitoring
249
HangMonitor bool
250
// Stdin specifies whether stdin input was given to the process
251
Stdin bool
252
// StopAtFirstMatch stops processing template at first full match (this may break chained requests)
253
StopAtFirstMatch bool
254
// Stream the input without sorting
255
Stream bool
256
// NoMeta disables display of metadata for the matches
257
NoMeta bool
258
// Timestamp enables display of timestamp for the matcher
259
Timestamp bool
260
// Project is used to avoid sending same HTTP request multiple times
261
Project bool
262
// NewTemplates only runs newly added templates from the repository
263
NewTemplates bool
264
// NewTemplatesWithVersion runs new templates added in specific version
265
NewTemplatesWithVersion goflags.StringSlice
266
// NoInteractsh disables use of interactsh server for interaction polling
267
NoInteractsh bool
268
// EnvironmentVariables enables support for environment variables
269
EnvironmentVariables bool
270
// MatcherStatus displays optional status for the failed matches as well
271
MatcherStatus bool
272
// ClientCertFile client certificate file (PEM-encoded) used for authenticating against scanned hosts
273
ClientCertFile string
274
// ClientKeyFile client key file (PEM-encoded) used for authenticating against scanned hosts
275
ClientKeyFile string
276
// ClientCAFile client certificate authority file (PEM-encoded) used for authenticating against scanned hosts
277
ClientCAFile string
278
// Deprecated: Use ZTLS library
279
ZTLS bool
280
// AllowLocalFileAccess allows local file access from templates payloads
281
AllowLocalFileAccess bool
282
// RestrictLocalNetworkAccess restricts local network access from templates requests
283
RestrictLocalNetworkAccess bool
284
// ShowMatchLine enables display of match line number
285
ShowMatchLine bool
286
// EnablePprof enables exposing pprof runtime information with a webserver.
287
EnablePprof bool
288
// StoreResponse stores received response to output directory
289
StoreResponse bool
290
// StoreResponseDir stores received response to custom directory
291
StoreResponseDir string
292
// DisableRedirects disables following redirects for http request module
293
DisableRedirects bool
294
// SNI custom hostname
295
SNI string
296
// InputFileMode specifies the mode of input file (jsonl, burp, openapi, swagger, etc)
297
InputFileMode string
298
// DialerKeepAlive sets the keep alive duration for network requests.
299
DialerKeepAlive time.Duration
300
// Interface to use for network scan
301
Interface string
302
// SourceIP sets custom source IP address for network requests
303
SourceIP string
304
// AttackType overrides template level attack-type configuration
305
AttackType string
306
// ResponseReadSize is the maximum size of response to read
307
ResponseReadSize int
308
// ResponseSaveSize is the maximum size of response to save
309
ResponseSaveSize int
310
// Health Check
311
HealthCheck bool
312
// Time to wait between each input read operation before closing the stream
313
InputReadTimeout time.Duration
314
// Disable stdin for input processing
315
DisableStdin bool
316
// IncludeConditions is the list of conditions templates should match
317
IncludeConditions goflags.StringSlice
318
// Enable uncover engine
319
Uncover bool
320
// Uncover search query
321
UncoverQuery goflags.StringSlice
322
// Uncover search engine
323
UncoverEngine goflags.StringSlice
324
// Uncover search field
325
UncoverField string
326
// Uncover search limit
327
UncoverLimit int
328
// Uncover search delay
329
UncoverRateLimit int
330
// ScanAllIPs associated to a dns record
331
ScanAllIPs bool
332
// IPVersion to scan (4,6)
333
IPVersion goflags.StringSlice
334
// PublicTemplateDisableDownload disables downloading templates from the nuclei-templates public repository
335
PublicTemplateDisableDownload bool
336
// GitHub token used to clone/pull from private repos for custom templates
337
GitHubToken string
338
// GitHubTemplateRepo is the list of custom public/private templates GitHub repos
339
GitHubTemplateRepo []string
340
// GitHubTemplateDisableDownload disables downloading templates from custom GitHub repositories
341
GitHubTemplateDisableDownload bool
342
// GitLabServerURL is the gitlab server to use for custom templates
343
GitLabServerURL string
344
// GitLabToken used to clone/pull from private repos for custom templates
345
GitLabToken string
346
// GitLabTemplateRepositoryIDs is the comma-separated list of custom gitlab repositories IDs
347
GitLabTemplateRepositoryIDs []int
348
// GitLabTemplateDisableDownload disables downloading templates from custom GitLab repositories
349
GitLabTemplateDisableDownload bool
350
// AWS access profile from ~/.aws/credentials file for downloading templates from S3 bucket
351
AwsProfile string
352
// AWS access key for downloading templates from S3 bucket
353
AwsAccessKey string
354
// AWS secret key for downloading templates from S3 bucket
355
AwsSecretKey string
356
// AWS bucket name for downloading templates from S3 bucket
357
AwsBucketName string
358
// AWS Region name where AWS S3 bucket is located
359
AwsRegion string
360
// AwsTemplateDisableDownload disables downloading templates from AWS S3 buckets
361
AwsTemplateDisableDownload bool
362
// AzureContainerName for downloading templates from Azure Blob Storage. Example: templates
363
AzureContainerName string
364
// AzureTenantID for downloading templates from Azure Blob Storage. Example: 00000000-0000-0000-0000-000000000000
365
AzureTenantID string
366
// AzureClientID for downloading templates from Azure Blob Storage. Example: 00000000-0000-0000-0000-000000000000
367
AzureClientID string
368
// AzureClientSecret for downloading templates from Azure Blob Storage. Example: 00000000-0000-0000-0000-000000000000
369
AzureClientSecret string
370
// AzureServiceURL for downloading templates from Azure Blob Storage. Example: https://XXXXXXXXXX.blob.core.windows.net/
371
AzureServiceURL string
372
// AzureTemplateDisableDownload disables downloading templates from Azure Blob Storage
373
AzureTemplateDisableDownload bool
374
// Scan Strategy (auto,hosts-spray,templates-spray)
375
ScanStrategy string
376
// Fuzzing Type overrides template level fuzzing-type configuration
377
FuzzingType string
378
// Fuzzing Mode overrides template level fuzzing-mode configuration
379
FuzzingMode string
380
// TlsImpersonate enables TLS impersonation
381
TlsImpersonate bool
382
// DisplayFuzzPoints enables display of fuzz points for fuzzing
383
DisplayFuzzPoints bool
384
// FuzzAggressionLevel is the level of fuzzing aggression (low, medium, high.)
385
FuzzAggressionLevel string
386
// FuzzParamFrequency is the frequency of fuzzing parameters
387
FuzzParamFrequency int
388
// CodeTemplateSignaturePublicKey is the custom public key used to verify the template signature (algorithm is automatically inferred from the length)
389
CodeTemplateSignaturePublicKey string
390
// CodeTemplateSignatureAlgorithm specifies the sign algorithm (rsa, ecdsa)
391
CodeTemplateSignatureAlgorithm string
392
// SignTemplates enables signing of templates
393
SignTemplates bool
394
// EnableCodeTemplates enables code templates
395
EnableCodeTemplates bool
396
// DisableUnsignedTemplates disables processing of unsigned templates
397
DisableUnsignedTemplates bool
398
// EnableSelfContainedTemplates enables processing of self-contained templates
399
EnableSelfContainedTemplates bool
400
// EnableGlobalMatchersTemplates enables processing of global-matchers templates
401
EnableGlobalMatchersTemplates bool
402
// EnableFileTemplates enables file templates
403
EnableFileTemplates bool
404
// Disables cloud upload
405
EnableCloudUpload bool
406
// ScanID is the scan ID to use for cloud upload
407
ScanID string
408
// ScanName is the name of the scan to be uploaded
409
ScanName string
410
// ScanUploadFile is the jsonl file to upload scan results to cloud
411
ScanUploadFile string
412
// TeamID is the team ID to use for cloud upload
413
TeamID string
414
// JsConcurrency is the number of concurrent js routines to run
415
JsConcurrency int
416
// SecretsFile is file containing secrets for nuclei
417
SecretsFile goflags.StringSlice
418
// PreFetchSecrets pre-fetches the secrets from the auth provider
419
PreFetchSecrets bool
420
// FormatUseRequiredOnly only uses required fields when generating requests
421
FormatUseRequiredOnly bool
422
// SkipFormatValidation is used to skip format validation
423
SkipFormatValidation bool
424
// PayloadConcurrency is the number of concurrent payloads to run per template
425
PayloadConcurrency int
426
// ProbeConcurrency is the number of concurrent http probes to run with httpx
427
ProbeConcurrency int
428
// Dast only runs DAST templates
429
DAST bool
430
// DASTServer is the flag to start nuclei as a DAST server
431
DASTServer bool
432
// DASTServerToken is the token optional for the dast server
433
DASTServerToken string
434
// DASTServerAddress is the address for the dast server
435
DASTServerAddress string
436
// DASTReport enables dast report server & final report generation
437
DASTReport bool
438
// Scope contains a list of regexes for in-scope URLS
439
Scope goflags.StringSlice
440
// OutOfScope contains a list of regexes for out-scope URLS
441
OutOfScope goflags.StringSlice
442
// HttpApiEndpoint is the experimental http api endpoint
443
HttpApiEndpoint string
444
// ListTemplateProfiles lists all available template profiles
445
ListTemplateProfiles bool
446
// LoadHelperFileFunction is a function that will be used to execute LoadHelperFile.
447
// If none is provided, then the default implementation will be used.
448
LoadHelperFileFunction LoadHelperFileFunction
449
// Logger is the gologger instance for this optionset
450
Logger *gologger.Logger
451
// NoCacheTemplates disables caching of templates
452
DoNotCacheTemplates bool
453
// Unique identifier of the execution session
454
ExecutionId string
455
// Parser is a cached parser for the template store
456
Parser any
457
// timeouts contains various types of timeouts used in nuclei
458
// these timeouts are derived from dial-timeout (-timeout) with known multipliers
459
// This is internally managed and does not need to be set by user by explicitly setting
460
// this overrides the default/derived one
461
timeouts *Timeouts
462
// m is a mutex to protect timeouts from concurrent access
463
m sync.Mutex
464
}
465
466
func (options *Options) Copy() *Options {
467
optCopy := &Options{
468
Tags: options.Tags,
469
ExcludeTags: options.ExcludeTags,
470
Workflows: options.Workflows,
471
WorkflowURLs: options.WorkflowURLs,
472
Templates: options.Templates,
473
TemplateURLs: options.TemplateURLs,
474
AITemplatePrompt: options.AITemplatePrompt,
475
RemoteTemplateDomainList: options.RemoteTemplateDomainList,
476
ExcludedTemplates: options.ExcludedTemplates,
477
ExcludeMatchers: options.ExcludeMatchers,
478
CustomHeaders: options.CustomHeaders,
479
Vars: options.Vars,
480
Severities: options.Severities,
481
ExcludeSeverities: options.ExcludeSeverities,
482
Authors: options.Authors,
483
Protocols: options.Protocols,
484
ExcludeProtocols: options.ExcludeProtocols,
485
IncludeTags: options.IncludeTags,
486
IncludeTemplates: options.IncludeTemplates,
487
IncludeIds: options.IncludeIds,
488
ExcludeIds: options.ExcludeIds,
489
InternalResolversList: options.InternalResolversList,
490
ProjectPath: options.ProjectPath,
491
InteractshURL: options.InteractshURL,
492
InteractshToken: options.InteractshToken,
493
Targets: options.Targets,
494
ExcludeTargets: options.ExcludeTargets,
495
TargetsFilePath: options.TargetsFilePath,
496
Resume: options.Resume,
497
Output: options.Output,
498
ProxyInternal: options.ProxyInternal,
499
ListDslSignatures: options.ListDslSignatures,
500
Proxy: options.Proxy,
501
AliveHttpProxy: options.AliveHttpProxy,
502
AliveSocksProxy: options.AliveSocksProxy,
503
NewTemplatesDirectory: options.NewTemplatesDirectory,
504
TraceLogFile: options.TraceLogFile,
505
ErrorLogFile: options.ErrorLogFile,
506
ReportingDB: options.ReportingDB,
507
ReportingConfig: options.ReportingConfig,
508
MarkdownExportDirectory: options.MarkdownExportDirectory,
509
MarkdownExportSortMode: options.MarkdownExportSortMode,
510
SarifExport: options.SarifExport,
511
ResolversFile: options.ResolversFile,
512
StatsInterval: options.StatsInterval,
513
MetricsPort: options.MetricsPort,
514
MaxHostError: options.MaxHostError,
515
TrackError: options.TrackError,
516
NoHostErrors: options.NoHostErrors,
517
BulkSize: options.BulkSize,
518
TemplateThreads: options.TemplateThreads,
519
HeadlessBulkSize: options.HeadlessBulkSize,
520
HeadlessTemplateThreads: options.HeadlessTemplateThreads,
521
Timeout: options.Timeout,
522
Retries: options.Retries,
523
RateLimit: options.RateLimit,
524
RateLimitDuration: options.RateLimitDuration,
525
RateLimitMinute: options.RateLimitMinute,
526
PageTimeout: options.PageTimeout,
527
InteractionsCacheSize: options.InteractionsCacheSize,
528
InteractionsPollDuration: options.InteractionsPollDuration,
529
InteractionsEviction: options.InteractionsEviction,
530
InteractionsCoolDownPeriod: options.InteractionsCoolDownPeriod,
531
MaxRedirects: options.MaxRedirects,
532
FollowRedirects: options.FollowRedirects,
533
FollowHostRedirects: options.FollowHostRedirects,
534
OfflineHTTP: options.OfflineHTTP,
535
ForceAttemptHTTP2: options.ForceAttemptHTTP2,
536
StatsJSON: options.StatsJSON,
537
Headless: options.Headless,
538
ShowBrowser: options.ShowBrowser,
539
HeadlessOptionalArguments: options.HeadlessOptionalArguments,
540
DisableClustering: options.DisableClustering,
541
UseInstalledChrome: options.UseInstalledChrome,
542
SystemResolvers: options.SystemResolvers,
543
ShowActions: options.ShowActions,
544
Metrics: options.Metrics,
545
Debug: options.Debug,
546
DebugRequests: options.DebugRequests,
547
DebugResponse: options.DebugResponse,
548
DisableHTTPProbe: options.DisableHTTPProbe,
549
LeaveDefaultPorts: options.LeaveDefaultPorts,
550
AutomaticScan: options.AutomaticScan,
551
Silent: options.Silent,
552
Validate: options.Validate,
553
NoStrictSyntax: options.NoStrictSyntax,
554
Verbose: options.Verbose,
555
VerboseVerbose: options.VerboseVerbose,
556
ShowVarDump: options.ShowVarDump,
557
VarDumpLimit: options.VarDumpLimit,
558
NoColor: options.NoColor,
559
UpdateTemplates: options.UpdateTemplates,
560
JSONL: options.JSONL,
561
JSONRequests: options.JSONRequests,
562
OmitRawRequests: options.OmitRawRequests,
563
HTTPStats: options.HTTPStats,
564
OmitTemplate: options.OmitTemplate,
565
JSONExport: options.JSONExport,
566
JSONLExport: options.JSONLExport,
567
Redact: options.Redact,
568
EnableProgressBar: options.EnableProgressBar,
569
TemplateDisplay: options.TemplateDisplay,
570
TemplateList: options.TemplateList,
571
TagList: options.TagList,
572
HangMonitor: options.HangMonitor,
573
Stdin: options.Stdin,
574
StopAtFirstMatch: options.StopAtFirstMatch,
575
Stream: options.Stream,
576
NoMeta: options.NoMeta,
577
Timestamp: options.Timestamp,
578
Project: options.Project,
579
NewTemplates: options.NewTemplates,
580
NewTemplatesWithVersion: options.NewTemplatesWithVersion,
581
NoInteractsh: options.NoInteractsh,
582
EnvironmentVariables: options.EnvironmentVariables,
583
MatcherStatus: options.MatcherStatus,
584
ClientCertFile: options.ClientCertFile,
585
ClientKeyFile: options.ClientKeyFile,
586
ClientCAFile: options.ClientCAFile,
587
ZTLS: options.ZTLS,
588
AllowLocalFileAccess: options.AllowLocalFileAccess,
589
RestrictLocalNetworkAccess: options.RestrictLocalNetworkAccess,
590
ShowMatchLine: options.ShowMatchLine,
591
EnablePprof: options.EnablePprof,
592
StoreResponse: options.StoreResponse,
593
StoreResponseDir: options.StoreResponseDir,
594
DisableRedirects: options.DisableRedirects,
595
SNI: options.SNI,
596
InputFileMode: options.InputFileMode,
597
DialerKeepAlive: options.DialerKeepAlive,
598
Interface: options.Interface,
599
SourceIP: options.SourceIP,
600
AttackType: options.AttackType,
601
ResponseReadSize: options.ResponseReadSize,
602
ResponseSaveSize: options.ResponseSaveSize,
603
HealthCheck: options.HealthCheck,
604
InputReadTimeout: options.InputReadTimeout,
605
DisableStdin: options.DisableStdin,
606
IncludeConditions: options.IncludeConditions,
607
Uncover: options.Uncover,
608
UncoverQuery: options.UncoverQuery,
609
UncoverEngine: options.UncoverEngine,
610
UncoverField: options.UncoverField,
611
UncoverLimit: options.UncoverLimit,
612
UncoverRateLimit: options.UncoverRateLimit,
613
ScanAllIPs: options.ScanAllIPs,
614
IPVersion: options.IPVersion,
615
PublicTemplateDisableDownload: options.PublicTemplateDisableDownload,
616
GitHubToken: options.GitHubToken,
617
GitHubTemplateRepo: options.GitHubTemplateRepo,
618
GitHubTemplateDisableDownload: options.GitHubTemplateDisableDownload,
619
GitLabServerURL: options.GitLabServerURL,
620
GitLabToken: options.GitLabToken,
621
GitLabTemplateRepositoryIDs: options.GitLabTemplateRepositoryIDs,
622
GitLabTemplateDisableDownload: options.GitLabTemplateDisableDownload,
623
AwsProfile: options.AwsProfile,
624
AwsAccessKey: options.AwsAccessKey,
625
AwsSecretKey: options.AwsSecretKey,
626
AwsBucketName: options.AwsBucketName,
627
AwsRegion: options.AwsRegion,
628
AwsTemplateDisableDownload: options.AwsTemplateDisableDownload,
629
AzureContainerName: options.AzureContainerName,
630
AzureTenantID: options.AzureTenantID,
631
AzureClientID: options.AzureClientID,
632
AzureClientSecret: options.AzureClientSecret,
633
AzureServiceURL: options.AzureServiceURL,
634
AzureTemplateDisableDownload: options.AzureTemplateDisableDownload,
635
ScanStrategy: options.ScanStrategy,
636
FuzzingType: options.FuzzingType,
637
FuzzingMode: options.FuzzingMode,
638
TlsImpersonate: options.TlsImpersonate,
639
DisplayFuzzPoints: options.DisplayFuzzPoints,
640
FuzzAggressionLevel: options.FuzzAggressionLevel,
641
FuzzParamFrequency: options.FuzzParamFrequency,
642
CodeTemplateSignaturePublicKey: options.CodeTemplateSignaturePublicKey,
643
CodeTemplateSignatureAlgorithm: options.CodeTemplateSignatureAlgorithm,
644
SignTemplates: options.SignTemplates,
645
EnableCodeTemplates: options.EnableCodeTemplates,
646
DisableUnsignedTemplates: options.DisableUnsignedTemplates,
647
EnableSelfContainedTemplates: options.EnableSelfContainedTemplates,
648
EnableGlobalMatchersTemplates: options.EnableGlobalMatchersTemplates,
649
EnableFileTemplates: options.EnableFileTemplates,
650
EnableCloudUpload: options.EnableCloudUpload,
651
ScanID: options.ScanID,
652
ScanName: options.ScanName,
653
ScanUploadFile: options.ScanUploadFile,
654
TeamID: options.TeamID,
655
JsConcurrency: options.JsConcurrency,
656
SecretsFile: options.SecretsFile,
657
PreFetchSecrets: options.PreFetchSecrets,
658
FormatUseRequiredOnly: options.FormatUseRequiredOnly,
659
SkipFormatValidation: options.SkipFormatValidation,
660
PayloadConcurrency: options.PayloadConcurrency,
661
ProbeConcurrency: options.ProbeConcurrency,
662
DAST: options.DAST,
663
DASTServer: options.DASTServer,
664
DASTServerToken: options.DASTServerToken,
665
DASTServerAddress: options.DASTServerAddress,
666
DASTReport: options.DASTReport,
667
Scope: options.Scope,
668
OutOfScope: options.OutOfScope,
669
HttpApiEndpoint: options.HttpApiEndpoint,
670
ListTemplateProfiles: options.ListTemplateProfiles,
671
LoadHelperFileFunction: options.LoadHelperFileFunction,
672
Logger: options.Logger,
673
DoNotCacheTemplates: options.DoNotCacheTemplates,
674
ExecutionId: options.ExecutionId,
675
Parser: options.Parser,
676
}
677
optCopy.SetTimeouts(options.timeouts)
678
return optCopy
679
}
680
681
// SetTimeouts sets the timeout variants to use for the executor
682
func (opts *Options) SetTimeouts(t *Timeouts) {
683
opts.timeouts = t
684
}
685
686
// GetTimeouts returns the timeout variants to use for the executor
687
func (eo *Options) GetTimeouts() *Timeouts {
688
eo.m.Lock()
689
defer eo.m.Unlock()
690
if eo.timeouts != nil {
691
// redundant but apply to avoid any potential issues
692
eo.timeouts.ApplyDefaults()
693
return eo.timeouts
694
}
695
// set timeout variant value
696
eo.timeouts = NewTimeoutVariant(eo.Timeout)
697
eo.timeouts.ApplyDefaults()
698
return eo.timeouts
699
}
700
701
// Timeouts is a struct that contains all the timeout variants for nuclei
702
// dialer timeout is used to derive other timeouts
703
type Timeouts struct {
704
// DialTimeout for fastdialer (default 10s)
705
DialTimeout time.Duration
706
// Tcp(Network Protocol) Read From Connection Timeout (default 5s)
707
TcpReadTimeout time.Duration
708
// Http Response Header Timeout (default 10s)
709
// this timeout prevents infinite hangs started by server if any
710
// this is temporarily overridden when using @timeout request annotation
711
HttpResponseHeaderTimeout time.Duration
712
// HttpTimeout for http client (default -> 3 x dial-timeout = 30s)
713
HttpTimeout time.Duration
714
// JsCompilerExec timeout/deadline (default -> 2 x dial-timeout = 20s)
715
JsCompilerExecutionTimeout time.Duration
716
// CodeExecutionTimeout for code execution (default -> 3 x dial-timeout = 30s)
717
CodeExecutionTimeout time.Duration
718
}
719
720
// NewTimeoutVariant creates a new timeout variant with the given dial timeout in seconds
721
func NewTimeoutVariant(dialTimeoutSec int) *Timeouts {
722
tv := &Timeouts{
723
DialTimeout: time.Duration(dialTimeoutSec) * time.Second,
724
}
725
tv.ApplyDefaults()
726
return tv
727
}
728
729
// ApplyDefaults applies default values to timeout variants when missing
730
func (tv *Timeouts) ApplyDefaults() {
731
if tv.DialTimeout == 0 {
732
tv.DialTimeout = 10 * time.Second
733
}
734
if tv.TcpReadTimeout == 0 {
735
tv.TcpReadTimeout = 5 * time.Second
736
}
737
if tv.HttpResponseHeaderTimeout == 0 {
738
tv.HttpResponseHeaderTimeout = 10 * time.Second
739
}
740
if tv.HttpTimeout == 0 {
741
tv.HttpTimeout = 3 * tv.DialTimeout
742
}
743
if tv.JsCompilerExecutionTimeout == 0 {
744
tv.JsCompilerExecutionTimeout = 2 * tv.DialTimeout
745
}
746
if tv.CodeExecutionTimeout == 0 {
747
tv.CodeExecutionTimeout = 3 * tv.DialTimeout
748
}
749
}
750
751
// ShouldLoadResume resume file
752
func (options *Options) ShouldLoadResume() bool {
753
return options.Resume != "" && fileutil.FileExists(options.Resume)
754
}
755
756
// ShouldSaveResume file
757
func (options *Options) ShouldSaveResume() bool {
758
return true
759
}
760
761
// ShouldFollowHTTPRedirects determines if http redirects should be followed
762
func (options *Options) ShouldFollowHTTPRedirects() bool {
763
return options.FollowRedirects || options.FollowHostRedirects
764
}
765
766
// HasClientCertificates determines if any client certificate was specified
767
func (options *Options) HasClientCertificates() bool {
768
return options.ClientCertFile != "" || options.ClientCAFile != "" || options.ClientKeyFile != ""
769
}
770
771
// DefaultOptions returns default options for nuclei
772
func DefaultOptions() *Options {
773
return &Options{
774
RateLimit: 150,
775
RateLimitDuration: time.Second,
776
BulkSize: 25,
777
TemplateThreads: 25,
778
HeadlessBulkSize: 10,
779
PayloadConcurrency: 25,
780
HeadlessTemplateThreads: 10,
781
ProbeConcurrency: 50,
782
Timeout: 5,
783
Retries: 1,
784
MaxHostError: 30,
785
ResponseReadSize: 10 * unitutils.Mega,
786
ResponseSaveSize: unitutils.Mega,
787
}
788
}
789
790
func (options *Options) ShouldUseHostError() bool {
791
return options.MaxHostError > 0 && !options.NoHostErrors
792
}
793
794
func (options *Options) ParseHeadlessOptionalArguments() map[string]string {
795
optionalArguments := make(map[string]string)
796
for _, v := range options.HeadlessOptionalArguments {
797
if argParts := strings.SplitN(v, "=", 2); len(argParts) >= 2 {
798
key := strings.TrimSpace(argParts[0])
799
value := strings.TrimSpace(argParts[1])
800
if key != "" && value != "" {
801
optionalArguments[key] = value
802
}
803
}
804
}
805
return optionalArguments
806
}
807
808
// LoadHelperFile loads a helper file needed for the template.
809
//
810
// If LoadHelperFileFunction is set, then that function will be used.
811
// Otherwise, the default implementation will be used, which respects the sandbox rules and only loads files from allowed directories.
812
func (options *Options) LoadHelperFile(helperFile, templatePath string, catalog catalog.Catalog) (io.ReadCloser, error) {
813
if options.LoadHelperFileFunction != nil {
814
return options.LoadHelperFileFunction(helperFile, templatePath, catalog)
815
}
816
return options.defaultLoadHelperFile(helperFile, templatePath, catalog)
817
}
818
819
// defaultLoadHelperFile loads a helper file needed for the template
820
// this respects the sandbox rules and only loads files from
821
// allowed directories
822
func (options *Options) defaultLoadHelperFile(helperFile, templatePath string, catalog catalog.Catalog) (io.ReadCloser, error) {
823
if !options.AllowLocalFileAccess {
824
// if global file access is disabled try loading with restrictions
825
absPath, err := options.GetValidAbsPath(helperFile, templatePath)
826
if err != nil {
827
return nil, err
828
}
829
helperFile = absPath
830
}
831
f, err := os.Open(helperFile)
832
if err != nil {
833
return nil, errkit.Wrapf(err, "could not open file %v", helperFile)
834
}
835
return f, nil
836
}
837
838
// GetValidAbsPath returns absolute path of helper file if it is allowed to be loaded
839
// this respects the sandbox rules and only loads files from allowed directories
840
func (o *Options) GetValidAbsPath(helperFilePath, templatePath string) (string, error) {
841
// Conditions to allow helper file
842
// 1. If helper file is present in nuclei-templates directory
843
// 2. If helper file and template file are in same directory given that its not root directory
844
845
// resolve and clean helper file path
846
// ResolveNClean uses a custom base path instead of CWD
847
resolvedPath, err := fileutil.ResolveNClean(helperFilePath, config.DefaultConfig.GetTemplateDir())
848
if err == nil {
849
// As per rule 1, if helper file is present in nuclei-templates directory, allow it
850
if strings.HasPrefix(resolvedPath, config.DefaultConfig.GetTemplateDir()) {
851
return resolvedPath, nil
852
}
853
}
854
855
// CleanPath resolves using CWD and cleans the path
856
helperFilePath, err = fileutil.CleanPath(helperFilePath)
857
if err != nil {
858
return "", errkit.Wrapf(err, "could not clean helper file path %v", helperFilePath)
859
}
860
861
templatePath, err = fileutil.CleanPath(templatePath)
862
if err != nil {
863
return "", errkit.Wrapf(err, "could not clean template path %v", templatePath)
864
}
865
866
// As per rule 2, if template and helper file exist in same directory or helper file existed in any child dir of template dir
867
// and both of them are present in user home directory, allow it
868
// Review: should we keep this rule ? add extra option to disable this ?
869
if isHomeDir(helperFilePath) && isHomeDir(templatePath) && strings.HasPrefix(filepath.Dir(helperFilePath), filepath.Dir(templatePath)) {
870
return helperFilePath, nil
871
}
872
873
// all other cases are denied
874
return "", errkit.Newf("access to helper file %v denied", helperFilePath)
875
}
876
877
// SetExecutionID sets the execution ID for the options
878
func (options *Options) SetExecutionID(id string) {
879
options.m.Lock()
880
defer options.m.Unlock()
881
options.ExecutionId = id
882
}
883
884
// GetExecutionID gets the execution ID for the options
885
func (options *Options) GetExecutionID() string {
886
options.m.Lock()
887
defer options.m.Unlock()
888
return options.ExecutionId
889
}
890
891
// isHomeDir checks if given is home directory
892
func isHomeDir(path string) bool {
893
homeDir := folderutil.HomeDirOrDefault("")
894
return strings.HasPrefix(path, homeDir)
895
}
896
897