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)2122var (23// ErrNoMoreRequests is internal error to indicate that generator has no more requests to generate24ErrNoMoreRequests = io.EOF25)2627// LoadHelperFileFunction can be used to load a helper file.28type LoadHelperFileFunction func(helperFile, templatePath string, catalog catalog.Catalog) (io.ReadCloser, error)2930// Options contains the configuration options for nuclei scanner.31type Options struct {32// Tags contains a list of tags to execute templates for. Multiple paths33// can be specified with -l flag and -tags can be used in combination with34// the -l flag.35Tags goflags.StringSlice36// ExcludeTags is the list of tags to exclude37ExcludeTags goflags.StringSlice38// Workflows specifies any workflows to run by nuclei39Workflows goflags.StringSlice40// WorkflowURLs specifies URLs to a list of workflows to use41WorkflowURLs goflags.StringSlice42// Templates specifies the template/templates to use43Templates goflags.StringSlice44// TemplateURLs specifies URLs to a list of templates to use45TemplateURLs goflags.StringSlice46// AITemplatePrompt specifies prompt to generate template using AI47AITemplatePrompt string48// RemoteTemplates specifies list of allowed URLs to load remote templates from49RemoteTemplateDomainList goflags.StringSlice50// ExcludedTemplates specifies the template/templates to exclude51ExcludedTemplates goflags.StringSlice52// ExcludeMatchers is a list of matchers to exclude processing53ExcludeMatchers goflags.StringSlice54// CustomHeaders is the list of custom global headers to send with each request.55CustomHeaders goflags.StringSlice56// Vars is the list of custom global vars57Vars goflags.RuntimeMap58// Severities filters templates based on their severity and only run the matching ones.59Severities severity.Severities60// ExcludeSeverities specifies severities to exclude61ExcludeSeverities severity.Severities62// Authors filters templates based on their author and only run the matching ones.63Authors goflags.StringSlice64// Protocols contains the protocols to be allowed executed65Protocols types.ProtocolTypes66// ExcludeProtocols contains protocols to not be executed67ExcludeProtocols types.ProtocolTypes68// IncludeTags includes specified tags to be run even while being in denylist69IncludeTags goflags.StringSlice70// IncludeTemplates includes specified templates to be run even while being in denylist71IncludeTemplates goflags.StringSlice72// IncludeIds includes specified ids to be run even while being in denylist73IncludeIds goflags.StringSlice74// ExcludeIds contains templates ids to not be executed75ExcludeIds goflags.StringSlice76// InternalResolversList is the list of internal resolvers to use77InternalResolversList []string78// ProjectPath allows nuclei to use a user defined project folder79ProjectPath string80// InteractshURL is the URL for the interactsh server.81InteractshURL string82// Interactsh Authorization header value for self-hosted servers83InteractshToken string84// Target URLs/Domains to scan using a template85Targets goflags.StringSlice86// ExcludeTargets URLs/Domains to exclude from scanning87ExcludeTargets goflags.StringSlice88// TargetsFilePath specifies the targets from a file to scan using templates.89TargetsFilePath string90// Resume the scan from the state stored in the resume config file91Resume string92// Output is the file to write found results to.93Output string94// ProxyInternal requests95ProxyInternal bool96// Show all supported DSL signatures97ListDslSignatures bool98// List of HTTP(s)/SOCKS5 proxy to use (comma separated or file input)99Proxy goflags.StringSlice100// AliveProxy is the alive proxy to use101AliveHttpProxy string102// AliveSocksProxy is the alive socks proxy to use103AliveSocksProxy string104// TemplatesDirectory is the directory to use for storing templates105NewTemplatesDirectory string106// TraceLogFile specifies a file to write with the trace of all requests107TraceLogFile string108// ErrorLogFile specifies a file to write with the errors of all requests109ErrorLogFile string110// ReportingDB is the db for report storage as well as deduplication111ReportingDB string112// ReportingConfig is the config file for nuclei reporting module113ReportingConfig string114// MarkdownExportDirectory is the directory to export reports in Markdown format115MarkdownExportDirectory string116// MarkdownExportSortMode is the method to sort the markdown reports (options: severity, template, host, none)117MarkdownExportSortMode string118// SarifExport is the file to export sarif output format to119SarifExport string120// ResolversFile is a file containing resolvers for nuclei.121ResolversFile string122// StatsInterval is the number of seconds to display stats after123StatsInterval int124// MetricsPort is the port to show metrics on125MetricsPort int126// MaxHostError is the maximum number of errors allowed for a host127MaxHostError int128// TrackError contains additional error messages that count towards the maximum number of errors allowed for a host129TrackError goflags.StringSlice130// NoHostErrors disables host skipping after maximum number of errors131NoHostErrors bool132// BulkSize is the of targets analyzed in parallel for each template133BulkSize int134// TemplateThreads is the number of templates executed in parallel135TemplateThreads int136// HeadlessBulkSize is the of targets analyzed in parallel for each headless template137HeadlessBulkSize int138// HeadlessTemplateThreads is the number of headless templates executed in parallel139HeadlessTemplateThreads int140// Timeout is the seconds to wait for a response from the server.141Timeout int142// Retries is the number of times to retry the request143Retries int144// Rate-Limit is the maximum number of requests per specified target145RateLimit int146// Rate Limit Duration interval between burst resets147RateLimitDuration time.Duration148// Rate-Limit is the maximum number of requests per minute for specified target149// Deprecated: Use RateLimitDuration - automatically set Rate Limit Duration to 60 seconds150RateLimitMinute int151// PageTimeout is the maximum time to wait for a page in seconds152PageTimeout int153// InteractionsCacheSize is the number of interaction-url->req to keep in cache at a time.154InteractionsCacheSize int155// InteractionsPollDuration is the number of seconds to wait before each interaction poll156InteractionsPollDuration int157// Eviction is the number of seconds after which to automatically discard158// interaction requests.159InteractionsEviction int160// InteractionsCoolDownPeriod is additional seconds to wait for interactions after closing161// of the poller.162InteractionsCoolDownPeriod int163// MaxRedirects is the maximum numbers of redirects to be followed.164MaxRedirects int165// FollowRedirects enables following redirects for http request module166FollowRedirects bool167// FollowRedirects enables following redirects for http request module only on the same host168FollowHostRedirects bool169// OfflineHTTP is a flag that specific offline processing of http response170// using same matchers/extractors from http protocol without the need171// to send a new request, reading responses from a file.172OfflineHTTP bool173// Force HTTP2 requests174ForceAttemptHTTP2 bool175// StatsJSON writes stats output in JSON format176StatsJSON bool177// Headless specifies whether to allow headless mode templates178Headless bool179// ShowBrowser specifies whether the show the browser in headless mode180ShowBrowser bool181// HeadlessOptionalArguments specifies optional arguments to pass to Chrome182HeadlessOptionalArguments goflags.StringSlice183// DisableClustering disables clustering of templates184DisableClustering bool185// UseInstalledChrome skips chrome install and use local instance186UseInstalledChrome bool187// SystemResolvers enables override of nuclei's DNS client opting to use system resolver stack.188SystemResolvers bool189// ShowActions displays a list of all headless actions190ShowActions bool191// Deprecated: Enabled by default through clistats . Metrics enables display of metrics via an http endpoint192Metrics bool193// Debug mode allows debugging request/responses for the engine194Debug bool195// DebugRequests mode allows debugging request for the engine196DebugRequests bool197// DebugResponse mode allows debugging response for the engine198DebugResponse bool199// DisableHTTPProbe disables http probing feature of input normalization200DisableHTTPProbe bool201// LeaveDefaultPorts skips normalization of default ports202LeaveDefaultPorts bool203// AutomaticScan enables automatic tech based template execution204AutomaticScan bool205// Silent suppresses any extra text and only writes found URLs on screen.206Silent bool207// Validate validates the templates passed to nuclei.208Validate bool209// NoStrictSyntax disables strict syntax check on nuclei templates (allows custom key-value pairs).210NoStrictSyntax bool211// Verbose flag indicates whether to show verbose output or not212Verbose bool213VerboseVerbose bool214// ShowVarDump displays variable dump215ShowVarDump bool216// VarDumpLimit limits the number of characters displayed in var dump217VarDumpLimit int218// No-Color disables the colored output.219NoColor bool220// UpdateTemplates updates the templates installed at startup (also used by cloud to update datasources)221UpdateTemplates bool222// JSON writes json line output to files223JSONL bool224// JSONRequests writes requests/responses for matches in JSON output225// Deprecated: use OmitRawRequests instead as of now JSONRequests(include raw requests) is always true226JSONRequests bool227// OmitRawRequests omits requests/responses for matches in JSON output228OmitRawRequests bool229// HTTPStats enables http statistics tracking and display.230HTTPStats bool231// OmitTemplate omits encoded template from JSON output232OmitTemplate bool233// JSONExport is the file to export JSON output format to234JSONExport string235// JSONLExport is the file to export JSONL output format to236JSONLExport string237// Redact redacts given keys in238Redact goflags.StringSlice239// EnableProgressBar enables progress bar240EnableProgressBar bool241// TemplateDisplay displays the template contents242TemplateDisplay bool243// TemplateList lists available templates244TemplateList bool245// TemplateList lists available tags246TagList bool247// HangMonitor enables nuclei hang monitoring248HangMonitor bool249// Stdin specifies whether stdin input was given to the process250Stdin bool251// StopAtFirstMatch stops processing template at first full match (this may break chained requests)252StopAtFirstMatch bool253// Stream the input without sorting254Stream bool255// NoMeta disables display of metadata for the matches256NoMeta bool257// Timestamp enables display of timestamp for the matcher258Timestamp bool259// Project is used to avoid sending same HTTP request multiple times260Project bool261// NewTemplates only runs newly added templates from the repository262NewTemplates bool263// NewTemplatesWithVersion runs new templates added in specific version264NewTemplatesWithVersion goflags.StringSlice265// NoInteractsh disables use of interactsh server for interaction polling266NoInteractsh bool267// EnvironmentVariables enables support for environment variables268EnvironmentVariables bool269// MatcherStatus displays optional status for the failed matches as well270MatcherStatus bool271// ClientCertFile client certificate file (PEM-encoded) used for authenticating against scanned hosts272ClientCertFile string273// ClientKeyFile client key file (PEM-encoded) used for authenticating against scanned hosts274ClientKeyFile string275// ClientCAFile client certificate authority file (PEM-encoded) used for authenticating against scanned hosts276ClientCAFile string277// Deprecated: Use ZTLS library278ZTLS bool279// AllowLocalFileAccess allows local file access from templates payloads280AllowLocalFileAccess bool281// RestrictLocalNetworkAccess restricts local network access from templates requests282RestrictLocalNetworkAccess bool283// ShowMatchLine enables display of match line number284ShowMatchLine bool285// EnablePprof enables exposing pprof runtime information with a webserver.286EnablePprof bool287// StoreResponse stores received response to output directory288StoreResponse bool289// StoreResponseDir stores received response to custom directory290StoreResponseDir string291// DisableRedirects disables following redirects for http request module292DisableRedirects bool293// SNI custom hostname294SNI string295// InputFileMode specifies the mode of input file (jsonl, burp, openapi, swagger, etc)296InputFileMode string297// DialerKeepAlive sets the keep alive duration for network requests.298DialerKeepAlive time.Duration299// Interface to use for network scan300Interface string301// SourceIP sets custom source IP address for network requests302SourceIP string303// AttackType overrides template level attack-type configuration304AttackType string305// ResponseReadSize is the maximum size of response to read306ResponseReadSize int307// ResponseSaveSize is the maximum size of response to save308ResponseSaveSize int309// Health Check310HealthCheck bool311// Time to wait between each input read operation before closing the stream312InputReadTimeout time.Duration313// Disable stdin for input processing314DisableStdin bool315// IncludeConditions is the list of conditions templates should match316IncludeConditions goflags.StringSlice317// Enable uncover engine318Uncover bool319// Uncover search query320UncoverQuery goflags.StringSlice321// Uncover search engine322UncoverEngine goflags.StringSlice323// Uncover search field324UncoverField string325// Uncover search limit326UncoverLimit int327// Uncover search delay328UncoverRateLimit int329// ScanAllIPs associated to a dns record330ScanAllIPs bool331// IPVersion to scan (4,6)332IPVersion goflags.StringSlice333// PublicTemplateDisableDownload disables downloading templates from the nuclei-templates public repository334PublicTemplateDisableDownload bool335// GitHub token used to clone/pull from private repos for custom templates336GitHubToken string337// GitHubTemplateRepo is the list of custom public/private templates GitHub repos338GitHubTemplateRepo []string339// GitHubTemplateDisableDownload disables downloading templates from custom GitHub repositories340GitHubTemplateDisableDownload bool341// GitLabServerURL is the gitlab server to use for custom templates342GitLabServerURL string343// GitLabToken used to clone/pull from private repos for custom templates344GitLabToken string345// GitLabTemplateRepositoryIDs is the comma-separated list of custom gitlab repositories IDs346GitLabTemplateRepositoryIDs []int347// GitLabTemplateDisableDownload disables downloading templates from custom GitLab repositories348GitLabTemplateDisableDownload bool349// AWS access profile from ~/.aws/credentials file for downloading templates from S3 bucket350AwsProfile string351// AWS access key for downloading templates from S3 bucket352AwsAccessKey string353// AWS secret key for downloading templates from S3 bucket354AwsSecretKey string355// AWS bucket name for downloading templates from S3 bucket356AwsBucketName string357// AWS Region name where AWS S3 bucket is located358AwsRegion string359// AwsTemplateDisableDownload disables downloading templates from AWS S3 buckets360AwsTemplateDisableDownload bool361// AzureContainerName for downloading templates from Azure Blob Storage. Example: templates362AzureContainerName string363// AzureTenantID for downloading templates from Azure Blob Storage. Example: 00000000-0000-0000-0000-000000000000364AzureTenantID string365// AzureClientID for downloading templates from Azure Blob Storage. Example: 00000000-0000-0000-0000-000000000000366AzureClientID string367// AzureClientSecret for downloading templates from Azure Blob Storage. Example: 00000000-0000-0000-0000-000000000000368AzureClientSecret string369// AzureServiceURL for downloading templates from Azure Blob Storage. Example: https://XXXXXXXXXX.blob.core.windows.net/370AzureServiceURL string371// AzureTemplateDisableDownload disables downloading templates from Azure Blob Storage372AzureTemplateDisableDownload bool373// Scan Strategy (auto,hosts-spray,templates-spray)374ScanStrategy string375// Fuzzing Type overrides template level fuzzing-type configuration376FuzzingType string377// Fuzzing Mode overrides template level fuzzing-mode configuration378FuzzingMode string379// TlsImpersonate enables TLS impersonation380TlsImpersonate bool381// DisplayFuzzPoints enables display of fuzz points for fuzzing382DisplayFuzzPoints bool383// FuzzAggressionLevel is the level of fuzzing aggression (low, medium, high.)384FuzzAggressionLevel string385// FuzzParamFrequency is the frequency of fuzzing parameters386FuzzParamFrequency int387// CodeTemplateSignaturePublicKey is the custom public key used to verify the template signature (algorithm is automatically inferred from the length)388CodeTemplateSignaturePublicKey string389// CodeTemplateSignatureAlgorithm specifies the sign algorithm (rsa, ecdsa)390CodeTemplateSignatureAlgorithm string391// SignTemplates enables signing of templates392SignTemplates bool393// EnableCodeTemplates enables code templates394EnableCodeTemplates bool395// DisableUnsignedTemplates disables processing of unsigned templates396DisableUnsignedTemplates bool397// EnableSelfContainedTemplates enables processing of self-contained templates398EnableSelfContainedTemplates bool399// EnableGlobalMatchersTemplates enables processing of global-matchers templates400EnableGlobalMatchersTemplates bool401// EnableFileTemplates enables file templates402EnableFileTemplates bool403// Disables cloud upload404EnableCloudUpload bool405// ScanID is the scan ID to use for cloud upload406ScanID string407// ScanName is the name of the scan to be uploaded408ScanName string409// ScanUploadFile is the jsonl file to upload scan results to cloud410ScanUploadFile string411// TeamID is the team ID to use for cloud upload412TeamID string413// JsConcurrency is the number of concurrent js routines to run414JsConcurrency int415// SecretsFile is file containing secrets for nuclei416SecretsFile goflags.StringSlice417// PreFetchSecrets pre-fetches the secrets from the auth provider418PreFetchSecrets bool419// FormatUseRequiredOnly only uses required fields when generating requests420FormatUseRequiredOnly bool421// SkipFormatValidation is used to skip format validation422SkipFormatValidation bool423// PayloadConcurrency is the number of concurrent payloads to run per template424PayloadConcurrency int425// ProbeConcurrency is the number of concurrent http probes to run with httpx426ProbeConcurrency int427// Dast only runs DAST templates428DAST bool429// DASTServer is the flag to start nuclei as a DAST server430DASTServer bool431// DASTServerToken is the token optional for the dast server432DASTServerToken string433// DASTServerAddress is the address for the dast server434DASTServerAddress string435// DASTReport enables dast report server & final report generation436DASTReport bool437// Scope contains a list of regexes for in-scope URLS438Scope goflags.StringSlice439// OutOfScope contains a list of regexes for out-scope URLS440OutOfScope goflags.StringSlice441// HttpApiEndpoint is the experimental http api endpoint442HttpApiEndpoint string443// ListTemplateProfiles lists all available template profiles444ListTemplateProfiles bool445// LoadHelperFileFunction is a function that will be used to execute LoadHelperFile.446// If none is provided, then the default implementation will be used.447LoadHelperFileFunction LoadHelperFileFunction448// Logger is the gologger instance for this optionset449Logger *gologger.Logger450// NoCacheTemplates disables caching of templates451DoNotCacheTemplates bool452// Unique identifier of the execution session453ExecutionId string454// Parser is a cached parser for the template store455Parser any456// timeouts contains various types of timeouts used in nuclei457// these timeouts are derived from dial-timeout (-timeout) with known multipliers458// This is internally managed and does not need to be set by user by explicitly setting459// this overrides the default/derived one460timeouts *Timeouts461// m is a mutex to protect timeouts from concurrent access462m sync.Mutex463}464465func (options *Options) Copy() *Options {466optCopy := &Options{467Tags: options.Tags,468ExcludeTags: options.ExcludeTags,469Workflows: options.Workflows,470WorkflowURLs: options.WorkflowURLs,471Templates: options.Templates,472TemplateURLs: options.TemplateURLs,473AITemplatePrompt: options.AITemplatePrompt,474RemoteTemplateDomainList: options.RemoteTemplateDomainList,475ExcludedTemplates: options.ExcludedTemplates,476ExcludeMatchers: options.ExcludeMatchers,477CustomHeaders: options.CustomHeaders,478Vars: options.Vars,479Severities: options.Severities,480ExcludeSeverities: options.ExcludeSeverities,481Authors: options.Authors,482Protocols: options.Protocols,483ExcludeProtocols: options.ExcludeProtocols,484IncludeTags: options.IncludeTags,485IncludeTemplates: options.IncludeTemplates,486IncludeIds: options.IncludeIds,487ExcludeIds: options.ExcludeIds,488InternalResolversList: options.InternalResolversList,489ProjectPath: options.ProjectPath,490InteractshURL: options.InteractshURL,491InteractshToken: options.InteractshToken,492Targets: options.Targets,493ExcludeTargets: options.ExcludeTargets,494TargetsFilePath: options.TargetsFilePath,495Resume: options.Resume,496Output: options.Output,497ProxyInternal: options.ProxyInternal,498ListDslSignatures: options.ListDslSignatures,499Proxy: options.Proxy,500AliveHttpProxy: options.AliveHttpProxy,501AliveSocksProxy: options.AliveSocksProxy,502NewTemplatesDirectory: options.NewTemplatesDirectory,503TraceLogFile: options.TraceLogFile,504ErrorLogFile: options.ErrorLogFile,505ReportingDB: options.ReportingDB,506ReportingConfig: options.ReportingConfig,507MarkdownExportDirectory: options.MarkdownExportDirectory,508MarkdownExportSortMode: options.MarkdownExportSortMode,509SarifExport: options.SarifExport,510ResolversFile: options.ResolversFile,511StatsInterval: options.StatsInterval,512MetricsPort: options.MetricsPort,513MaxHostError: options.MaxHostError,514TrackError: options.TrackError,515NoHostErrors: options.NoHostErrors,516BulkSize: options.BulkSize,517TemplateThreads: options.TemplateThreads,518HeadlessBulkSize: options.HeadlessBulkSize,519HeadlessTemplateThreads: options.HeadlessTemplateThreads,520Timeout: options.Timeout,521Retries: options.Retries,522RateLimit: options.RateLimit,523RateLimitDuration: options.RateLimitDuration,524RateLimitMinute: options.RateLimitMinute,525PageTimeout: options.PageTimeout,526InteractionsCacheSize: options.InteractionsCacheSize,527InteractionsPollDuration: options.InteractionsPollDuration,528InteractionsEviction: options.InteractionsEviction,529InteractionsCoolDownPeriod: options.InteractionsCoolDownPeriod,530MaxRedirects: options.MaxRedirects,531FollowRedirects: options.FollowRedirects,532FollowHostRedirects: options.FollowHostRedirects,533OfflineHTTP: options.OfflineHTTP,534ForceAttemptHTTP2: options.ForceAttemptHTTP2,535StatsJSON: options.StatsJSON,536Headless: options.Headless,537ShowBrowser: options.ShowBrowser,538HeadlessOptionalArguments: options.HeadlessOptionalArguments,539DisableClustering: options.DisableClustering,540UseInstalledChrome: options.UseInstalledChrome,541SystemResolvers: options.SystemResolvers,542ShowActions: options.ShowActions,543Metrics: options.Metrics,544Debug: options.Debug,545DebugRequests: options.DebugRequests,546DebugResponse: options.DebugResponse,547DisableHTTPProbe: options.DisableHTTPProbe,548LeaveDefaultPorts: options.LeaveDefaultPorts,549AutomaticScan: options.AutomaticScan,550Silent: options.Silent,551Validate: options.Validate,552NoStrictSyntax: options.NoStrictSyntax,553Verbose: options.Verbose,554VerboseVerbose: options.VerboseVerbose,555ShowVarDump: options.ShowVarDump,556VarDumpLimit: options.VarDumpLimit,557NoColor: options.NoColor,558UpdateTemplates: options.UpdateTemplates,559JSONL: options.JSONL,560JSONRequests: options.JSONRequests,561OmitRawRequests: options.OmitRawRequests,562HTTPStats: options.HTTPStats,563OmitTemplate: options.OmitTemplate,564JSONExport: options.JSONExport,565JSONLExport: options.JSONLExport,566Redact: options.Redact,567EnableProgressBar: options.EnableProgressBar,568TemplateDisplay: options.TemplateDisplay,569TemplateList: options.TemplateList,570TagList: options.TagList,571HangMonitor: options.HangMonitor,572Stdin: options.Stdin,573StopAtFirstMatch: options.StopAtFirstMatch,574Stream: options.Stream,575NoMeta: options.NoMeta,576Timestamp: options.Timestamp,577Project: options.Project,578NewTemplates: options.NewTemplates,579NewTemplatesWithVersion: options.NewTemplatesWithVersion,580NoInteractsh: options.NoInteractsh,581EnvironmentVariables: options.EnvironmentVariables,582MatcherStatus: options.MatcherStatus,583ClientCertFile: options.ClientCertFile,584ClientKeyFile: options.ClientKeyFile,585ClientCAFile: options.ClientCAFile,586ZTLS: options.ZTLS,587AllowLocalFileAccess: options.AllowLocalFileAccess,588RestrictLocalNetworkAccess: options.RestrictLocalNetworkAccess,589ShowMatchLine: options.ShowMatchLine,590EnablePprof: options.EnablePprof,591StoreResponse: options.StoreResponse,592StoreResponseDir: options.StoreResponseDir,593DisableRedirects: options.DisableRedirects,594SNI: options.SNI,595InputFileMode: options.InputFileMode,596DialerKeepAlive: options.DialerKeepAlive,597Interface: options.Interface,598SourceIP: options.SourceIP,599AttackType: options.AttackType,600ResponseReadSize: options.ResponseReadSize,601ResponseSaveSize: options.ResponseSaveSize,602HealthCheck: options.HealthCheck,603InputReadTimeout: options.InputReadTimeout,604DisableStdin: options.DisableStdin,605IncludeConditions: options.IncludeConditions,606Uncover: options.Uncover,607UncoverQuery: options.UncoverQuery,608UncoverEngine: options.UncoverEngine,609UncoverField: options.UncoverField,610UncoverLimit: options.UncoverLimit,611UncoverRateLimit: options.UncoverRateLimit,612ScanAllIPs: options.ScanAllIPs,613IPVersion: options.IPVersion,614PublicTemplateDisableDownload: options.PublicTemplateDisableDownload,615GitHubToken: options.GitHubToken,616GitHubTemplateRepo: options.GitHubTemplateRepo,617GitHubTemplateDisableDownload: options.GitHubTemplateDisableDownload,618GitLabServerURL: options.GitLabServerURL,619GitLabToken: options.GitLabToken,620GitLabTemplateRepositoryIDs: options.GitLabTemplateRepositoryIDs,621GitLabTemplateDisableDownload: options.GitLabTemplateDisableDownload,622AwsProfile: options.AwsProfile,623AwsAccessKey: options.AwsAccessKey,624AwsSecretKey: options.AwsSecretKey,625AwsBucketName: options.AwsBucketName,626AwsRegion: options.AwsRegion,627AwsTemplateDisableDownload: options.AwsTemplateDisableDownload,628AzureContainerName: options.AzureContainerName,629AzureTenantID: options.AzureTenantID,630AzureClientID: options.AzureClientID,631AzureClientSecret: options.AzureClientSecret,632AzureServiceURL: options.AzureServiceURL,633AzureTemplateDisableDownload: options.AzureTemplateDisableDownload,634ScanStrategy: options.ScanStrategy,635FuzzingType: options.FuzzingType,636FuzzingMode: options.FuzzingMode,637TlsImpersonate: options.TlsImpersonate,638DisplayFuzzPoints: options.DisplayFuzzPoints,639FuzzAggressionLevel: options.FuzzAggressionLevel,640FuzzParamFrequency: options.FuzzParamFrequency,641CodeTemplateSignaturePublicKey: options.CodeTemplateSignaturePublicKey,642CodeTemplateSignatureAlgorithm: options.CodeTemplateSignatureAlgorithm,643SignTemplates: options.SignTemplates,644EnableCodeTemplates: options.EnableCodeTemplates,645DisableUnsignedTemplates: options.DisableUnsignedTemplates,646EnableSelfContainedTemplates: options.EnableSelfContainedTemplates,647EnableGlobalMatchersTemplates: options.EnableGlobalMatchersTemplates,648EnableFileTemplates: options.EnableFileTemplates,649EnableCloudUpload: options.EnableCloudUpload,650ScanID: options.ScanID,651ScanName: options.ScanName,652ScanUploadFile: options.ScanUploadFile,653TeamID: options.TeamID,654JsConcurrency: options.JsConcurrency,655SecretsFile: options.SecretsFile,656PreFetchSecrets: options.PreFetchSecrets,657FormatUseRequiredOnly: options.FormatUseRequiredOnly,658SkipFormatValidation: options.SkipFormatValidation,659PayloadConcurrency: options.PayloadConcurrency,660ProbeConcurrency: options.ProbeConcurrency,661DAST: options.DAST,662DASTServer: options.DASTServer,663DASTServerToken: options.DASTServerToken,664DASTServerAddress: options.DASTServerAddress,665DASTReport: options.DASTReport,666Scope: options.Scope,667OutOfScope: options.OutOfScope,668HttpApiEndpoint: options.HttpApiEndpoint,669ListTemplateProfiles: options.ListTemplateProfiles,670LoadHelperFileFunction: options.LoadHelperFileFunction,671Logger: options.Logger,672DoNotCacheTemplates: options.DoNotCacheTemplates,673ExecutionId: options.ExecutionId,674Parser: options.Parser,675}676optCopy.SetTimeouts(options.timeouts)677return optCopy678}679680// SetTimeouts sets the timeout variants to use for the executor681func (opts *Options) SetTimeouts(t *Timeouts) {682opts.timeouts = t683}684685// GetTimeouts returns the timeout variants to use for the executor686func (eo *Options) GetTimeouts() *Timeouts {687eo.m.Lock()688defer eo.m.Unlock()689if eo.timeouts != nil {690// redundant but apply to avoid any potential issues691eo.timeouts.ApplyDefaults()692return eo.timeouts693}694// set timeout variant value695eo.timeouts = NewTimeoutVariant(eo.Timeout)696eo.timeouts.ApplyDefaults()697return eo.timeouts698}699700// Timeouts is a struct that contains all the timeout variants for nuclei701// dialer timeout is used to derive other timeouts702type Timeouts struct {703// DialTimeout for fastdialer (default 10s)704DialTimeout time.Duration705// Tcp(Network Protocol) Read From Connection Timeout (default 5s)706TcpReadTimeout time.Duration707// Http Response Header Timeout (default 10s)708// this timeout prevents infinite hangs started by server if any709// this is temporarily overridden when using @timeout request annotation710HttpResponseHeaderTimeout time.Duration711// HttpTimeout for http client (default -> 3 x dial-timeout = 30s)712HttpTimeout time.Duration713// JsCompilerExec timeout/deadline (default -> 2 x dial-timeout = 20s)714JsCompilerExecutionTimeout time.Duration715// CodeExecutionTimeout for code execution (default -> 3 x dial-timeout = 30s)716CodeExecutionTimeout time.Duration717}718719// NewTimeoutVariant creates a new timeout variant with the given dial timeout in seconds720func NewTimeoutVariant(dialTimeoutSec int) *Timeouts {721tv := &Timeouts{722DialTimeout: time.Duration(dialTimeoutSec) * time.Second,723}724tv.ApplyDefaults()725return tv726}727728// ApplyDefaults applies default values to timeout variants when missing729func (tv *Timeouts) ApplyDefaults() {730if tv.DialTimeout == 0 {731tv.DialTimeout = 10 * time.Second732}733if tv.TcpReadTimeout == 0 {734tv.TcpReadTimeout = 5 * time.Second735}736if tv.HttpResponseHeaderTimeout == 0 {737tv.HttpResponseHeaderTimeout = 10 * time.Second738}739if tv.HttpTimeout == 0 {740tv.HttpTimeout = 3 * tv.DialTimeout741}742if tv.JsCompilerExecutionTimeout == 0 {743tv.JsCompilerExecutionTimeout = 2 * tv.DialTimeout744}745if tv.CodeExecutionTimeout == 0 {746tv.CodeExecutionTimeout = 3 * tv.DialTimeout747}748}749750// ShouldLoadResume resume file751func (options *Options) ShouldLoadResume() bool {752return options.Resume != "" && fileutil.FileExists(options.Resume)753}754755// ShouldSaveResume file756func (options *Options) ShouldSaveResume() bool {757return true758}759760// ShouldFollowHTTPRedirects determines if http redirects should be followed761func (options *Options) ShouldFollowHTTPRedirects() bool {762return options.FollowRedirects || options.FollowHostRedirects763}764765// HasClientCertificates determines if any client certificate was specified766func (options *Options) HasClientCertificates() bool {767return options.ClientCertFile != "" || options.ClientCAFile != "" || options.ClientKeyFile != ""768}769770// DefaultOptions returns default options for nuclei771func DefaultOptions() *Options {772return &Options{773RateLimit: 150,774RateLimitDuration: time.Second,775BulkSize: 25,776TemplateThreads: 25,777HeadlessBulkSize: 10,778PayloadConcurrency: 25,779HeadlessTemplateThreads: 10,780ProbeConcurrency: 50,781Timeout: 5,782Retries: 1,783MaxHostError: 30,784ResponseReadSize: 10 * unitutils.Mega,785ResponseSaveSize: unitutils.Mega,786}787}788789func (options *Options) ShouldUseHostError() bool {790return options.MaxHostError > 0 && !options.NoHostErrors791}792793func (options *Options) ParseHeadlessOptionalArguments() map[string]string {794optionalArguments := make(map[string]string)795for _, v := range options.HeadlessOptionalArguments {796if argParts := strings.SplitN(v, "=", 2); len(argParts) >= 2 {797key := strings.TrimSpace(argParts[0])798value := strings.TrimSpace(argParts[1])799if key != "" && value != "" {800optionalArguments[key] = value801}802}803}804return optionalArguments805}806807// LoadHelperFile loads a helper file needed for the template.808//809// If LoadHelperFileFunction is set, then that function will be used.810// Otherwise, the default implementation will be used, which respects the sandbox rules and only loads files from allowed directories.811func (options *Options) LoadHelperFile(helperFile, templatePath string, catalog catalog.Catalog) (io.ReadCloser, error) {812if options.LoadHelperFileFunction != nil {813return options.LoadHelperFileFunction(helperFile, templatePath, catalog)814}815return options.defaultLoadHelperFile(helperFile, templatePath, catalog)816}817818// defaultLoadHelperFile loads a helper file needed for the template819// this respects the sandbox rules and only loads files from820// allowed directories821func (options *Options) defaultLoadHelperFile(helperFile, templatePath string, catalog catalog.Catalog) (io.ReadCloser, error) {822if !options.AllowLocalFileAccess {823// if global file access is disabled try loading with restrictions824absPath, err := options.GetValidAbsPath(helperFile, templatePath)825if err != nil {826return nil, err827}828helperFile = absPath829}830f, err := os.Open(helperFile)831if err != nil {832return nil, errkit.Wrapf(err, "could not open file %v", helperFile)833}834return f, nil835}836837// GetValidAbsPath returns absolute path of helper file if it is allowed to be loaded838// this respects the sandbox rules and only loads files from allowed directories839func (o *Options) GetValidAbsPath(helperFilePath, templatePath string) (string, error) {840// Conditions to allow helper file841// 1. If helper file is present in nuclei-templates directory842// 2. If helper file and template file are in same directory given that its not root directory843844// resolve and clean helper file path845// ResolveNClean uses a custom base path instead of CWD846resolvedPath, err := fileutil.ResolveNClean(helperFilePath, config.DefaultConfig.GetTemplateDir())847if err == nil {848// As per rule 1, if helper file is present in nuclei-templates directory, allow it849if strings.HasPrefix(resolvedPath, config.DefaultConfig.GetTemplateDir()) {850return resolvedPath, nil851}852}853854// CleanPath resolves using CWD and cleans the path855helperFilePath, err = fileutil.CleanPath(helperFilePath)856if err != nil {857return "", errkit.Wrapf(err, "could not clean helper file path %v", helperFilePath)858}859860templatePath, err = fileutil.CleanPath(templatePath)861if err != nil {862return "", errkit.Wrapf(err, "could not clean template path %v", templatePath)863}864865// As per rule 2, if template and helper file exist in same directory or helper file existed in any child dir of template dir866// and both of them are present in user home directory, allow it867// Review: should we keep this rule ? add extra option to disable this ?868if isHomeDir(helperFilePath) && isHomeDir(templatePath) && strings.HasPrefix(filepath.Dir(helperFilePath), filepath.Dir(templatePath)) {869return helperFilePath, nil870}871872// all other cases are denied873return "", errkit.Newf("access to helper file %v denied", helperFilePath)874}875876// SetExecutionID sets the execution ID for the options877func (options *Options) SetExecutionID(id string) {878options.m.Lock()879defer options.m.Unlock()880options.ExecutionId = id881}882883// GetExecutionID gets the execution ID for the options884func (options *Options) GetExecutionID() string {885options.m.Lock()886defer options.m.Unlock()887return options.ExecutionId888}889890// isHomeDir checks if given is home directory891func isHomeDir(path string) bool {892homeDir := folderutil.HomeDirOrDefault("")893return strings.HasPrefix(path, homeDir)894}895896897