package types12import (3"io"4"os"5"path/filepath"6"strings"7"sync"8"time"910"github.com/projectdiscovery/goflags"11"github.com/projectdiscovery/gologger"12"github.com/projectdiscovery/nuclei/v3/pkg/catalog"13"github.com/projectdiscovery/nuclei/v3/pkg/catalog/config"14"github.com/projectdiscovery/nuclei/v3/pkg/model/types/severity"15"github.com/projectdiscovery/nuclei/v3/pkg/templates/types"16"github.com/projectdiscovery/utils/errkit"17fileutil "github.com/projectdiscovery/utils/file"18folderutil "github.com/projectdiscovery/utils/folder"19unitutils "github.com/projectdiscovery/utils/unit"20"github.com/rs/xid"21)2223const DefaultTemplateLoadingConcurrency = 502425var (26// ErrNoMoreRequests is internal error to indicate that generator has no more requests to generate27ErrNoMoreRequests = io.EOF28)2930// LoadHelperFileFunction can be used to load a helper file.31type LoadHelperFileFunction func(helperFile, templatePath string, catalog catalog.Catalog) (io.ReadCloser, error)3233// Options contains the configuration options for nuclei scanner.34type Options struct {35// Tags contains a list of tags to execute templates for. Multiple paths36// can be specified with -l flag and -tags can be used in combination with37// the -l flag.38Tags goflags.StringSlice39// ExcludeTags is the list of tags to exclude40ExcludeTags goflags.StringSlice41// Workflows specifies any workflows to run by nuclei42Workflows goflags.StringSlice43// WorkflowURLs specifies URLs to a list of workflows to use44WorkflowURLs goflags.StringSlice45// Templates specifies the template/templates to use46Templates goflags.StringSlice47// TemplateURLs specifies URLs to a list of templates to use48TemplateURLs goflags.StringSlice49// AITemplatePrompt specifies prompt to generate template using AI50AITemplatePrompt string51// RemoteTemplates specifies list of allowed URLs to load remote templates from52RemoteTemplateDomainList goflags.StringSlice53// ExcludedTemplates specifies the template/templates to exclude54ExcludedTemplates goflags.StringSlice55// ExcludeMatchers is a list of matchers to exclude processing56ExcludeMatchers goflags.StringSlice57// CustomHeaders is the list of custom global headers to send with each request.58CustomHeaders goflags.StringSlice59// Vars is the list of custom global vars60Vars goflags.RuntimeMap61// Severities filters templates based on their severity and only run the matching ones.62Severities severity.Severities63// ExcludeSeverities specifies severities to exclude64ExcludeSeverities severity.Severities65// Authors filters templates based on their author and only run the matching ones.66Authors goflags.StringSlice67// Protocols contains the protocols to be allowed executed68Protocols types.ProtocolTypes69// ExcludeProtocols contains protocols to not be executed70ExcludeProtocols types.ProtocolTypes71// IncludeTags includes specified tags to be run even while being in denylist72IncludeTags goflags.StringSlice73// IncludeTemplates includes specified templates to be run even while being in denylist74IncludeTemplates goflags.StringSlice75// IncludeIds includes specified ids to be run even while being in denylist76IncludeIds goflags.StringSlice77// ExcludeIds contains templates ids to not be executed78ExcludeIds goflags.StringSlice79// InternalResolversList is the list of internal resolvers to use80InternalResolversList []string81// ProjectPath allows nuclei to use a user defined project folder82ProjectPath string83// InteractshURL is the URL for the interactsh server.84InteractshURL string85// Interactsh Authorization header value for self-hosted servers86InteractshToken string87// Target URLs/Domains to scan using a template88Targets goflags.StringSlice89// ExcludeTargets URLs/Domains to exclude from scanning90ExcludeTargets goflags.StringSlice91// TargetsFilePath specifies the targets from a file to scan using templates.92TargetsFilePath string93// Resume the scan from the state stored in the resume config file94Resume string95// Output is the file to write found results to.96Output string97// ProxyInternal requests98ProxyInternal bool99// Show all supported DSL signatures100ListDslSignatures bool101// List of HTTP(s)/SOCKS5 proxy to use (comma separated or file input)102Proxy goflags.StringSlice103// AliveProxy is the alive proxy to use104AliveHttpProxy string105// AliveSocksProxy is the alive socks proxy to use106AliveSocksProxy string107// TemplatesDirectory is the directory to use for storing templates108NewTemplatesDirectory string109// TraceLogFile specifies a file to write with the trace of all requests110TraceLogFile string111// ErrorLogFile specifies a file to write with the errors of all requests112ErrorLogFile string113// ReportingDB is the db for report storage as well as deduplication114ReportingDB string115// ReportingConfig is the config file for nuclei reporting module116ReportingConfig string117// MarkdownExportDirectory is the directory to export reports in Markdown format118MarkdownExportDirectory string119// MarkdownExportSortMode is the method to sort the markdown reports (options: severity, template, host, none)120MarkdownExportSortMode string121// SarifExport is the file to export sarif output format to122SarifExport string123// ResolversFile is a file containing resolvers for nuclei.124ResolversFile string125// StatsInterval is the number of seconds to display stats after126StatsInterval int127// MetricsPort is the port to show metrics on128MetricsPort int129// MaxHostError is the maximum number of errors allowed for a host130MaxHostError int131// TrackError contains additional error messages that count towards the maximum number of errors allowed for a host132TrackError goflags.StringSlice133// NoHostErrors disables host skipping after maximum number of errors134NoHostErrors bool135// BulkSize is the of targets analyzed in parallel for each template136BulkSize int137// TemplateThreads is the number of templates executed in parallel138TemplateThreads int139// HeadlessBulkSize is the of targets analyzed in parallel for each headless template140HeadlessBulkSize int141// HeadlessTemplateThreads is the number of headless templates executed in parallel142HeadlessTemplateThreads int143// Timeout is the seconds to wait for a response from the server.144Timeout int145// Retries is the number of times to retry the request146Retries int147// Rate-Limit is the maximum number of requests per specified target148RateLimit int149// Rate Limit Duration interval between burst resets150RateLimitDuration time.Duration151// Rate-Limit is the maximum number of requests per minute for specified target152// Deprecated: Use RateLimitDuration - automatically set Rate Limit Duration to 60 seconds153RateLimitMinute int154// PageTimeout is the maximum time to wait for a page in seconds155PageTimeout int156// InteractionsCacheSize is the number of interaction-url->req to keep in cache at a time.157InteractionsCacheSize int158// InteractionsPollDuration is the number of seconds to wait before each interaction poll159InteractionsPollDuration int160// Eviction is the number of seconds after which to automatically discard161// interaction requests.162InteractionsEviction int163// InteractionsCoolDownPeriod is additional seconds to wait for interactions after closing164// of the poller.165InteractionsCoolDownPeriod int166// MaxRedirects is the maximum numbers of redirects to be followed.167MaxRedirects int168// FollowRedirects enables following redirects for http request module169FollowRedirects bool170// FollowRedirects enables following redirects for http request module only on the same host171FollowHostRedirects bool172// OfflineHTTP is a flag that specific offline processing of http response173// using same matchers/extractors from http protocol without the need174// to send a new request, reading responses from a file.175OfflineHTTP bool176// Force HTTP2 requests177ForceAttemptHTTP2 bool178// StatsJSON writes stats output in JSON format179StatsJSON bool180// CDPEndpoint specifies the endpoint for Chrome DevTools Protocol (CDP)181CDPEndpoint string182// Headless specifies whether to allow headless mode templates183Headless bool184// ShowBrowser specifies whether the show the browser in headless mode185ShowBrowser bool186// HeadlessOptionalArguments specifies optional arguments to pass to Chrome187HeadlessOptionalArguments goflags.StringSlice188// DisableClustering disables clustering of templates189DisableClustering bool190// UseInstalledChrome skips chrome install and use local instance191UseInstalledChrome bool192// SystemResolvers enables override of nuclei's DNS client opting to use system resolver stack.193SystemResolvers bool194// ShowActions displays a list of all headless actions195ShowActions bool196// Deprecated: Enabled by default through clistats . Metrics enables display of metrics via an http endpoint197Metrics bool198// Debug mode allows debugging request/responses for the engine199Debug bool200// DebugRequests mode allows debugging request for the engine201DebugRequests bool202// DebugResponse mode allows debugging response for the engine203DebugResponse bool204// DisableHTTPProbe disables http probing feature of input normalization205DisableHTTPProbe bool206// LeaveDefaultPorts skips normalization of default ports207LeaveDefaultPorts bool208// AutomaticScan enables automatic tech based template execution209AutomaticScan bool210// Silent suppresses any extra text and only writes found URLs on screen.211Silent bool212// Validate validates the templates passed to nuclei.213Validate bool214// NoStrictSyntax disables strict syntax check on nuclei templates (allows custom key-value pairs).215NoStrictSyntax bool216// Verbose flag indicates whether to show verbose output or not217Verbose bool218VerboseVerbose bool219// ShowVarDump displays variable dump220ShowVarDump bool221// VarDumpLimit limits the number of characters displayed in var dump222VarDumpLimit int223// No-Color disables the colored output.224NoColor bool225// UpdateTemplates updates the templates installed at startup (also used by cloud to update datasources)226UpdateTemplates bool227// JSON writes json line output to files228JSONL bool229// JSONRequests writes requests/responses for matches in JSON output230// Deprecated: use OmitRawRequests instead as of now JSONRequests(include raw requests) is always true231JSONRequests bool232// OmitRawRequests omits requests/responses for matches in JSON output233OmitRawRequests bool234// HTTPStats enables http statistics tracking and display.235HTTPStats bool236// OmitTemplate omits encoded template from JSON output237OmitTemplate bool238// JSONExport is the file to export JSON output format to239JSONExport string240// JSONLExport is the file to export JSONL output format to241JSONLExport string242// Redact redacts given keys in243Redact goflags.StringSlice244// EnableProgressBar enables progress bar245EnableProgressBar bool246// TemplateDisplay displays the template contents247TemplateDisplay bool248// TemplateList lists available templates249TemplateList bool250// TemplateList lists available tags251TagList bool252// HangMonitor enables nuclei hang monitoring253HangMonitor bool254// Stdin specifies whether stdin input was given to the process255Stdin bool256// StopAtFirstMatch stops processing template at first full match (this may break chained requests)257StopAtFirstMatch bool258// Stream the input without sorting259Stream bool260// NoMeta disables display of metadata for the matches261NoMeta bool262// Timestamp enables display of timestamp for the matcher263Timestamp bool264// Project is used to avoid sending same HTTP request multiple times265Project bool266// NewTemplates only runs newly added templates from the repository267NewTemplates bool268// NewTemplatesWithVersion runs new templates added in specific version269NewTemplatesWithVersion goflags.StringSlice270// NoInteractsh disables use of interactsh server for interaction polling271NoInteractsh bool272// EnvironmentVariables enables support for environment variables273EnvironmentVariables bool274// MatcherStatus displays optional status for the failed matches as well275MatcherStatus bool276// ClientCertFile client certificate file (PEM-encoded) used for authenticating against scanned hosts277ClientCertFile string278// ClientKeyFile client key file (PEM-encoded) used for authenticating against scanned hosts279ClientKeyFile string280// ClientCAFile client certificate authority file (PEM-encoded) used for authenticating against scanned hosts281ClientCAFile string282// Deprecated: Use ZTLS library283ZTLS bool284// AllowLocalFileAccess allows local file access from templates payloads285AllowLocalFileAccess bool286// RestrictLocalNetworkAccess restricts local network access from templates requests287RestrictLocalNetworkAccess bool288// ShowMatchLine enables display of match line number289ShowMatchLine bool290// EnablePprof enables exposing pprof runtime information with a webserver.291EnablePprof bool292// StoreResponse stores received response to output directory293StoreResponse bool294// StoreResponseDir stores received response to custom directory295StoreResponseDir string296// DisableRedirects disables following redirects for http request module297DisableRedirects bool298// SNI custom hostname299SNI string300// InputFileMode specifies the mode of input file (jsonl, burp, openapi, swagger, etc)301InputFileMode string302// DialerKeepAlive sets the keep alive duration for network requests.303DialerKeepAlive time.Duration304// Interface to use for network scan305Interface string306// SourceIP sets custom source IP address for network requests307SourceIP string308// AttackType overrides template level attack-type configuration309AttackType string310// ResponseReadSize is the maximum size of response to read311ResponseReadSize int312// ResponseSaveSize is the maximum size of response to save313ResponseSaveSize int314// Health Check315HealthCheck bool316// Time to wait between each input read operation before closing the stream317InputReadTimeout time.Duration318// Disable stdin for input processing319DisableStdin bool320// IncludeConditions is the list of conditions templates should match321IncludeConditions goflags.StringSlice322// Enable uncover engine323Uncover bool324// Uncover search query325UncoverQuery goflags.StringSlice326// Uncover search engine327UncoverEngine goflags.StringSlice328// Uncover search field329UncoverField string330// Uncover search limit331UncoverLimit int332// Uncover search delay333UncoverRateLimit int334// ScanAllIPs associated to a dns record335ScanAllIPs bool336// IPVersion to scan (4,6)337IPVersion goflags.StringSlice338// PublicTemplateDisableDownload disables downloading templates from the nuclei-templates public repository339PublicTemplateDisableDownload bool340// GitHub token used to clone/pull from private repos for custom templates341GitHubToken string342// GitHubTemplateRepo is the list of custom public/private templates GitHub repos343GitHubTemplateRepo []string344// GitHubTemplateDisableDownload disables downloading templates from custom GitHub repositories345GitHubTemplateDisableDownload bool346// GitLabServerURL is the gitlab server to use for custom templates347GitLabServerURL string348// GitLabToken used to clone/pull from private repos for custom templates349GitLabToken string350// GitLabTemplateRepositoryIDs is the comma-separated list of custom gitlab repositories IDs351GitLabTemplateRepositoryIDs []int352// GitLabTemplateDisableDownload disables downloading templates from custom GitLab repositories353GitLabTemplateDisableDownload bool354// AWS access profile from ~/.aws/credentials file for downloading templates from S3 bucket355AwsProfile string356// AWS access key for downloading templates from S3 bucket357AwsAccessKey string358// AWS secret key for downloading templates from S3 bucket359AwsSecretKey string360// AWS bucket name for downloading templates from S3 bucket361AwsBucketName string362// AWS Region name where AWS S3 bucket is located363AwsRegion string364// AwsTemplateDisableDownload disables downloading templates from AWS S3 buckets365AwsTemplateDisableDownload bool366// AzureContainerName for downloading templates from Azure Blob Storage. Example: templates367AzureContainerName string368// AzureTenantID for downloading templates from Azure Blob Storage. Example: 00000000-0000-0000-0000-000000000000369AzureTenantID string370// AzureClientID for downloading templates from Azure Blob Storage. Example: 00000000-0000-0000-0000-000000000000371AzureClientID string372// AzureClientSecret for downloading templates from Azure Blob Storage. Example: 00000000-0000-0000-0000-000000000000373AzureClientSecret string374// AzureServiceURL for downloading templates from Azure Blob Storage. Example: https://XXXXXXXXXX.blob.core.windows.net/375AzureServiceURL string376// AzureTemplateDisableDownload disables downloading templates from Azure Blob Storage377AzureTemplateDisableDownload bool378// Scan Strategy (auto,hosts-spray,templates-spray)379ScanStrategy string380// Fuzzing Type overrides template level fuzzing-type configuration381FuzzingType string382// Fuzzing Mode overrides template level fuzzing-mode configuration383FuzzingMode string384// TlsImpersonate enables TLS impersonation385TlsImpersonate bool386// DisplayFuzzPoints enables display of fuzz points for fuzzing387DisplayFuzzPoints bool388// FuzzAggressionLevel is the level of fuzzing aggression (low, medium, high.)389FuzzAggressionLevel string390// FuzzParamFrequency is the frequency of fuzzing parameters391FuzzParamFrequency int392// CodeTemplateSignaturePublicKey is the custom public key used to verify the template signature (algorithm is automatically inferred from the length)393CodeTemplateSignaturePublicKey string394// CodeTemplateSignatureAlgorithm specifies the sign algorithm (rsa, ecdsa)395CodeTemplateSignatureAlgorithm string396// SignTemplates enables signing of templates397SignTemplates bool398// EnableCodeTemplates enables code templates399EnableCodeTemplates bool400// DisableUnsignedTemplates disables processing of unsigned templates401DisableUnsignedTemplates bool402// EnableSelfContainedTemplates enables processing of self-contained templates403EnableSelfContainedTemplates bool404// EnableGlobalMatchersTemplates enables processing of global-matchers templates405EnableGlobalMatchersTemplates bool406// EnableFileTemplates enables file templates407EnableFileTemplates bool408// Disables cloud upload409EnableCloudUpload bool410// ScanID is the scan ID to use for cloud upload411ScanID string412// ScanName is the name of the scan to be uploaded413ScanName string414// ScanUploadFile is the jsonl file to upload scan results to cloud415ScanUploadFile string416// TeamID is the team ID to use for cloud upload417TeamID string418// JsConcurrency is the number of concurrent js routines to run419JsConcurrency int420// SecretsFile is file containing secrets for nuclei421SecretsFile goflags.StringSlice422// PreFetchSecrets pre-fetches the secrets from the auth provider423PreFetchSecrets bool424// FormatUseRequiredOnly only uses required fields when generating requests425FormatUseRequiredOnly bool426// SkipFormatValidation is used to skip format validation427SkipFormatValidation bool428// VarsTextTemplating is used to inject variables into yaml input files429VarsTextTemplating bool430// VarsFilePaths is used to inject variables into yaml input files from a file431VarsFilePaths goflags.StringSlice432// PayloadConcurrency is the number of concurrent payloads to run per template433PayloadConcurrency int434// ProbeConcurrency is the number of concurrent http probes to run with httpx435ProbeConcurrency int436// TemplateLoadingConcurrency is the number of concurrent template loading operations437TemplateLoadingConcurrency int438// Dast only runs DAST templates439DAST bool440// DASTServer is the flag to start nuclei as a DAST server441DASTServer bool442// DASTServerToken is the token optional for the dast server443DASTServerToken string444// DASTServerAddress is the address for the dast server445DASTServerAddress string446// DASTReport enables dast report server & final report generation447DASTReport bool448// Scope contains a list of regexes for in-scope URLS449Scope goflags.StringSlice450// OutOfScope contains a list of regexes for out-scope URLS451OutOfScope goflags.StringSlice452// HttpApiEndpoint is the experimental http api endpoint453HttpApiEndpoint string454// ListTemplateProfiles lists all available template profiles455ListTemplateProfiles bool456// LoadHelperFileFunction is a function that will be used to execute LoadHelperFile.457// If none is provided, then the default implementation will be used.458LoadHelperFileFunction LoadHelperFileFunction459// Logger is the gologger instance for this optionset460Logger *gologger.Logger461// NoCacheTemplates disables caching of templates462DoNotCacheTemplates bool463// Unique identifier of the execution session464ExecutionId string465// Parser is a cached parser for the template store466Parser any467// timeouts contains various types of timeouts used in nuclei468// these timeouts are derived from dial-timeout (-timeout) with known multipliers469// This is internally managed and does not need to be set by user by explicitly setting470// this overrides the default/derived one471timeouts *Timeouts472// m is a mutex to protect timeouts from concurrent access473m sync.Mutex474}475476func (options *Options) Copy() *Options {477optCopy := &Options{478Tags: options.Tags,479ExcludeTags: options.ExcludeTags,480Workflows: options.Workflows,481WorkflowURLs: options.WorkflowURLs,482Templates: options.Templates,483TemplateURLs: options.TemplateURLs,484AITemplatePrompt: options.AITemplatePrompt,485RemoteTemplateDomainList: options.RemoteTemplateDomainList,486ExcludedTemplates: options.ExcludedTemplates,487ExcludeMatchers: options.ExcludeMatchers,488CustomHeaders: options.CustomHeaders,489Vars: options.Vars,490Severities: options.Severities,491ExcludeSeverities: options.ExcludeSeverities,492Authors: options.Authors,493Protocols: options.Protocols,494ExcludeProtocols: options.ExcludeProtocols,495IncludeTags: options.IncludeTags,496IncludeTemplates: options.IncludeTemplates,497IncludeIds: options.IncludeIds,498ExcludeIds: options.ExcludeIds,499InternalResolversList: options.InternalResolversList,500ProjectPath: options.ProjectPath,501InteractshURL: options.InteractshURL,502InteractshToken: options.InteractshToken,503Targets: options.Targets,504ExcludeTargets: options.ExcludeTargets,505TargetsFilePath: options.TargetsFilePath,506Resume: options.Resume,507Output: options.Output,508ProxyInternal: options.ProxyInternal,509ListDslSignatures: options.ListDslSignatures,510Proxy: options.Proxy,511AliveHttpProxy: options.AliveHttpProxy,512AliveSocksProxy: options.AliveSocksProxy,513NewTemplatesDirectory: options.NewTemplatesDirectory,514TraceLogFile: options.TraceLogFile,515ErrorLogFile: options.ErrorLogFile,516ReportingDB: options.ReportingDB,517ReportingConfig: options.ReportingConfig,518MarkdownExportDirectory: options.MarkdownExportDirectory,519MarkdownExportSortMode: options.MarkdownExportSortMode,520SarifExport: options.SarifExport,521ResolversFile: options.ResolversFile,522StatsInterval: options.StatsInterval,523MetricsPort: options.MetricsPort,524MaxHostError: options.MaxHostError,525TrackError: options.TrackError,526NoHostErrors: options.NoHostErrors,527BulkSize: options.BulkSize,528TemplateThreads: options.TemplateThreads,529HeadlessBulkSize: options.HeadlessBulkSize,530HeadlessTemplateThreads: options.HeadlessTemplateThreads,531Timeout: options.Timeout,532Retries: options.Retries,533RateLimit: options.RateLimit,534RateLimitDuration: options.RateLimitDuration,535RateLimitMinute: options.RateLimitMinute,536PageTimeout: options.PageTimeout,537InteractionsCacheSize: options.InteractionsCacheSize,538InteractionsPollDuration: options.InteractionsPollDuration,539InteractionsEviction: options.InteractionsEviction,540InteractionsCoolDownPeriod: options.InteractionsCoolDownPeriod,541MaxRedirects: options.MaxRedirects,542FollowRedirects: options.FollowRedirects,543FollowHostRedirects: options.FollowHostRedirects,544OfflineHTTP: options.OfflineHTTP,545ForceAttemptHTTP2: options.ForceAttemptHTTP2,546StatsJSON: options.StatsJSON,547Headless: options.Headless,548ShowBrowser: options.ShowBrowser,549HeadlessOptionalArguments: options.HeadlessOptionalArguments,550DisableClustering: options.DisableClustering,551UseInstalledChrome: options.UseInstalledChrome,552SystemResolvers: options.SystemResolvers,553ShowActions: options.ShowActions,554Metrics: options.Metrics,555Debug: options.Debug,556DebugRequests: options.DebugRequests,557DebugResponse: options.DebugResponse,558DisableHTTPProbe: options.DisableHTTPProbe,559LeaveDefaultPorts: options.LeaveDefaultPorts,560AutomaticScan: options.AutomaticScan,561Silent: options.Silent,562Validate: options.Validate,563NoStrictSyntax: options.NoStrictSyntax,564Verbose: options.Verbose,565VerboseVerbose: options.VerboseVerbose,566ShowVarDump: options.ShowVarDump,567VarDumpLimit: options.VarDumpLimit,568NoColor: options.NoColor,569UpdateTemplates: options.UpdateTemplates,570JSONL: options.JSONL,571JSONRequests: options.JSONRequests,572OmitRawRequests: options.OmitRawRequests,573HTTPStats: options.HTTPStats,574OmitTemplate: options.OmitTemplate,575JSONExport: options.JSONExport,576JSONLExport: options.JSONLExport,577Redact: options.Redact,578EnableProgressBar: options.EnableProgressBar,579TemplateDisplay: options.TemplateDisplay,580TemplateList: options.TemplateList,581TagList: options.TagList,582HangMonitor: options.HangMonitor,583Stdin: options.Stdin,584StopAtFirstMatch: options.StopAtFirstMatch,585Stream: options.Stream,586NoMeta: options.NoMeta,587Timestamp: options.Timestamp,588Project: options.Project,589NewTemplates: options.NewTemplates,590NewTemplatesWithVersion: options.NewTemplatesWithVersion,591NoInteractsh: options.NoInteractsh,592EnvironmentVariables: options.EnvironmentVariables,593MatcherStatus: options.MatcherStatus,594ClientCertFile: options.ClientCertFile,595ClientKeyFile: options.ClientKeyFile,596ClientCAFile: options.ClientCAFile,597ZTLS: options.ZTLS,598AllowLocalFileAccess: options.AllowLocalFileAccess,599RestrictLocalNetworkAccess: options.RestrictLocalNetworkAccess,600ShowMatchLine: options.ShowMatchLine,601EnablePprof: options.EnablePprof,602StoreResponse: options.StoreResponse,603StoreResponseDir: options.StoreResponseDir,604DisableRedirects: options.DisableRedirects,605SNI: options.SNI,606InputFileMode: options.InputFileMode,607DialerKeepAlive: options.DialerKeepAlive,608Interface: options.Interface,609SourceIP: options.SourceIP,610AttackType: options.AttackType,611ResponseReadSize: options.ResponseReadSize,612ResponseSaveSize: options.ResponseSaveSize,613HealthCheck: options.HealthCheck,614InputReadTimeout: options.InputReadTimeout,615DisableStdin: options.DisableStdin,616IncludeConditions: options.IncludeConditions,617Uncover: options.Uncover,618UncoverQuery: options.UncoverQuery,619UncoverEngine: options.UncoverEngine,620UncoverField: options.UncoverField,621UncoverLimit: options.UncoverLimit,622UncoverRateLimit: options.UncoverRateLimit,623ScanAllIPs: options.ScanAllIPs,624IPVersion: options.IPVersion,625PublicTemplateDisableDownload: options.PublicTemplateDisableDownload,626GitHubToken: options.GitHubToken,627GitHubTemplateRepo: options.GitHubTemplateRepo,628GitHubTemplateDisableDownload: options.GitHubTemplateDisableDownload,629GitLabServerURL: options.GitLabServerURL,630GitLabToken: options.GitLabToken,631GitLabTemplateRepositoryIDs: options.GitLabTemplateRepositoryIDs,632GitLabTemplateDisableDownload: options.GitLabTemplateDisableDownload,633AwsProfile: options.AwsProfile,634AwsAccessKey: options.AwsAccessKey,635AwsSecretKey: options.AwsSecretKey,636AwsBucketName: options.AwsBucketName,637AwsRegion: options.AwsRegion,638AwsTemplateDisableDownload: options.AwsTemplateDisableDownload,639AzureContainerName: options.AzureContainerName,640AzureTenantID: options.AzureTenantID,641AzureClientID: options.AzureClientID,642AzureClientSecret: options.AzureClientSecret,643AzureServiceURL: options.AzureServiceURL,644AzureTemplateDisableDownload: options.AzureTemplateDisableDownload,645ScanStrategy: options.ScanStrategy,646FuzzingType: options.FuzzingType,647FuzzingMode: options.FuzzingMode,648TlsImpersonate: options.TlsImpersonate,649DisplayFuzzPoints: options.DisplayFuzzPoints,650FuzzAggressionLevel: options.FuzzAggressionLevel,651FuzzParamFrequency: options.FuzzParamFrequency,652CodeTemplateSignaturePublicKey: options.CodeTemplateSignaturePublicKey,653CodeTemplateSignatureAlgorithm: options.CodeTemplateSignatureAlgorithm,654SignTemplates: options.SignTemplates,655EnableCodeTemplates: options.EnableCodeTemplates,656DisableUnsignedTemplates: options.DisableUnsignedTemplates,657EnableSelfContainedTemplates: options.EnableSelfContainedTemplates,658EnableGlobalMatchersTemplates: options.EnableGlobalMatchersTemplates,659EnableFileTemplates: options.EnableFileTemplates,660EnableCloudUpload: options.EnableCloudUpload,661ScanID: options.ScanID,662ScanName: options.ScanName,663ScanUploadFile: options.ScanUploadFile,664TeamID: options.TeamID,665JsConcurrency: options.JsConcurrency,666SecretsFile: options.SecretsFile,667PreFetchSecrets: options.PreFetchSecrets,668FormatUseRequiredOnly: options.FormatUseRequiredOnly,669SkipFormatValidation: options.SkipFormatValidation,670PayloadConcurrency: options.PayloadConcurrency,671ProbeConcurrency: options.ProbeConcurrency,672DAST: options.DAST,673DASTServer: options.DASTServer,674DASTServerToken: options.DASTServerToken,675DASTServerAddress: options.DASTServerAddress,676DASTReport: options.DASTReport,677Scope: options.Scope,678OutOfScope: options.OutOfScope,679HttpApiEndpoint: options.HttpApiEndpoint,680ListTemplateProfiles: options.ListTemplateProfiles,681LoadHelperFileFunction: options.LoadHelperFileFunction,682Logger: options.Logger,683DoNotCacheTemplates: options.DoNotCacheTemplates,684ExecutionId: options.ExecutionId,685Parser: options.Parser,686}687optCopy.SetTimeouts(options.timeouts)688return optCopy689}690691// SetTimeouts sets the timeout variants to use for the executor692func (opts *Options) SetTimeouts(t *Timeouts) {693opts.timeouts = t694}695696// GetTimeouts returns the timeout variants to use for the executor697func (eo *Options) GetTimeouts() *Timeouts {698eo.m.Lock()699defer eo.m.Unlock()700if eo.timeouts != nil {701// redundant but apply to avoid any potential issues702eo.timeouts.ApplyDefaults()703return eo.timeouts704}705// set timeout variant value706eo.timeouts = NewTimeoutVariant(eo.Timeout)707eo.timeouts.ApplyDefaults()708return eo.timeouts709}710711// Timeouts is a struct that contains all the timeout variants for nuclei712// dialer timeout is used to derive other timeouts713type Timeouts struct {714// DialTimeout for fastdialer (default 10s)715DialTimeout time.Duration716// Tcp(Network Protocol) Read From Connection Timeout (default 5s)717TcpReadTimeout time.Duration718// Http Response Header Timeout (default 10s)719// this timeout prevents infinite hangs started by server if any720// this is temporarily overridden when using @timeout request annotation721HttpResponseHeaderTimeout time.Duration722// HttpTimeout for http client (default -> 3 x dial-timeout = 30s)723HttpTimeout time.Duration724// JsCompilerExec timeout/deadline (default -> 2 x dial-timeout = 20s)725JsCompilerExecutionTimeout time.Duration726// CodeExecutionTimeout for code execution (default -> 3 x dial-timeout = 30s)727CodeExecutionTimeout time.Duration728}729730// NewTimeoutVariant creates a new timeout variant with the given dial timeout in seconds731func NewTimeoutVariant(dialTimeoutSec int) *Timeouts {732tv := &Timeouts{733DialTimeout: time.Duration(dialTimeoutSec) * time.Second,734}735tv.ApplyDefaults()736return tv737}738739// ApplyDefaults applies default values to timeout variants when missing740func (tv *Timeouts) ApplyDefaults() {741if tv.DialTimeout == 0 {742tv.DialTimeout = 10 * time.Second743}744if tv.TcpReadTimeout == 0 {745tv.TcpReadTimeout = 5 * time.Second746}747if tv.HttpTimeout == 0 {748tv.HttpTimeout = 3 * tv.DialTimeout749}750if tv.HttpResponseHeaderTimeout < tv.HttpTimeout {751tv.HttpResponseHeaderTimeout = tv.HttpTimeout752}753if tv.JsCompilerExecutionTimeout == 0 {754tv.JsCompilerExecutionTimeout = 2 * tv.DialTimeout755}756if tv.CodeExecutionTimeout == 0 {757tv.CodeExecutionTimeout = 3 * tv.DialTimeout758}759}760761// ShouldLoadResume resume file762func (options *Options) ShouldLoadResume() bool {763return options.Resume != "" && fileutil.FileExists(options.Resume)764}765766// ShouldSaveResume file767func (options *Options) ShouldSaveResume() bool {768return true769}770771// ShouldFollowHTTPRedirects determines if http redirects should be followed772func (options *Options) ShouldFollowHTTPRedirects() bool {773return options.FollowRedirects || options.FollowHostRedirects774}775776// HasClientCertificates determines if any client certificate was specified777func (options *Options) HasClientCertificates() bool {778return options.ClientCertFile != "" || options.ClientCAFile != "" || options.ClientKeyFile != ""779}780781// DefaultOptions returns default options for nuclei782func DefaultOptions() *Options {783return &Options{784RateLimit: 150,785RateLimitDuration: time.Second,786BulkSize: 25,787TemplateThreads: 25,788HeadlessBulkSize: 10,789PayloadConcurrency: 25,790HeadlessTemplateThreads: 10,791ProbeConcurrency: 50,792TemplateLoadingConcurrency: DefaultTemplateLoadingConcurrency,793Timeout: 5,794Retries: 1,795MaxHostError: 30,796ResponseReadSize: 10 * unitutils.Mega,797ResponseSaveSize: unitutils.Mega,798ExecutionId: xid.New().String(),799Logger: &gologger.Logger{},800}801}802803func (options *Options) ShouldUseHostError() bool {804return options.MaxHostError > 0 && !options.NoHostErrors805}806807func (options *Options) ParseHeadlessOptionalArguments() map[string]string {808optionalArguments := make(map[string]string)809for _, v := range options.HeadlessOptionalArguments {810if argParts := strings.SplitN(v, "=", 2); len(argParts) >= 2 {811key := strings.TrimSpace(argParts[0])812value := strings.TrimSpace(argParts[1])813if key != "" && value != "" {814optionalArguments[key] = value815}816}817}818return optionalArguments819}820821// LoadHelperFile loads a helper file needed for the template.822//823// If LoadHelperFileFunction is set, then that function will be used.824// Otherwise, the default implementation will be used, which respects the sandbox rules and only loads files from allowed directories.825func (options *Options) LoadHelperFile(helperFile, templatePath string, catalog catalog.Catalog) (io.ReadCloser, error) {826if options.LoadHelperFileFunction != nil {827return options.LoadHelperFileFunction(helperFile, templatePath, catalog)828}829return options.defaultLoadHelperFile(helperFile, templatePath, catalog)830}831832// defaultLoadHelperFile loads a helper file needed for the template833// this respects the sandbox rules and only loads files from834// allowed directories835func (options *Options) defaultLoadHelperFile(helperFile, templatePath string, catalog catalog.Catalog) (io.ReadCloser, error) {836if !options.AllowLocalFileAccess {837// if global file access is disabled try loading with restrictions838absPath, err := options.GetValidAbsPath(helperFile, templatePath)839if err != nil {840return nil, err841}842helperFile = absPath843}844f, err := os.Open(helperFile)845if err != nil {846return nil, errkit.Wrapf(err, "could not open file %v", helperFile)847}848return f, nil849}850851// GetValidAbsPath returns absolute path of helper file if it is allowed to be loaded852// this respects the sandbox rules and only loads files from allowed directories853func (o *Options) GetValidAbsPath(helperFilePath, templatePath string) (string, error) {854// Conditions to allow helper file855// 1. If helper file is present in nuclei-templates directory856// 2. If helper file and template file are in same directory given that its not root directory857858// resolve and clean helper file path859// ResolveNClean uses a custom base path instead of CWD860resolvedPath, err := fileutil.ResolveNClean(helperFilePath, config.DefaultConfig.GetTemplateDir())861if err == nil {862// As per rule 1, if helper file is present in nuclei-templates directory, allow it863if strings.HasPrefix(resolvedPath, config.DefaultConfig.GetTemplateDir()) {864return resolvedPath, nil865}866}867868// CleanPath resolves using CWD and cleans the path869helperFilePath, err = fileutil.CleanPath(helperFilePath)870if err != nil {871return "", errkit.Wrapf(err, "could not clean helper file path %v", helperFilePath)872}873874templatePath, err = fileutil.CleanPath(templatePath)875if err != nil {876return "", errkit.Wrapf(err, "could not clean template path %v", templatePath)877}878879// As per rule 2, if template and helper file exist in same directory or helper file existed in any child dir of template dir880// and both of them are present in user home directory, allow it881// Review: should we keep this rule ? add extra option to disable this ?882if isHomeDir(helperFilePath) && isHomeDir(templatePath) && strings.HasPrefix(filepath.Dir(helperFilePath), filepath.Dir(templatePath)) {883return helperFilePath, nil884}885886// all other cases are denied887return "", errkit.Newf("access to helper file %v denied", helperFilePath)888}889890// SetExecutionID sets the execution ID for the options891func (options *Options) SetExecutionID(id string) {892options.m.Lock()893defer options.m.Unlock()894options.ExecutionId = id895}896897// GetExecutionID gets the execution ID for the options898func (options *Options) GetExecutionID() string {899options.m.Lock()900defer options.m.Unlock()901return options.ExecutionId902}903904// isHomeDir checks if given is home directory905func isHomeDir(path string) bool {906homeDir := folderutil.HomeDirOrDefault("")907return strings.HasPrefix(path, homeDir)908}909910911