### Install Nuclei Library Source: https://github.com/projectdiscovery/nuclei/blob/dev/lib/README.md Add the Nuclei library to your Go project using the go get command or by importing it directly into your Go file. ```bash go get -u github.com/projectdiscovery/nuclei/v3/lib ``` ```go import nuclei "github.com/projectdiscovery/nuclei/v3/lib" ``` -------------------------------- ### Install Nuclei using Go Source: https://github.com/projectdiscovery/nuclei/blob/dev/README.md Install the Nuclei tool using the Go package manager. Ensure you have Go version 1.24.2 or higher installed. ```sh go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest ``` -------------------------------- ### Matcher Size Examples Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Examples demonstrating how to specify acceptable response sizes for a matcher. ```yaml size: - 3029 - 2042 ``` -------------------------------- ### File Request Extractor Example Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Example of a file request with regex extractor and specified extensions. Matches specific GUID patterns in .txt, .go, and .json files. ```yaml extractors: - type: regex regex: - amzn.mws.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} extensions: - all ``` -------------------------------- ### Matcher Part Examples Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Examples demonstrating how to specify the 'part' field for matchers, indicating which part of the response to analyze. ```yaml part: body ``` ```yaml part: raw ``` -------------------------------- ### Matcher Name Example Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Example of how to name a matcher. The name should be lowercase and contain no spaces or underscores. ```yaml name: cookie-matcher ``` -------------------------------- ### Matcher Status Code Examples Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Examples showing how to define acceptable status codes for a matcher. ```yaml status: - 200 - 302 ``` -------------------------------- ### Template Description Example Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Example of a description highlighting a specific vulnerability. ```yaml description: Subversion ALM for the enterprise before 8.8.2 allows reflected XSS at multiple locations ``` -------------------------------- ### StringSlice Example - CVE ID Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Example of a CVE ID string. ```yaml CVE-2020-14420 ``` -------------------------------- ### Network Input Data Examples Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Examples of data formats for network inputs. Supports plain text and hex-decoded strings. ```yaml data: TEST ``` ```yaml data: hex_decode('50494e47') ``` -------------------------------- ### Nuclei Help Output Example Source: https://github.com/projectdiscovery/nuclei/blob/dev/README.md This is a sample of the full help output for Nuclei, detailing its usage and available flags categorized by function. ```yaml Nuclei is a fast, template based vulnerability scanner focusing On extensive configurability, massive extensibility and ease of use. Usage: ./nuclei [flags] Flags: TARGET: -u, -target string[] target URLs/hosts to scan -l, -list string path to file containing a list of target URLs/hosts to scan (one per line) -eh, -exclude-hosts string[] hosts to exclude to scan from the input list (ip, cidr, hostname) -resume string resume scan from and save to specified file (clustering will be disabled) -sa, -scan-all-ips scan all the IP's associated with dns record -iv, -ip-version string[] IP version to scan of hostname (4,6) - (default 4) TARGET-FORMAT: -im, -input-mode string mode of input file (list, burp, jsonl, yaml, openapi, swagger) (default "list") -ro, -required-only use only required fields in input format when generating requests -sfv, -skip-format-validation skip format validation (like missing vars) when parsing input file TEMPLATES: -nt, -new-templates run only new templates added in latest nuclei-templates release -ntv, -new-templates-version string[] run new templates added in specific version -as, -automatic-scan automatic web scan using wappalyzer technology detection to tags mapping -t, -templates string[] list of template or template directory to run (comma-separated, file) -turl, -template-url string[] template url or list containing template urls to run (comma-separated, file) -ai, -prompt string generate and run template using ai prompt -w, -workflows string[] list of workflow or workflow directory to run (comma-separated, file) -wurl, -workflow-url string[] workflow url or list containing workflow urls to run (comma-separated, file) -validate validate the passed templates to nuclei -nss, -no-strict-syntax disable strict syntax check on templates -td, -template-display displays the templates content -tl list all templates matching current filters -tgl list all available tags -sign signs the templates with the private key defined in NUCLEI_SIGNATURE_PRIVATE_KEY env variable -code enable loading code protocol-based templates -dut, -disable-unsigned-templates disable running unsigned templates or templates with mismatched signature -esc, -enable-self-contained enable loading self-contained templates -egm, -enable-global-matchers enable loading global matchers templates -file enable loading file templates ``` -------------------------------- ### RawStringSlice Example - References Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Example of a list of raw string references for a Nuclei template. ```yaml - https://github.com/strapi/strapi - https://github.com/getgrav/grav ``` -------------------------------- ### scrapefuncs Example Source: https://github.com/projectdiscovery/nuclei/blob/dev/pkg/js/devtools/scrapefuncs/README.md An example demonstrating how to use scrapefuncs with an API key file and showcasing the output, including scraped function details and generated JSDoc comments. ```APIDOC ### Example ```console $ ./scrapefuncs -keyfile ~/.openai.key [+] Scraped 7 functions Name: Rand Signatures: "Rand(n int) []byte" Description: Rand returns a random byte slice of length n Name: RandInt Signatures: "RandInt() int" Description: RandInt returns a random int Name: log Signatures: "log(msg string)" Signatures: "log(msg map[string]interface{}) Description: log prints given input to stdout with [JS] prefix for debugging purposes Name: getNetworkPort Signatures: "getNetworkPort(port string, defaultPort string) string" Description: getNetworkPort registers defaultPort and returns defaultPort if it is a colliding port with other protocols Name: isPortOpen Signatures: "isPortOpen(host string, port string, [timeout int]) bool" Description: isPortOpen checks if given TCP port is open on host. timeout is optional and defaults to 5 seconds Name: isUDPPortOpen Signatures: "isUDPPortOpen(host string, port string, [timeout int]) bool" Description: isUDPPortOpen checks if the given UDP port is open on the host. Timeout is optional and defaults to 5 seconds. Name: ToBytes Signatures: "ToBytes(...interface{}) []byte" Description: ToBytes converts given input to byte slice Name: ToString Signatures: "ToString(...interface{}) string" Description: ToString converts given input to string [+] Generating jsdoc for all functions /** * Rand returns a random byte slice of length n * Rand(n int) []byte * @function * @param {number} n - The length of the byte slice. */ function Rand(n) { // implemented in go }; /** * RandInt returns a random int * RandInt() int * @function */ function RandInt() { // implemented in go }; /** * log prints given input to stdout with [JS] prefix for debugging purposes * log(msg string) * log(msg map[string]interface{}) * @function * @param {string|Object} msg - The message to print. */ function log(msg) { // implemented in go }; /** * getNetworkPort registers defaultPort and returns defaultPort if it is a colliding port with other protocols * getNetworkPort(port string, defaultPort string) string * @function * @param {string} port - The port to check. * @param {string} defaultPort - The default port to return if the port is colliding. */ function getNetworkPort(port, defaultPort) { // implemented in go }; /** * isPortOpen checks if given port is open on host. timeout is optional and defaults to 5 seconds * isPortOpen(host string, port string, [timeout int]) bool * @function * @param {string} host - The host to check. * @param {string} port - The port to check. * @param {number} [timeout=5] - The timeout in seconds. */ function isPortOpen(host, port, timeout = 5) { // implemented in go }; /** * ToBytes converts given input to byte slice * ToBytes(...interface{}) []byte * @function * @param {...any} args - The input to convert. */ function ToBytes(...args) { // implemented in go }; /** * ToString converts given input to string * ToString(...interface{}) string * @function * @param {...any} args - The input to convert. */ function ToString(...args) { // implemented in go }; ``` ``` -------------------------------- ### StringSlice Example - Tags Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Example of multiple tags for a Nuclei template, comma-separated. ```yaml # Example tags cve,cve2019,grafana,auth-bypass,dos ``` -------------------------------- ### Template Description Example Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Example of a detailed description for a Nuclei template. ```yaml description: Bower is a package manager which stores package information in the bower.json file ``` -------------------------------- ### DNS Request Name Example Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md This example shows how to set the 'name' field for a DNS request, typically using the '{{FQDN}}' variable to represent the input domain. ```yaml name: '{{FQDN}}' ``` -------------------------------- ### Matcher Binary Examples Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Examples of using the 'binary' field in matchers to specify hexadecimal byte patterns to search for in the response. ```yaml # Match for Springboot Heapdump Actuator "JAVA PROFILE", "HPROF", "Gunzip magic byte" binary: - 4a4156412050524f46494c45 - 4850524f46 - 1f8b080000000000 ``` ```yaml # Match for 7zip files binary: - 377ABCAF271C ``` -------------------------------- ### Specify File Extensions for Matching Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Define a list of file extensions or MIME types to perform matching on. Example includes .txt, .go, and .json. ```yaml extensions: - .txt - .go - .json ``` -------------------------------- ### StringSlice Example - Author Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Example of a single author string for a Nuclei template. ```yaml ``` -------------------------------- ### Template Name Example Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Example of a concise name for a Nuclei template. ```yaml name: bower.json file disclosure ``` -------------------------------- ### Template Tags Example Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Example of tags for a Nuclei template, separated by commas. ```yaml # Example tags tags: cve,cve2019,grafana,auth-bypass,dos ``` -------------------------------- ### DNS Request Retries Example Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md This example demonstrates setting the 'retries' field for a DNS request, indicating the number of times the request should be retried. ```yaml # Use a retry of 3 to 5 generally retries: 5 ``` -------------------------------- ### Template Metadata Example Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Example of custom metadata fields for a Nuclei template. ```yaml metadata: customField1: customValue1 ``` -------------------------------- ### Matcher Words Examples Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Examples of using the 'words' field in matchers to specify string patterns to look for in the response. ```yaml # Match for Outlook mail protection domain words: - mail.protection.outlook.com ``` ```yaml # Match for application/json in response headers words: - application/json ``` -------------------------------- ### Matcher Regex Examples Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Examples of using the 'regex' field in matchers to specify regular expression patterns to match against the response. ```yaml # Match for Linkerd Service via Regex regex: - (?mi)^Via\s*?:.*?linkerd.*$ ``` ```yaml # Match for Open Redirect via Location header regex: - (?m)^(?:Location\s*?:\s*?)(?:https?://|//)?(?:[a-zA-Z0-9\-_\.@]*)example\.com.*$ ``` -------------------------------- ### Template Name Example Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Example of a descriptive name for a Nuclei template. ```yaml name: Nagios Default Credentials Check ``` -------------------------------- ### Matcher XPath Example Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Example of using the 'xpath' field in matchers to query XML or HTML response content. ```yaml # XPath Matcher to check a title xpath: - /html/head/title[contains(text(), 'How to Find XPath')] ``` -------------------------------- ### Template References Example Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Lists relevant references and links for a Nuclei template. ```yaml reference: - https://github.com/strapi/strapi - https://github.com/getgrav/grav ``` -------------------------------- ### Define Denied File Extensions and MIME Types Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Specify a list of file extensions, directories, or MIME types to exclude from matching. Example includes .avi, .mov, and .mp3. ```yaml denylist: - .avi - .mov - .mp3 ``` -------------------------------- ### Configure HTTP Request with Matchers Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md This snippet demonstrates a basic HTTP GET request configuration with multiple matchers. It includes word, DSL, and status code matchers, combined with an 'and' condition. ```yaml matchers: - type: word words: - '[core]' - type: dsl condition: and dsl: - '!contains(tolower(body), '' ``` -------------------------------- ### Generate CPU, Memory, and Trace Profiles Source: https://github.com/projectdiscovery/nuclei/blob/dev/DESIGN.md Use the `-profile-mem` flag with Nuclei to generate CPU, memory, and execution trace files. The filename is dynamically generated using the current Git tag. ```bash nuclei -t nuclei-templates/ -u https://example.com -profile-mem=nuclei-$(git describe --tags) ``` -------------------------------- ### NewInputProvider Source: https://github.com/projectdiscovery/nuclei/blob/dev/pkg/input/README.md This function returns an InputProvider based on the input format. It selects the appropriate provider (list or http) to handle the given input. ```APIDOC ## NewInputProvider ### Description This function returns an InputProvider based by appropriately selecting input provider based on the input format (i.e. either list or http) and returns the provider that can handle that input format. ### Signature ```go func NewInputProvider(opts InputOptions) (InputProvider, error) ``` ### Parameters #### Path Parameters - **opts** (InputOptions) - Required - Options for input provider configuration. ``` -------------------------------- ### Run Single Go Test Source: https://github.com/projectdiscovery/nuclei/blob/dev/CLAUDE.md Runs a single Go test case for a specific package. Use -v for verbose output. ```bash go test -v ./pkg/path/to/package -run TestName ``` -------------------------------- ### Build go-fuzz targets Source: https://github.com/projectdiscovery/nuclei/blob/dev/FUZZING.md Use these Makefile targets to build go-fuzz harnesses for specified packages. Ensure `GOFUZZ_PACKAGE` is set to a valid package path. ```bash make build-fuzz GOFUZZ_PACKAGE=./pkg/operators/matchers ``` ```bash make fuzz GOFUZZ_PACKAGE=./pkg/operators/matchers ``` -------------------------------- ### Basic Nuclei Engine Usage Source: https://github.com/projectdiscovery/nuclei/blob/dev/lib/README.md Initialize and execute the Nuclei engine with specific template filters, such as severity. Ensure to close the engine when done. ```go // create nuclei engine with options ne, err := nuclei.NewNucleiEngine( nuclei.WithTemplateFilters(nuclei.TemplateFilters{Severity: "critical"}), // run critical severity templates only ) if err != nil { panic(err) } // load targets and optionally probe non http/https targets ne.LoadTargets([]string{"scanme.sh"}, false) err = ne.ExecuteWithCallback(nil) if err != nil { panic(err) } defer ne.Close() ``` -------------------------------- ### Raw HTTP Requests Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Defines raw HTTP requests for testing. Supports basic GET and more complex POST requests with path traversal payloads. ```yaml GET /etc/passwd HTTP/1.1 Host: Content-Length: 4 ``` ```yaml POST /.%0d./.%0d./.%0d./.%0d./bin/sh HTTP/1.1 Host: {{Hostname}} User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0 Content-Length: 1 Connection: close echo echo cat /etc/passwd 2>&1 ``` -------------------------------- ### Display Nuclei Help Flags Source: https://github.com/projectdiscovery/nuclei/blob/dev/README.md Run this command to view all available command-line flags and options for the Nuclei tool. ```sh nuclei -h ``` -------------------------------- ### Generate API Reference with JSDoc Source: https://github.com/projectdiscovery/nuclei/blob/dev/pkg/js/devtools/README.md Use JSDoc to generate a static API reference site from JavaScript files. The generated site will be available in the 'api_reference/' directory. ```bash jsdoc -R [Homepage.md] -r -d api_reference -t [optional: jsdoc theme to use] generated/js ``` -------------------------------- ### Iterate Helper Function Examples Source: https://github.com/projectdiscovery/nuclei/blob/dev/pkg/tmplexec/flow/README.md Use the iterate function to loop over arrays or maps, safely handling empty or nil values. It can also be used with a custom separator for string iteration. ```javascript iterate(123,{"a":1,"b":2,"c":3}) // iterate over array with custom separator iterate([1,2,3,4,5], " ") ``` -------------------------------- ### Thread-Safe Nuclei Engine for Concurrency Source: https://github.com/projectdiscovery/nuclei/blob/dev/lib/README.md Utilize the thread-safe Nuclei engine for concurrent scans by managing goroutines with a WaitGroup. This example demonstrates running different types of templates on specified targets. ```go // create nuclei engine with options ne, err := nuclei.NewThreadSafeNucleiEngine() if err != nil{ panic(err) } // setup waitgroup to handle concurrency wg := &sync.WaitGroup{} // scan 1 = run dns templates on scanme.sh wg.Add(1) go func() { defer wg.Done() err = ne.ExecuteNucleiWithOpts([]string{"scanme.sh"}, nuclei.WithTemplateFilters(nuclei.TemplateFilters{ProtocolTypes: "http"})) if err != nil { panic(err) } }() // scan 2 = run http templates on honey.scanme.sh wg.Add(1) go func() { defer wg.Done() err = ne.ExecuteNucleiWithOpts([]string{"honey.scanme.sh"}, nuclei.WithTemplateFilters(nuclei.TemplateFilters{ProtocolTypes: "dns"})) if err != nil { panic(err) } }() // wait for all scans to finish wg.Wait() defer ne.Close() ``` -------------------------------- ### Set Maximum File Size for Processing Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Configure the maximum file size that Nuclei will process. Defaults to 1 GB, but can be adjusted or set to 'no' to process all content. Example sets limit to 5MB. ```yaml max-size: 5Mb ``` -------------------------------- ### Run Tests Source: https://github.com/projectdiscovery/nuclei/blob/dev/CONTRIBUTING.md Execute all project tests to ensure code integrity. This command should be run before submitting a Pull Request. ```sh make test ``` -------------------------------- ### Enable Archive Elaboration Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Set to true to enable the elaboration of archive files during matching. ```yaml archive: true ``` -------------------------------- ### Analyze Execution Trace with go tool trace Source: https://github.com/projectdiscovery/nuclei/blob/dev/DESIGN.md Examine the execution trace file generated by Nuclei using the `go tool trace` command to understand the program's execution flow. ```bash go tool trace nuclei.trace ``` -------------------------------- ### Format Go Code Source: https://github.com/projectdiscovery/nuclei/blob/dev/CLAUDE.md Formats Go code according to standard Go conventions. ```bash go fmt ./... ``` -------------------------------- ### Run Linters and Vet Source: https://github.com/projectdiscovery/nuclei/blob/dev/CONTRIBUTING.md Check code quality and identify potential issues using linters and the vet tool. This is a required step before submitting a PR. ```sh make vet ``` -------------------------------- ### Enable MIME Type Checking Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md Set to true to enable MIME type checks for file matching. ```yaml mime-type: true ``` -------------------------------- ### Expose Protocol Response Variables in Multi-Protocol Templates Source: https://github.com/projectdiscovery/nuclei/blob/dev/pkg/tmplexec/multiproto/README.md After a response is processed, this code adds its variables to the template context. This is a no-op if the template is not multi-protocol. Use `AddTemplateVars` to expose response variables in `proto_var` format. ```go outputEvent := request.responseToDSLMap(compiledRequest, response, domain, question, traceData) // expose response variables in proto_var format // this is no-op if the template is not a multi protocol template request.options.AddTemplateVars(request.Type(),request.ID, outputEvent) ``` -------------------------------- ### Run Nuclei on a Single Host Source: https://github.com/projectdiscovery/nuclei/blob/dev/README_ID.md Use this command to initiate a scan against a single target domain or URL. ```sh nuclei -target example.com ``` -------------------------------- ### Fuzzing Rule Keys Regex Source: https://github.com/projectdiscovery/nuclei/blob/dev/SYNTAX-REFERENCE.md An optional list of regular expressions to match key names for fuzzing. ```yaml # Examples of key regex keys-regex: - url.* ``` -------------------------------- ### Clean Up Go Modules Source: https://github.com/projectdiscovery/nuclei/blob/dev/CLAUDE.md Cleans up Go modules using the tidy command. ```bash make tidy ``` -------------------------------- ### Basic VHost Enumeration Flow Source: https://github.com/projectdiscovery/nuclei/blob/dev/pkg/tmplexec/flow/README.md This JavaScript code orchestrates vhost enumeration by executing SSL and DNS requests, iterating through potential vhosts, and then performing HTTP requests. It uses Nuclei JS bindings like `ssl()`, `dns()`, `iterate()`, and `set()`. ```javascript ssl(); dns(); for (let vhost of iterate(template["ssl_subject_cn"],template["ssl_subject_an"])) { set("vhost", vhost); http(); } ``` -------------------------------- ### Scrape JavaScript Helper Functions Source: https://github.com/projectdiscovery/nuclei/blob/dev/pkg/js/devtools/scrapefuncs/README.md Use this command to scrape helper functions from JavaScript files and generate JSDoc comments. Specify the OpenAI API key via a file or directly. The output is a JS file containing the documented functions. ```console Usage of ./scrapefuncs: -dir string directory to process (default "pkg/js/global") -key string openai api key -keyfile string openai api key file -out string output js file with declarations of all global functions ``` ```console $ ./scrapefuncs -keyfile ~/.openai.key [+] Scraped 7 functions ``` -------------------------------- ### Toggle Theme Functionality Source: https://github.com/projectdiscovery/nuclei/blob/dev/internal/server/templates/index.html Handles switching between light and dark themes and saves the user's preference in local storage. Updates the theme icon accordingly. ```javascript function toggleTheme() { const body = document.body; const themeIcon = document.getElementById('theme-icon'); const currentTheme = body.getAttribute('data-theme'); if (currentTheme === 'light') { body.removeAttribute('data-theme'); localStorage.setItem('theme', 'dark'); themeIcon.className = 'bi bi-moon-fill theme-icon'; } else { body.setAttribute('data-theme', 'light'); localStorage.setItem('theme', 'light'); themeIcon.className = 'bi bi-sun-fill theme-icon'; } } ``` ```javascript document.addEventListener('DOMContentLoaded', () => { const savedTheme = localStorage.getItem('theme'); const themeIcon = document.getElementById('theme-icon'); if (savedTheme === 'light') { document.body.setAttribute('data-theme', 'light'); themeIcon.className = 'bi bi-sun-fill theme-icon'; } }); ``` -------------------------------- ### Access Application with ClusterIP Service Source: https://github.com/projectdiscovery/nuclei/blob/dev/helm/templates/NOTES.txt For ClusterIP services, this script forwards traffic from localhost to the cluster and provides the access URL. ```bash {{- else if contains "ClusterIP" .Values.interactsh.service.type }} export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "nuclei.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}") export CONTAINER_PORT=$(kubectl get pod --namespace {{ .Release.Namespace }} $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}") echo "Visit http://127.0.0.1:8080 to use your application" kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:$CONTAINER_PORT {{- end }} ``` -------------------------------- ### Websocket Protocol Implementation in Go Source: https://github.com/projectdiscovery/nuclei/blob/dev/DESIGN.md This Go code defines the structure and methods for the websocket protocol within Nuclei. It includes fields for operators, address, and compilation logic, along with methods for executing requests, matching, and extracting data. Ensure all necessary imports and dependencies are handled for a complete implementation. ```go package websocket // Request is a request for the Websocket protocol type Request struct { // Operators for the current request go here. operators.Operators `yaml:",inline,omitempty"` CompiledOperators *operators.Operators `yaml:"-"` // description: | // Address contains address for the request Address string `yaml:"address,omitempty" jsonschema:"title=address for the websocket request,description=Address contains address for the request" // declarations here } // Compile compiles the request generators preparing any requests possible. func (r *Request) Compile(options *protocols.ExecuterOptions) error { r.options = options // request compilation here as well as client creation if len(r.Matchers) > 0 || len(r.Extractors) > 0 { compiled := &r.Operators if err := compiled.Compile(); err != nil { return errors.Wrap(err, "could not compile operators") } r.CompiledOperators = compiled } return nil } // Requests returns the total number of requests the rule will perform func (r *Request) Requests() int { if r.generator != nil { return r.generator.NewIterator().Total() } return 1 } // GetID returns the ID for the request if any. func (r *Request) GetID() string { return "" } // ExecuteWithResults executes the protocol requests and returns results instead of writing them. func (r *Request) ExecuteWithResults(input string, dynamicValues, previous output.InternalEvent, callback protocols.OutputEventCallback) error { // payloads init here if err := r.executeRequestWithPayloads(input, hostname, value, previous, callback); err != nil { return err } return nil } // ExecuteWithResults executes the protocol requests and returns results instead of writing them. func (r *Request) executeRequestWithPayloads(input, hostname string, dynamicValues, previous output.InternalEvent, callback protocols.OutputEventCallback) error { header := http.Header{} // make the actual request here after setting all options event := eventcreator.CreateEventWithAdditionalOptions(r, data, r.options.Options.Debug || r.options.Options.DebugResponse, func(internalWrappedEvent *output.InternalWrappedEvent) { internalWrappedEvent.OperatorsResult.PayloadValues = payloadValues }) if r.options.Options.Debug || r.options.Options.DebugResponse { responseOutput := responseBuilder.String() gologger.Debug().Msgf("[%s] Dumped Websocket response for %s", r.options.TemplateID, input) gologger.Print().Msgf("%s", responsehighlighter.Highlight(event.OperatorsResult, responseOutput, r.options.Options.NoColor)) } callback(event) return nil } func (r *Request) MakeResultEventItem(wrapped *output.InternalWrappedEvent) *output.ResultEvent { data := &output.ResultEvent{ TemplateID: types.ToString(r.options.TemplateID), TemplatePath: types.ToString(r.options.TemplatePath), // ... setting more values for result event } return data } // Match performs matching operation for a matcher on model and returns: // true and a list of matched snippets if the matcher type is supports it // otherwise false and an empty string slice func (r *Request) Match(data map[string]interface{}, matcher *matchers.Matcher) (bool, []string) { return protocols.MakeDefaultMatchFunc(data, matcher) } // Extract performs extracting operation for an extractor on model and returns true or false. func (r *Request) Extract(data map[string]interface{}, matcher *extractors.Extractor) map[string]struct{} { return protocols.MakeDefaultExtractFunc(data, matcher) } // MakeResultEvent creates a result event from internal wrapped event func (r *Request) MakeResultEvent(wrapped *output.InternalWrappedEvent) []*output.ResultEvent { return protocols.MakeDefaultResultEvent(r, wrapped) } // GetCompiledOperators returns a list of the compiled operators func (r *Request) GetCompiledOperators() []*operators.Operators { return []*operators.Operators{r.CompiledOperators} } // Type returns the type of the protocol request func (r *Request) Type() templateTypes.ProtocolType { return templateTypes.WebsocketProtocol } ``` -------------------------------- ### VHost Enumeration with Data Cleaning Source: https://github.com/projectdiscovery/nuclei/blob/dev/pkg/tmplexec/flow/README.md This template demonstrates vhost enumeration using flow, including cleaning extracted data. It removes wildcard prefixes from subject CN/AN and trailing dots from PTR values before performing HTTP requests. The `trim_suffix` function is used to clean the vhost before the HTTP request. ```yaml id: vhost-enum-flow info: name: vhost enum flow author: tarunKoyalwar severity: info description: | vhost enumeration by extracting potential vhost names from ssl certificate and dns ptr records flow: | ssl(); dns({hide: true}); for (let vhost of iterate(template["ssl_subject_cn"],template["ssl_subject_an"])) { vhost = vhost.replace("*.", "") set("vhost", vhost); http(); } ssl: - address: "{{Host}}:{{Port}}" dns: - name: "{{FQDN}}" type: PTR matchers: - type: word words: - "IN\tPTR" extractors: - type: regex name: ptrValue internal: true group: 1 regex: - "IN\tPTR\t(.+)" http: - raw: - | GET / HTTP/1.1 Host: {{trim_suffix(vhost, ".")}} matchers: - type: status negative: true status: - 400 - 502 extractors: - type: dsl dsl: - '"VHOST: " + vhost + ", SC: " + status_code + ", CL: " + content_length' ``` -------------------------------- ### Validate Host Access in Go Source: https://github.com/projectdiscovery/nuclei/blob/dev/pkg/js/CONTRIBUTE.md Use protocolstate.IsHostAllowed to validate host access before dialing connections when protocolstate.Dialer cannot be used. This enforces network policies. ```go if !protocolstate.IsHostAllowed(host) { // host is not valid according to network policy return false, protocolstate.ErrHostDenied.Msgf(host) } ```