nuclei/pkg/templates/templates.go

564 lines
23 KiB
Go
Raw Permalink Normal View History

//go:generate dstdocgen -path "" -structure Template -output templates_doc.go -package templates
package templates
import (
"fmt"
"io"
"path/filepath"
"strconv"
"strings"
"github.com/projectdiscovery/nuclei/v3/pkg/model"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/code"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/variables"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/dns"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/file"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/headless"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/http"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/javascript"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/network"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/ssl"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/websocket"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/whois"
"github.com/projectdiscovery/nuclei/v3/pkg/templates/types"
"github.com/projectdiscovery/nuclei/v3/pkg/utils"
"github.com/projectdiscovery/nuclei/v3/pkg/utils/json"
"github.com/projectdiscovery/nuclei/v3/pkg/workflows"
"github.com/projectdiscovery/utils/errkit"
fileutil "github.com/projectdiscovery/utils/file"
"go.uber.org/multierr"
"gopkg.in/yaml.v2"
)
2021-08-04 14:20:48 +05:30
// Template is a YAML input file which defines all the requests and
// other metadata for a template.
type Template struct {
2021-07-27 16:03:56 +05:30
// description: |
2021-09-01 15:48:01 +05:30
// ID is the unique id for the template.
2021-07-27 16:03:56 +05:30
//
// #### Good IDs
//
2021-08-03 20:36:26 +05:30
// A good ID uniquely identifies what the requests in the template
2021-07-27 16:03:56 +05:30
// are doing. Let's say you have a template that identifies a git-config
// file on the webservers, a good name would be `git-config-exposure`. Another
// example name is `azure-apps-nxdomain-takeover`.
// examples:
// - name: ID Example
2021-09-01 15:53:30 +05:30
// value: "\"CVE-2021-19520\""
2024-03-27 23:52:08 +05:30
ID string `yaml:"id" json:"id" jsonschema:"title=id of the template,description=The Unique ID for the template,required,example=cve-2021-19520,pattern=^([a-zA-Z0-9]+[-_])*[a-zA-Z0-9]+$"`
2021-07-27 16:03:56 +05:30
// description: |
2021-08-19 16:51:02 +05:30
// Info contains metadata information about the template.
2021-08-04 14:20:48 +05:30
// examples:
// - value: exampleInfoStructure
2024-03-27 23:52:08 +05:30
Info model.Info `yaml:"info" json:"info" jsonschema:"title=info for the template,description=Info contains metadata for the template,required,type=object"`
2021-07-27 16:03:56 +05:30
// description: |
// Flow contains the execution flow for the template.
// examples:
// - flow: |
// for region in regions {
// http(0)
// }
// for vpc in vpcs {
// http(1)
// }
//
2024-03-27 23:52:08 +05:30
Flow string `yaml:"flow,omitempty" json:"flow,omitempty" jsonschema:"title=template execution flow in js,description=Flow contains js code which defines how the template should be executed,type=string,example='flow: http(0) && http(1)'"`
// description: |
2021-08-04 14:20:48 +05:30
// Requests contains the http request to make in the template.
// WARNING: 'requests' will be deprecated and will be removed in a future release. Please use 'http' instead.
2021-08-04 14:20:48 +05:30
// examples:
// - value: exampleNormalHTTPRequest
2024-03-27 23:52:08 +05:30
RequestsHTTP []*http.Request `yaml:"requests,omitempty" json:"requests,omitempty" jsonschema:"title=http requests to make,description=HTTP requests to make for the template,deprecated=true"`
2021-07-27 16:03:56 +05:30
// description: |
// HTTP contains the http request to make in the template.
// examples:
// - value: exampleNormalHTTPRequest
// RequestsWithHTTP is placeholder(internal) only, and should not be used instead use RequestsHTTP
// Deprecated: Use RequestsHTTP instead.
RequestsWithHTTP []*http.Request `yaml:"http,omitempty" json:"http,omitempty" jsonschema:"title=http requests to make,description=HTTP requests to make for the template"`
// description: |
2021-07-27 16:03:56 +05:30
// DNS contains the dns request to make in the template
2021-08-04 14:20:48 +05:30
// examples:
// - value: exampleNormalDNSRequest
RequestsDNS []*dns.Request `yaml:"dns,omitempty" json:"dns,omitempty" jsonschema:"title=dns requests to make,description=DNS requests to make for the template"`
2021-07-27 16:03:56 +05:30
// description: |
// File contains the file request to make in the template
2021-08-04 14:20:48 +05:30
// examples:
// - value: exampleNormalFileRequest
RequestsFile []*file.Request `yaml:"file,omitempty" json:"file,omitempty" jsonschema:"title=file requests to make,description=File requests to make for the template"`
2021-07-27 16:03:56 +05:30
// description: |
// Network contains the network request to make in the template
// WARNING: 'network' will be deprecated and will be removed in a future release. Please use 'tcp' instead.
2021-08-04 14:20:48 +05:30
// examples:
// - value: exampleNormalNetworkRequest
2024-03-27 23:52:08 +05:30
RequestsNetwork []*network.Request `yaml:"network,omitempty" json:"network,omitempty" jsonschema:"title=network requests to make,description=Network requests to make for the template,deprecated=true"`
2021-07-27 16:03:56 +05:30
// description: |
// TCP contains the network request to make in the template
// examples:
// - value: exampleNormalNetworkRequest
// RequestsWithTCP is placeholder(internal) only, and should not be used instead use RequestsNetwork
// Deprecated: Use RequestsNetwork instead.
RequestsWithTCP []*network.Request `yaml:"tcp,omitempty" json:"tcp,omitempty" jsonschema:"title=network(tcp) requests to make,description=Network requests to make for the template"`
// description: |
2021-07-27 16:03:56 +05:30
// Headless contains the headless request to make in the template.
RequestsHeadless []*headless.Request `yaml:"headless,omitempty" json:"headless,omitempty" jsonschema:"title=headless requests to make,description=Headless requests to make for the template"`
2021-09-22 22:41:07 +05:30
// description: |
// SSL contains the SSL request to make in the template.
RequestsSSL []*ssl.Request `yaml:"ssl,omitempty" json:"ssl,omitempty" jsonschema:"title=ssl requests to make,description=SSL requests to make for the template"`
// description: |
// Websocket contains the Websocket request to make in the template.
RequestsWebsocket []*websocket.Request `yaml:"websocket,omitempty" json:"websocket,omitempty" jsonschema:"title=websocket requests to make,description=Websocket requests to make for the template"`
// description: |
// WHOIS contains the WHOIS request to make in the template.
RequestsWHOIS []*whois.Request `yaml:"whois,omitempty" json:"whois,omitempty" jsonschema:"title=whois requests to make,description=WHOIS requests to make for the template"`
Adding support for code templates (#2930) * Adding support for code templates * adding support for python, powershell and echo (test) * removing debug code * introducing command + trivial trust store mechanism * updating tests * adding basic tests * removing deprecated oracle * mod tidy * adding signature proto with debug prints * removing debug code * fixing test * fixing param order * improving test conditional build * disable file+offlinehttp+code with cloud * adding env vars * removing debug code * reorganizing test folders * adding code template test prototype with dummy priv/pub keys * bump go to 1.20 * fixing go version * fixing lint errors * adding fatal on pub-key test failure * switching to ecdsa asn1 * removing unused signature * fixing signature * adding more tests * extending core with engine args + powershell win test * adding unsigned code test * skip template signing in particular test case * improving test coverage * refactoring key names + adding already signed algo * removing debug code * fixing syntax * fixing lint issues * removing test template * fixing dns tests path * output fmt * adding interact * fixing lint issues * adding -sign cli helper * fixing nil pointer + parse inline keys * making rsa default * adding code prot. ref * moving file to correct loc * moving test * Issue 3339 headless fuzz (#3790) * Basic headless fuzzing * Remove debug statements * Add integration tests * Update template * Fix recognize payload value in matcher * Update tempalte * use req.SetURL() --------- Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io> * Auto Generate Syntax Docs + JSONSchema [Fri Jun 9 00:23:32 UTC 2023] :robot: * Add headless header and status matchers (#3794) * add headless header and status matchers * rename headers as header * add integration test for header+status * fix typo * add retry to py-interactsh integration test --------- Co-authored-by: Sandeep Singh <sandeep@projectdiscovery.io> Co-authored-by: Shubham Rasal <shubham@projectdiscovery.io> Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io> Co-authored-by: GitHub Action <action@github.com> Co-authored-by: Dogan Can Bakir <65292895+dogancanbakir@users.noreply.github.com> Co-authored-by: Tarun Koyalwar <45962551+tarunKoyalwar@users.noreply.github.com>
2023-06-09 17:24:24 +02:00
// description: |
// Code contains code snippets.
RequestsCode []*code.Request `yaml:"code,omitempty" json:"code,omitempty" jsonschema:"title=code snippets to make,description=Code snippets"`
javascript protocol for scripting (includes 15+ proto libs) (#4109) * rebase js-layer PR from @ice3man543 * package restructuring * working * fix duplicated event & matcher status * fix lint error * fix response field * add new functions * multiple minor improvements * fix incorrect stats in js protocol * sort output metadata in cli * remove temp files * remove dead code * add unit and integration test * fix lint error * add jsdoclint using llm * fix error in test * add js lint using llm * generate docs of libs * llm lint * remove duplicated docs * update generated docs * update prompt in doclint * update docs * temp disable version check test * fix unit test and add retry * fix panic in it * update and move jsdocs * updated jsdocs * update docs * update container platform in test * dir restructure and adding docs * add api_reference and remove markdown docs * fix imports * add javascript design and contribution docs * add js protocol documentation * update integration test and docs * update doc ext mdx->md * minor update to docs * new integration test and more * move go libs and add docs * gen new net docs and more * final docs update * add new devtool * use fastdialer * fix build fail * use fastdialer + network sandbox support * add reserved keyword 'Port' * update Port to new syntax * misc update * always enable templatectx in js protocol * move docs to 'js-proto-docs' repo * remove scrapefuncs binary --------- Co-authored-by: sandeep <8293321+ehsandeep@users.noreply.github.com>
2023-09-16 16:02:17 +05:30
// description: |
// Javascript contains the javascript request to make in the template.
RequestsJavascript []*javascript.Request `yaml:"javascript,omitempty" json:"javascript,omitempty" jsonschema:"title=javascript requests to make,description=Javascript requests to make for the template"`
Adding support for code templates (#2930) * Adding support for code templates * adding support for python, powershell and echo (test) * removing debug code * introducing command + trivial trust store mechanism * updating tests * adding basic tests * removing deprecated oracle * mod tidy * adding signature proto with debug prints * removing debug code * fixing test * fixing param order * improving test conditional build * disable file+offlinehttp+code with cloud * adding env vars * removing debug code * reorganizing test folders * adding code template test prototype with dummy priv/pub keys * bump go to 1.20 * fixing go version * fixing lint errors * adding fatal on pub-key test failure * switching to ecdsa asn1 * removing unused signature * fixing signature * adding more tests * extending core with engine args + powershell win test * adding unsigned code test * skip template signing in particular test case * improving test coverage * refactoring key names + adding already signed algo * removing debug code * fixing syntax * fixing lint issues * removing test template * fixing dns tests path * output fmt * adding interact * fixing lint issues * adding -sign cli helper * fixing nil pointer + parse inline keys * making rsa default * adding code prot. ref * moving file to correct loc * moving test * Issue 3339 headless fuzz (#3790) * Basic headless fuzzing * Remove debug statements * Add integration tests * Update template * Fix recognize payload value in matcher * Update tempalte * use req.SetURL() --------- Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io> * Auto Generate Syntax Docs + JSONSchema [Fri Jun 9 00:23:32 UTC 2023] :robot: * Add headless header and status matchers (#3794) * add headless header and status matchers * rename headers as header * add integration test for header+status * fix typo * add retry to py-interactsh integration test --------- Co-authored-by: Sandeep Singh <sandeep@projectdiscovery.io> Co-authored-by: Shubham Rasal <shubham@projectdiscovery.io> Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io> Co-authored-by: GitHub Action <action@github.com> Co-authored-by: Dogan Can Bakir <65292895+dogancanbakir@users.noreply.github.com> Co-authored-by: Tarun Koyalwar <45962551+tarunKoyalwar@users.noreply.github.com>
2023-06-09 17:24:24 +02:00
2021-07-27 16:03:56 +05:30
// description: |
// Workflows is a yaml based workflow declaration code.
workflows.Workflow `yaml:",inline,omitempty" jsonschema:"title=workflows to run,description=Workflows to run for the template"`
2021-05-01 18:28:24 +05:30
CompiledWorkflow *workflows.Workflow `yaml:"-" json:"-" jsonschema:"-"`
2020-12-30 13:26:55 +05:30
// description: |
2021-10-19 22:28:48 +05:30
// Self Contained marks Requests for the template as self-contained
2023-02-07 16:10:40 +08:00
SelfContained bool `yaml:"self-contained,omitempty" json:"self-contained,omitempty" jsonschema:"title=mark requests as self-contained,description=Mark Requests for the template as self-contained"`
// description: |
// Stop execution once first match is found
2023-02-07 16:10:40 +08:00
StopAtFirstMatch bool `yaml:"stop-at-first-match,omitempty" json:"stop-at-first-match,omitempty" jsonschema:"title=stop at first match,description=Stop at first match for the template"`
2021-11-17 01:28:35 +01:00
// description: |
// Signature is the request signature method
// WARNING: 'signature' will be deprecated and will be removed in a future release. Prefer using 'code' protocol for writing cloud checks
2021-11-17 01:28:35 +01:00
// values:
// - "AWS"
2024-03-27 23:52:08 +05:30
Signature http.SignatureTypeHolder `yaml:"signature,omitempty" json:"signature,omitempty" jsonschema:"title=signature is the http request signature method,description=Signature is the HTTP Request signature Method,enum=AWS,deprecated=true"`
// description: |
// Variables contains any variables for the current request.
2024-03-27 23:52:08 +05:30
Variables variables.Variable `yaml:"variables,omitempty" json:"variables,omitempty" jsonschema:"title=variables for the http request,description=Variables contains any variables for the current request,type=object"`
// description: |
Spelling (#4008) * spelling: addresses Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: asynchronous Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: basic Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: brute force Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: constant Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: disables Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: engine Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: every time Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: execution Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: false positives Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: from Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: further Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: github Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: gitlab Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: highlight Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: hygiene Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: ignore Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: input Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: item Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: itself Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: latestxxx Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: navigation Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: negative Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: nonexistent Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: occurred Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: override Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: overrides Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: payload Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: performed Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: respective Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: retrieve Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: scanlist Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: separated Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: separator Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: severity Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: source Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: strategy Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: string Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: templates Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: terminal Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: timeout Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: trailing slash Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: trailing Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> * spelling: websocket Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> --------- Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>
2023-08-01 14:33:43 -04:00
// Constants contains any scalar constant for the current template
2024-03-27 23:52:08 +05:30
Constants map[string]interface{} `yaml:"constants,omitempty" json:"constants,omitempty" jsonschema:"title=constant for the template,description=constants contains any constant for the template,type=object"`
// TotalRequests is the total number of requests for the template.
2021-05-01 18:28:24 +05:30
TotalRequests int `yaml:"-" json:"-"`
// Executer is the actual template executor for running template requests
2021-05-01 18:28:24 +05:30
Executer protocols.Executer `yaml:"-" json:"-"`
2021-06-05 23:00:59 +05:30
Path string `yaml:"-" json:"-"`
// Verified defines if the template signature is digitally verified
Verified bool `yaml:"-" json:"-"`
// TemplateVerifier is identifier verifier used to verify the template (default nuclei-templates have projectdiscovery/nuclei-templates)
TemplateVerifier string `yaml:"-" json:"-"`
// RequestsQueue contains all template requests in order (both protocol & request order)
RequestsQueue []protocols.Request `yaml:"-" json:"-"`
// ImportedFiles contains list of files whose contents are imported after template was compiled
ImportedFiles []string `yaml:"-" json:"-"`
}
// Type returns the type of the template
2021-11-25 16:57:43 +02:00
func (template *Template) Type() types.ProtocolType {
switch {
2021-11-25 16:57:43 +02:00
case len(template.RequestsDNS) > 0:
return types.DNSProtocol
2021-11-25 16:57:43 +02:00
case len(template.RequestsFile) > 0:
return types.FileProtocol
2021-11-25 16:57:43 +02:00
case len(template.RequestsHTTP) > 0:
return types.HTTPProtocol
2021-11-25 16:57:43 +02:00
case len(template.RequestsHeadless) > 0:
return types.HeadlessProtocol
2021-11-25 16:57:43 +02:00
case len(template.RequestsNetwork) > 0:
return types.NetworkProtocol
2021-11-25 16:57:43 +02:00
case len(template.RequestsSSL) > 0:
2021-11-03 18:58:00 +05:30
return types.SSLProtocol
2021-11-25 16:57:43 +02:00
case len(template.RequestsWebsocket) > 0:
2021-11-03 18:58:00 +05:30
return types.WebsocketProtocol
case len(template.RequestsWHOIS) > 0:
return types.WHOISProtocol
Adding support for code templates (#2930) * Adding support for code templates * adding support for python, powershell and echo (test) * removing debug code * introducing command + trivial trust store mechanism * updating tests * adding basic tests * removing deprecated oracle * mod tidy * adding signature proto with debug prints * removing debug code * fixing test * fixing param order * improving test conditional build * disable file+offlinehttp+code with cloud * adding env vars * removing debug code * reorganizing test folders * adding code template test prototype with dummy priv/pub keys * bump go to 1.20 * fixing go version * fixing lint errors * adding fatal on pub-key test failure * switching to ecdsa asn1 * removing unused signature * fixing signature * adding more tests * extending core with engine args + powershell win test * adding unsigned code test * skip template signing in particular test case * improving test coverage * refactoring key names + adding already signed algo * removing debug code * fixing syntax * fixing lint issues * removing test template * fixing dns tests path * output fmt * adding interact * fixing lint issues * adding -sign cli helper * fixing nil pointer + parse inline keys * making rsa default * adding code prot. ref * moving file to correct loc * moving test * Issue 3339 headless fuzz (#3790) * Basic headless fuzzing * Remove debug statements * Add integration tests * Update template * Fix recognize payload value in matcher * Update tempalte * use req.SetURL() --------- Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io> * Auto Generate Syntax Docs + JSONSchema [Fri Jun 9 00:23:32 UTC 2023] :robot: * Add headless header and status matchers (#3794) * add headless header and status matchers * rename headers as header * add integration test for header+status * fix typo * add retry to py-interactsh integration test --------- Co-authored-by: Sandeep Singh <sandeep@projectdiscovery.io> Co-authored-by: Shubham Rasal <shubham@projectdiscovery.io> Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io> Co-authored-by: GitHub Action <action@github.com> Co-authored-by: Dogan Can Bakir <65292895+dogancanbakir@users.noreply.github.com> Co-authored-by: Tarun Koyalwar <45962551+tarunKoyalwar@users.noreply.github.com>
2023-06-09 17:24:24 +02:00
case len(template.RequestsCode) > 0:
return types.CodeProtocol
javascript protocol for scripting (includes 15+ proto libs) (#4109) * rebase js-layer PR from @ice3man543 * package restructuring * working * fix duplicated event & matcher status * fix lint error * fix response field * add new functions * multiple minor improvements * fix incorrect stats in js protocol * sort output metadata in cli * remove temp files * remove dead code * add unit and integration test * fix lint error * add jsdoclint using llm * fix error in test * add js lint using llm * generate docs of libs * llm lint * remove duplicated docs * update generated docs * update prompt in doclint * update docs * temp disable version check test * fix unit test and add retry * fix panic in it * update and move jsdocs * updated jsdocs * update docs * update container platform in test * dir restructure and adding docs * add api_reference and remove markdown docs * fix imports * add javascript design and contribution docs * add js protocol documentation * update integration test and docs * update doc ext mdx->md * minor update to docs * new integration test and more * move go libs and add docs * gen new net docs and more * final docs update * add new devtool * use fastdialer * fix build fail * use fastdialer + network sandbox support * add reserved keyword 'Port' * update Port to new syntax * misc update * always enable templatectx in js protocol * move docs to 'js-proto-docs' repo * remove scrapefuncs binary --------- Co-authored-by: sandeep <8293321+ehsandeep@users.noreply.github.com>
2023-09-16 16:02:17 +05:30
case len(template.RequestsJavascript) > 0:
return types.JavascriptProtocol
case len(template.Workflows) > 0:
return types.WorkflowProtocol
default:
return types.InvalidProtocol
}
}
Fuzzing layer enhancements + input-types support (#4477) * feat: move fuzz package to root directory * feat: added support for input providers like openapi,postman,etc * feat: integration of new fuzzing logic in engine * bugfix: use and instead of or * fixed lint errors * go mod tidy * add new reqresp type + bump utils * custom http request parser * use new struct type RequestResponse * introduce unified input/target provider * abstract input formats via new inputprovider * completed input provider refactor * remove duplicated code * add sdk method to load targets * rename component url->path * add new yaml format + remove duplicated code * use gopkg.in/yaml.v3 for parsing * update .gitignore * refactor/move + docs fuzzing in http protocol * fuzz: header + query integration test using fuzzplayground * fix integration test runner in windows * feat add support for filter in http fuzz * rewrite header/query integration test with filter * add replace regex rule * support kv fuzzing + misc updates * add path fuzzing example + misc improvements * fix matchedURL + skip httpx on multi formats * cookie fuzz integration test * add json body + params body tests * feat add multipart/form-data fuzzing support * add all fuzz body integration test * misc bug fixes + minor refactor * add multipart form + body form unit tests * only run fuzzing templates if -fuzz flag is given * refactor/move fuzz playground server to pkg * fix integration test + refactor * add auth types and strategies * add file auth provider * start implementing auth logic in http * add logic in http protocol * static auth implemented for http * default :80,:443 normalization * feat: dynamic auth init * feat: dynamic auth using templates * validate targets count in openapi+swagger * inputformats: add support to accept variables * fix workflow integration test * update lazy cred fetch logic * fix unit test * drop postman support * domain related normalization * update secrets.yaml file format + misc updates * add auth prefetch option * remove old secret files * add fuzzing+auth related sdk options * fix/support multiple mode in kv header fuzzing * rename 'headers' -> 'header' in fuzzing rules * fix deadlock due to merge conflict resolution * misc update * add bool type in parsed value * add openapi validation+override+ new flags * misc updates * remove optional path parameters when unavailable * fix swagger.yaml file * misc updates * update print msg * multiple openapi validation enchancements + appMode * add optional params in required_openapi_vars.yaml file * improve warning/verbose msgs in format * fix skip-format-validation not working * use 'params/parameter' instead of 'variable' in openapi * add retry support for falky tests * fix nuclei loading ignored templates (#4849) * fix tag include logic * fix unit test * remove quoting in extractor output * remove quote in debug code command * feat: issue tracker URLs in JSON + misc fixes (#4855) * feat: issue tracker URLs in JSON + misc fixes * misc changes * feat: status update support for issues * feat: report metadata generation hook support * feat: added CLI summary of tickets created * misc changes * introduce `disable-unsigned-templates` flag (#4820) * introduce `disable-unsigned-templates` flag * minor * skip instead of exit * remove duplicate imports * use stats package + misc enhancements * force display warning + adjust skipped stats in unsigned count * include unsigned skipped templates without -dut flag --------- Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io> * Purge cache on global callback set (#4840) * purge cache on global callback set * lint * purging cache * purge cache in runner after loading templates * include internal cache from parsers + add global cache register/purge via config * remove disable cache purge option --------- Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io> * misc update * add application/octet-stream support * openapi: support path specific params * misc option + readme update --------- Co-authored-by: Sandeep Singh <sandeep@projectdiscovery.io> Co-authored-by: sandeep <8293321+ehsandeep@users.noreply.github.com> Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io> Co-authored-by: Tarun Koyalwar <45962551+tarunKoyalwar@users.noreply.github.com> Co-authored-by: Dogan Can Bakir <65292895+dogancanbakir@users.noreply.github.com> Co-authored-by: Mzack9999 <mzack9999@protonmail.com>
2024-03-14 03:08:53 +05:30
// IsFuzzing returns true if the template is a fuzzing template
func (template *Template) IsFuzzing() bool {
if len(template.RequestsHTTP) == 0 && len(template.RequestsHeadless) == 0 {
// fuzzing is only supported for http and headless protocols
return false
}
if len(template.RequestsHTTP) > 0 {
for _, request := range template.RequestsHTTP {
if len(request.Fuzzing) > 0 {
return true
}
}
}
if len(template.RequestsHeadless) > 0 {
for _, request := range template.RequestsHeadless {
if len(request.Fuzzing) > 0 {
return true
}
}
}
return false
}
// UsesRequestSignature returns true if the template uses a request signature like AWS
func (template *Template) UsesRequestSignature() bool {
return template.Signature.Value.String() != ""
}
// HasCodeProtocol returns true if the template has a code protocol section
func (template *Template) HasCodeProtocol() bool {
return len(template.RequestsCode) > 0
}
// validateAllRequestIDs check if that protocol already has given id if not
// then is is manually set to proto_index
func (template *Template) validateAllRequestIDs() {
// this is required in multiprotocol and flow where we save response variables
// and all other data in template context if template as two requests in a protocol
// then it is overwritten to avoid this we use proto_index as request ID
if len(template.RequestsCode) > 1 {
for i, req := range template.RequestsCode {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if len(template.RequestsDNS) > 1 {
for i, req := range template.RequestsDNS {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if len(template.RequestsFile) > 1 {
for i, req := range template.RequestsFile {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if len(template.RequestsHTTP) > 1 {
for i, req := range template.RequestsHTTP {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if len(template.RequestsHeadless) > 1 {
for i, req := range template.RequestsHeadless {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if len(template.RequestsNetwork) > 1 {
for i, req := range template.RequestsNetwork {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if len(template.RequestsSSL) > 1 {
for i, req := range template.RequestsSSL {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if len(template.RequestsWebsocket) > 1 {
for i, req := range template.RequestsWebsocket {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
if len(template.RequestsWHOIS) > 1 {
for i, req := range template.RequestsWHOIS {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
}
}
}
javascript protocol for scripting (includes 15+ proto libs) (#4109) * rebase js-layer PR from @ice3man543 * package restructuring * working * fix duplicated event & matcher status * fix lint error * fix response field * add new functions * multiple minor improvements * fix incorrect stats in js protocol * sort output metadata in cli * remove temp files * remove dead code * add unit and integration test * fix lint error * add jsdoclint using llm * fix error in test * add js lint using llm * generate docs of libs * llm lint * remove duplicated docs * update generated docs * update prompt in doclint * update docs * temp disable version check test * fix unit test and add retry * fix panic in it * update and move jsdocs * updated jsdocs * update docs * update container platform in test * dir restructure and adding docs * add api_reference and remove markdown docs * fix imports * add javascript design and contribution docs * add js protocol documentation * update integration test and docs * update doc ext mdx->md * minor update to docs * new integration test and more * move go libs and add docs * gen new net docs and more * final docs update * add new devtool * use fastdialer * fix build fail * use fastdialer + network sandbox support * add reserved keyword 'Port' * update Port to new syntax * misc update * always enable templatectx in js protocol * move docs to 'js-proto-docs' repo * remove scrapefuncs binary --------- Co-authored-by: sandeep <8293321+ehsandeep@users.noreply.github.com>
2023-09-16 16:02:17 +05:30
if len(template.RequestsJavascript) > 1 {
for i, req := range template.RequestsJavascript {
if req.ID == "" {
req.ID = req.Type().String() + "_" + strconv.Itoa(i+1)
javascript protocol for scripting (includes 15+ proto libs) (#4109) * rebase js-layer PR from @ice3man543 * package restructuring * working * fix duplicated event & matcher status * fix lint error * fix response field * add new functions * multiple minor improvements * fix incorrect stats in js protocol * sort output metadata in cli * remove temp files * remove dead code * add unit and integration test * fix lint error * add jsdoclint using llm * fix error in test * add js lint using llm * generate docs of libs * llm lint * remove duplicated docs * update generated docs * update prompt in doclint * update docs * temp disable version check test * fix unit test and add retry * fix panic in it * update and move jsdocs * updated jsdocs * update docs * update container platform in test * dir restructure and adding docs * add api_reference and remove markdown docs * fix imports * add javascript design and contribution docs * add js protocol documentation * update integration test and docs * update doc ext mdx->md * minor update to docs * new integration test and more * move go libs and add docs * gen new net docs and more * final docs update * add new devtool * use fastdialer * fix build fail * use fastdialer + network sandbox support * add reserved keyword 'Port' * update Port to new syntax * misc update * always enable templatectx in js protocol * move docs to 'js-proto-docs' repo * remove scrapefuncs binary --------- Co-authored-by: sandeep <8293321+ehsandeep@users.noreply.github.com>
2023-09-16 16:02:17 +05:30
}
}
}
}
// MarshalYAML forces recursive struct validation during marshal operation
func (template *Template) MarshalYAML() ([]byte, error) {
out, marshalErr := yaml.Marshal(template)
// Use shared validator to avoid rebuilding struct cache for every template marshal
errValidate := tplValidator.Struct(template)
return out, multierr.Append(marshalErr, errValidate)
}
// UnmarshalYAML forces recursive struct validation after unmarshal operation
func (template *Template) UnmarshalYAML(unmarshal func(interface{}) error) error {
type Alias Template
alias := &Alias{}
err := unmarshal(alias)
if err != nil {
return err
}
*template = Template(*alias)
if !ReTemplateID.MatchString(template.ID) {
return errkit.New(fmt.Sprintf("invalid template: template id must match expression %v", ReTemplateID)).Build()
}
info := template.Info
if utils.IsBlank(info.Name) {
return errkit.New("invalid template: no template name field provided").Build()
}
if info.Authors.IsEmpty() {
return errkit.New("invalid template: no template author field provided").Build()
}
if len(template.RequestsHTTP) > 0 || len(template.RequestsNetwork) > 0 {
_ = deprecatedProtocolNameTemplates.Set(template.ID, true)
}
if len(alias.RequestsHTTP) > 0 && len(alias.RequestsWithHTTP) > 0 {
return errkit.New("invalid template: use http or requests, both are not supported").Build()
}
if len(alias.RequestsNetwork) > 0 && len(alias.RequestsWithTCP) > 0 {
return errkit.New("invalid template: use tcp or network, both are not supported").Build()
}
if len(alias.RequestsWithHTTP) > 0 {
template.RequestsHTTP = alias.RequestsWithHTTP
}
if len(alias.RequestsWithTCP) > 0 {
template.RequestsNetwork = alias.RequestsWithTCP
}
err = tplValidator.Struct(template)
if err != nil {
return err
}
// check if the template contains more than 1 protocol request
// if so preserve the order of the protocols and requests
if template.hasMultipleRequests() {
var tempmap yaml.MapSlice
err = unmarshal(&tempmap)
if err != nil {
return errkit.Append(errkit.New(fmt.Sprintf("failed to unmarshal multi protocol template %s", template.ID)), err)
}
arr := []string{}
for _, v := range tempmap {
key, ok := v.Key.(string)
if !ok {
continue
}
arr = append(arr, key)
}
// add protocols to the protocol stack (the idea is to preserve the order of the protocols)
template.addRequestsToQueue(arr...)
}
return nil
}
// ImportFileRefs checks if sensitive fields like `flow` , `source` in code protocol are referencing files
// instead of actual javascript / engine code if so it loads the file contents and replaces the reference
func (template *Template) ImportFileRefs(options *protocols.ExecutorOptions) error {
var errs []error
loadFile := func(source string) (string, bool) {
// load file respecting sandbox
data, err := options.Options.LoadHelperFile(source, options.TemplatePath, options.Catalog)
if err == nil {
defer func() {
_ = data.Close()
}()
bin, err := io.ReadAll(data)
if err == nil {
return string(bin), true
} else {
errs = append(errs, err)
}
} else {
errs = append(errs, err)
}
return "", false
}
// for code protocol requests
for _, request := range template.RequestsCode {
// simple test to check if source is a file or a snippet
if len(strings.Split(request.Source, "\n")) == 1 && fileutil.FileExists(request.Source) {
if val, ok := loadFile(request.Source); ok {
template.ImportedFiles = append(template.ImportedFiles, request.Source)
request.Source = val
}
}
}
// for javascript protocol code references
for _, request := range template.RequestsJavascript {
// simple test to check if source is a file or a snippet
if len(strings.Split(request.Code, "\n")) == 1 && fileutil.FileExists(request.Code) {
if val, ok := loadFile(request.Code); ok {
template.ImportedFiles = append(template.ImportedFiles, request.Code)
request.Code = val
}
}
}
// flow code references
if template.Flow != "" {
if len(template.Flow) > 0 && filepath.Ext(template.Flow) == ".js" && fileutil.FileExists(template.Flow) {
if val, ok := loadFile(template.Flow); ok {
template.ImportedFiles = append(template.ImportedFiles, template.Flow)
template.Flow = val
}
}
options.Flow = template.Flow
}
// for multiprotocol requests
// mutually exclusive with flow
if len(template.RequestsQueue) > 0 && template.Flow == "" {
// this is most likely a multiprotocol template
for _, req := range template.RequestsQueue {
if req.Type() == types.CodeProtocol {
request := req.(*code.Request)
// simple test to check if source is a file or a snippet
if len(strings.Split(request.Source, "\n")) == 1 && fileutil.FileExists(request.Source) {
if val, ok := loadFile(request.Source); ok {
template.ImportedFiles = append(template.ImportedFiles, request.Source)
request.Source = val
}
}
}
}
// for javascript protocol code references
for _, req := range template.RequestsQueue {
if req.Type() == types.JavascriptProtocol {
request := req.(*javascript.Request)
// simple test to check if source is a file or a snippet
if len(strings.Split(request.Code, "\n")) == 1 && fileutil.FileExists(request.Code) {
if val, ok := loadFile(request.Code); ok {
template.ImportedFiles = append(template.ImportedFiles, request.Code)
request.Code = val
}
}
}
}
}
return multierr.Combine(errs...)
}
// GetFileImports returns a list of files that are imported by the template
func (template *Template) GetFileImports() []string {
return template.ImportedFiles
}
// addRequestsToQueue adds protocol requests to the queue and preserves order of the protocols and requests
func (template *Template) addRequestsToQueue(keys ...string) {
for _, key := range keys {
switch key {
case types.DNSProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsDNS)...)
case types.FileProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsFile)...)
case types.HTTPProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsHTTP)...)
case types.HeadlessProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsHeadless)...)
case types.NetworkProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsNetwork)...)
case types.SSLProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsSSL)...)
case types.WebsocketProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsWebsocket)...)
case types.WHOISProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsWHOIS)...)
case types.CodeProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsCode)...)
javascript protocol for scripting (includes 15+ proto libs) (#4109) * rebase js-layer PR from @ice3man543 * package restructuring * working * fix duplicated event & matcher status * fix lint error * fix response field * add new functions * multiple minor improvements * fix incorrect stats in js protocol * sort output metadata in cli * remove temp files * remove dead code * add unit and integration test * fix lint error * add jsdoclint using llm * fix error in test * add js lint using llm * generate docs of libs * llm lint * remove duplicated docs * update generated docs * update prompt in doclint * update docs * temp disable version check test * fix unit test and add retry * fix panic in it * update and move jsdocs * updated jsdocs * update docs * update container platform in test * dir restructure and adding docs * add api_reference and remove markdown docs * fix imports * add javascript design and contribution docs * add js protocol documentation * update integration test and docs * update doc ext mdx->md * minor update to docs * new integration test and more * move go libs and add docs * gen new net docs and more * final docs update * add new devtool * use fastdialer * fix build fail * use fastdialer + network sandbox support * add reserved keyword 'Port' * update Port to new syntax * misc update * always enable templatectx in js protocol * move docs to 'js-proto-docs' repo * remove scrapefuncs binary --------- Co-authored-by: sandeep <8293321+ehsandeep@users.noreply.github.com>
2023-09-16 16:02:17 +05:30
case types.JavascriptProtocol.String():
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsJavascript)...)
// for deprecated protocols
case "requests":
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsHTTP)...)
case "network":
template.RequestsQueue = append(template.RequestsQueue, template.convertRequestToProtocolsRequest(template.RequestsNetwork)...)
}
}
}
// hasMultipleRequests checks if the template has multiple requests
// if so it preserves the order of the request during compile and execution
func (template *Template) hasMultipleRequests() bool {
counter := len(template.RequestsDNS) + len(template.RequestsFile) +
len(template.RequestsHTTP) + len(template.RequestsHeadless) +
len(template.RequestsNetwork) + len(template.RequestsSSL) +
javascript protocol for scripting (includes 15+ proto libs) (#4109) * rebase js-layer PR from @ice3man543 * package restructuring * working * fix duplicated event & matcher status * fix lint error * fix response field * add new functions * multiple minor improvements * fix incorrect stats in js protocol * sort output metadata in cli * remove temp files * remove dead code * add unit and integration test * fix lint error * add jsdoclint using llm * fix error in test * add js lint using llm * generate docs of libs * llm lint * remove duplicated docs * update generated docs * update prompt in doclint * update docs * temp disable version check test * fix unit test and add retry * fix panic in it * update and move jsdocs * updated jsdocs * update docs * update container platform in test * dir restructure and adding docs * add api_reference and remove markdown docs * fix imports * add javascript design and contribution docs * add js protocol documentation * update integration test and docs * update doc ext mdx->md * minor update to docs * new integration test and more * move go libs and add docs * gen new net docs and more * final docs update * add new devtool * use fastdialer * fix build fail * use fastdialer + network sandbox support * add reserved keyword 'Port' * update Port to new syntax * misc update * always enable templatectx in js protocol * move docs to 'js-proto-docs' repo * remove scrapefuncs binary --------- Co-authored-by: sandeep <8293321+ehsandeep@users.noreply.github.com>
2023-09-16 16:02:17 +05:30
len(template.RequestsWebsocket) + len(template.RequestsWHOIS) +
len(template.RequestsCode) + len(template.RequestsJavascript)
return counter > 1
}
// MarshalJSON forces recursive struct validation during marshal operation
func (template *Template) MarshalJSON() ([]byte, error) {
type TemplateAlias Template //avoid recursion
out, marshalErr := json.Marshal((*TemplateAlias)(template))
errValidate := tplValidator.Struct(template)
return out, multierr.Append(marshalErr, errValidate)
}
// UnmarshalJSON forces recursive struct validation after unmarshal operation
func (template *Template) UnmarshalJSON(data []byte) error {
type Alias Template
alias := &Alias{}
err := json.Unmarshal(data, alias)
if err != nil {
return err
}
*template = Template(*alias)
err = tplValidator.Struct(template)
if err != nil {
return err
}
// check if the template contains more than 1 protocol request
// if so preserve the order of the protocols and requests
if template.hasMultipleRequests() {
var tempMap map[string]interface{}
err = json.Unmarshal(data, &tempMap)
if err != nil {
return errkit.Append(errkit.New(fmt.Sprintf("failed to unmarshal multi protocol template %s", template.ID)), err)
}
arr := []string{}
for k := range tempMap {
arr = append(arr, k)
}
template.addRequestsToQueue(arr...)
}
return nil
}
// HasFileProtocol returns true if the template has a file protocol section
func (template *Template) HasFileProtocol() bool {
return len(template.RequestsFile) > 0
}