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