nuclei/pkg/templates/compile.go

648 lines
20 KiB
Go
Raw Normal View History

2020-04-04 02:50:32 +05:30
package templates
import (
2024-03-13 21:02:36 +01:00
"bytes"
"fmt"
2022-12-13 12:57:47 +05:30
"io"
"reflect"
"sync"
"sync/atomic"
2020-04-04 02:50:32 +05:30
"github.com/logrusorgru/aurora"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
"github.com/projectdiscovery/gologger"
"github.com/projectdiscovery/nuclei/v3/pkg/catalog/config"
"github.com/projectdiscovery/nuclei/v3/pkg/js/compiler"
"github.com/projectdiscovery/nuclei/v3/pkg/model/types/severity"
"github.com/projectdiscovery/nuclei/v3/pkg/operators"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/generators"
feat: global matchers (#5701) * feat: global matchers Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Ice3man543 <ice3man543@users.noreply.github.com> * feat(globalmatchers): make `Callback` as type Signed-off-by: Dwi Siswanto <git@dw1.io> * feat: update `passive` term to `(matchers-)static` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): add `origin-template-*` event also use `Set` method instead of `maps.Clone` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat: update `matchers-static` term to `global-matchers` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): clone event before `operator.Execute` Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(tmplexec): don't store `matched` on `global-matchers` templ This will end up generating 2 events from the same `scan.ScanContext` if one of the templates has `global-matchers` enabled. This way, non- `global-matchers` templates can enter the `writeFailureCallback` func to log failure output. Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): initializes `requests` on `New` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): add `hasStorage` method Signed-off-by: Dwi Siswanto <git@dw1.io> * refactor(templates): rename global matchers checks method Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(loader): handle nil `templates.Template` pointer Signed-off-by: Dwi Siswanto <git@dw1.io> --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Ice3man543 <ice3man543@users.noreply.github.com>
2024-10-14 20:55:46 +07:00
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/globalmatchers"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/offlinehttp"
"github.com/projectdiscovery/nuclei/v3/pkg/templates/signer"
"github.com/projectdiscovery/nuclei/v3/pkg/tmplexec"
"github.com/projectdiscovery/nuclei/v3/pkg/utils"
"github.com/projectdiscovery/nuclei/v3/pkg/utils/json"
"github.com/projectdiscovery/utils/errkit"
stringsutil "github.com/projectdiscovery/utils/strings"
2020-04-04 02:50:32 +05:30
)
var (
ErrCreateTemplateExecutor = errors.New("cannot create template executer")
ErrIncompatibleWithOfflineMatching = errors.New("template can't be used for offline matching")
// track how many templates are verfied and by which signer
SignatureStats = map[string]*atomic.Uint64{}
)
2021-08-27 17:06:06 +03:00
const (
Unsigned = "unsigned"
)
2021-08-28 00:27:37 +05:30
2024-03-13 02:59:34 +01:00
func init() {
for _, verifier := range signer.DefaultTemplateVerifiers {
SignatureStats[verifier.Identifier()] = &atomic.Uint64{}
}
SignatureStats[Unsigned] = &atomic.Uint64{}
}
2020-06-29 17:43:08 +05:30
// Parse parses a yaml request template file
2021-08-27 17:06:06 +03:00
// TODO make sure reading from the disk the template parsing happens once: see parsers.ParseTemplate vs templates.Parse
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
func Parse(filePath string, preprocessor Preprocessor, options *protocols.ExecutorOptions) (*Template, error) {
parser, ok := options.Parser.(*Parser)
if !ok {
panic("not a parser")
}
if !options.DoNotCache {
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
if value, _, _ := parser.compiledTemplatesCache.Has(filePath); value != nil {
// Copy the template, apply new options, and recompile requests
tplCopy := *value
newBase := options.Copy()
newBase.TemplateID = tplCopy.Options.TemplateID
newBase.TemplatePath = tplCopy.Options.TemplatePath
newBase.TemplateInfo = tplCopy.Options.TemplateInfo
newBase.TemplateVerifier = tplCopy.Options.TemplateVerifier
newBase.RawTemplate = tplCopy.Options.RawTemplate
fix: segfault in template caching logic (#6421) * fix: segfault in template caching logic when templates had no executable requests after option updates. the cached templates could end up with 0 requests and no flow execution path, resulting in a nil engine pointer that was later derefer w/o validation. bug seq: caching template (w/ valid requests) -> get cached template -> `*ExecutorOptions.Options` copied and modified (inconsistent) -> requests updated (with new options -- some may be invalid, and without recompile) -> template returned w/o validation -> `compileProtocolRequests` -> `NewTemplateExecuter` receive empty requests + empty flow = nil engine -> `*TemplateExecuter.{Compile,Execute}` invoked on nil engine = panic. RCA: 1. `*ExecutorOptions.ApplyNewEngineOptions` overwriting many fields. 2. copy op pointless; create a copy of options and then immediately replace it with original pointer. 3. missing executable requests validation after cached templates is reconstructed with updated options. Thus, this affected `--automatic-scan` mode where tech detection templates often have conditional requests that may be filtered based on runtime options. Fixes #6417 Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(templates): recompile workflow with `tplCopy.Options` Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(templates): strengthen cache hit guard Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(protocols): skips template-specific fields Signed-off-by: Dwi Siswanto <git@dw1.io> --------- Signed-off-by: Dwi Siswanto <git@dw1.io>
2025-08-23 21:31:23 +07:00
if tplCopy.Options.Variables.Len() > 0 {
newBase.Variables = tplCopy.Options.Variables
}
if len(tplCopy.Options.Constants) > 0 {
newBase.Constants = tplCopy.Options.Constants
}
tplCopy.Options = newBase
tplCopy.Options.ApplyNewEngineOptions(options)
if tplCopy.CompiledWorkflow != nil {
tplCopy.CompiledWorkflow.Options.ApplyNewEngineOptions(options)
for _, w := range tplCopy.CompiledWorkflow.Workflows {
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
for _, ex := range w.Executers {
ex.Options.ApplyNewEngineOptions(options)
}
}
}
// TODO: Reconsider whether to recompile requests. Compiling these is just as slow
// as not using a cache at all, but may be necessary.
for i, r := range tplCopy.RequestsDNS {
rCopy := *r
rCopy.UpdateOptions(tplCopy.Options)
// rCopy.Compile(tplCopy.Options)
tplCopy.RequestsDNS[i] = &rCopy
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
}
for i, r := range tplCopy.RequestsHTTP {
rCopy := *r
rCopy.UpdateOptions(tplCopy.Options)
// rCopy.Compile(tplCopy.Options)
tplCopy.RequestsHTTP[i] = &rCopy
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
}
for i, r := range tplCopy.RequestsCode {
rCopy := *r
rCopy.UpdateOptions(tplCopy.Options)
// rCopy.Compile(tplCopy.Options)
tplCopy.RequestsCode[i] = &rCopy
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
}
for i, r := range tplCopy.RequestsFile {
rCopy := *r
rCopy.UpdateOptions(tplCopy.Options)
// rCopy.Compile(tplCopy.Options)
tplCopy.RequestsFile[i] = &rCopy
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
}
for i, r := range tplCopy.RequestsHeadless {
rCopy := *r
rCopy.UpdateOptions(tplCopy.Options)
// rCopy.Compile(tplCopy.Options)
tplCopy.RequestsHeadless[i] = &rCopy
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
}
for i, r := range tplCopy.RequestsNetwork {
rCopy := *r
rCopy.UpdateOptions(tplCopy.Options)
// rCopy.Compile(tplCopy.Options)
tplCopy.RequestsNetwork[i] = &rCopy
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
}
for i, r := range tplCopy.RequestsJavascript {
rCopy := *r
rCopy.UpdateOptions(tplCopy.Options)
//rCopy.Compile(tplCopy.Options)
tplCopy.RequestsJavascript[i] = &rCopy
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
}
for i, r := range tplCopy.RequestsSSL {
rCopy := *r
rCopy.UpdateOptions(tplCopy.Options)
// rCopy.Compile(tplCopy.Options)
tplCopy.RequestsSSL[i] = &rCopy
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
}
for i, r := range tplCopy.RequestsWHOIS {
rCopy := *r
rCopy.UpdateOptions(tplCopy.Options)
// rCopy.Compile(tplCopy.Options)
tplCopy.RequestsWHOIS[i] = &rCopy
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
}
for i, r := range tplCopy.RequestsWebsocket {
rCopy := *r
rCopy.UpdateOptions(tplCopy.Options)
// rCopy.Compile(tplCopy.Options)
tplCopy.RequestsWebsocket[i] = &rCopy
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
}
template := &tplCopy
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
if template.isGlobalMatchersEnabled() {
item := &globalmatchers.Item{
TemplateID: template.ID,
TemplatePath: filePath,
TemplateInfo: template.Info,
}
for _, request := range template.RequestsHTTP {
item.Operators = append(item.Operators, request.CompiledOperators)
}
options.GlobalMatchers.AddOperator(item)
return nil, nil
}
// Compile the workflow request
if len(template.Workflows) > 0 {
compiled := &template.Workflow
fix: segfault in template caching logic (#6421) * fix: segfault in template caching logic when templates had no executable requests after option updates. the cached templates could end up with 0 requests and no flow execution path, resulting in a nil engine pointer that was later derefer w/o validation. bug seq: caching template (w/ valid requests) -> get cached template -> `*ExecutorOptions.Options` copied and modified (inconsistent) -> requests updated (with new options -- some may be invalid, and without recompile) -> template returned w/o validation -> `compileProtocolRequests` -> `NewTemplateExecuter` receive empty requests + empty flow = nil engine -> `*TemplateExecuter.{Compile,Execute}` invoked on nil engine = panic. RCA: 1. `*ExecutorOptions.ApplyNewEngineOptions` overwriting many fields. 2. copy op pointless; create a copy of options and then immediately replace it with original pointer. 3. missing executable requests validation after cached templates is reconstructed with updated options. Thus, this affected `--automatic-scan` mode where tech detection templates often have conditional requests that may be filtered based on runtime options. Fixes #6417 Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(templates): recompile workflow with `tplCopy.Options` Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(templates): strengthen cache hit guard Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(protocols): skips template-specific fields Signed-off-by: Dwi Siswanto <git@dw1.io> --------- Signed-off-by: Dwi Siswanto <git@dw1.io>
2025-08-23 21:31:23 +07:00
compileWorkflow(filePath, preprocessor, tplCopy.Options, compiled, tplCopy.Options.WorkflowLoader)
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
template.CompiledWorkflow = compiled
fix: segfault in template caching logic (#6421) * fix: segfault in template caching logic when templates had no executable requests after option updates. the cached templates could end up with 0 requests and no flow execution path, resulting in a nil engine pointer that was later derefer w/o validation. bug seq: caching template (w/ valid requests) -> get cached template -> `*ExecutorOptions.Options` copied and modified (inconsistent) -> requests updated (with new options -- some may be invalid, and without recompile) -> template returned w/o validation -> `compileProtocolRequests` -> `NewTemplateExecuter` receive empty requests + empty flow = nil engine -> `*TemplateExecuter.{Compile,Execute}` invoked on nil engine = panic. RCA: 1. `*ExecutorOptions.ApplyNewEngineOptions` overwriting many fields. 2. copy op pointless; create a copy of options and then immediately replace it with original pointer. 3. missing executable requests validation after cached templates is reconstructed with updated options. Thus, this affected `--automatic-scan` mode where tech detection templates often have conditional requests that may be filtered based on runtime options. Fixes #6417 Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(templates): recompile workflow with `tplCopy.Options` Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(templates): strengthen cache hit guard Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(protocols): skips template-specific fields Signed-off-by: Dwi Siswanto <git@dw1.io> --------- Signed-off-by: Dwi Siswanto <git@dw1.io>
2025-08-23 21:31:23 +07:00
template.CompiledWorkflow.Options = tplCopy.Options
}
if isCachedTemplateValid(template) {
// options.Logger.Error().Msgf("returning cached template %s after recompiling %d requests", tplCopy.Options.TemplateID, tplCopy.Requests())
return template, nil
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
}
fix: segfault in template caching logic (#6421) * fix: segfault in template caching logic when templates had no executable requests after option updates. the cached templates could end up with 0 requests and no flow execution path, resulting in a nil engine pointer that was later derefer w/o validation. bug seq: caching template (w/ valid requests) -> get cached template -> `*ExecutorOptions.Options` copied and modified (inconsistent) -> requests updated (with new options -- some may be invalid, and without recompile) -> template returned w/o validation -> `compileProtocolRequests` -> `NewTemplateExecuter` receive empty requests + empty flow = nil engine -> `*TemplateExecuter.{Compile,Execute}` invoked on nil engine = panic. RCA: 1. `*ExecutorOptions.ApplyNewEngineOptions` overwriting many fields. 2. copy op pointless; create a copy of options and then immediately replace it with original pointer. 3. missing executable requests validation after cached templates is reconstructed with updated options. Thus, this affected `--automatic-scan` mode where tech detection templates often have conditional requests that may be filtered based on runtime options. Fixes #6417 Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(templates): recompile workflow with `tplCopy.Options` Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(templates): strengthen cache hit guard Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(protocols): skips template-specific fields Signed-off-by: Dwi Siswanto <git@dw1.io> --------- Signed-off-by: Dwi Siswanto <git@dw1.io>
2025-08-23 21:31:23 +07:00
// else: fallthrough to re-parse template from scratch
}
2021-08-27 17:06:06 +03:00
}
var reader io.ReadCloser
2024-03-13 21:02:36 +01:00
if !options.DoNotCache {
_, raw, err := parser.parsedTemplatesCache.Has(filePath)
if err == nil && raw != nil {
reader = io.NopCloser(bytes.NewReader(raw))
}
2024-03-13 21:02:36 +01:00
}
var err error
if reader == nil {
reader, err = utils.ReaderFromPathOrURL(filePath, options.Catalog)
if err != nil {
return nil, err
}
2021-07-20 22:32:44 -07:00
}
2024-03-13 21:02:36 +01:00
defer func() {
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
_ = reader.Close()
}()
2024-03-13 21:02:36 +01:00
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
// Make a copy of the options for this template
options = options.Copy()
options.TemplatePath = filePath
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
template, err := ParseTemplateFromReader(reader, preprocessor, options)
if err != nil {
return nil, err
2020-04-04 02:50:32 +05:30
}
feat: global matchers (#5701) * feat: global matchers Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Ice3man543 <ice3man543@users.noreply.github.com> * feat(globalmatchers): make `Callback` as type Signed-off-by: Dwi Siswanto <git@dw1.io> * feat: update `passive` term to `(matchers-)static` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): add `origin-template-*` event also use `Set` method instead of `maps.Clone` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat: update `matchers-static` term to `global-matchers` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): clone event before `operator.Execute` Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(tmplexec): don't store `matched` on `global-matchers` templ This will end up generating 2 events from the same `scan.ScanContext` if one of the templates has `global-matchers` enabled. This way, non- `global-matchers` templates can enter the `writeFailureCallback` func to log failure output. Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): initializes `requests` on `New` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): add `hasStorage` method Signed-off-by: Dwi Siswanto <git@dw1.io> * refactor(templates): rename global matchers checks method Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(loader): handle nil `templates.Template` pointer Signed-off-by: Dwi Siswanto <git@dw1.io> --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Ice3man543 <ice3man543@users.noreply.github.com>
2024-10-14 20:55:46 +07:00
if template.isGlobalMatchersEnabled() {
item := &globalmatchers.Item{
TemplateID: template.ID,
TemplatePath: filePath,
TemplateInfo: template.Info,
}
for _, request := range template.RequestsHTTP {
item.Operators = append(item.Operators, request.CompiledOperators)
}
options.GlobalMatchers.AddOperator(item)
return nil, nil
}
// Compile the workflow request
if len(template.Workflows) > 0 {
2020-12-30 13:26:55 +05:30
compiled := &template.Workflow
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
compileWorkflow(filePath, preprocessor, options, compiled, options.WorkflowLoader)
2020-12-30 13:26:55 +05:30
template.CompiledWorkflow = compiled
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
template.CompiledWorkflow.Options = options
}
2021-09-22 22:41:07 +05:30
template.Path = filePath
if !options.DoNotCache {
2024-03-13 21:02:36 +01:00
parser.compiledTemplatesCache.Store(filePath, template, nil, err)
}
2021-09-22 22:41:07 +05:30
return template, nil
}
feat: global matchers (#5701) * feat: global matchers Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Ice3man543 <ice3man543@users.noreply.github.com> * feat(globalmatchers): make `Callback` as type Signed-off-by: Dwi Siswanto <git@dw1.io> * feat: update `passive` term to `(matchers-)static` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): add `origin-template-*` event also use `Set` method instead of `maps.Clone` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat: update `matchers-static` term to `global-matchers` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): clone event before `operator.Execute` Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(tmplexec): don't store `matched` on `global-matchers` templ This will end up generating 2 events from the same `scan.ScanContext` if one of the templates has `global-matchers` enabled. This way, non- `global-matchers` templates can enter the `writeFailureCallback` func to log failure output. Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): initializes `requests` on `New` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): add `hasStorage` method Signed-off-by: Dwi Siswanto <git@dw1.io> * refactor(templates): rename global matchers checks method Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(loader): handle nil `templates.Template` pointer Signed-off-by: Dwi Siswanto <git@dw1.io> --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Ice3man543 <ice3man543@users.noreply.github.com>
2024-10-14 20:55:46 +07:00
// isGlobalMatchersEnabled checks if any of requests in the template
// have global matchers enabled. It iterates through all requests and
// returns true if at least one request has global matchers enabled;
// otherwise, it returns false. If global matchers templates are not
// enabled in the options, the method will immediately return false.
feat: global matchers (#5701) * feat: global matchers Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Ice3man543 <ice3man543@users.noreply.github.com> * feat(globalmatchers): make `Callback` as type Signed-off-by: Dwi Siswanto <git@dw1.io> * feat: update `passive` term to `(matchers-)static` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): add `origin-template-*` event also use `Set` method instead of `maps.Clone` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat: update `matchers-static` term to `global-matchers` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): clone event before `operator.Execute` Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(tmplexec): don't store `matched` on `global-matchers` templ This will end up generating 2 events from the same `scan.ScanContext` if one of the templates has `global-matchers` enabled. This way, non- `global-matchers` templates can enter the `writeFailureCallback` func to log failure output. Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): initializes `requests` on `New` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): add `hasStorage` method Signed-off-by: Dwi Siswanto <git@dw1.io> * refactor(templates): rename global matchers checks method Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(loader): handle nil `templates.Template` pointer Signed-off-by: Dwi Siswanto <git@dw1.io> --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Ice3man543 <ice3man543@users.noreply.github.com>
2024-10-14 20:55:46 +07:00
//
// Note: This method only checks the `RequestsHTTP`
// field of the template, which is specific to http-protocol-based
// templates.
//
// TODO: support all protocols.
func (template *Template) isGlobalMatchersEnabled() bool {
if !template.Options.Options.EnableGlobalMatchersTemplates {
return false
}
feat: global matchers (#5701) * feat: global matchers Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Ice3man543 <ice3man543@users.noreply.github.com> * feat(globalmatchers): make `Callback` as type Signed-off-by: Dwi Siswanto <git@dw1.io> * feat: update `passive` term to `(matchers-)static` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): add `origin-template-*` event also use `Set` method instead of `maps.Clone` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat: update `matchers-static` term to `global-matchers` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): clone event before `operator.Execute` Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(tmplexec): don't store `matched` on `global-matchers` templ This will end up generating 2 events from the same `scan.ScanContext` if one of the templates has `global-matchers` enabled. This way, non- `global-matchers` templates can enter the `writeFailureCallback` func to log failure output. Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): initializes `requests` on `New` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): add `hasStorage` method Signed-off-by: Dwi Siswanto <git@dw1.io> * refactor(templates): rename global matchers checks method Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(loader): handle nil `templates.Template` pointer Signed-off-by: Dwi Siswanto <git@dw1.io> --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Ice3man543 <ice3man543@users.noreply.github.com>
2024-10-14 20:55:46 +07:00
for _, request := range template.RequestsHTTP {
if request.GlobalMatchers {
return true
}
}
return false
}
// parseSelfContainedRequests parses the self contained template requests.
func (template *Template) parseSelfContainedRequests() {
2021-11-17 01:28:35 +01:00
if template.Signature.Value.String() != "" {
2021-11-12 19:58:12 +01:00
for _, request := range template.RequestsHTTP {
2021-11-17 01:28:35 +01:00
request.Signature = template.Signature
2021-11-12 19:29:45 +01:00
}
}
if !template.SelfContained {
return
2020-12-29 16:33:25 +05:30
}
for _, request := range template.RequestsHTTP {
request.SelfContained = true
2020-12-30 14:54:20 +05:30
}
for _, request := range template.RequestsNetwork {
request.SelfContained = true
}
for _, request := range template.RequestsHeadless {
request.SelfContained = true
}
}
// Requests returns the total request count for the template
func (template *Template) Requests() int {
return len(template.RequestsDNS) +
len(template.RequestsHTTP) +
len(template.RequestsFile) +
len(template.RequestsNetwork) +
len(template.RequestsHeadless) +
2021-10-29 18:26:06 +05:30
len(template.Workflows) +
len(template.RequestsSSL) +
len(template.RequestsWebsocket) +
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
len(template.RequestsWHOIS) +
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.RequestsCode) +
len(template.RequestsJavascript)
}
// compileProtocolRequests compiles all the protocol requests for the template
func (template *Template) compileProtocolRequests(options *protocols.ExecutorOptions) error {
templateRequests := template.Requests()
if templateRequests == 0 {
return fmt.Errorf("no requests defined for %s", template.ID)
2021-02-07 15:12:38 +05:30
}
if options.Options.OfflineHTTP {
return template.compileOfflineHTTPRequest(options)
}
2021-08-27 17:06:06 +03:00
var requests []protocols.Request
if template.hasMultipleRequests() {
// when multiple requests are present preserve the order of requests and protocols
// which is already done during unmarshalling
requests = template.RequestsQueue
if options.Flow == "" {
options.IsMultiProtocol = true
}
} else {
if len(template.RequestsDNS) > 0 {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsDNS)...)
}
if len(template.RequestsFile) > 0 {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsFile)...)
}
if len(template.RequestsNetwork) > 0 {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsNetwork)...)
}
if len(template.RequestsHTTP) > 0 {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsHTTP)...)
}
if len(template.RequestsHeadless) > 0 && options.Options.Headless {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsHeadless)...)
}
if len(template.RequestsSSL) > 0 {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsSSL)...)
}
if len(template.RequestsWebsocket) > 0 {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsWebsocket)...)
}
if len(template.RequestsWHOIS) > 0 {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsWHOIS)...)
}
if len(template.RequestsCode) > 0 && options.Options.EnableCodeTemplates {
requests = append(requests, 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
if len(template.RequestsJavascript) > 0 {
requests = append(requests, template.convertRequestToProtocolsRequest(template.RequestsJavascript)...)
}
}
var err error
template.Executer, err = tmplexec.NewTemplateExecuter(requests, options)
return err
2020-04-04 02:50:32 +05:30
}
// convertRequestToProtocolsRequest is a convenience wrapper to convert
// arbitrary interfaces which are slices of requests from the template to a
// slice of protocols.Request interface items.
func (template *Template) convertRequestToProtocolsRequest(requests interface{}) []protocols.Request {
switch reflect.TypeOf(requests).Kind() {
case reflect.Slice:
s := reflect.ValueOf(requests)
requestSlice := make([]protocols.Request, s.Len())
for i := 0; i < s.Len(); i++ {
value := s.Index(i)
valueInterface := value.Interface()
requestSlice[i] = valueInterface.(protocols.Request)
}
return requestSlice
}
return nil
}
// compileOfflineHTTPRequest iterates all requests if offline http mode is
// specified and collects all matchers for all the base request templates
// (those with URL {{BaseURL}} and it's slash variation.)
func (template *Template) compileOfflineHTTPRequest(options *protocols.ExecutorOptions) error {
operatorsList := []*operators.Operators{}
mainLoop:
for _, req := range template.RequestsHTTP {
hasPaths := len(req.Path) > 0
if !hasPaths {
break mainLoop
}
for _, path := range req.Path {
pathIsBaseURL := stringsutil.EqualFoldAny(path, "{{BaseURL}}", "{{BaseURL}}/", "/")
if !pathIsBaseURL {
break mainLoop
}
}
operatorsList = append(operatorsList, &req.Operators)
}
if len(operatorsList) > 0 {
options.Operators = operatorsList
var err error
template.Executer, err = tmplexec.NewTemplateExecuter([]protocols.Request{&offlinehttp.Request{}}, options)
if err != nil {
// it seems like flow executor cannot be used for offline http matching (ex:http(1) && http(2))
return ErrIncompatibleWithOfflineMatching
}
return err
}
return ErrIncompatibleWithOfflineMatching
2020-04-04 02:50:32 +05:30
}
2022-12-13 12:57:47 +05:30
// ParseTemplateFromReader reads the template from reader
2022-12-13 12:57:47 +05:30
// returns the parsed template
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
func ParseTemplateFromReader(reader io.Reader, preprocessor Preprocessor, options *protocols.ExecutorOptions) (*Template, error) {
data, err := io.ReadAll(reader)
2022-12-13 12:57:47 +05:30
if err != nil {
return nil, err
}
// a preprocessor is a variable like
// {{randstr}} which is replaced before unmarshalling
// as it is known to be a random static value per template
hasPreprocessor := false
allPreprocessors := getPreprocessors(preprocessor)
for _, preprocessor := range allPreprocessors {
if preprocessor.Exists(data) {
hasPreprocessor = true
break
}
}
if !hasPreprocessor {
// if no preprocessors exists parse template and exit
template, err := parseTemplate(data, options)
if err != nil {
return nil, err
}
if !template.Verified && len(template.Workflows) == 0 {
if config.DefaultConfig.LogAllEvents {
gologger.DefaultLogger.Print().Msgf("[%v] Template %s is not signed or tampered\n", aurora.Yellow("WRN").String(), template.ID)
}
}
return template, nil
}
// if preprocessor is required / exists in this template
// first unmarshal it and check if its verified
// persist verified status value and then
// expand all preprocessor and reparse template
// === signature verification before preprocessors ===
template, err := parseTemplate(data, options)
if err != nil {
return nil, err
}
isVerified := template.Verified
if !template.Verified && len(template.Workflows) == 0 {
// workflows are not signed by default
if config.DefaultConfig.LogAllEvents {
gologger.DefaultLogger.Print().Msgf("[%v] Template %s is not signed or tampered\n", aurora.Yellow("WRN").String(), template.ID)
}
}
generatedConstants := map[string]interface{}{}
// ==== execute preprocessors ======
for _, v := range allPreprocessors {
var replaced map[string]interface{}
data, replaced = v.ProcessNReturnData(data)
// preprocess kind of act like a constant and are generated while loading
// and stay constant for the template lifecycle
generatedConstants = generators.MergeMaps(generatedConstants, replaced)
}
reParsed, err := parseTemplate(data, options)
if err != nil {
2022-12-13 12:57:47 +05:30
return nil, err
}
// add generated constants to constants map and executer options
reParsed.Constants = generators.MergeMaps(reParsed.Constants, generatedConstants)
reParsed.Options.Constants = reParsed.Constants
reParsed.Verified = isVerified
return reParsed, nil
}
// this method does not include any kind of preprocessing
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
func parseTemplate(data []byte, srcOptions *protocols.ExecutorOptions) (*Template, error) {
// Create a copy of the options specifically for this template
options := srcOptions.Copy()
template := &Template{}
var err error
switch config.GetTemplateFormatFromExt(template.Path) {
case config.JSON:
err = json.Unmarshal(data, template)
case config.YAML:
err = yaml.Unmarshal(data, template)
default:
// assume its yaml
if err = yaml.Unmarshal(data, template); err != nil {
return nil, err
}
}
if err != nil {
return nil, errkit.Append(errkit.New(fmt.Sprintf("failed to parse %s", template.Path)), err)
}
2022-12-13 12:57:47 +05:30
if utils.IsBlank(template.Info.Name) {
return nil, errors.New("no template name field provided")
}
if template.Info.Authors.IsEmpty() {
return nil, errors.New("no template author field provided")
}
numberOfWorkflows := len(template.Workflows)
if numberOfWorkflows > 0 && numberOfWorkflows != template.Requests() {
return nil, errors.New("workflows cannot have other protocols")
}
// use default unknown severity
if len(template.Workflows) == 0 {
if template.Info.SeverityHolder.Severity == severity.Undefined {
// set unknown severity with counter and forced warning
template.Info.SeverityHolder.Severity = severity.Unknown
if options.Options.Validate {
// when validating return error
return nil, errors.New("no template severity field provided")
}
}
}
2022-12-13 12:57:47 +05:30
// Setting up variables regarding template metadata
options.TemplateID = template.ID
options.TemplateInfo = template.Info
options.StopAtFirstMatch = template.StopAtFirstMatch
if template.Variables.Len() > 0 {
options.Variables = template.Variables
}
// if more than 1 request per protocol exist we add request id to protocol request
// since in template context we have proto_prefix for each protocol it is overwritten
// if request id is not present
template.validateAllRequestIDs()
// create empty context args for template scope
options.CreateTemplateCtxStore()
options.ProtocolType = template.Type()
options.Constants = template.Constants
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
// initialize the js compiler if missing
if options.JsCompiler == nil {
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
options.JsCompiler = GetJsCompiler() // this is a singleton
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
}
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
template.Options = options
2022-12-13 12:57:47 +05:30
// If no requests, and it is also not a workflow, return error.
if template.Requests() == 0 {
return nil, fmt.Errorf("no requests defined for %s", template.ID)
}
// load `flow` and `source` in code protocol from file
// if file is referenced instead of actual source code
if err := template.ImportFileRefs(template.Options); err != nil {
return nil, errkit.Append(errkit.New(fmt.Sprintf("failed to load file refs for %s", template.ID)), err)
}
if err := template.compileProtocolRequests(template.Options); err != nil {
2022-12-13 12:57:47 +05:30
return nil, err
}
if template.Executer != nil {
if err := template.Executer.Compile(); err != nil {
return nil, errors.Wrap(err, "could not compile request")
}
template.TotalRequests = template.Executer.Requests()
}
if template.Executer == nil && template.CompiledWorkflow == nil {
return nil, ErrCreateTemplateExecutor
}
template.parseSelfContainedRequests()
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
// check if the template is verified
// only valid templates can be verified or signed
var verifier *signer.TemplateSigner
for _, verifier = range signer.DefaultTemplateVerifiers {
template.Verified, _ = verifier.Verify(data, template)
if config.DefaultConfig.LogAllEvents {
gologger.Verbose().Msgf("template %v verified by %s : %v", template.ID, verifier.Identifier(), template.Verified)
}
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
if template.Verified {
template.TemplateVerifier = verifier.Identifier()
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
break
}
}
options.TemplateVerifier = template.TemplateVerifier
Remove singletons from Nuclei engine (continuation of #6210) (#6296) * introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <git@dw1.io> * Revert "disable upload" This reverts commit 114fbe6663361bf41cf8b2645fd2d57083d53682. * Revert "hardcoding path" This reverts commit cf12ca800e0a0e974bd9fd4826a24e51547f7c00. --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Mzack9999 <mzack9999@protonmail.com> Co-authored-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Dwi Siswanto <25837540+dwisiswant0@users.noreply.github.com>
2025-07-09 14:47:26 -05:00
//nolint
if !(template.Verified && verifier.Identifier() == "projectdiscovery/nuclei-templates") {
template.Options.RawTemplate = data
}
2022-12-13 12:57:47 +05:30
return template, nil
}
fix: segfault in template caching logic (#6421) * fix: segfault in template caching logic when templates had no executable requests after option updates. the cached templates could end up with 0 requests and no flow execution path, resulting in a nil engine pointer that was later derefer w/o validation. bug seq: caching template (w/ valid requests) -> get cached template -> `*ExecutorOptions.Options` copied and modified (inconsistent) -> requests updated (with new options -- some may be invalid, and without recompile) -> template returned w/o validation -> `compileProtocolRequests` -> `NewTemplateExecuter` receive empty requests + empty flow = nil engine -> `*TemplateExecuter.{Compile,Execute}` invoked on nil engine = panic. RCA: 1. `*ExecutorOptions.ApplyNewEngineOptions` overwriting many fields. 2. copy op pointless; create a copy of options and then immediately replace it with original pointer. 3. missing executable requests validation after cached templates is reconstructed with updated options. Thus, this affected `--automatic-scan` mode where tech detection templates often have conditional requests that may be filtered based on runtime options. Fixes #6417 Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(templates): recompile workflow with `tplCopy.Options` Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(templates): strengthen cache hit guard Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(protocols): skips template-specific fields Signed-off-by: Dwi Siswanto <git@dw1.io> --------- Signed-off-by: Dwi Siswanto <git@dw1.io>
2025-08-23 21:31:23 +07:00
// isCachedTemplateValid validates that a cached template is still usable after
// option updates
func isCachedTemplateValid(template *Template) bool {
// no requests or workflows
if template.Requests() == 0 && len(template.Workflows) == 0 {
return false
}
// options not initialized
if template.Options == nil {
return false
}
// executer not available for non-workflow template
if len(template.Workflows) == 0 && template.Executer == nil {
return false
}
// compiled workflow not available
if len(template.Workflows) > 0 && template.CompiledWorkflow == nil {
return false
}
// template ID mismatch
if template.Options.TemplateID != template.ID {
return false
}
// executer exists but no requests or flow available
if template.Executer != nil {
// NOTE(dwisiswant0): This is a basic sanity check since we can't access
// private fields, but we can check requests tho
if template.Requests() == 0 && template.Options.Flow == "" {
return false
}
}
if template.Options.Options == nil {
return false
}
return true
}
var (
jsCompiler *compiler.Compiler
jsCompilerOnce = sync.OnceFunc(func() {
jsCompiler = compiler.New()
})
)
func GetJsCompiler() *compiler.Compiler {
jsCompilerOnce()
return jsCompiler
}