executeTurboHTTP dialed pipelined connections with context.Background(),
so a pipelined request of a pinned target resolved the host instead of
connecting to its ip. It now dials with the input context, which carries
the pin. protocols/http/target-line-ip-pipeline.yaml runs the pinned
target test with pipeline: true, and gets no result without the change.
ProbeKey joins the input and the ip with a NUL byte, which no input
holds, instead of "@", which a scheme-less input may hold itself.
A pinned input whose ip had no probe result fell back to Transform,
which takes the result probed for the input without an ip, so the
pinned target could get the scheme of another server. It now gets the
conversion of an input that was not probed.
A target without a scheme is probed through its pinned ip, but the
result was stored under the target alone, so the last probe of a host
pinned to several ips set the scheme for all of them, and a server that
answered only on the other scheme was not scanned. The result is now
stored under the target and its ip, and TransformPinned looks it up for
a pinned input.
-replay-proxy re-sends the requests behind a finding through a proxy,
which resolves the host itself, so the replay of a pinned target would
not reach the pinned ip. The pinned-target checks move into
pinnedTargetConflict with a table test, and the input README lists
-replay-proxy next to -proxy and -automatic-scan.
dev requires fastdialer v0.6.0, which has WithResolveOverride and the
dial cache fix, so go.mod and go.sum take dev's versions and the
fastdialer replace is dropped.
Templates that send multi-MB bodies (e.g. CVE-2026-109618 sends 1, 8 and
20 MB) kept 8-10 copies of each body alive per request. With 25 hosts in
flight this reached ~10 GB RSS and OOM-killed scan VMs.
- add pkg/utils/httpbody: a zero-copy request body that rewinds on EOF;
GetBody hands out new cursors over the same slice instead of cloning
- build raw, model and fuzzed request bodies with httpbody instead of
retryablehttp's ReusableReadCloser, which tees every read into a second
growing buffer and clones on each GetBody
- dump requests with http.Request.Write into a capped writer instead of
retryablehttp Dump/httputil.DumpRequestOut; output is unchanged for
bodies under the cap
- keep only the first 32 KiB of a body in request dumps (new
-rqss/-request-size-save flag, 0 keeps all) and leave bodies over 4 KiB
out of curl commands
- build the project cache key only when a project file is used, hashing
the body when the dump is truncated
- replay sends the full body when the dump was truncated
- slice the raw request body from the request instead of reading it out
- pass replacer values to fasttemplate as []byte so writes don't copy them
Co-Authored-By: Claude Opus 5.5 <[email protected]>
fastdialer#580 is merged into main, so the fork branch it was on no longer
exists. The replace resolves the same commit through the upstream module
path github.com/projectdiscovery/fastdialer.
The domain search stopped at 62 bits, so a total above 2^62 was handed a
domain smaller than the range and encrypt dropped the top bit, breaking the
one-to-one mapping. Stop at 63 bits (rounded up to an even 64), which covers
every representable combination total.
The random-order iterator built the shuffled order with rand.Perm(total),
allocating an int slice for the whole combination space before the first
request. For a clusterbomb product that is O(total): four 100-value lists
need ~800 MB up front, which can exhaust memory on the large, partially
sent scans the flag is meant for.
Replace it with an on-demand pseudo-random permutation of [0,total): a
4-round Feistel network over the enclosing power-of-two domain, restricted
to the range by cycle-walking. It visits every combination exactly once in
a random order, stays deterministic per iterator so Reset replays the same
order, and uses O(1) memory. The combination decode and Total() are
unchanged.
Add coverage for larger, non-power-of-two totals to exercise the
cycle-walking, and point the default-off guard at the new field.
Add -pro, -payload-random-order to run a template's payload combinations
in a random order instead of the sequential order of the payload sets.
The iterator shuffles the combination indices [0,total) and decodes each
index back to a combination, so it visits every combination exactly once
for batteringram, pitchfork and clusterbomb, keeping pitchfork's
index-aligned pairs and the full clusterbomb product. Total() is
unchanged, so request estimates and progress stay correct. When the flag
is off the sequential path is used as before.
net/smtp reads replies through net/textproto, which buffers a line until
"\n" with no length limit, so IsOpenRelay and SendMail buffered whatever a
port streaming without newlines sent. Their reads now fail after 1 MiB.
SendMail dials through the execution's dialer like IsOpenRelay so its
connection can be wrapped; smtp.SendMail dials on its own.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
go-redis reads a reply line until "\n" with no length limit, so a port that
streams bytes without one was buffered for as long as it kept sending: one
GetServerInfoAuth call against such a port grew the heap by about 1 GiB.
The redis clients now dial through go-redis's default dialer and wrap the
connection so reads fail past 16 MiB, far above any reply these calls expect.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
go-ldap waits for a reply with no timeout and net/smtp reads with no
deadline. Neither takes a context, so on a server that accepts and never
answers the call stays blocked after the session is abandoned, and the
goroutine keeps the runtime and everything it references alive for the life
of the process.
Close the connection when the template's context is done. SendMail now
dials through the execution's dialer like IsSMTP and IsOpenRelay, instead of
net/smtp.SendMail dialing on its own past the network policy.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Include the effective read limit in projectCacheKey so requests with different
limits (such as small template max-size previews) do not share truncated cached
bodies with larger reads.
When -response-size-read (-rsr) is configured, use it as a ceiling while
preserving a template's own MaxSize when smaller, rather than unconditionally
overwriting it. Also account for ResponseReadSize in response truncation detection.
Fixes#7873
* feat(reporting): close Linear issues when a finding is fixed
CloseIssue moves the matching Linear issue to the team's completed
workflow state (lowest position), or to closed-state-id when set.
Issues already completed or canceled are left alone.
Claude-Session: https://claude.ai/code/session_01Ud2FL9XNTahVE1Ke8W6y1M
Claude-Local-Session: claude --resume c4f3697b-a416-4c11-b645-e5dde2109626
* fix: address PR review comments
Claude-Session: https://claude.ai/code/session_01Ud2FL9XNTahVE1Ke8W6y1M
Claude-Local-Session: claude --resume c4f3697b-a416-4c11-b645-e5dde2109626
* fix: address PR review comments
Claude-Session: https://claude.ai/code/session_01Ud2FL9XNTahVE1Ke8W6y1M
Claude-Local-Session: claude --resume c4f3697b-a416-4c11-b645-e5dde2109626
When an HTTP(S) proxy is configured, the nuclei/net JS library dialed the
proxy through Fastdialer (which validates the proxy host) but tunneled the
connection target inside an HTTP CONNECT without validating it. This let a
template reach a deny-listed destination (-exclude-hosts /
-restrict-local-network-access) that a direct dial would have blocked,
bypassing the network policy.
Validate the target host against the network policy in the proxy branch of
Dial() before contacting the proxy, matching the guard the direct path gets
from Fastdialer. Adds a regression test asserting the proxy is never
contacted for a deny-listed target.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Fixes#7875
When options.ProxyInternal was enabled, only HTTP_PROXY was set in the environment.
Because Go standard library http.ProxyFromEnvironment inspects HTTPS_PROXY for https URLs,
internal HTTPS requests (such as template updates via GitHub API / releases, pdtm, etc.)
failed to route through the specified proxy in restricted or proxy-required environments.
This sets HTTP_PROXY, HTTPS_PROXY, ALL_PROXY (and lowercase counterparts) when ProxyInternal
is enabled, and adds unit test coverage. Also fixes operator precedence for ProxyInternal
checks in runner.go and sdk_private.go.
The archive link points to a different host than the API, and the github
client sends the token to every request it makes. The archive is public,
so only the API call needs the token now, and the archive url has to be
https.
Also adds doc comments to the new functions and tests.
Adds -utc / -update-templates-channel (stable, latest). stable keeps the
current behaviour. latest installs the head of the nuclei-templates main
branch, so templates merged after the last release are available without
waiting for the next one.
The version for the latest channel is the last release plus the short
commit as semver build metadata (e.g. v10.5.0+3de629d). Build metadata is
ignored when comparing versions, so switching back to stable doesn't
downgrade, and only a newer release makes it outdated there. Since the
version check only knows about releases, the latest channel compares the
installed version against the current head to decide when to update.
The channel can also be set in the config file like the other options.
Closes#5608
go.mod takes dev's versions, including fastdialer v0.5.25, and keeps
fastdialer replaced by the branch of projectdiscovery/fastdialer#580,
which now includes v0.5.25.
Previously, isValidHost only checked targets with http: and https:
prefixes, allowing ws: and wss: connections in headless mode to bypass
configured network policies (e.g. -exclude-hosts or local network restrictions).
This commit normalizes the scheme check and enforces host validation
against the network policy for ws: and wss: protocols as well.
Scanning a vhost on a given server, or an origin behind a CDN, needs the
hostname in the Host header, SNI and template variables while the
connection goes to another ip, and one host often has to be scanned on
several ips. -sa scans the ips DNS returns, and a target of the ip with
a Host header sends no SNI and sets {{Hostname}} to the ip.
A target line can now pin its target to an ip, like curl --resolve:
{"target": "https://app.example", "ip": "192.0.2.10"}
Each target and ip pair is a separate target with its own template
selection. The ip is validated and canonicalized, the target must have
a hostname, -sa and -iv don't resolve a pinned target, and an ip the
network policy denies is skipped. Pinned targets are refused with
-proxy and -automatic-scan.
The engine pins the host of every target with a CustomIP, from a target
line or -sa, with fastdialer.WithResolveOverride on the context each
template runs with. HTTP, network, websocket and javascript templates
then connect to the ip, while redirects to other hosts and the proxy
dial are no longer pinned. HTTP keeps a client per pinned ip, network
and websocket results report the ip, and scheme-less targets are probed
through it.
The host errors cache keys a failed dial of a pinned target by its ip,
also for IDN hosts, and -mup counts the urls of each ip apart, so a url
listed with several ips, or resolved to several with -sa, is kept on
each of them.
go.mod points fastdialer at a fork commit with WithResolveOverride until
a fastdialer release includes it.
The -stats percentage was requests sent against a total estimated
before the scan: TotalRequests of each template after clustering, times
the number of targets. The estimate leaves out workflows, whose requests
are added while they run, counts a self-contained template once per
target although it runs once, and doesn't follow stop-at-first-match or
a template that runs once per origin. A scan could end at 108% or stop
at 25%.
The engine now counts tasks: one per template, cluster or workflow run
on a target, and one per self-contained template. The total is known
when the scan starts. A task is done when it runs, when -resume skips
it, when its host is unresponsive, or when it repeats its origin.
progress.TaskTracker is an optional interface that StatsTicker
implements, so Progress and lib.StatsWriter don't change. The stats
line shows Tasks: done/total and takes the percentage from it, and -sj
and the metrics endpoint report tasks, totalTasks and the same percent.
The catalog skipped any template whose name contained a known config file
name (cves.json, contributors.json, TEMPLATES-STATS.json) since the check
used substring matching. A template like http/cves.json.yaml was silently
dropped both when passed directly and during directory traversal.
Add config.IsKnownConfigFile which compares the base name exactly, use it
in IsTemplateWithRoot and GetTemplatesPath, and drop the duplicate list in
the disk package.
Closes#7610
The http-to-https-tracker only recorded a host:port as https-only
after a plain-HTTP request received the "plain HTTP request was sent
to HTTPS port" 400 response, and used that record solely to
pre-emptively rewrite the scheme of later requests. The request that
first discovered the mismatch was never retried, so it matched
against the wrong-scheme 400 instead of the real page.
This produced a false negative on whichever request happened to run
first against a given host:port, including every request racing out
before the tracker learned about it under default concurrency - and
template loading itself races, so results could flip between runs of
the same scan even at -c 1.
Peek the response immediately after the first send and, if it matches
the signature, retry the same request over https before handing it to
the matcher pipeline, instead of only caching the fact for next time.
Fixes#7849
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Dial the test listener directly while retaining distinct request
hosts for cookie scope checks. This avoids localhost lookup failures
on Windows.
Signed-off-by: Dwi Siswanto <[email protected]>
The pipeline branch that sends a built request via pipelinedClient.Dor
never set hostname, unlike the raw pipeline branch. With an empty
hostname, the dial-history lookup, the IP-literal fallback in outputIP
and the cname lookup had nothing to work with, so `ip` was always empty
for these requests.
Set hostname from the request URL's host when the URL is non-nil,
matching the normal request path.
`Cookie.String` sanitizes values that can be deliberate fuzz payloads.
Stored cookies can also introduce a second value for the cookie under
test.
Build Cookie headers from raw fields and track the keys selected for
fuzzing. Use a filtered jar on an isolated client to retain session
updates without replacing those fields.
Fixes#7813Fixes#7826
Signed-off-by: Dwi Siswanto <[email protected]>
Resolve the output ip in a single helper, outputIP, used by both the
request-error and response paths: CustomIP first, then dial history,
then the target host if it is an IP literal. The helper splits the port
from the unstripped host with net.SplitHostPort, because the existing
LastIndex(":") strip truncates bracketed IPv6 without a port and, in
the redirect loop, truncates bracketed IPv6 further on each iteration.
`attribute` is read only by the xpath extractors, but it is accepted on
every extractor type and then dropped. A template that sets it on a json
extractor compiles, runs, and returns whatever the extractor collects.
Nothing reports the drop, so the result is indistinguishable from "the
target did not match" — a silent false negative for a scanner.
CompileExtractors already rejects a misapplied field, `case-insensitive`
outside kval extractors. Extend that pattern so a misapplied `attribute`
fails at template load through Operators.Compile, which reports it as
"could not compile extractor". The check runs after the per-type
required-value validation so the more useful "requires at least one
<field> value" error still wins.
`group` is a no-op outside regex extractors in the same way but is
deliberately left alone. A survey of all 14,029 templates in
nuclei-templates found 17 extractors that set `group` on a json or kval
extractor, all published CVE detections such as CVE-2024-3848, so
enforcing it breaks real templates. Two tests pin that behaviour.
Verified with nuclei -validate over all 14,029 templates: "All templates
validated successfully".
A two-field request line omits the path, so the second field is the
version, and the branch that handles it tested the field with
strings.Contains(parts[1], "HTTP"). Any path containing that substring
matched, so the field was treated as the version and the path was
replaced with "".
GET /HTTPProxy -> Method=GET Path=""
GET /api/HTTPHandler -> Method=GET Path=""
GET /admin -> Method=GET Path="/admin"
For a normal raw template the request then goes to the path of the input
URL instead of the one the template asked for, with no warning. For a
self-contained template the symptom is worse: ParseRawRequest refuses an
empty path, so the template fails with "path cannot be empty in self
contained request" while the path is plainly there.
Testing the field with HasPrefix(parts[1], "HTTP/") keeps the case the
branch exists for, "GET HTTP/1.1", and stops a path from being mistaken
for a version. The sibling raw parser in pkg/input/types already works
this way: it requires three fields and uses a prefix test for the scheme.
The header loop treats an empty line as the end of the block only when
the read succeeded. When the request ends with a newline and the next
read returns io.EOF, the guard falls through and the empty line is
processed as a header, so Headers gains an entry named "".
That entry reaches the wire. rawhttp's serializer writes a header with
an empty value as just the key followed by CRLF, so a key of "" is
written as a bare CRLF, which ends the header block. Map iteration order
decides where it lands, so a random subset of the remaining headers is
sent as body instead:
GET /admin HTTP/1.1
Host: example.com
<- header block ends here
Authorization: Bearer s3cr3t
Before the previous commit the entry held the preceding header's value
and serialized as a malformed ": value" line. With values no longer
reused it holds "", which is why the fix belongs with that change rather
than after it.
An empty line now ends the block regardless of the read error, and a
real read error still stops the loop without storing anything.
- Reject non-zero 'group' on non-regex extractor types with descriptive compilation error
- Reject non-empty 'attribute' on non-xpath extractor types with descriptive compilation error
- Implement String() on ExtractorTypeHolder so formatted error strings output clean type names
- Add unit tests covering rejection of misapplied fields across all extractor types
The octet-stream branch compared the schema format against "bindary",
so a requestBody with format: binary went out with Content-Type:
text/plain and only format: byte kept application/octet-stream.
Use v92 for template downloads and issue reporting, removing the direct
v30 dependency. Adapt client construction, issue request types, and
archive calls while preserving authentication fallback, custom API
paths, and the single repository-rename redirect.
Signed-off-by: Dwi Siswanto <[email protected]>
readRawRequest reused key and value across loop iterations and only
reassigned value when the line contained a colon. A line carrying no colon
therefore stored the value of the line before it under its own name:
GET /admin HTTP/1.1
Host: example.com
Authorization: Bearer s3cr3t
X-Forwarded-For
parsed to X-Forwarded-For: Bearer s3cr3t, so the credential went out under
the wrong header name.
Declaring both inside the loop fixes it by construction rather than by
remembering to reset. The parser stays as lenient as before: the malformed
line is still accepted as a header, now with an empty value.
RequestResponse.MarshalJSON stored the pre-marshaled request/response bytes as []byte inside map[string]interface{}, which encoding/json (and sonic) encode as base64 strings. The type's own UnmarshalJSON expects JSON objects under those keys, so the marshal -> unmarshal round-trip always failed when Request != nil, breaking the json.JSONCodec contract asserted at pkg/input/types/http.go.
MetaInput.ReqResp serializes under the raw-request key with this codec (MetaInput.MarshalString -> MetaInput.Unmarshal), used by host-map scans and exclusion processing in pkg/input/provider/list/hmap.go and internal/runner/preflight_portscan.go: a captured request attached to a MetaInput produced an encoded key that could not be decoded.
Wrap the pre-marshaled bytes as json.Message so they are emitted verbatim, and omit the keys for nil Request/Response instead of encoding base64 null, mirroring UnmarshalJSON's optional-key behavior.
Fixes#7795
An XML array example has no single root to encode, and the request
still went out with no body or Content-Type. Skip it after the warning,
like the default branch does for content types it cannot build.
When a request body had no schema, the generator used the schema that
generateEmptySchemaValue returned as the body value itself. An
application/xml body then hit the unchecked map assertion and nuclei
panicked while loading the spec, a JSON body was sent as
{"type":"object"}, and a text/plain body as a dump of the schema struct.
Generate an example from the empty schema instead, and let the XML
branch take a string example as the body and warn on types it cannot
encode instead of panicking. The empty schema for
application/octet-stream has no example, so that body now gets the
placeholder the octet-stream branch already has for an empty value.
* feat(js): expose SMB auth status & migrate goimpacket
Add `SMBClient.Authenticate` to check session setup without accessing
shares. Report success and the server's guest and null-session flags so
callers can distinguish credential authentication from guest or anonymous
access. Return failures as errors and close the session after each call.
Switch to projectdiscovery/[email protected]. Adapt krbforge to upstream's
mandatory <username>.ccache output in the current directory. Validate
the destination against the existing file policy before ticket creation
and return the actual filename. Reject custom output paths and "-", as
upstream no longer supports custom paths or in-memory ticket generation.
Closes#7760Closes#7752Fixes#7761
Signed-off-by: Dwi Siswanto <[email protected]>
* chore: satisfy lint
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(js): validate execution ID in smb.Authenticate
Return an error when the executionId context value is missing, empty, or
not a string. This prevents the unchecked type assertion from panicking
for missing or incorrectly typed values.
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
* Bump projectdiscovery/utils to pick up the zstd decoder leak fix
http.NewResponseChain() decompresses Content-Encoding: zstd responses
through utils's wrapDecodeReader(), which builds a *zstd.Decoder and
wraps it in io.NopCloser. The decoder is never closed, and klauspost's
zstd decoder keeps background worker goroutines alive until Close() is
called. When a response's decompressed size exceeds MaxBodyRead, the
LimitReader stops before EOF, the decoder's workers block permanently,
and the goroutines plus their window buffers leak for the life of the
process (projectdiscovery/nuclei#7749). gzip/deflate/brotli don't spawn
goroutines, so only zstd is affected.
The fix (github.com/projectdiscovery/utils@27864e5, PR #783) already
landed on utils's main branch, but no tagged release contains it yet
(latest is v0.11.5), so go.mod still points at v0.11.4. Bump to a
pseudo-version pinned at that commit as the interim step the issue
calls for, to be replaced by a tagged version once utils cuts one.
Verified with the deterministic reproducer from the issue report
(NewResponseChain + Fill against a >cap zstd body, 50 iterations):
goroutine count returns to baseline (delta=0) instead of leaking ~1
goroutine per response.
* chore(deps): bump github.com/projectdiscovery/[email protected].6
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Co-authored-by: Dwi Siswanto <[email protected]>
Pass scan options through rendering, variables, matchers, and extractors
so resolve(), public_ip()/publicip(), and jarm() honor -lna and -eh.
These helpers previously performed network I/O outside the scan's network
policy.
Use the scan dialer for HTTP and JARM connections and reject restricted
IP addresses in DNS answers. Validate original and normalized hostnames
to prevent exclusion bypasses through DNS escapes and trailing dots.
Enforce -eh with or without -lna, including in unsigned templates.
Keep local access available without -lna unless excluded, and preserve
configured DNS resolvers, including local ones.
Bind helpers at evaluation time without storing scan state in cached
expressions. Reject network helper calls without initialized scan
context.
Fixes#7769
Signed-off-by: Dwi Siswanto <[email protected]>
staticcheck QF1008: Operators is embedded in Request, so Matchers and
Extractors are reachable directly.
Co-Authored-By: Claude Opus 5 <[email protected]>
executeRequest calls respChain.FullResponseString() for every response.
That allocates a copy of headers+body (a make plus two copies) and keeps
it reachable for as long as the event is -- including inside the
interactsh request cache, which holds events until their OAST callback
arrives or the eviction window closes.
Almost nothing reads it. Across the public template corpus only 81 of
11,634 http templates (0.7%) reference "response" or part "all". The rest
match on body or headers, which are already materialised separately.
Gate the build on a scan of the request's own matchers and extractors,
plus the debug and fuzz-stats paths that consume it independently of any
template.
Measured against 4 hosts serving 2MB responses, 4 concurrent runs, with
GOMEMLIMIT at 1.73GiB:
full profile (73,856 requests) 9,559MB -> 4,760MB peak
http/vulnerabilities/ subset 7,445MB -> 3,796MB peak
Behaviour is unchanged for part: response, part: body, part: all and a
dsl contains(response, ...) expression, checked against a target whose
token appears only in a response header, so the concatenation is the
only thing that can match it.
Co-Authored-By: Claude Opus 5 <[email protected]>
Include Port, Scheme, and URL in the deduplication key so distinct
inputs that redirect to the same matched URL remain separate findings.
Encode field and collection lengths to prevent ambiguous keys, and sort
metadata keys to make hashing deterministic.
Protect the LevelDB lookup and insert with a mutex to prevent
concurrent calls from accepting the same finding more than once.
Version the stored keys and document the upgrade behavior. Existing
report databases may report previous findings once again because old
hashes cannot recover the missing input fields.
Fixes#7745
Signed-off-by: Dwi Siswanto <[email protected]>
The shared fixture used an empty word matcher,
causing four tests to fail after operator
compilation began rejecting missing values.
Signed-off-by: Dwi Siswanto <[email protected]>
Require at least one value for the selected
operator type during compilation. Empty lists
previously compiled without an error and produced
no results.
Fixes#7604
Signed-off-by: Dwi Siswanto <[email protected]>
* refactor(installer): preserve local templates during updates
Track files installed by each official release and
remove only retired templates whose contents still
match the recorded digest. Bootstrap ownership for
existing installations so upgrades keep unknown
and locally modified templates intact.
Write templates, ownership state, and config thru
synced temporary files. Recover interrupted
cleanup before another update and record the new
version only after metadata finalization succeeds.
Signed-off-by: Dwi Siswanto <[email protected]>
* Harden restore
* test(installer): compare restored permissions with source
Use the quarantined file's reported mode as the
expected value so the test works on cross-plats.
Signed-off-by: Dwi Siswanto <[email protected]>
* chore(installer): rm deprecated UpdateNucleiIgnoreHash call
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Co-authored-by: Mzack9999 <[email protected]>
applyRequiredDefaults installs the .nuclei-ignore deny-list into
Options.ExcludeTags once, while the engine is built.
ExecuteNucleiWithOptsCtx applies per-execution options to a COPY of
those options afterwards, and WithTemplateFilters assigns the whole
filter set — so a literal naming only Tags cleared ExcludeTags.
Nothing re-reads the ignore file after construction, so every execution
that varied tags per call ran with an empty exclude list and executed
templates tagged dos, local, fuzz, bruteforce and txt-service. The
failure was silent. Varying filters across concurrent executions is the
documented purpose of the thread-safe engine, so this was reachable
through intended use.
Restore the engine's baseline exclusions after per-execution options are
applied: a per-execution filter can now add exclusions but not silently
discard them. IncludeTags is untouched and remains the explicit per-tag
override for callers who do want an ignored template to run.
No extra I/O — the deny-list is already on the base engine's options —
and only missing entries are appended, so the helper is idempotent
across executions against a long-lived engine.
Fixes#7695
ReadIgnoreFile returns both `tags` and `files`, but applyRequiredDefaults
applied only `tags`, leaving ExcludedTemplates empty. The CLI runner
applies both, so the `files` section was inert for every SDK consumer.
That section exists to suppress templates known to have weak matchers,
so library users received false positives the CLI would never report.
Populate ExcludedTemplates from ignoreFile.Files, matching
internal/runner. ExcludedTemplates already flows to the loader as
Config.ExcludeTemplates, so no new plumbing is needed.
Fixes#7696
* refactor(exporters): improve exported sarif rule and result metadata
Normalize rule ids and descriptions, attach help
text, references and GitHub security properties,
and enrich result messages with target, matcher,
extractor, extracted values and reproduction
details.
Keep rule indices stable, generate better artifact
locations, mark the invocation successful, and
export with normalization and empty-object pruning
enabled.
Also adapt the exporter to the updated sarif API.
Signed-off-by: Dwi Siswanto <[email protected]>
* adding tests
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Co-authored-by: Mzack9999 <[email protected]>
Return .nuclei-ignore read and parse failures to
callers instead of continuing with an empty
exclusion set.
Treat only a missing active ignore file as
recoverable and log it as a warning. Apply this
behavior to the CLI, SDK, and loader paths.
Fixes#7691
Signed-off-by: Dwi Siswanto <[email protected]>
* refactor: adopt XDG storage and layered configs
Load XDG system configuration (and /etc/nuclei/config.yaml) before the
active user configuration, selected config, profile, and command line.
Preserve explicit command-line values, replace collections between
layers, and defer stateful option handling until the final values are
known. Keep callback flags and authentication setup limited to the CLI.
Move configuration loading, profile resolution, inline targets, and
inline secrets into internal/configuration. Keep NUCLEI_CONFIG_DIR as
a compatibility override for the user configuration directory.
Use platform directories for configuration, template data, persistent
state, and cache data. Discover default template roots through
XDG_DATA_HOME and XDG_DATA_DIRS without assigning ownership semantics
to the selected path.
Store template state in XDG_STATE_HOME and migrate the legacy
.templates-config.json file when needed. Persist the active template
path, keep custom provider templates below that root, and apply the
same installation, update, health-check, and reset behavior to every
root.
Keep .nuclei-ignore with the active template root. Derive its local
hash from the file and pass the remote hash through the update check
without persisting either value.
Move generated resume and crash-recovery files into persistent state
and use XDG_CACHE_HOME for the catalog index. Write template state and
cache snapshots atomically with private permissions.
Validate every reset target before deleting any path. Reject broad or
unsafe targets, preserve explicit resume paths, and remove generated
inline-secret directories on normal, interrupted, and fatal exits.
Isolate configuration, state, cache, and template paths in functional
and integration tests, and add coverage for layered precedence, state
migration, active-root lifecycle, reset safety, and private file modes.
Closes#6755
Signed-off-by: Dwi Siswanto <[email protected]>
* chore(cmd): use memProfile+ext instead
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(lib): gate SDK version check
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Review asked for the pool to be sized from the configured concurrency instead of
a constant, as max(TemplateThreads, request Threads) with TemplateThreads
defaulting to 25. The first half of that is right and is what this does now:
TemplateThreads and a template's payload Threads both raise the pool, which fixes
-c 800 being served by a 500-deep pool.
They cannot also lower it, because -c is not an upper bound on how many
connections the transport has open. http.Transport starts a dial whenever a
request does not find an idle connection; if one frees up first the request
takes it and the racing dial still completes. Measured against a keep-alive
target at -c 25, 1,965 templates, 5,388 requests, counting at the target:
requests in flight peaked at 22-31
open connections peaked at 121-178
Sizing the pool at -c therefore discards most of what the transport opened:
pool 500 (floor) 414 connections 13.0 req/conn
pool 25 (= -c) 3,070 connections 1.8 req/conn
pool 4 (v3.11.1) 4,352 connections 1.2 req/conn
So the floor stays at 500 and the configured concurrency raises it. A pool that
is never filled costs nothing: it is a ceiling on retained connections, not an
allocation, and the transport only ever holds connections it actually opened.
Tests: TestIdleConnPoolSize is the requested table (unset, -c 50, -c 800,
payload threads raising the pool, payload threads never shrinking it);
TestIdleConnPoolSizeIsWiredToTransport asserts the size reaches http.Transport
rather than only the helper; TestIdleConnPoolAllowsKeepAliveReuseWithPayloadThreads
covers the client that payload templates share -- Configuration.Threads is in the
client cache key, so every template with the same payload thread count piles onto
one pool. It holds each group of requests at a cyclic barrier so the overlap is
sustained for the whole run; with a single-shot barrier a pool that is too small
still passes, because once requests stop overlapping a shallow pool is enough.
The connection-count assertion held trivially in two cases the test did not
rule out: if every request errored (client.Do errors were swallowed, so zero
successful requests also means zero connections), or if the requests happened
to serialise, since the semaphore caps concurrency without forcing overlap.
Requests now block in the handler until "concurrency" of them have arrived, so
that many connections are genuinely required, and the test asserts every
request succeeded before looking at the connection count. A timer releases the
barrier so a shortfall fails on the assertions rather than hanging.
Verified both ways: reverting the pool to 4 fails on the connection count (400
requests over 176 connections), and pointing the client at a closed server
fails on "requests must succeed" rather than passing on zero connections.
Counts connections accepted by the server rather than requests served,
because the regression is invisible in request counts: the scan still issues
every request, it just opens a new connection for most of them.
Fails at MaxIdleConnsPerHost=4 (400 requests over 157 connections) and passes
with the pool sized to concurrency (400 requests over 50 connections).
The per-host client pool introduced in v3.10.0 sets MaxIdleConns and
MaxIdleConnsPerHost to 4. http.Transport closes a connection returned to a
host whose idle pool is already full, so an idle pool smaller than the number
of requests in flight against that host silently defeats keep-alive: every
request past the fourth pays a fresh TCP (and TLS) handshake instead of
reusing a pooled connection.
Clients are scoped to a single host and, in host-spray mode, every template
runs against that host, so concurrency is TemplateThreads multiplied by a
template's payload parallelism. With the defaults that is far above 4.
Measured against a local keep-alive target (6,674 templates, host-spray,
TemplateThreads=50), counting connections accepted by the target:
before: 17,564 connections for 19,997 requests (1.14 requests/connection)
after: 885 connections for 19,997 requests (22.6 requests/connection)
Identical request count and identical findings (7 and 7), so this is purely
connection reuse. The connection churn also defeats NAT: behind a Cloud NAT
gateway the pre-fix rate of ~147 new connections/sec per scanner exhausted
per-endpoint port mappings and the gateway began dropping outbound SYNs.
configuration.Threads may now only raise the pool, never lower it, since one
template's thread count does not bound total concurrency against the host.
Four acquires in the scan path ignored the context they were given, so a
cancelled scan could not leave until unrelated work finished:
- executeTemplateSpray and executeTemplatesOnTarget acquire a worker slot via
AdaptiveWaitGroup.Add, which passes context.Background().
- executeHostSpray does the same.
- flow.GetJSRuntime acquires from a process-global goja pool with
sizedpool.Get(context.TODO()).
Each of these can wait a long time. A worker slot is held for as long as a
template runs, and a JS runtime stays checked out for the whole flow including
any wait on the rate limiter, so the pool saturates under concurrent scans.
A scan whose context is already cancelled then queues for a runtime it only
needs in order to unwind, and its own cancellation cannot break the wait.
Both spray loops already check ctx.Done() at the top of each iteration, so the
acquire was the only place cancellation was invisible.
GetJSRuntime now takes a context and returns an error. This changes an
exported signature; it has one caller in-tree.
Keep the regression test focused on behavior without restating the method name.
Signed-off-by: Muhammad Rehan Khan <[email protected]>
Signed-off-by: Rehan Khan <[email protected]>
Honor disable-cookie when a workflow supplies a shared cookie jar. Add an integration fixture proving that a cookie set by one request is not attached to a later request with cookie handling disabled.
Signed-off-by: Muhammad Rehan Khan <[email protected]>
Signed-off-by: Rehan Khan <[email protected]>
readRawRequest() skips the malformed-field guard when unsafe is true,
so a raw request line with a single token (e.g. "GET\n", no path or
HTTP version) falls through to rawRequest.Path = parts[1] and panics
with "index out of range [1] with length 1". Since unsafe mode exists
specifically to tolerate malformed request lines, this is directly
reachable via a template's raw HTTP request block.
Guard the assignment so a one-token request line degrades to an empty
path instead of panicking; the existing case rawrequest.Path == "" in
Parse() already handles an empty path correctly by automerging with
the input URL.
* test(templates): add parse across engine local caches bench test
Signed-off-by: Dwi Siswanto <[email protected]>
* perf(templates): reuse parsed templates across engines
Clone cached parsed templates before compiling
them with engine-local options to avoid reopening
and decoding the same source for every engine
without sharing mutable compiled state.
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(templates): preserve aliases when cloning templates
Use one visited map for the full clone and
register maps and slices before walking their
contents to preserve shared values and handles
cycles without infinite recursion.
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Compiled template cache entries retain mutable
`ExecutorOptions` and can keep closed engines
alive.
Move those entries into an engine-local cache.
Leave the caller-owned parsed cache intact and
purge only compiled entries on `Close`.
Fixes#7656
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(raw): preserve abs targets in unsafe requests
Keep absolute request targets unchanged on the
wire. Derive the effective URL from the scan
target authority and the raw target path and query,
without merging the input path or query. Also
handle mixed-case schemes and single-label hosts.
Fixes#7382Fixes#7649
Signed-off-by: Dwi Siswanto <[email protected]>
* test(raw): add unsafe w/ full URL w/o path test
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Verify signatures before protocol compilation so
unsigned init blocks cannot run, and enforce the
same check at request execution.
Bind cached results to the template, imported file
contents, and verifier key. Use the loaded import
snapshot for signing and verification, and apply
the executable-template re-signing rule to
JavaScript.
Signed-off-by: Dwi Siswanto <[email protected]>
The previous test called the resolver directly, so it passed even with the
TryFillCustomHeaders wiring reverted and therefore guarded nothing.
Drive real request generation instead and read UnsafeRawBytes, asserting
the marker is absent, the tag survives, and the user agent still varies
across requests. Confirmed by reverting the fix: the test now fails with
"expression reached the wire unevaluated".
Unsafe raw requests do not go through setCustomHeaders for the value that
reaches the wire: TryFillCustomHeaders splices the -H line straight into
UnsafeRawBytes, and rawhttp sends those bytes. So a header carrying an
expression was sent with the literal {{...}} marker intact.
Evaluate the -H strings before they are spliced in, and share one
evaluation helper between both paths so they cannot drift.
Verified against a local server with an unsafe: true template:
before: {{rand_user_agent()}} myprop/value
after: Mozilla/5.0 (Macintosh ...) Safari/605.1.15 myprop/value
Adds a rand_user_agent() DSL helper and evaluates helper expressions in
global custom header values once per generated request.
This implements the approach proposed in #7446 instead of a dedicated
CLI flag, so attribution tagging needs no new global option:
-H "User-Agent: {{rand_user_agent()}} myprop/value"
The helper is registered with cacheable=false, otherwise a cached result
would freeze the user agent for the whole run. It is backed by the
existing projectdiscovery/useragent pool that nuclei already uses for UA
randomization, so tagged scans send the same class of user agent as
untagged ones and no new dependency is introduced. The name matches the
slug dsl.FakerFunctions() would expose, so wiring faker later is a
drop in.
Values come from the operator's own -H flag or config file, the same
trust boundary as a template, and response data is never evaluated here.
Values with no {{ }} marker skip evaluation entirely, and compile or
evaluation errors keep the original value so a typo degrades the header
rather than failing the scan. The unsafe raw request path is unchanged.
The DAST fuzzing/stats server (-dast-server) constructed its http.Server
with no timeouts, leaving it open to a Slowloris-style slow-header DoS.
Only ReadHeaderTimeout is set (not ReadTimeout/WriteTimeout) since /fuzz
requests can legitimately take a while to process. Same class of fix
already applied to internal/httpapi/apiendpoint.go.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QSCzGpK3LLQDKXtHCew5CG
ParseRawRequest read the request line and headers positionally: the
second line was always treated as the Host line regardless of content,
and header values were read by skipping exactly one byte past the
colon. This meant:
- a valueless header (e.g. "X-Empty:") panicked with a slice-bounds
error, taking down the whole scan
- a Host header anywhere but the second line was silently dropped from
the header map, so header-based preconditions never matched
- "Host:target" (no space after colon) parsed the host as "arget"
- an absolute-form request target, as used by proxy captures
(GET http://target/p HTTP/1.1), got appended to the Host rather than
replacing it
Every request-shaped input mode (burp, jsonl, yaml, openapi) goes
through this parser. Parse headers uniformly first, look up Host by
name, trim header values instead of assuming one space, and treat an
absolute-form request target as replacing the authority outright -
matching how pkg/protocols/http/raw.readRawRequest already handles
raw template requests.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QSCzGpK3LLQDKXtHCew5CG
The experimental -http-api-endpoint server used http.ListenAndServe(addr,
nil), which serves Go's global DefaultServeMux. Since net/http/pprof is
blank-imported elsewhere in the binary for the separate, opt-in
-enable-pprof feature, enabling -http-api-endpoint silently exposed
/debug/pprof/* (process cmdline, heap/goroutine dumps, CPU profiling) on
the same address. The endpoint's PUT /api/concurrency also had no
authentication. Give the server its own ServeMux, add an optional
-http-api-token flag (mirroring -dast-server-token) with a warning when
unset, and add request timeouts.
Also tighten file/directory permissions (0644->0600, 0755/0775->0750)
across report exporters, the template installer/signer, custom-template
downloaders, and output writers, so scan results and downloaded
templates aren't left world-readable on shared systems.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QSCzGpK3LLQDKXtHCew5CG
Harden Markdown report filenames and update Go dependencies (go1.26.5, go-github v81)
# Markdown and security change report
This file is a standalone, downloadable summary of the Markdown report filename
hardening and Go vulnerability remediation work.
## Executive summary
The change set:
- prevents Markdown report paths from being influenced by directory traversal
sequences;
- prevents long template IDs and hosts from removing the per-finding UUID;
- includes the selected matcher or extractor name in result filenames;
- truncates filenames without producing invalid UTF-8;
- updates the Go toolchain and vulnerable dependencies; and
- reduces reachable `govulncheck` findings from 23 to one upstream advisory
with no fixed dependency version.
## Markdown filename hardening
Markdown finding files use this structure:
```text
<template-id>-<host>-<uuid>-<matcher-or-extractor>.md
```
The matcher name is selected when both a matcher and extractor name are
available. Extractor-only findings use the extractor name.
Before a file is written, unsafe filesystem characters, path separators, and
parent-directory references are replaced. The resulting filename is limited to
255 bytes and truncated only at a valid UTF-8 boundary. Prefix truncation does
not remove the UUID or `.md` extension, so findings cannot collide merely
because their long template and host prefixes are identical.
## Dependency remediation
| Component | Previous version | Updated version |
| --- | --- | --- |
| Go toolchain | 1.26.0 | 1.26.5 |
| `golang.org/x/text` | v0.38.0 | v0.39.0 |
| `github.com/yuin/goldmark` | v1.7.13 | v1.7.17 |
| Direct `github.com/google/go-github` use | v30.1.0 | v81.0.0 |
The direct GitHub client migration covers the custom-template downloader and
GitHub reporting tracker. Module metadata was refreshed after the upgrades.
## Vulnerability scan result
The initial source scan reported 23 reachable vulnerabilities. After the
updates, the scan reports only GO-2026-5932.
GO-2026-5932 remains reachable through the latest available
`github.com/projectdiscovery/utils/update` dependency, which transitively uses
`github.com/google/go-github/v30` and `golang.org/x/crypto/openpgp`. The advisory
does not identify a fixed `golang.org/x/crypto` release. Eliminating this final
result requires the upstream update package to migrate away from the older
GitHub client or a replacement of that update subsystem.
Run the vulnerability scan with:
```console
go run golang.org/x/vuln/cmd/govulncheck@latest \
-db=https://storage.googleapis.com/go-vulndb ./...
```
An exit status indicating GO-2026-5932 is expected until the upstream
dependency is migrated.
## Validation commands
```console
go mod verify
go test ./pkg/reporting/exporters/markdown
go test ./pkg/external/customtemplates -run '^$'
go test ./pkg/reporting/trackers/github
go vet ./pkg/external/customtemplates \
./pkg/reporting/trackers/github \
./pkg/reporting/exporters/markdown
```
The `-run '^$'` custom-template command checks compilation without running the
network-dependent GitHub download tests.
## Detailed documentation
- [Markdown report filenames](markdown-report-filenames.md)
- [Go vulnerability remediation](security-remediation.md)
govulncheck on dev reports x/text and goldmark as reachable, and compress and
otel as imported. Remaining findings are the unmaintained x/crypto/openpgp
advisory, which has no fixed version and is reached only through go-github's
init, and stdlib patches that the build toolchain supplies.
Fuzzing takes the request shape from the input, so a bare URL is always fuzzed
as a GET and anything else needed a spec, captured traffic or a hand-written
proxify document. -im http reads requests as they appear on the wire, which is
what Burp and browser devtools already put on the clipboard.
The second line was always consumed as the Host line, so any request-shaped
input whose Host header sat elsewhere lost that header silently and skipped
fuzzing. Reading values by skipping one byte past the colon also truncated
unspaced values and panicked on valueless headers, crashing the scan. Absolute
request targets, as used by proxy captures, were appended to the authority
instead of replacing it.
Do not let parsed template cache hits bypass
protocol compilation, making `-validate` reject
templates with runtime compilation errors.
Fixes#7602
Signed-off-by: Dwi Siswanto <[email protected]>
ExtractRegex skips any submatch where len(match) < RegexGroup+1, and
FindAllStringSubmatch returns exactly NumSubexp()+1 entries. So a group
index beyond the pattern's capture count can never match: the template
compiles, runs, and silently extracts nothing. An empty result is
indistinguishable from 'the pattern did not match the target', which is
the same silent-failure class as the negative-group case already
rejected two lines above.
Scanning nuclei-templates (13451 files, 2100 regex extractors with
group > 0) finds 4 real instances, and they look like genuine bugs
rather than false positives. The clearest is
smtp-credentials-exposure.yaml, where two patterns share one group: 1:
regex:
- smtp_username":".*" <- 0 groups
- <smtp_username>(.*)</smtp_username> <- 1 group
Against a body containing both forms it extracts only the XML one; the
JSON credential is missed with no indication. That template has been
half-working since it was written.
Validation runs on the cached-regex branch too. The compile path
short-circuits on a cache hit, so checking only the freshly-compiled
branch would let the same pattern through unvalidated as soon as any
other template had already compiled it.
The fuzz harness picks a group index independently of its patterns (its
own defaults include the group-less https?://[^\s"']+), so it now
clamps the group to what the narrowest pattern captures -- otherwise it
would fail at compile time on inputs it deliberately generates, instead
of exercising extraction.
Tests fail without the fix: removing both call sites gives 2 failures,
and removing only the cached-branch check still fails the cache test.
kin-openapi now represents exclusive minimum and
maximum as `ExclusiveBound` values. Use `IsTrue()`
to preserve their boolean semantics when
generating numeric examples.
Signed-off-by: Dwi Siswanto <[email protected]>
Keep one engine-owned metadata index across SDK
calls and persist it at shutdown instead of
loading and saving a new index for each execution.
Track dirty state and parser validation so
compatible metadata can skip redundant filtering
parses w/o trusting lax entries in strict mode.
Defensively copy cached values, invalidate stale
entries synchronously, and remove the unused
ephemeral engine allocation.
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(index): limit include-tags to matching tag exclusions
IncludeTags in the metadata index was treated as
a forced include, so `-itags` could bypass
explicit ID/path filters and other include
criteria, while also let a template thru when it
had both an included tag and a different excluded
tag.
Match the parsed-template filter instead: an
included tag only cancels exclusion for that same
tag. Other exclusions and normal include filters
still apply, while IncludeTemplates remains the
explicit path override.
Fixes#7534
Signed-off-by: Dwi Siswanto <[email protected]>
* Skip include-tags functional parity until release
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Co-authored-by: Mzack9999 <[email protected]>
* improving lua script with args and values
* fixing comments
* keys to string
* fixing context
* fix(test): drop log() calls inflating redis-lua-script result count
The two log() calls each emitted a [JS] stdout line that the integration
harness counted as a result, yielding 3 results vs the expected 1. The
matcher reads `response` from the final expression value (not stdout), so
returning the get RunLuaScript call directly keeps the assertion intact
with a single result.
* fix flaky
* harden sdk tests
Avoid shared templates-dir update races across parallel go test packages and ignore known leveldb/ratelimit/memguardian goroutines in goleak.
* fix sdk templates
Keep goleak ignores, drop DisableUpdateCheck so CI can install templates, and serialize UpdateIfOutdated across processes.
* refactor: replace Split in loops with more efficient SplitSeq
Signed-off-by: stringsbuilder <[email protected]>
* minor refactor
* strict checksum
* fix typo
* harden sdk tests
Avoid shared templates-dir update races across parallel go test packages and ignore known leveldb/ratelimit/memguardian goroutines in goleak.
* bind splitseq temps
Keep SplitSeq inputs in locals so iterator substrings cannot outlive a temporary string expression.
* fix sdk templates
Keep goleak ignores, drop DisableUpdateCheck so CI can install templates, and serialize UpdateIfOutdated across processes.
---------
Signed-off-by: stringsbuilder <[email protected]>
Co-authored-by: Mzack9999 <[email protected]>
MatchWords lowercased the corpus and literal words but not the rendered template word, so a case-insensitive word matcher backed by a {{var}} that resolved to an uppercase value never matched (false negative). Lowercase the rendered word when CaseInsensitive is set.
Co-authored-by: Synvoya <[email protected]>
* Guard against a negative regex extractor group to avoid an index-out-of-range panic
A community template with group: -1 crashes the scan since the protocol path
has no recover. ExtractRegex indexes match[e.RegexGroup], and the len(match) <
groupPlusOne guard never catches a negative group, so match[-1] panics with
index out of range [-1]. A negative group is meaningless, so return no results
early instead.
Signed-off-by: Arpit Jain <[email protected]>
* Harden extractors
---------
Signed-off-by: Arpit Jain <[email protected]>
Co-authored-by: Mzack9999 <[email protected]>
Render locator arguments thru the action renderer
for every element lookup mode (selector, regex,
XPath, JavaScript, and search locators). Keep
rendered values local and reuse selectors instead
of rendering them twice.
Render `waitvisible` locators on the owning page
so Interactsh URLs remain attached to the request.
Use a local URL source in tests to avoid network
access.
Closes#7542
Signed-off-by: Dwi Siswanto <[email protected]>
Build the signer fragment from `PublicKey.Bytes()`
instead of reading the raw ECDSA X coordinate.
Keep the existing fragment format by hashing the
trimmed X-coordinate bytes, and propagate key
encoding errors thru signing & verification.
Signed-off-by: Dwi Siswanto <[email protected]>
* feat(templates): require signatures for javascript templates
Unsigned javascript templates should not be
accepted into execution paths when template
signing is enforced.
Apply the signature check to javascript protocol
templates in both direct loading and workflows,
and report those skips separately from code
templates.
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(signer): normalize line endings when signing
The verifier already canonicalizes CRLF to LF
before checking the digest, but the signer still
hashed the raw file content. Templates signed from
a CRLF checkout could fail verification later,
which showed up on Windows after javascript
fixtures started being signed in the integration
harness.
Use the same canonical content for signing and
verification, and add a CRLF sign-and-verify
regression.
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
* refactor(protocols): template rendering boundary
Stop treating every marker-shaped string as
template source after it has entered runtime data.
Template-authored text is rendered once, while
values from payload results, previous responses,
overrides, constants, and rendered outputs stay as
data.
Route protocol payload rendering through a shared
render boundary. Authored Interactsh markers still
allocate OAST URLs, including when helper-
transformed, but runtime marker-shaped values stay
literal and do not allocate stale URLs or trigger
another DSL pass.
Keep the same boundary inside helper expressions.
Placeholders embedded in authored govaluate string
literals are escaped before compilation, so a
value used by `{{contains('{{body}}', 'x')}}`
cannot become new expression syntax.
Track fuzz value provenance explicitly instead of
inferring it from merged map values, and share
govaluate string escaping with the matcher
fallback.
Signed-off-by: Dwi Siswanto <[email protected]>
* Update pkg/protocols/websocket/websocket.go
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* refactor(variables): preserve ownership across eval
Carry variable inputs thru an owner-aware scope
instead of merging template text and runtime data
into the same plain map before eval.
This keeps declared template variables renderable
when later values satisfy their dependencies,
while keeping runtime, extracted, previous, option,
constant, and generated values as terminal data.
A dynamic value can still shadow a declared
variable (though), but the selected value is not
eval'ed again and does not allocate Interactsh
URLs.
Store template-owned values separately in template
context so flow and multiprotocol execution can
reuse declared variable text w/o turning
extracted data into template source.
Migrate fuzz, HTTP, JavaScript, network, headless,
code, DNS, SSL, websocket, whois, flow, and
multiprotocol paths to the owner-aware evaluation
path, and add regressions for equal-value
overrides, lazy declared variables, Interactsh
allocation, and context ownership.
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(protocols): keep interactsh render state explicit
Do not let Interactsh allocation failures
disappear behind a successful render. Return the
partial render state with the error so callers can
keep URLs that were already allocated, and fix the
encoded marker regexp so `|` is not treated as a
brace digit.
Preserve caller-provided Interactsh URLs in fuzz
execution, propagate payload render errors, and
avoid persisting network precompile output when
data introduces a marker that runtime would later
treat as source.
Also keep previous/template-context values in SSL,
WebSocket, and WHOIS render scopes, and make
multiproto compile retain constants and CLI vars
as read-only data without marking them as
template-owned values.
Signed-off-by: Dwi Siswanto <[email protected]>
* refactor(render): centralize interactsh marker scanning
Move default interactsh marker detection into the
common marker pkg and use a small scanner instead
of duplicated regexes in render and interactsh.
Raw and fully URL-encoded markers still work, but
mixed raw/encoded brace pairs and bad numeric
suffixes are rejected.
Keep partially rendered map values when `RenderMap`
stops on an error.
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* fix(yaml): reject recursive include chains
Track the include stack while expanding YAML
includes and fail when a file is seen again or the
nesting limit is reached, keeping circular
includes from recursing until the process panics.
Also handle includes at the start of the buffer,
where the old padding lookup could slice from -1.
Signed-off-by: Dwi Siswanto <[email protected]>
* fix indentation
* fix typo
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Co-authored-by: Mzack9999 <[email protected]>
HTTP fuzzing does not maintain the ordered request
history used by request-condition fields. Reject
fuzzing templates that reference those fields at
validation time instead of letting them eval with
an invalid request count.
Fixes#4891
Signed-off-by: Dwi Siswanto <[email protected]>
* fuzz: add parser harnesses for raw requests & templates
Add go-fuzz harnesses for raw request and template
parsing.
The new coverage exercises input raw request
parsing, HTTP raw request parsing across safe and
unsafe modes, and YAML/JSON template parsing with
lightweight compile-time validation. Seed corpora
cover common ingestion shapes, host reconstruction,
full URL paths, empty path automerge, relative
query paths, and raw HTTP template requests.
Part of #7312
Signed-off-by: Dwi Siswanto <[email protected]>
* fuzz(types): add fuzz coverage for raw request parsing
Add a go-fuzz harness for `ParseRawRequest` and
`ParseRawRequestWithURL`.
The seed corpus covers common raw request ingestion
shapes, including simple GET requests, form posts,
JSON bodies, and URL override cases.
Signed-off-by: Dwi Siswanto <[email protected]>
* fuzz(http): add fuzz coverage for raw request modes
Add a go-fuzz harness for `Parse` and
`ParseRawRequest`.
The corpus covers unsafe requests, self-contained
host reconstruction, empty path handling, path
automerge, full URL paths, and relative query paths.
Signed-off-by: Dwi Siswanto <[email protected]>
* fuzz(templates): add fuzz coverage for parsing & compile checks
Add a go-fuzz harness for YAML and JSON template
parsing.
Generated templates are parsed in both formats and
passed thru lightweight compile-time validation.
Helper file loading is disabled so fuzz inputs
cannot turn the compile check into filesystem
access, and no protocol execution is run.
Signed-off-by: Dwi Siswanto <[email protected]>
* chore: satisfy lints
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
`OutputFile` was treated as a goimpacket option
instead of a fs sink. Since goimpacket writes the
ccache itself, krbforge had to enforce nuclei's
local file policy before building the ticket
config.
Add execution-aware JS wrappers, normalize
relative output paths into the template sandbox,
and deny outside paths unless local file access is
enabled. Keep empty output as in-memory only by
passing "-".
Signed-off-by: Dwi Siswanto <[email protected]>
The MSSQL helpers put `dbName` directly in the URL
query as the database parameter. A template could
include '&' in the database name and append driver
options such as certificate/Kerberos file paths.
Build the URL through a shared helper and query-
escape the database value so it stays part of the
database parameter.
Signed-off-by: Dwi Siswanto <[email protected]>
go-ora accepts `TRACE {FILE,DIR}`-style DSN options
and may create those files while opening the conn.
Normalize those paths and reject outside paths
unless `-allow-local-file-access` is enabled.
Signed-off-by: Dwi Siswanto <[email protected]>
LDAP was the only JS protocol client that reached
the dialer without an `IsHostAllowed` check.
Validate ldap, ldaps, and cldap hosts before
connecting, and treat ldapi as loopback so
restricted local network access rejects Unix
socket LDAP before the socket path is opened.
Signed-off-by: Dwi Siswanto <[email protected]>
Move template execution requirements into a shared
capability table that maps each capability to its
flag, stats key, and template predicate. Use the
shared model from template loading, workflow
parsing, request compilation, and runner stats
display so file, self-contained, headless, code,
DAST, and global matcher gates stay in sync.
Signed-off-by: Dwi Siswanto <[email protected]>
`PGClient.ExecuteQuery` built the connection URL
by interpolating the dbname directly into the path.
A value containing '?' could start the query string
and inject lib/pq options such as `sslrootcert`
before the appended `sslmode=disable`.
Build the URL from escaped userinfo, path and query
values so dbname stays part of the dbname.
Signed-off-by: Dwi Siswanto <[email protected]>
`highlightAsciiSection` built a regex like `(.\n*)(.\n*)` for every
non-printable byte in a matcher snippet, intending the `.` as the
literal character hex.Dump puts in the ASCII column. The regex engine
treated it as "any char". On the first pass this over-highlights every
character in the row; on the second highlight pass (when more than one
matcher hit), the now ANSI-coloured row is full of 2-character
fragments like "\x1b[", "32", "0m" that all match. Each
strings.ReplaceAll in the highlight loop then inflates the buffer
3-10x, producing exponential growth that pegs CPU and OOMs the
process within seconds.
Triggered by any TCP/network template with >=2 binary matchers of
different lengths over a response containing non-printable bytes, run
with -debug / -debug-resp / -store-resp.
Adds a regression test that fails (hangs >5s) on the bug and passes
in <10ms with the fix.
Upgrade github.com/projectdiscovery/govaluate from
v0.0.0-20260504230327-80320480bb6e to
v0.0.0-20260615100919-5ee2581bbf7e to consume the fix merged in
projectdiscovery/govaluate#4.
The govaluate lexer advanced strPosition by utf8.RuneLen(utf8.RuneError)
== 3 for invalid bytes, even though only 1 byte was consumed. This
caused byte-offset drift past the actual string length and a
`slice bounds out of range` panic in readUntilFalse.
Nuclei's expressions.Evaluate only caught govaluate errors, not panics,
so targets returning invalid UTF-8 in response data could crash the
entire process.
Fixes#7462
* fix: preserve explicit target port in network templates (fixes#7323)
Problem
-------
When a user specifies a port explicitly on the command line, e.g.:
nuclei -target TARGET:80 -t network/cves/2001/CVE-2001-1473.yaml
UseNetworkPort() was overriding port 80 with the template's port (22).
This happened because reservedPorts (80, 443, 8080, …) were always
replaced by the template port, regardless of whether the port was
deliberately chosen by the operator or merely implied by the URL scheme.
As a result, services running on non-standard ports (SSH on 80, FTP on
443, etc.) were silently scanned on the wrong port, or the connection
was refused, and the target was effectively invisible to Nuclei.
Root cause
----------
UseNetworkPort() treated a bare 'host:80' the same as 'http://host:80'.
In the former the operator explicitly chose port 80; in the latter the
port was implied by the http:// scheme.
Fix
---
Only replace a reserved port when the input contains a URL scheme
('://'), indicating the port was scheme-implied.
A bare 'host:port' form means the operator deliberately chose that port
and it is preserved unchanged.
Regression tests
----------------
Seven table-driven cases added to contextargs_test.go covering:
- No port in input → template port used (existing behaviour)
- Explicit non-reserved port → preserved
- Bare host:80 (key regression) → preserved
- http://host:80 (scheme-implied) → replaced
- http://host (no port) → template port used
- Empty template port → no-op
- Explicit port == template port → unchanged
Fixes#7323
* expand tests
* fix tests
---------
Co-authored-by: XananasX7 <[email protected]>
Co-authored-by: Mzack9999 <[email protected]>
* fix(hosterrorscache): skip hosts that consistently time out
Count ErrKindNetworkTemporary (request timeouts) toward MaxHostError so a
host that times out on every request is skipped, instead of being probed by
every template. Reset-on-success still protects slow-but-alive hosts, so only
consecutive timeouts with no successful response reach the threshold.
Closes#7454
* fix(hosterrorscache): count rawhttp i/o timeouts toward host skip
rawhttp/unsafe templates surface read timeouts as a plain-string error
("ReadStatusLine: ... i/o timeout") that errkit cannot classify, so it
reaches the regex fallback. The regex did not list i/o timeout, so a host
that timed out on every rawhttp request was never skipped. Add i/o timeout
to the pattern. Verified: 30 unsafe templates vs one unresponsive host went
from 271s with no skip to skipping after the threshold.
* fix(hosterrorscache): reset on success and ignore parent-context cancellation
Addresses review feedback on the timeout-skip change:
- The non-clustered HTTP path never reset the host-errors cache on a
successful response (markHostError ignores nil, success branch only
incremented progress), so timeout counts were not consecutive and a live
host with intermittent timeouts could be skipped. Add markHostSuccess and
call it on a successful request, mirroring the clustered path.
- context.DeadlineExceeded classifies as ErrKindNetworkTemporary, so a
failure from the parent scan context being cancelled/deadlined would count
as a host failure. Ignore failures in MarkFailedOrRemove when the caller's
context is already done; success still resets.
Tests: parent-context cancellation not counted, non-consecutive timeouts do
not skip, and the HTTP path resets the cache on success.
* fix(hosterrorscache): reset host cache on success across all HTTP paths
The timeout-counting change is global (in the cache), but reset-on-success was
only wired into the sequential HTTP path. The parallel, race and pipeline paths
counted failures without resetting on success, so a live host with intermittent
timeouts could be falsely skipped in those modes.
Consolidate mark-and-reset into recordHostResult and call it from every HTTP
execution path (sequential, parallel, race, pipeline). The SPM handler invokes
the result callback for every request outcome including success, so resetting
there is sufficient.
* test(http): add test for the parallel generated-host case
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(http): use generated input when record host errors
The async HTTP paths checked generated requests
with the updated input, but recorded host-error
results with the original input. If a generated
URL changed the effective host/port, `Check()` and
`MarkFailedOrRemove()` operated on different cache
keys.
So record race, parallel, and pipeline results with
the same updated input used for the request to
keep timeout counts and success resets attached to
the host that was actually checked.
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Co-authored-by: Dwi Siswanto <[email protected]>
* fix(templates): reject unknown fields when loading JSON templates
`-validate` and the runtime loader silently accepted JSON templates with
unknown or HTTP-only fields on non-HTTP request blocks because
`Template.UnmarshalJSON` delegated to a non-strict `json.Unmarshal`. The
same templates failed at scan time with `yaml: unmarshal errors ...` when
parsed as YAML, which is the regression reported in #7448.
Mirror the YAML strict-mode pattern for JSON:
- Wire `DisallowUnknownFields` on the outer JSON decoder in
`Parser.ParseTemplate`, gated by the existing `NoStrictSyntax` flag.
- Add `templates.NoStrictJSON`, a package-level toggle consulted from
inside `Template.UnmarshalJSON` (the decoder cannot propagate
strictness through a custom unmarshaler, hence the global, matching
the existing `yaml.StrictSyntax` idiom).
- Set `templates.NoStrictJSON` from the runner alongside
`yaml.StrictSyntax`, so `-no-strict-syntax` continues to opt out for
both formats.
Adds a regression test that asserts a JSON template with HTTP-only
fields on a `tcp:` request fails to parse under the default strict
mode and passes when `NoStrictJSON` is set.
Fixes#7448
* fix(templates): per-parser strict JSON, reject trailing data
Address CodeRabbit review on #7453:
1. Drop the process-wide `templates.NoStrictJSON` global and the runner.go
wire-up. Strictness is now scoped per parser instance so concurrent
Runner instances (#6322) with different `-no-strict-syntax` settings
cannot race on or override each other's strictness.
Implementation: add `(*Template).unmarshalJSONStrict`, a sibling to
the public `UnmarshalJSON`, that decodes via a `json.Decoder` with
`DisallowUnknownFields()`. The parser's JSON branch now calls it
directly when `!p.NoStrictSyntax`; the lax path continues to use
`json.Unmarshal`. Post-decode validation is factored into
`finalizeFromJSON` so both paths stay in sync.
2. Reject trailing data after the strict JSON decode. `json.Decoder` by
design only consumes one top-level value, so without an explicit
check a template like `{"id":"safe",...}{"id":"hijack",...}` would
silently load the first document. A second `Decode` into a throwaway
must return `io.EOF` (i.e. only whitespace remained).
Adds two regression sub-tests:
- `strictJSONRejectsTrailingData` — concatenated JSON documents error.
- `strictJSONIsPerParser` — two parsers in the same process with
different `NoStrictSyntax` settings produce the expected
per-instance outcomes.
Existing `strictJSONRejectsUnknownFields` test updated to use the
per-parser flag.
Move the shared goja execution lifecycle out of
the pooled and non-pooled paths into a common
session helper.
Per-path hooks now handle setup, callback
registration, interrupt waiting, cleanup, runtime
return, and slot release, while abandon handling
stays centralized. Abandoned runtimes are no
longer touched or reused until their orphaned
goroutine exits.
Closes#7417
Signed-off-by: Dwi Siswanto <[email protected]>
* feat(filepath): add IsPathWithinAnyDirectory func
Signed-off-by: Dwi Siswanto <[email protected]>
* refactor: use path-aware filesystem containment checks
Several filesystem trust boundaries relied on
lexical prefix checks to decide whether a path
fell under an allowed directory. That let sibling
paths be treated as if they were children of
trusted directories.
Replace those checks with canonical path
containment checks for helper payload loading,
template archive extraction, custom template
metadata, template path classification, and
headless screenshot output validation.
Signed-off-by: Dwi Siswanto <[email protected]>
* adding more tests
* fixing tests
* adding test
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Co-authored-by: Mzack9999 <[email protected]>
`ConnectSMBInfoMode` only tried SMBv1 when SMB2/3
negotiation failed so dual-stack servers could
report `SupportV1` as false even when SMBv1 was
enabled.
Run a same-target SMBv1 probe after successful
SMB2/3 negotiation and merge the support flag into
the returned log w/o changing the negotiated
SMB2/3 version.
Fixes#4832
Signed-off-by: Dwi Siswanto <[email protected]>
- Add TestParseNTLMResponse_Minimal48Bytes to explicitly cover the exact
lower boundary of the len<48 guard (minimal valid challenge, no target
name or info)
- Replace the inline immediately-invoked function for the wrong-message-type
case with a pre-built local variable for readability
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
ParseNTLMResponse read fixed-header fields at offsets 12-14, 16-20, 40-42,
and 44-48 after only checking len>=12, causing a slice-bounds-out-of-range
panic for any NTLM section between 12 and 47 bytes. Because this input comes
from untrusted network data, a malicious or malformed telnet server could crash
the scanner (or the embedding host process when used via the SDK).
Raise the guard to len<48 so the full fixed header is present before any field
is touched. Add unit tests covering the happy path, existing error cases, and a
no-panic regression table for every truncated length in [12,47].
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Prevent pooled and non-pooled goja runtimes from
being reused or cleaned up when the `RunProgram`
goroutine fails to exit after context cancellation
and `Interrupt()`. In that state, the goroutine
may still be mutating runtime state, so touching
the runtime/returning it to the pool can cause
fatal concurrent map access panics.
Add an explicit `errRuntimeTerminationTimeout`
path that abandons the runtime, keeps the related
concurrency slot reserved, and releases that slot
only from a reaper after the orphaned goroutine
exits. Preserve `errors.Is` compatibility with the
original context cancellation cause.
Keep normal cleanup behavior unchanged, including
callback panic cleanup, and add regression tests
for stuck-interrupt handling that verify runtime
abandonment and delayed slot release.
Fixes#7376
* fix race condition
* fixing review comments
* fix(js): defer runtime cleanup
When a runtime is abandoned, we must not touch the
goja runtime after `RunProgram` has exceeded the
interrupt grace period. At the same time, cleanup
still needs to run on every normal exit before
returning the runtime to the pool, including setup
callback panics.
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Co-authored-by: Dwi Siswanto <[email protected]>
Bumps clistats, fastdialer, retryablehttp-go, dsl, networkpolicy,
ratelimit, sarif, utils, wappalyzergo, cdncheck. dsl v0.8.18 moves to
the projectdiscovery/govaluate fork, and utils v0.11.0 pulls aurora v4,
so the corresponding imports and type references are migrated.
Refs #7380.
The QueryAuthStrategy case in raw.Request.ApplyAuthStrategy parses
r.FullURL into a local 'parsed', appends auth params to parsed.Params,
then returns without writing back to r.FullURL. Every other branch in
the same switch mutates r.Headers, and the standalone QueryAuthStrategy
.Apply / .ApplyOnRR in pkg/authprovider/authx/query_auth.go both write
back to req.URL.RawQuery. Only the raw-request branch was missing the
write-back, so raw templates matching a 'query' auth secret silently
drop the auth params.
Adds r.FullURL = parsed.String() after the loop. New unit test fails
on dev and passes with the fix.
WithConfigFile/Bytes now decode YAML directly into a typed RuntimeConfig
struct and apply it via MergeOptions(opts). The goflags-backed reflection
overlay had too much surface area (266-line flag inventory duplicate plus
a flag-default vs DefaultOptions diff) for the actual SDK use case, which
is accepting a known set of scan knobs from cloud-shipped YAML.
RuntimeConfig schema covers tags/severity filtering, headers/vars,
interactsh, socks5-proxy, plus rate-limit/bulk-size/concurrency/timeout/
retries/rate-limit-host. Scalar knobs use *int so omitted keys preserve
the engine's existing value.
Drops internal/runner/flags.go (266 lines) and lib/config_load.go (86
lines). Reverts internal/runner/runner.go to dev (no SetupPDCPUpload
export; SDK inlines its own PDCP wrap). Keeps the LoadReportingOptionsFromBytes
extract in internal/runner/options.go for WithReportingConfigFile/Bytes.
The BindOptionFlags refactor of readConfig() caused duplicate group
headers in `nuclei -h` (CLI-only flags appended new same-named groups
after the shared ones). Suppressing the disabled-message on the CLI
was also a behavior change.
Both are scope creep. This PR is for SDK additions, not CLI refactor.
- Revert cmd/nuclei/main.go to dev. `nuclei -h` byte-identical.
- Restore "Scan results upload to cloud is disabled." in SetupPDCPUpload.
- flags.go stays for SDK-only use via lib/config_load.go.
SetupPDCPUpload returned a non-empty status string in the
upload-disabled branch, which displayExecutionInfo then logs as a
Warning on every nuclei run that doesn't request -dashboard. That
also suppresses the friendlier dashboard hint Info line.
Return empty for the default-disabled case so the Info hint fires.
The latent issue predates this PR; CodeRabbit surfaced it on the
refactor.
DisableUpdateCheck() mutates DefaultConfig process-globally. config_test.go
files run alphabetically before sdk_test.go, so my tests were disabling the
update-check globally and TestContextCancelNucleiEngine (which depends on
template auto-install) was hitting an empty template store on first run.
Drop the option from the seven test sites. First test in the binary now
triggers template install (sync.Once gated; subsequent tests free).
client-go v1.x widened ID fields from int to int64 across the API surface
(User.ID, Issue.ID, ListOptions.Page/PerPage). Adjust the tracker to the
new signatures: Integration.userID, the assignee slice, the FormatInt
arguments, and ListOptions casts.
Keep Options.DuplicateIssuePageSize / DuplicateIssueMaxPages as int —
that struct is user-facing YAML and YAML ints round-trip into int64 fine.
Cast at the call site only.
UpdateIssue and CreateIssueNote signatures also widened, but issue.IID
is already int64 in v1.x, so existing call sites compile unchanged.
Extracted into flags.go from cmd/nuclei/main.go but the trailing
//nolint:all was dropped — golangci-lint trips on SA1019 in the
SDK-shared path. Restoring matches the dev branch line.
- L1: sdk_private.go references SetupPDCPUpload (was lowercase).
- L2: config_test.go test comment describes how tmpEngine is constructed
rather than incorrectly claiming "inherits from parent".
- Trim godocs and inline comments across the PR — drop restated WHAT,
keep WHY and limitations.
- Inline (*Runner).setupPDCPUpload — wrapper just delegated to the
package-level SetupPDCPUpload. Call site inlines the three lines.
- Dedupe reporting-config file load: WithReportingConfigFile and
loadImplicitReportingConfig share loadReportingConfigFromPath.
- Move config-overlay/load helpers (newConfigFlagSet, overlayConfigFromFile,
applyOverlay, loadReportingConfigFromPath, loadImplicitReportingConfig)
out of lib/config.go into lib/config_load.go.
- Drop threadSafePerScan engine mode and isThreadSafe helper. The four
new With* options no longer gate per-scan use. pd-agent doesn't enter
thread-safe mode; reintroducing the gate ships as a follow-up PR with
its own scope.
`FindExpressions` checks marker contents with
govaluate before doing normal placeholder
replacement. That breaks valid hyphenated names
like `request-id`: govaluate reads them as
subtraction lol, and the lookup fails with a
missing request parameter.
If a marker exactly matches a key in the
replacement map, treat it as a plain placeholder
and let normal replacement handle it. Authored
expressions should still be evaluated, and
malformed helper calls should still return errors.
Fixes#7395
Signed-off-by: Dwi Siswanto <[email protected]>
SDK consumers had to rebuild types.Options by hand or shell out to the
CLI to get config-file parity. This shares BindOptionFlags,
LoadReportingOptionsFromBytes, ApplyExporterOptionsFromTypes, and
SetupPDCPUpload between cmd/nuclei and lib/ so both paths produce
identical engine state.
WithConfigFile/Bytes apply only YAML-set fields (reflection diff against
goflags defaults) so prior With* and DefaultOptions() values survive
YAML that omits them. Per-scan ExecuteNucleiWithOpts rejects these
options via a new threadSafePerScan mode, matching the pattern for
options that only make sense at construction.
Add shared auth, options, result, redaction, and
adapter support for GoExec-backed JavaScript
helpers, including:
* `nuclei/wmi`
* `nuclei/tsch`
* `nuclei/scmr`
* `nuclei/dcom`
through generated bindings, and register them with
the JS compiler.
Also make JS generators to skip internal helper
packages and test files.
Signed-off-by: Dwi Siswanto <[email protected]>
Workflow inputs get updated with extracted values,
but later executors don't refresh their template
contexts from that state. Child subtemplates reuse
the same input object, letting sibling state leak
across concurrent executions. HTTP race requests
also ignore dynamic values when building requests.
Fix this by syncing the current workflow input
into each executor's template context, cloning
inputs passed to subtemplates, and forwarding
dynamic values to race request generation.
Fixes#5399
Signed-off-by: Dwi Siswanto <[email protected]>
propagation, sibling isolation, and same-step
refresh, plus an integration workflow test
covering the race path.
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(runner): write unsigned-templates WRN to stderr (#7314)
`r.Logger.Print()` is `gologger`'s LevelSilent helper — it bypasses
level filtering but routes to stdout. Using it for the unsigned-
templates "Use with caution" warning means the line collides with the
JSON / JSONL stream when the user runs with `-j`/`-jsonl`, breaking
downstream `jq` and any other consumer that expects clean JSON on
stdout.
Write the warning to os.Stderr directly (keeping the colorized [WRN]
prefix and the always-emitted semantics) so the JSON output stays
parseable. The integration suite's filterUnsignedTemplatesWarnings
helper already strips this message defensively, so no test churn is
needed.
Closes#7314.
* address review: route remaining Print() WRN sites to stderr too
CodeRabbit flagged that the rate-limit-deprecated, concurrency-vs-max-host-error,
and DAST-no-templates warnings have the same stdout-pollution problem the
unsigned-templates one had. Same fix — fmt.Fprintf to os.Stderr — applied to all
three so the stdout stream stays clean for -j / -jsonl consumers regardless of
which warning fires.
* address review: use Logger.Warning() per @dwisiswant0
Per the review on #7371, swap the four `fmt.Fprintf(os.Stderr, ...)`
WRN sites for `r.Logger.Warning().Msgf(...)`. Same stderr destination,
no duplicated WRN-prefix logic, follows the existing pattern used
across the runner package.
---------
Co-authored-by: Chris (ChrisJr404) <[email protected]>
CloseIssue iterated transitions comparing transition.Name against StatusNot.
StatusNot is semantically a status name (same field is used for the JQL
"status != ..." clause in FindExistingIssue), so the transition-name match
broke any workflow whose transitions have distinct verb-style names (common
in customized enterprise workflows). With default Atlassian workflows the
transition name happens to equal the target status name, masking the bug.
Compare against transition.To.Name instead, so the behavior is consistent
with the field's semantics and with how StatusNot is already used in JQL.
* Interrupt goja runtime on context cancel
* undo import formats
* do both actions in same go-routine to prevent any possible race condition
* Convert the watchdog, into a simpeler construction which still guarantees the same promises
* move the recover to the go routine, and return named return since we now can use the channel
* remove unnecessary tests
* add extra safety in case process refuses to get interrupted
* remove unnecessary ExecFuncWithTwoReturns
* remove named return values
when creating default limiter.
The engine could be set up with custom rate limits
through `WithOptions()`, but internal was still
hardcoding `e.rateLimiter` to 150 RPS when no
global limiter was explicitly set.
Now it builds the default limiter from the
resolved options:
1. Applies `RateLimitMinute` translation,
2. Defaults `RateLimitDuration` to 1s when
`RateLimit > 0` and no duration is given, then
3. Creates the limiter via `GetRateLimiter()`.
Fixes#7341
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(expressions): avoid helper eval in literal checks
`hasLiteralsOnly()` currently evaluates helper
expressions while deciding whether "{{...}}"
contains unresolved variables, which makes
validation paths run side-effectful helpers.
Just replace that runtime eval with a
`Vars()` len check so unresolved-variable
detection literally stays literal (am I writing it
right?), and of course side-effect free.
Also make `Evaluate()` return template-authored
expression compile/eval errors instead of
logging and then keep continuing, so malformed
helper calls still fail in the rendering path.
Fixes#7320
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(javascript): avoid nil map panic on arg eval failure
`getArgsCopy()` logs and counts argument
evaluation failures, but continues to store Port
in `argsCopy` even when `evaluateArgs()` returns.
This causes malformed JavaScript args like
"{{base64()}}" to panic instead of returning the
original error.
Return the evaluation error immediately after
reporting it to prevent the panic and make sure
proper error propagation.
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(js): respect `allow-local-file-access` in `require`
The goja `require() `function used the default
host filesystem loader which let JavaScript
templates import any local files even when
`allow-local-file-access` was disabled.
Pooled runtimes kept `require()` state around so
a module loaded during a privileged execution
could remain cached for a later restricted one.
Rebuild the require registry per execution after
setting the execution context, and route file-
backed module loads to preserve native modules
while enforcing the same sandbox rules (as
`nuclei/fs`).
Signed-off-by: Dwi Siswanto <[email protected]>
* fix: cross-platform sandbox path checks
Replace lexical prefix checks in the template file
sandbox with a shared path containment helper that
canonicalizes both paths before comparing them to
prevent false rejections when the configured
templates directory and the resolved file path
differ only due to symlink expansion on macOS or
path normalization on Windows.
Apply the helper in `protocolstate.NormalizePath()`
and `Options.GetValidAbsPath()` so JS `require()`-
based module loads and helper file resolution use
the same rules.
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
`interactsh.(*Client).processInteractionForRequest`
was updating the wrapped event under lock but
releasing it before calling `Operators.Execute()`,
allowing async interactsh updates to race with
matcher expr evaluation on the same `InternalEvent`
map, causing fatal concurrent map iteration/write
crashes.
Hold the event lock while populating interactsh
fields and running operators, and use a locked
`eventHash()` helper for matched-template cache
lookups that access the same event data.
Fixes#7319
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(js): prevent pool slot starvation under load
Zombie goroutines from timed-out JS executions held pool slots
indefinitely: Add() blocked with context.Background(), and defer Done()
only ran when the goroutine eventually completed. Under load, both
pools (80 pooled + 20 non-pooled slots) filled with zombies, silently
dropping all subsequent matches.
Three changes fix slot lifecycle management:
1. Propagate the 20s deadline context into ExecuteProgram (compiler.go)
so both execution paths can respect the deadline.
2. Replace Add() with AddWithContext(ctx) in both pool.go and
non-pool.go so goroutines waiting for a slot fail fast when the
deadline expires instead of blocking indefinitely.
3. Add a watchdog goroutine that releases the slot when the deadline
expires, even if the zombie is still running. An atomic.Bool
ensures exactly one Done() call between the watchdog and the
normal defer path.
* adding context
* refactor(js): derived the ctx to remaining tractable deadline leaks (#7302)
* refactor(js): use `context.Background` as default instead
Signed-off-by: Dwi Siswanto <[email protected]>
* refactor(js): derived the ctx to remaining tractable deadline leaks
Signed-off-by: Dwi Siswanto <[email protected]>
* test(js): add `NucleiJS.Context` tests
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(cmd): context param exclusion in memoization hash
The memoization template condition for excluding
context parameters from hash keys was incorrect.
The memoize package represents context.Context
types as "&{context Context}" (AST string
representation), not "context.Context".
Signed-off-by: Dwi Siswanto <[email protected]>
* chore(js): memogen'ed
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(js): hangs in checkRDPEncryption
by bounding socket I/O
Add `setConnDeadlineFromContext` helper to set
deadlines on conns derived from context timeouts.
Move conn cleanup out of loop-scoped defers to
make sure immediate cleanup per probe attempt.
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Co-authored-by: Niek den Breeje <[email protected]>
Co-authored-by: Dwi Siswanto <[email protected]>
Co-authored-by: Dwi Siswanto <[email protected]>
* fix(fuzz): prevent path mutation across sequential Rebuild calls (#6398)
retryablehttp.Request.Clone() shares the URL pointer, so when
Rebuild() calls UpdateRelPath() on the cloned request it mutates
q.req.URL.Path. On subsequent Rebuild() calls the original path
segments are wrong, causing corrupted fuzz requests (especially
visible with numeric path parts like /user/55/profile).
Snapshot the original path during Parse() and use the snapshot in
Rebuild() instead of reading from the mutable request.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* remove embedded URL field
---------
Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: Mzack9999 <[email protected]>
This commit fixes a race condition where templates start executing before
the secret file's login flow completes when using -secret-file flag.
Changes:
- pkg/authprovider/authx/dynamic.go: Replace atomic.Bool-based synchronization
with sync.Once to ensure fetch callback runs exactly once and all concurrent
callers block until completion. This prevents the race where multiple goroutines
would see fetching=true and return early with nil error before secrets were ready.
- internal/runner/runner.go: Always prefetch secrets when AuthProvider exists,
removing the PreFetchSecrets flag check. This ensures authentication completes
before scanning starts regardless of flag settings.
- lib/sdk_private.go: Same change as runner.go for SDK mode consistency.
- pkg/authprovider/file_test.go: Add test for concurrent dynamic secret access
to verify fetch happens exactly once and all workers get authenticated.
- pkg/authprovider/authx/dynamic_test.go: Add concurrent fetch tests to verify
proper synchronization behavior.
Fixes#6592
Co-authored-by: Mzack9999 <[email protected]>
- Update -omit-raw help text to include PDF in scope
- Move require.NoError out of goroutine in concurrency test (FailNow semantics)
- Truncate raw request/response at buffer time in Export() to prevent memory accumulation
* fix(expressions): only eval template-authored expressions
`expressions.Evaluate()` currently replaces
placeholders first and then scans the substituted
output for expressions which allows
response-derived values, including extractor
output, to be reinterpreted as DSL/helper syntax
on a second pass, which then becomes more serious
when env-backed variables are enabled.
So making this by collecting expressions from the
original template text before placeholder
substitution and then evaluating only those
original expressions after normal replacement to
keep trusted template-authored helpers working,
including placeholders nested inside helper
arguments while treating substituted response data
as literal text.
Fixes#7210
Signed-off-by: Dwi Siswanto <[email protected]>
* test: add resp data literal reuse test
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Replace insecure math/rand PRNG with crypto/rand in Rand() and
RandInt() JavaScript helper functions. math/rand is predictable
and unsuitable when these functions are used for generating
security-sensitive values like tokens or nonces in templates.
Implements context-aware XSS reflection analysis for the nuclei fuzzing
engine, addressing issue #5838. Uses golang.org/x/net/html tokenizer
for robust context detection across 8 injection contexts including
javascript: URIs, non-executable script blocks, srcdoc attributes,
event handlers, style blocks, and HTML comments.
All 48 tests pass with comprehensive table-driven coverage including
malformed HTML, empty inputs, and case-insensitive matching.
Zero modifications to existing files.
Retain the old exported identifier as a deprecated alias pointing to
the corrected ExcludedDastTmplStats so external consumers are not broken
by the rename.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Uses metadata caching via catalog index to reduce
runtime overhead.
Add `(*Store).LoadTemplateTags` for efficient tag
aggregation.
Signed-off-by: Dwi Siswanto <[email protected]>
Tag listing (`-tgl`) output was moved to debug log
level, making it invisible during normal runs.
Restore tag output to default log level (Print)
for better usability.
Fixes#7142
Signed-off-by: Dwi Siswanto <[email protected]>
In host-spray mode (executeTemplatesOnTarget), the goroutine-spawn loop
iterated over ALL templates for a target even after HostErrorsCache had
marked that target as permanently unresponsive. Each spawned goroutine
immediately detected the unresponsive state and wrote a 'skipped' event
to the output before returning.
Without JSON output the skip events are cheap (no I/O), so the scan
still finishes quickly. With -j or -je enabled, each skip event
triggers a synchronous JSON write; for a full template set (~18k
templates) this serialises thousands of writes and keeps the process
running for hours instead of the expected few minutes (issue #7049).
Fix: check HostErrorsCache at the top of the template-spawn loop and
break out as soon as the target is known to be permanently unresponsive.
This mirrors the identical guard already present in the template-spray
path (executeTemplateWithTargets, line 153) and avoids spawning
O(templates) no-op goroutines for dead hosts.
Fixes#7049
The time_delay analyzer's reqSender rebuilt follow-up requests from
gr.Component.Rebuild() which clones the component's base request. That
base request is parsed from rule.BaseRequest *before* post-parse header
injection happens (custom -H flags, auth provider headers, cookies).
As a result every follow-up request was sent without the headers that the
original triggering request carried, including Cookie/Authorization —
the server rejected them or ran the SQL in an unauthenticated context.
Fix: after Rebuild(), copy the complete header set from gr.Request (the
original fuzz-generated request, which has all headers) into the rebuilt
request. This mirrors the same approach used everywhere else in the
request pipeline and makes the time_delay analyzer behave consistently.
Fixes#7106
Apply request annotations during `unsafe` raw
request generation so @Host/@timeout/etc affect
the effective target and execution context.
Strip leading annotation directives from `unsafe`
wire bytes before sending, since `rawhttp`
transmits raw payload verbatim and annotation
lines can produce malformed HTTP requests.
Close#6747
Signed-off-by: Dwi Siswanto <[email protected]>
Prev. project keyed cache lookups from dumped HTTP
request bytes alone. For eq requests, this allowed
"http" and "https" targets to collide and reuse
cached responses across schemes.
Derive a scoped cache key by prefixing normalized
scheme://host before `projectfile.{Get,Set}`
keying input in the HTTP protocol path.
Close#6866
Signed-off-by: Dwi Siswanto <[email protected]>
Fix ambiguous interpretation of IPv6 addresses
like "::1:8065" by bracketing them before URL
formation to make sure they are treated as hosts
rather than "host:port" pairs.
Close#6960
Signed-off-by: Dwi Siswanto <[email protected]>
Resume files are runtime artifacts and SHOULD NOT
be presented as persistent config.
Update reset messaging to separate config vs cache
and explicitly include resume state under cache
cleanup. Also delete the cache dir during `-reset`
to keep behavior aligned with the new semantics.
Close#6792
Signed-off-by: Dwi Siswanto <[email protected]>
Drop global Chrome process sweeping from browser
shutdown.
The `previousPIDs` snapshot + delta kill logic is
unsafe on shared/parallel runners: a test can
classify another test's Chrome as "new" and kill
it during `(*Browser).Close()`, triggering
intermittent Rod panics (use of closed network
connection).
Signed-off-by: Dwi Siswanto <[email protected]>
When a variable value contains unresolved {{...}} markers (e.g. {{contact_id}})
and is passed through an encoding function like base64(), the markers get encoded
into an opaque blob that ContainsUnresolvedVariables cannot detect, causing
requests to fire with garbage data instead of being blocked.
Before evaluating an expression, check if its variable values contain unresolved
markers. If so, propagate those markers into the output so the existing downstream
check catches them with the correct variable names.
Clone the data map before modification to prevent race conditions when
multiple goroutines call evaluateVarsWithInteractsh concurrently with
a shared map.
Co-authored-by: Claude Opus 4.5 <[email protected]>
Refactor `ParseTemplateFromReader` to parse YAML
once after applying preprocessors, avoiding
redundant parsing for verification. Also add
`parseTemplateNoVerify` and
`applyTemplateVerification` helpers to separate
parsing from signature verification logic to
reduce CPU overhead during startup template
loading.
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(http): interactsh matching with `payloads`
in parallel execution.
Templates using `payloads` with Interactsh
matchers failed to detect OAST interactions
because the parallel HTTP execution path (used
when `payloads` are present) did not register
Interactsh request events, unlike the seq path.
This caused incoming interactions to lack
associated request context, preventing matchers
from running and resulting in missed detections.
Fix#5485 by wiring
`(*interactsh.Client).RequestEvent` registration
into the parallel worker goroutine, make sure both
execution paths handle Interactsh correlation
equally.
Signed-off-by: Dwi Siswanto <[email protected]>
* test: add interactsh with `payloads` integration
Signed-off-by: Dwi Siswanto <[email protected]>
* test: disable interactsh-with-payloads
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Use `jq` to deduplicate tags in the SARIF file
generated by `govulncheck` before uploading,
preventing validation failures in GitHub Actions.
Signed-off-by: Dwi Siswanto <[email protected]>
The `race` condition directive was broken due to
a strict dependency on `threads > 0` for parallel
execution, causing templates with `race` directive
enabled but no explicit threads to fall back to
seq execution.
This regression was introduced in v3.2.0 (#4868),
which restricted parallel execution to only when
`payloads` were present.
Fixes#5713 to allow race conditions even w/o
explicit `payloads`, and add a default thread
count when race is enabled but threads is 0.
Signed-off-by: Dwi Siswanto <[email protected]>
* adding min auth support
* adding unauth list modules + auth list files in module
* example
* adding rsync test
* bump go.mod
---------
Co-authored-by: Dwi Siswanto <[email protected]>
`hasMatchers` was not nil-safe when iterating over
the slice of operators. Check if the operator is
nil before accessing
`*operators.Operators.Matchers` to prevent a panic
when a protocol implementation returns a slice
containing a nil element.
This can happen when a request has no local
matchers/extractors but is processed in a flow
where global matchers are present.
Fixes#6738.
Signed-off-by: Dwi Siswanto <[email protected]>
The `connectWithDSN` func used `db.Exec()` which
implicitly uses `context.Background()`[1]. This
caused the registered "nucleitcp" dialer
callback to receive a ctx missing the
`executionId`, leading to a panic during type
assertion.
Refactor `connectWithDSN` to accept `executionId`
explicitly and use it to create a `context` for
`db.PingContext()` (yeah, instead of `db.Exec()`).
And, add a defensive check in the dialer callback
to handle nil values gracefully.
Fixes#6733 regression introduced in #6296.
[1]: "Exec uses `context.Background` internally" -
https://pkg.go.dev/database/sql#DB.Exec.
Signed-off-by: Dwi Siswanto <[email protected]>
Make sure postgres Exec/ExecContext are invoked with the correct
argument order, preventing context from being passed as the query.
* fixing pg syntax
* adding test
`MergeMaps` accounts for 11.41% of allocs (13.8
GB) in clusterbomb mode. With 1,305 combinations
per target, this function is called millions of
times in the hot path.
RCA:
* Request generator calls `MergeMaps` with single
arg on every payload combination, incurring
variadic overhead.
* Build request merges same maps multiple times
per request.
* `BuildPayloadFromOptions` recomputes static CLI
options on every call.
* Variables calls `MergeMaps` $$2×N$$ times per
variable evaluation (once in loop, once in
`evaluateVariableValue`)
Changes:
Core optimizations in maps.go:
* Pre-size merged map to avoid rehashing (30-40%
reduction)
* Add `CopyMap` for efficient single-map copy
without variadic overhead.
* Add `MergeMapsInto` for in-place mutation when
caller owns destination.
Hot path fixes:
* Replace `MergeMaps(r.currentPayloads)` with
`CopyMap(r.currentPayloads)` to eliminates
allocation on every combination iteration.
* Pre-allocate combined map once, extend in-place
during `ForEach` loop instead of creating new
map per variable (eliminates $$2×N$$ allocations
per request).
Caching with concurrency safety:
* Cache `BuildPayloadFromOptions` computation in
`sync.Map` keyed by `types.Options` ptr, but
return copy to prevent concurrent modification.
* Cost: shallow copy of ~10-20 entries vs. full
merge of vars + env (85-90% savings in typical
case)
* Clear cache in `closeInternal()` to prevent
memory leaks when SDK instances are created or
destroyed.
Estimated impact: 40-60% reduction in `MergeMaps`
allocations (5.5-8.3 GB savings from original
13.8 GB). Safe for concurrent execution and SDK
usage with multiple instances.
Signed-off-by: Dwi Siswanto <[email protected]>
* feat: add site-url to optionally provide jira server URL for oauth
* chore(cmd): add `site-url` config option
Adds optional `site-url` field to JIRA issue
tracker configuration for specifying browsable URL
when it differs from the API endpoint. This is
particularly useful for OAuth-based JIRA Cloud
integrations where `issue.Self` contains
"api.atlassian.com" instead of the user-facing
domain.
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Co-authored-by: Dwi Siswanto <[email protected]>
This patch enables TLS session resumption by
setting a shared LRU session cache
(`ClientSessionCache`) in all HTTP client TLS
configs. This reduces handshake overhead and CPU
usage for repeated conns to the same host,
improving throughput and efficiency in
clusterbomb/pitchfork modes.
This applied to HTTP-request-based and headless-
request-based protocols.
No runtime/compatibility impact.
Signed-off-by: Dwi Siswanto <[email protected]>
with configurable limits
This patch fixes duplicate issue detection for
GitLab trackers by implementing paginated search
with configurable page size and max pages. Adds
`duplicate-issue-page-size` and
`duplicate-issue-max-pages` options to the config.
Fixes#6711.
Signed-off-by: Dwi Siswanto <[email protected]>
Restore backwards compat for JavaScript protocol
templates that omit the `Port` argument.
Regression was introduced in f4f2e9f2, which
removed the fallback for empty `Port` in
`(*Request).ExecuteWithResults`, causing templates
without `Port` to be silently skipped.
Now, if no `Port` is specified, the engine
executes the JavaScript block using the target
URL's port.
Fixes#6708.
Signed-off-by: Dwi Siswanto <[email protected]>
The "Skipped X from target list as found
unresponsive permanently" message was logged on
every `(*Cache).Check()` call for hosts with
permanent errors, resulting in thousands of
duplicate log entries in verbose mode.
Wrap the log statement in `sync.Once` to match the
behavior already used for non-permanent error
logging.
Signed-off-by: Dwi Siswanto <[email protected]>
Continue the fix from #6666 by converting
remaining direct Body assignments to use setter
methods:
* pkg/fuzz/component/body.go:139: use
`SetBodyReader()` in transfer-encoding path.
* pkg/protocols/http/request.go:694: use
`SetBodyString()` in fuzz component `Rebuild()`.
Fixes#6692.
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(http): pass `dynamicValues` to `EvaluateWithInteractsh`
When `LazyEval` is true (triggered by `variables`
containing `BaseURL`, `Hostname`,
`interactsh-url`, etc.), variable expressions are not
eval'ed during YAML parsing & remain as raw exprs
like "{{rand_base(5)}}".
At request build time, `EvaluateWithInteractsh()`
checks if a variable already has a value in the
passed map before re-evaluating its expression.
But, `dynamicValues` (which contains the template
context with previously eval'ed values) was not
being passed, causing exprs like `rand_*` to be
re-evaluated on each request, producing different
values.
Fixes#6684 by including `dynamicValues` in the
map passed to `EvaluateWithInteractsh()`, so
variables evaluated in earlier requests retain
their values in subsequent requests.
Signed-off-by: Dwi Siswanto <[email protected]>
* chore(http): rm early eval in `(*Request).ExecuteWithResults()`
Signed-off-by: Dwi Siswanto <[email protected]>
* test: adds variables-threads-previous integration test
Signed-off-by: Dwi Siswanto <[email protected]>
* test: adds constants-with-threads integration test
Signed-off-by: Dwi Siswanto <[email protected]>
* test: adds race-with-variables integration test
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
The `(*Page).HistoryData` was being read w/o
holding the mutex lock after
`(*Page).ExecuteActions()` returns, while the
background hijack goroutine could still be writing
to it via `(*Page).addToHistory()`.
Copy the first history item by value while holding
RLock to avoid racing with concurrent append ops.
Fixes#6686.
Signed-off-by: Dwi Siswanto <[email protected]>
Prev, `FullResponseString()`, `BodyString()`, and
`HeadersString()` were called multiple times per
HTTP response iteration, each call allocating a
new string copy of the response data.
For a 10MB response, this resulted in ~60MB of
redundant string allocs/response (6 calls x 10MB).
Cache the string representations once per `Fill()`
cycle and reuse them throughout the response
processing loop. This reduces allocs from 6 to 3
per response, cutting memory usage by ~50% for
response string handling.
Profiling showed these functions accounting for
~89% of heap allocs (5.7GB out of 6.17GB) during
large scans.
Signed-off-by: Dwi Siswanto <[email protected]>
Bump `github.com/ericlagergren/decimal` dep to
resolve an "undefined: c.MaxScale" error
encountered during build on linux/loong64 plat.
Fixes#6664.
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(http): lost request body on retries & redirects
Updates the HTTP protocol to use
`(*retryablehttp.Request).SetBodyString` instead
of direct `Body` assignment.
This fixes#6665 where the request body was
dropped during retries or 307/308 redirects
because `GetBody` was not being populated.
Thanks to @zzyjsj for reporting the bug in the
upstream dependency and the hints!
Signed-off-by: Dwi Siswanto <[email protected]>
* empty: add co-author
Co-authored-by: zzy <[email protected]>
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Co-authored-by: zzy <[email protected]>
Prev, the template exclusion logic checked if the
full file path contained any of the known
miscellaneous directory names (e.g., helpers,
.git). This caused false positives when valid
templates were stored in paths where a parent
directory matched one of these names (e.g.,
/path/to/somewhere/that/has/helpers/dir/name/).
This commit introduces `IsTemplateWithRoot`, which
checks for excluded directories relative to a
provided root directory. It splits the relative
path into components.
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(lib): segfault when init engine with `EnableHeadlessWithOpts`
The panic was caused by attempting to log a
sandbox warning before the logger was initialized.
RCA:
* SDK option funcs were exec'd before logger init.
* `EnableHeadlessWithOpts()` attempted to create
browser instance & log warnings during the
config phase.
* `Logger` was only init'd later in `init()`
phase.
* This caused nil pointer dereference when
`MustDisableSandbox()` returned true (root on
Linux/Unix or Windows).
Changes:
* Init `Logger` in `types.DefaultOptions()` to
ensure it's always available before any option
functions execute.
* Init `Logger` field in both
`NewNucleiEngineCtx()` and
`NewThreadSafeNucleiEngineCtx()` from
`defaultOptions.Logger`.
* Move browser instance creation from
`EnableHeadlessWithOpts()` to the `init()` phase
where `Logger` is guaranteed to be available.
* Simplify logger sync logic in `init()` to only
update if changed by `WithLogger` option.
* Add test case to verify headless initialization
works without panic.
The fix maintains backward compatibility while
make sure the logger is always available when
needed by any SDK option function.
Fixes#6601.
Signed-off-by: Dwi Siswanto <[email protected]>
* build(make): adds `-timeout 30m -count 1` GOFLAGS in `test` cmd
Signed-off-by: Dwi Siswanto <[email protected]>
* Revert "fix(lib): segfault when init engine with `EnableHeadlessWithOpts`"
let see if this pass flaky test.
This reverts commit 63fcb6a1cbe7a4db7a78be766affc70eb237e57e.
* test(engine): let see if this pass flaky test
Signed-off-by: Dwi Siswanto <[email protected]>
* Revert "Revert "fix(lib): segfault when init engine with `EnableHeadlessWithOpts`""
This reverts commit 62b4223803ccb1e93593e2e08e39923d76aa20b1.
* test(engine): increase `TestActionNavigate` timeout
Signed-off-by: Dwi Siswanto <[email protected]>
* Revert "test(engine): let see if this pass flaky test"
This reverts commit d27cd985cff1b06aa1965ea11f8aa32f00778ab5.
---------
Signed-off-by: Dwi Siswanto <[email protected]>
* feat(loader): implement persistent metadata cache
for template filtering optimization.
Introduce a new template metadata indexing system
with persistent caching to dramatically improve
template loading perf when filters are applied.
The implementation adds a new index pkg that
caches lightweight template metadata (ID, tags,
authors, severity, .etc) and enables filtering
templates before expensive YAML parsing occurs.
The index uses an in-memory LRU cache backed by
`otter` pkg for efficient memory management with
adaptive sizing based on entry weight, defaulting
to approx. 40MB for 50K templates.
Metadata is persisted to disk using gob encoding
at "~/.cache/nuclei/index.gob" with atomic writes
to prevent corruption. The cache automatically
invalidates stale entries using `ModTime` to
detect file modifications, ensuring metadata
freshness w/o manual intervention.
Filtering has been refactored from the previous
`TagFilter` and `PathFilter` approach into a
unified `index.Filter` type that handles all basic
filtering ops including severity, authors, tags,
template IDs with wildcard support, protocol
types, and path-based inclusion and exclusion. The
filter implements OR logic within each field type
and AND logic across different field types, with
exclusion filters taking precedence over inclusion
filters and forced inclusion via
`IncludeTemplates` and `IncludeTags` overriding
exclusions.
The `loader` integration creates an index filter
from store configuration via `buildIndexFilter`
and manages the cache lifecycle through
`loadTemplatesIndex` and `saveTemplatesIndex`
methods. When `LoadTemplatesOnlyMetadata` or
`LoadTemplatesWithTags` is called, the system
first checks the metadata cache for each template
path. If cached metadata exists and passes
validation, the filter is applied directly against
the metadata without parsing. Only templates
matching the filter criteria proceed to full YAML
parsing, resulting in significant performance
gains.
Advanced filtering via "-tc" flag
(`IncludeConditions`) still requires template
parsing as these are expression-based filters that
cannot be evaluated from metadata alone. The
`TagFilter` has been simplified to handle only
`IncludeConditions` while all other filtering ops
are delegated to the index-based filtering system.
Cache management is fully automatic with no user
configuration required. The cache gracefully
handles errors by logging warnings & falling back
to normal op w/o caching. Cache files use schema
versioning to invalidate incompatible cache
formats across nuclei updates (well, specifically
`Index` and `Metadata` changes).
This optimization particularly benefits repeated
scans with the same filters, CI/CD pipelines
running nuclei regularly, development and testing
workflows with frequent template loading, and any
scenario with large template collections where
filtering would exclude most templates.
* test(loader): adds `BenchmarkLoadTemplates{,OnlyMetadata}` benchs
Signed-off-by: Dwi Siswanto <[email protected]>
* ci: cache nuclei-templates index
Signed-off-by: Dwi Siswanto <[email protected]>
* chore(index): satisfy lints
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(index): correct metadata filter logic
for proper template matching.
The `filter.matchesIncludes()` was using OR logic
across different filter types, causing incorrect
template matching. Additionally, ID matching was
case-sensitive, failing to match patterns like
'CVE-2021-*'.
The filter now correctly implements: (author1 OR
author2) AND (tag1 OR tag2) AND (severity1 OR
severity2) - using OR within each filter type and
AND across different types.
Signed-off-by: Dwi Siswanto <[email protected]>
* test(index): resolve test timing issue
in CI environments.
Some test was failing in CI due to filesystem
timestamp resolution limitations. On filesystems
with 1s ModTime granularity (common in CI),
modifying a file immediately after capturing its
timestamp resulted in identical ModTime values,
causing IsValid() to incorrectly return true.
Signed-off-by: Dwi Siswanto <[email protected]>
* ci: cache nuclei with composite action
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(index): file locking issue on Windows
during cache save/load.
Explicitly close file handles before performing
rename/remove ops in `Save` and `Load` methods.
* In `Save`, close temp file before rename.
* In `Load`, close file before remove during error
handling/version mismatch.
Signed-off-by: Dwi Siswanto <[email protected]>
* test(index): flaky index tests on Windows
Fix path separator mismatch in `TestCacheSize`
and `TestCachePersistenceWithLargeDataset` by
using `filepath.Join` consistently instead of
hardcoded forward slashes.
Signed-off-by: Dwi Siswanto <[email protected]>
* test(cmd): init logger to prevent nil pointer deref
The integration tests were panicking with a nil
pointer dereference in `pkg/catalog/loader`
because the logger was not init'ed.
When `store.saveMetadataIndexOnce` attempted to
log the result of the metadata cache op, it
dereferenced the nil logger, causing a crash.
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(loader): resolve include/exclude paths
for metadata cache filter.
The `indexFilter` was previously init'ed using raw
relative paths from the config for
`IncludeTemplates` and `ExcludeTemplates`.
But the persistent metadata cache stores templates
using their absolute paths. This mismatch caused
the `matchesPath` check to fail, leading to
templates being incorrectly excluded even when
explicitly included via flags
(e.g., "-include-templates
loader/excluded-template.yaml").
This commit updates `buildIndexFilter` to resolve
these paths to their absolute versions using
`store.config.Catalog.GetTemplatesPath` before
creating the filter, ensuring consistent path
matching against the metadata cache.
Signed-off-by: Dwi Siswanto <[email protected]>
* feat(index): adds `NewMetadataFromTemplate` func
Signed-off-by: Dwi Siswanto <[email protected]>
* refactor(index): return metadata when `(*Index).cache` is nil
Signed-off-by: Dwi Siswanto <[email protected]>
* refactor(loader): restore pre‑index behavior semantics
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(interactsh): skip DNS lookups on interactsh domains
to prevent false positives.
Prevents nuclei from resolving interactsh domains
injected in Host headers, which would cause
self-interactions to be incorrectly reported as
matches.
Changes:
* Add `GetHostname()` method to `interactsh.Client`
to expose active server domain.
* Skip CNAME DNS lookups in
`(*http.Request).addCNameIfAvailable` when
hostname matches the
`(*interactsh.Client).GetHostname`.
Fixes#6613
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(http): prevent false `interactshDomain` matches
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
Previously, when using `unsafe: true` with full
URLs (e.g., `GET http://example.com/path HTTP/1.1`),
the `Parse` func would treat the full URL as a
relative path, resulting in malformed requests
like `GET /http://example.com/path HTTP/1.1`.
This occurred because the full URL handling
logic was only executed for non-unsafe requests,
causing unsafe requests with full URLs to fall
through to the unsafe case which wasn't designed
to handle them.
Changes:
* Extract full URL handling before mode-specific
logic runs.
* Convert full URLs to relative paths for both
safe and unsafe modes.
* Update `UnsafeRawBytes` with the correct
relative path when unsafe is true.
* Ensure path merging works correctly with
`disable-path-automerge`.
This fix maintains backward compatibility while
properly supporting the previously broken
combination of unsafe mode with full URLs.
Fixes#6558.
Signed-off-by: Dwi Siswanto <[email protected]>
across multiple layers
Fixes timeout configuration conflicts where HTTP
requests would timeout prematurely despite
configured values in `@timeout` annotations or
`-timeout` flags.
RCA:
* `retryablehttp` pkg overriding with default
30s timeout.
* Custom timeouts not propagating to
`retryablehttp` layer.
* Multiple timeout layers not sync properly.
Changes:
* Propagate custom timeouts from `@timeout`
annotations to `retryablehttp` layer.
* Adjust 5-minute maximum cap to prevent DoS via
extremely large timeouts.
* Ensure `retryableHttpOptions.Timeout` respects
`ResponseHeaderTimeout`.
* Add comprehensive tests for timeout capping
behavior.
This allows templates to override global timeout
via `@timeout` annotations while preventing abuse
thru unreasonably large timeout values.
Fixes#6560.
Signed-off-by: Dwi Siswanto <[email protected]>
Fixes duplicate template storage & removes
unnecessary raw bytes caching.
Mem usage reduced by ~30%.
> 423MB => 299MB heap alloc.
* Use `StoreWithoutRaw()` to avoid storing raw
bytes.
* Remove duplicate storage in both caches.
* Remove ineffective raw bytes retrieval logic.
Benchmarks show 45% perf improvement with no
regressions.
Signed-off-by: Dwi Siswanto <[email protected]>
caused by shared context callbacks.
it was exposed after adding concurrent exec to
workflow processing and occurred when multiple
goroutines attempted to write to the same
`ctx.OnResult` callback field simultaneously,
causing data races during workflow template exec.
Signed-off-by: Dwi Siswanto <[email protected]>
add missing `go` keyword to anonymous funcs that
were intended to run as goroutines but were
executing synchronously instead.
Fixes#6492
Signed-off-by: Dwi Siswanto <[email protected]>
by:
* implement regex-based prompt matching for
password variants.
* add support for filling username prompts in
keyboard interactive challenges.
* improve debug logging with structured output.
this addresses issues with servers using
non-standard prompt formats and provides better
visibility into auth failures.
Signed-off-by: Dwi Siswanto <[email protected]>
* feat: Assume HTTP(S) server on high port is HTTP
* feat: enhance http probing tests
* improving issue description
---------
Co-authored-by: Matej Smycka <[email protected]>
Co-authored-by: Mzack9999 <[email protected]>
* fix(variable): global variable not same between two request in flow mode(#6337)
* update gitignore
---------
Co-authored-by: chuu <[email protected]>
Co-authored-by: PDTeamX <[email protected]>
Co-authored-by: Mzack9999 <[email protected]>
* normalize file `fpath` in `IsTemplate` using
filepath.FromSlash to ensure consistent matching
across platforms.
* update `GetKnownMiscDirectories` docs to clarify
that trailing slashes prevent false positives,
since `IsTemplate` compares against normalized
full paths.
Signed-off-by: Dwi Siswanto <[email protected]>
* jira: hotfix for Cloud to use /rest/api/3/search/jql in FindExistingIssue; add live test verifying v3 endpoint
* jira: fix Cloud v3 search response handling (no total); set Self from base
* fix lint error
* tests(jira): apply De Morgan to satisfy staticcheck QF1001
* Refactored header-based auth scans not to normalize the header names.
* Removed the header validation as it's not really useful here.
* adding docs
---------
Co-authored-by: Mzack9999 <[email protected]>
* Enhance matcher compilation with caching for regex and DSL expressions to improve performance. Update template parsing to conditionally retain raw templates based on size constraints.
* Implement caching for regex and DSL expressions in extractors and matchers to enhance performance. Introduce a buffer pool in raw requests to reduce memory allocations. Update template cache management for improved efficiency.
* feat: improve concurrency to be bound
* refactor: replace fmt.Sprintf with fmt.Fprintf for improved performance in header handling
* feat: add regex matching tests and benchmarks for performance evaluation
* feat: add prefix check in regex extraction to optimize matching process
* feat: implement regex caching mechanism to enhance performance in extractors and matchers, along with tests and benchmarks for validation
* feat: add unit tests for template execution in the core engine, enhancing test coverage and reliability
* feat: enhance error handling in template execution and improve regex caching logic for better performance
* Implement caching for regex and DSL expressions in the cache package, replacing previous sync.Map usage. Add unit tests for cache functionality, including eviction by capacity and retrieval of cached items. Update extractors and matchers to utilize the new cache system for improved performance and memory efficiency.
* Add tests for SetCapacities in cache package to ensure cache behavior on capacity changes
- Implemented TestSetCapacities_NoRebuildOnZero to verify that setting capacities to zero does not clear existing caches.
- Added TestSetCapacities_BeforeFirstUse to confirm that initial cache settings are respected and not overridden by subsequent capacity changes.
* Refactor matchers and update load test generator to use io package
- Removed maxRegexScanBytes constant from match.go.
- Replaced ioutil with io package in load_test.go for NopCloser usage.
- Restored TestValidate_AllowsInlineMultiline in load_test.go to ensure inline validation functionality.
* Add cancellation support in template execution and enhance test coverage
- Updated executeTemplateWithTargets to respect context cancellation.
- Introduced fakeTargetProvider and slowExecuter for testing.
- Added Test_executeTemplateWithTargets_RespectsCancellation to validate cancellation behavior during template execution.
* fix: handle jira deprecated endpoint
* refactor: update Jira issue search result structure to include 'Self' field
* Revert "refactor: update Jira issue search result structure to include 'Self' field"
This reverts commit b0953419d3.
* Revert "fix: handle jira deprecated endpoint"
This reverts commit 1fc05076cd.
* chore(deps): bump github.com/andygrunwald/go-jira to v1.16.1 and tidy
* fix(jira): migrate Issue.Search to SearchV2JQL with explicit Fields
* remove the stack trace when the nuclei-ignore file does not exist
* removing useless debug stack
---------
Co-authored-by: Mzack9999 <[email protected]>
* test(reporting/exporters/mongo): add mongo integration test with testcontainer-go module
Signed-off-by: Lorenzo Susini <[email protected]>
* execute exportes only on linux
---------
Signed-off-by: Lorenzo Susini <[email protected]>
Co-authored-by: Mzack9999 <[email protected]>
* 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 <[email protected]>
* fix(templates): recompile workflow with `tplCopy.Options`
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(templates): strengthen cache hit guard
Signed-off-by: Dwi Siswanto <[email protected]>
* fix(protocols): skips template-specific fields
Signed-off-by: Dwi Siswanto <[email protected]>
---------
Signed-off-by: Dwi Siswanto <[email protected]>
* fix: remove undefined errorutil.ShowStackTrace
* feat: add make lint support and integrate with test
* refactor: migrate errorutil to errkit across codebase
- Replace deprecated errorutil with modern errkit
- Convert error declarations from var to func for better compatibility
- Fix all SA1019 deprecation warnings
- Maintain error chain support and stack traces
* fix: improve DNS test reliability using Google DNS
- Configure test to use Google DNS (8.8.8.8) for stability
- Fix nil pointer issue in DNS client initialization
- Keep production defaults unchanged
* fixing logic
* removing unwanted branches in makefile
---------
Co-authored-by: Mzack9999 <[email protected]>
Steps to reproduce the behavior, for example, commands to run Nuclei.
📝 For a more detailed output that could help in troubleshooting, you may want to run Nuclei with the **`-verbose`** or **`-debug`** flags. This will provide additional insights into what's happening under the hood.
💡 Prefer copying text output over using screenshots for easier troubleshooting.
📝 For a more detailed output that could help in troubleshooting, you may want to run Nuclei with the **`-verbose`** or **`-debug`** flags. This will provide additional insights into what's happening under the hood.<br>
📊 For performance or memory investigations, use **`-profile-mem`**, which generates `*.cpu`, `*.mem`, and `*.trace` files. Since GitHub doesn't support these formats directly, compress them (e.g., .zip or .tar.gz) and attach the archive under the "Anything else" section below.
:warning: **Please redact any literal target hosts/URLs or other sensitive information.**
placeholder:|
@@ -49,7 +52,10 @@ body:
description:|
Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
📝 For a more detailed output that could help in troubleshooting, you may want to run Nuclei with the **`-verbose`** or **`-debug`** flags. This will provide additional insights into what's happening under the hood.
💡 Prefer copying text output over using screenshots for easier troubleshooting.
📝 For a more detailed output that could help in troubleshooting, you may want to run Nuclei with the **`-verbose`** or **`-debug`** flags. This will provide additional insights into what's happening under the hood.<br>
📊 For performance or memory investigations, use **`-profile-mem`**, which generates `*.cpu`, `*.mem`, and `*.trace` files. Since GitHub doesn't support these formats directly, compress them (e.g., .zip or .tar.gz) and attach the archive under the "Anything else" section below.
:warning: **Please redact any literal target hosts/URLs or other sensitive information.**
render:shell
@@ -58,9 +64,9 @@ body:
label:Environment
description:|
Examples:
- **OS**: Ubuntu 20.04
- **Nuclei** (`nuclei -version`): v3.3.1
- **Go** (`go version`): go1.22.0 _(only if you've installed it via the `go install` command)_
- **OS**: Ubuntu 24.04
- **Nuclei** (`nuclei -version`): v3.6.0
- **Go** (`go version`): go1.24.0 _(only if you've installed it via the `go install` command)_
value:|
- OS:
- Nuclei:
@@ -72,7 +78,7 @@ body:
attributes:
label:Anything else?
description:|
Links? References? Templates? Anything that will give us more context about the issue you are encountering!
Links? References? Templates? CPU, memory, and trace profiles? Anything that will give us more context about the issue you are encountering!
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
This folder contains the preserved issue templates that are **not** directly accessible to users. These templates serve as references for maintainers when converting discussions to issues.
<!-- Describe the overall picture of your modifications to help maintainers understand the pull request. PRs are required to be associated to their related issue tickets or feature request. -->
### Proof
<!-- How has this been tested? Please describe the tests that you ran to verify your changes. -->
line="See SECURITY_CONTEXT.md for this repo's known vulnerabilities and recurring weak spots. Check it before writing or reviewing security-sensitive code."
touched=""
paths="SECURITY_CONTEXT.md"
for f in CLAUDE.md AGENTS.md; do
if [ ! -f "$f" ]; then continue; fi
paths="$(printf '%s\n%s' "$paths" "$f")"
if grep -q "SECURITY_CONTEXT.md" "$f"; then continue; fi
printf '\n%s\n' "$line" >> "$f"
if [ -n "$touched" ]; then touched="$touched and $f"; else touched="$f"; fi
done
echo "touched=$touched" >> "$GITHUB_OUTPUT"
# Title the pull request for what it actually carries: when the
# analysis is unchanged, the only edit is the agent-instructions line.
if [ "$REPORT_CHANGED" = "false" ]; then
echo "subject=chore: reference security context from agent instructions" >> "$GITHUB_OUTPUT"
Refreshes `SECURITY_CONTEXT.md`, this repository's security-fix history as working context, so agents and reviewers don't reintroduce fixes that already shipped.
${{ steps.context.outputs.visibility == 'private' && format('[Read the updated file]({0}/{1}/blob/security-context/refresh/SECURITY_CONTEXT.md)', github.server_url, github.repository) || format('[Full report for this repository](https://securitycontext.dev/r/{0})', github.repository) }}
${{ steps.agents.outputs.touched != '' && format('Also adds a one-line reference to {0} so your coding agent picks this up automatically.', steps.agents.outputs.touched) || 'Tip: reference `SECURITY_CONTEXT.md` from your agent instructions file (`CLAUDE.md` or `AGENTS.md`) so your coding agent reads it automatically.' }}
---
_Your agent doesn't know this repo's security history. [Security Context](https://securitycontext.dev) keeps it where your agent can see it, so old vulnerabilities and their variants don't come back in new code._
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
Nuclei is a modern, high-performance vulnerability scanner built in Go that leverages YAML-based templates for customizable vulnerability detection. It supports multiple protocols (HTTP, DNS, TCP, SSL, WebSocket, WHOIS, JavaScript, Code) and is designed for zero false positives through real-world condition simulation.
## Development Commands
### Building and Testing
-`make build` - Build the main nuclei binary to ./bin/nuclei
-`make test` - Run unit tests with race detection
-`make integration` - Run the native integration suite via `go test -tags=integration ./internal/tests/integration`
-`make functional` - CI-only functional suite entry point
-`make vet` - Run go vet for code analysis
-`make tidy` - Clean up go modules
### Validation and Linting
-`make template-validate` - Validate nuclei templates using the built binary
-`go fmt ./...` - Format Go code
-`go vet ./...` - Static analysis
### Development Tools
-`make devtools-all` - Build all development tools (bindgen, tsgen, scrapefuncs)
-`make jsupdate-all` - Update JavaScript bindings and TypeScript definitions
-`make docs` - Generate documentation
-`make memogen` - Generate memoization code for JavaScript libraries
### Testing Specific Components
- Run single test: `go test -v ./pkg/path/to/package -run TestName`
- Integration tests are in `internal/tests/integration/` and run via `go test -tags=integration ./internal/tests/integration`
## Architecture Overview
### Core Components
- **cmd/nuclei** - Main CLI entry point with flag parsing and configuration
- **internal/runner** - Core runner that orchestrates the entire scanning process
- **pkg/core** - Execution engine with work pools and template clustering
- **pkg/templates** - Template parsing, compilation, and management
@@ -22,7 +22,7 @@ When this flag is provided, nuclei will print the list of all helper functions a
-`-svd` flag
When this flag is provided, nuclei will print all `variables` pre and postexecution of a request for a template. This is useful to understand what variables are available for a template and what values they have.
When this flag is provided, nuclei will print all `variables` pre- and post-execution of a request for a template. This is useful to understand what variables are available for a template and what values they have.
-`-elog = errors.txt` flag
@@ -40,6 +40,8 @@ Nuclei was built with some environment variables in mind to help with debugging.
| `SHOW_DSL_ERRORS=true` | Enables Printing DSL Errors (that are hidden by default) |
That's it, you've added a new protocol to Nuclei. The next good step would be to write integration tests which are described in `integration-tests` and `cmd/integration-tests` directories.
That's it, you've added a new protocol to Nuclei. The next good step would be to add native integration coverage under `internal/tests/integration` and run it with `go test -tags=integration ./internal/tests/integration`.
Nuclei uses `go-fuzz` for targeted harnesses behind the `gofuzz` build tag.
## Targets
The Makefile exposes these go-fuzz targets:
```bash
make build-fuzz GOFUZZ_PACKAGE=./pkg/operators/matchers
make fuzz GOFUZZ_PACKAGE=./pkg/operators/matchers
```
Required variable:
-`GOFUZZ_PACKAGE`: any package path that `go list` can resolve from the repo root. The normal form in this repo is a relative package path such as `./pkg/operators/matchers`.
`build-fuzz`, `fuzz`, and `fuzz-ci` derive everything else from that package path:
`discover-fuzz-packages` emits the GitHub Actions matrix JSON to stdout, and writes `matrix=...` to `GITHUB_OUTPUT` when that file is present.
`fuzz-ci` wraps `make fuzz` in the CI timeout.
`build-fuzz` and `fuzz` fail immediately if `GOFUZZ_PACKAGE` is missing, the package cannot be resolved, or the seed corpus directory is missing or empty.
## Examples
Operators (matchers & extractors) harness:
```bash
make fuzz GOFUZZ_PACKAGE=./pkg/operators/matchers
make fuzz GOFUZZ_PACKAGE=./pkg/operators/extractors
```
**Harness Coverage**:
Matchers exercise `Matcher.CompileMatchers()` through a compact line-based grammar. Supported keys are:
-`type`
-`condition`
-`part`
-`encoding`
-`negative`
-`case-insensitive`
-`match-all`
-`name`
-`value`
-`status`
-`size`
Extractors exercise `Extractor.CompileExtractors()` and the matching extraction path with fixed local corpora. Supported keys are:
-`type`
-`part`
-`name`
-`internal`
-`case-insensitive`
-`group`
-`attribute`
-`value`
-`regex`
-`kval`
-`json`
-`xpath`
-`dsl`
## Artifacts
Each run writes under `<package>/.gofuzz/`:
-`corpus/`: evolving seed corpus used by `go-fuzz`.
-`crashers/`: saved crashing inputs.
-`*-fuzz.zip`: the instrumented build output created by `go-fuzz-build`.
Promote real crashers into ordinary regression tests in the owning package once the underlying issue is fixed.
## GitHub Actions
The repository also has a dedicated GitHub Actions fuzz workflow in `.github/workflows/fuzz.yaml`.
- Triggers: `workflow_dispatch` and a weekly `schedule`.
- Scheduled runs: limited to `projectdiscovery/nuclei`; manual dispatch still works in forks.
- Matrix source: any package that has committed seeds under `testdata/gofuzz-corpus/` and a sibling `fuzz.go` harness.
- Current package matrix: `./pkg/operators/matchers` and `./pkg/operators/extractors`.
- Runtime model: discovery runs `make discover-fuzz-packages`, and each package runs `CI=true make fuzz-ci GOFUZZ_PACKAGE=... FUZZ_DURATION=15m`.
- Artifacts: each matrix job uploads the full `<package>/.gofuzz/` as the artifacts.
- Failure policy: crashers are summarized and uploaded, but they do not fail the workflow; build/setup errors still fail the job.
- Reduce false positives by simulating real-world steps to verify a vulnerability.
- Ultra-fast parallel scan processing and request clustering.
- Integrate into CI/CD pipelines for vulnerability detection and regression testing.
- Supports multiple protocols like TCP, DNS, HTTP, SSL, WHOIS JavaScript, Code and more.
- Supports multiple protocols like TCP, DNS, HTTP, SSL, WHOIS, JavaScript, Code and more.
- Integrate with Jira, Splunk, GitHub, Elastic, GitLab.
<br>
@@ -65,11 +65,11 @@
### **1. Nuclei CLI**
_Install Nuclei on your machine. Get started by following the installation guide [**`here`**](https://docs.projectdiscovery.io/tools/nuclei/install?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme). Additionally, We provide [**`a free cloud tier`**](https://cloud.projectdiscovery.io/sign-up) and comes with a generous monthly free limits:_
_Install Nuclei on your machine. Get started by following the installation guide [**`here`**](https://docs.projectdiscovery.io/tools/nuclei/install?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme). Additionally, we provide [**`a free cloud tier`**](https://cloud.projectdiscovery.io/sign-up) that comes with generous monthly free limits:_
- Store and visualize your vulnerability findings
- Write and manage your nuclei templates
- Access latest nuclei templates
- Write and manage your Nuclei templates
- Access the latest Nuclei templates
- Discover and store your targets
> [!Important]
@@ -85,21 +85,21 @@ _For security teams and enterprises, we provide a cloud-hosted service built on
- Plus: Real-time scanning, SAML SSO, SOC 2 compliant platform (with EU and US hosting options), shared team workspaces, and more
- We're constantly [**`adding new features`**](https://feedback.projectdiscovery.io/changelog)!
- **Ideal for:** Pentesters, security teams, and enterprises
[**`Sign up to Pro`**](https://projectdiscovery.io/pricing?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) or [**`Talk to our team`**](https://projectdiscovery.io/request-demo?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) if you have large organization and complex requirements.
[**`Sign up to Pro`**](https://projectdiscovery.io/pricing?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) or [**`Talk to our team`**](https://projectdiscovery.io/request-demo?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) if you have a large organization and complex requirements.
<br>
<br>
## Documentation
Browse the full Nuclei [**`documentation here`**](https://docs.projectdiscovery.io/tools/nuclei/running). If you’re new to Nuclei, check out our [**`foundational Youtube series`**](https://www.youtube.com/playlist?list=PLZRbR9aMzTTpItEdeNSulo8bYsvil80Rl).
Browse the full Nuclei [**`documentation here`**](https://docs.projectdiscovery.io/tools/nuclei/running). If you’re new to Nuclei, check out our [**`foundational YouTube series`**](https://www.youtube.com/playlist?list=PLZRbR9aMzTTpItEdeNSulo8bYsvil80Rl).
<div align="center">
@@ -111,7 +111,7 @@ Browse the full Nuclei [**`documentation here`**](https://docs.projectdiscovery.
### Installation
`nuclei` requires **go1.23** to install successfully. Run the following command to get the repo:
`nuclei` requires **go >= 1.27.3** to install successfully. Run the following command to get the repo:
```sh
go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest
@@ -141,15 +141,20 @@ Flags:
TARGET:
-u, -target string[] target URLs/hosts to scan
-l, -list string path to file containing a list of target URLs/hosts to scan (one per line)
-targets-inline string inline multiline target list (for use in template profiles)
-eh, -exclude-hosts string[] hosts to exclude to scan from the input list (ip, cidr, hostname)
-resume string resume scan using resume.cfg (clustering will be disabled)
-resume string resume scan from and save to specified file (clustering will be disabled)
-sa, -scan-all-ips scan all the IP's associated with dns record
-iv, -ip-version string[] IP version to scan of hostname (4,6) - (default 4)
-dun, -disable-url-normalization keep targets exactly as supplied instead of collapsing urls that address the same resource
-mup, -max-urls-per-pattern int scan at most this many urls sharing one structural shape, e.g. /user/1 and /user/2 (0 to scan all)
-rlm, -rate-limit-minute int maximum number of requests to send per minute (DEPRECATED)
-bs, -bulk-size int maximum number of hosts to be analyzed in parallel per template (default 25)
-c, -concurrency int maximum number of templates to be executed in parallel (default 25)
@@ -286,6 +308,7 @@ RATE-LIMIT:
-jsc, -js-concurrency int maximum number of javascript runtimes to be executed in parallel (default 120)
-pc, -payload-concurrency int max payload concurrency for each template (default 25)
-prc, -probe-concurrency int http probe concurrency with httpx (default 50)
-tlc, -template-loading-concurrency int maximum number of concurrent template loading operations (default 50)
OPTIMIZATIONS:
-timeout int time to wait in seconds before timeout (default 10)
@@ -300,7 +323,11 @@ OPTIMIZATIONS:
-stream stream mode - start elaborating without sorting the input
-ss, -scan-strategy value strategy to use while scanning(auto/host-spray/template-spray) (default auto)
-irt, -input-read-timeout value timeout on input read (default 3m0s)
-response-cache reuse identical safe GET/HEAD responses within a scan (lossless:skips requests with auth, cookies, body or custom headers)
-nh, -no-httpx disable httpx probing for non-url input
-stp, -strict-probe skip templates whose target service is unreachable:HTTP/headless on hosts httpx could not confirm and network templates on closed ports (lossless, no raw-input fallback)
-tf, -tech-filter opt-in:fingerprint HTTP targets and skip product/macro-tagged templates that cannot match (off by default; enables scan-scoped GET cache; fail-open; no-op if no tech-bound templates)
-preflight-portscan run preflight resolve + TCP portscan and filter targets before scanning (disabled by default)
-no-stdin disable stdin processing
HEADLESS:
@@ -309,6 +336,7 @@ HEADLESS:
-sb, -show-browser show the browser on the screen when running templates with headless mode
-ho, -headless-options string[] start headless chrome with additional options
-sc, -system-chrome use local installed Chrome browser instead of nuclei installed
-cdpe, -cdp-endpoint string use remote browser via Chrome DevTools Protocol (CDP) endpoint
-lha, -list-headless-action list available headless actions
DEBUG:
@@ -317,6 +345,7 @@ DEBUG:
-dresp, -debug-resp show all received responses
-p, -proxy string[] list of http/socks5 proxy to use (comma separated or file input)
-pi, -proxy-internal proxy all internal requests
-rp, -replay-proxy string http/socks5 proxy to re-send requests that produced a finding through (e.g. burp)
-ldf, -list-dsl-function list all supported DSL function signatures
-tlog, -trace-log string file to write sent requests trace log
-elog, -error-log string file to write sent requests error log
@@ -332,10 +361,16 @@ DEBUG:
-hc, -health-check run diagnostic check up
UPDATE:
-up, -update update nuclei engine to the latest released version
-ut, -update-templates update nuclei-templates to latest released version
-ud, -update-template-dir string custom directory to install / update nuclei-templates
Additional documentation is available at:https://docs.nuclei.sh/getting-started/running
Additional documentation is available at:https://docs.projectdiscovery.io/getting-started/running
```
Additional documentation is available at: [**`docs.nuclei.sh/getting-started/running`**](https://docs.nuclei.sh/getting-started/running?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme)
Additional documentation is available at: [**`docs.projectdiscovery.io/getting-started/running`**](https://docs.projectdiscovery.io/getting-started/running?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme)
> This feature is absolutely free and does not require any subscription. For a detailed guide, refer to the [**`documentation`**](https://docs.projectdiscovery.io/cloud/scanning/nuclei-scan?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme).
> This feature is absolutely free and does not require any subscription. For a detailed guide, refer to the [**`documentation`**](https://docs.projectdiscovery.io/cloud/scanning/overview?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme).
<br>
<br>
@@ -651,7 +687,7 @@ Thanks to all the amazing [**`community contributors for sending PRs`**](https:/
<br>
<div align="center">
<sub>**`nuclei`** is distributed under [**MIT License**](https://github.com/projectdiscovery/nuclei/blob/main/LICENSE.md)</sub>
**Nuclei es un escáner de vulnerabilidades moderno y de alto rendimiento que aprovecha plantillas simples basadas en YAML. Te permite diseñar escenarios personalizados de detección de vulnerabilidades que imitan condiciones del mundo real, logrando cero falsos positivos.**
Nuclei se utiliza para enviar peticiones a múltiples objetivos basándose en una plantilla, lo que resulta en cero falsos positivos y proporciona un escaneo rápido en un gran número de hosts. Nuclei ofrece escaneos para una variedad de protocolos, incluyendo TCP, DNS, HTTP, SSL, File, Whois, Websocket, Headless, Code, etc. Con plantillas potentes y flexibles, Nuclei puede utilizarse para modelar todo tipo de comprobaciones de seguridad.
- Formato YAML simple para crear y personalizar plantillas de vulnerabilidades.
- Contribuido por miles de profesionales de seguridad para abordar vulnerabilidades emergentes.
- Reduce los falsos positivos simulando pasos del mundo real para verificar una vulnerabilidad.
- Procesamiento de escaneos paralelo ultrarrápido y agrupación de peticiones.
- Se integra en pipelines de CI/CD para detección de vulnerabilidades y pruebas de regresión.
- Soporta múltiples protocolos como TCP, DNS, HTTP, SSL, WHOIS, JavaScript, Code y más.
- Se integra con Jira, Splunk, GitHub, Elastic, GitLab.
Tenemos un [repositorio dedicado](https://github.com/projectdiscovery/nuclei-templates) que alberga varios tipos de plantillas de vulnerabilidades, contribuidas por **más de 300** investigadores y ingenieros de seguridad.
<br>
<br>
## Cómo funciona
## Índice
- [**`Primeros Pasos`**](#primeros-pasos)
- [_`1. Nuclei CLI`_](#1-nuclei-cli)
- [_`2. Ediciones Pro y Enterprise`_](#2-ediciones-pro-y-enterprise)
- [**`Documentación`**](#documentación)
- [_`Banderas de Línea de Comandos`_](#banderas-de-línea-de-comandos)
- [_`Escaneo de un solo objetivo`_](#escaneo-de-un-solo-objetivo)
- [_`Escaneo de múltiples objetivos`_](#escaneo-de-múltiples-objetivos)
- [_`Escaneo de red`_](#escaneo-de-red)
- [_`Escaneo con tu plantilla personalizada`_](#escaneo-con-tu-plantilla-personalizada)
- [_`Conectar Nuclei a ProjectDiscovery`_](#conectar-nuclei-a-projectdiscovery)
- [**`Plantillas de Nuclei, Comunidad y Recompensas`**](#plantillas-de-nuclei-comunidad-y-recompensas-) 💎
| **Este proyecto está en desarrollo activo**. Es de esperar que se produzcan cambios importantes con las nuevas versiones. Consulte el registro de cambios de la versión antes de actualizar. |
| Este proyecto fue principalmente desarrollado para ser utilizado como una herramienta CLI independiente. **Ejecutar nuclei como un servicio puede suponer riesgos de seguridad.** Se recomienda utilizarlo con precaución y tomar medidas de seguridad adicionales. |
### **1. Nuclei CLI**
# Instalación de Nuclei
_Instala Nuclei en tu máquina. Comienza siguiendo la guía de instalación [**`aquí`**](https://docs.projectdiscovery.io/tools/nuclei/install?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme). Adicionalmente, ofrecemos [**`una capa gratuita en la nube`**](https://cloud.projectdiscovery.io/sign-up) con generosos límites mensuales gratuitos:_
Nuclei requiere **go1.22** para instalarse correctamente. Ejecute el siguiente comando para instalar la última versión -
- Almacena y visualiza tus hallazgos de vulnerabilidades
- Escribe y gestiona tus plantillas de nuclei
- Accede a las últimas plantillas de nuclei
- Descubre y almacena tus objetivos
> [!Important]
> |**Este proyecto está en desarrollo activo**. Espera cambios incompatibles entre versiones. Revisa el changelog antes de actualizar.|
> |:--------------------------------|
> | Este proyecto está construido principalmente para ser utilizado como herramienta CLI independiente. **Ejecutar nuclei como servicio puede suponer riesgos de seguridad.** Se recomienda usarlo con precaución y medidas de seguridad adicionales. |
<br>
### **2. Ediciones Pro y Enterprise**
_Para equipos de seguridad y empresas, ofrecemos un servicio alojado en la nube construido sobre Nuclei OSS, optimizado para ayudarte a ejecutar escaneos de vulnerabilidades de forma continua y a escala con tu equipo y flujos de trabajo existentes:_
- Además: Escaneo en tiempo real, SAML SSO, plataforma compatible con SOC 2 (con opciones de alojamiento en UE y EE.UU.), espacios de trabajo compartidos por equipo y más
- **Ideal para:** Pentesters, equipos de seguridad y empresas
[**`Regístrate en Pro`**](https://projectdiscovery.io/pricing?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) o [**`habla con nuestro equipo`**](https://projectdiscovery.io/request-demo?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) si tienes una organización grande y requisitos complejos.
<br>
<br>
## Documentación
Consulta la [**`documentación completa de Nuclei aquí`**](https://docs.projectdiscovery.io/tools/nuclei/running). Si eres nuevo en Nuclei, mira nuestra [**`serie introductoria en YouTube`**](https://www.youtube.com/playlist?list=PLZRbR9aMzTTpItEdeNSulo8bYsvil80Rl).
`nuclei` requiere **go >= 1.27.3** para instalarse correctamente. Ejecuta el siguiente comando para obtener el repositorio:
```sh
go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest
```
<details>
<summary>Brew</summary>
```sh
brew install nuclei
```
</details>
<details>
<summary>Docker</summary>
```sh
docker pull projectdiscovery/nuclei:latest
```
</details>
Para saber más sobre cómo instalar nuclei, consulta `https://docs.projectdiscovery.io/tools/nuclei/install`.
**Más métodos de instalación [pueden encontrarse aquí](https://docs.projectdiscovery.io/tools/nuclei/install).**
### Banderas de Línea de Comandos
<table>
<tr>
<td>
### Plantillas de Nuclei
Nuclei cuenta con soporte incorporado para la descarga/actualización automática de plantillas desde la versión [v2.5.2](https://github.com/projectdiscovery/nuclei/releases/tag/v2.5.2) en adelante. El proyecto [**Nuclei-Templates**](https://github.com/projectdiscovery/nuclei-templates) proporciona una lista de plantillas listas para usar, aportadas por la comunidad, y que se actualizan constantemente.
También puedes utilizar la bandera `update-templates` para actualizar las plantillas de Nuclei en cualquier momento; puedes escribir tus propias pruebas para tu flujo de trabajo y necesidades individuales siguiendo la [guía de plantillas](https://docs.projectdiscovery.io/templates/) de Nuclei.
La sintaxis de referencia YAML DSL está disponible [aquí](SYNTAX-REFERENCE.md).
</td>
</tr>
</table>
### Uso
Para mostrar todas las banderas de la herramienta:
```sh
nuclei -h
```
Esto mostrará ayuda sobre la herramienta. Aquí están todas las opciones que soporta.
<details>
<summary>Expandir todas las banderas de ayuda</summary>
```console
Nuclei es un escáner de vulnerabilidades rápido y basado en plantillas
que se centra en su amplia configurabilidad, extensibilidad y facilidad de uso.
```yaml
Nuclei is a fast, template based vulnerability scanner focusing
onextensive configurability, massive extensibility and ease of use.
Usage:
./nuclei [flags]
Flags:
TARGET:
-u, -target string[] URLs/hosts a escanear
-l, -list string ruta al archivo que contiene la lista de URLs/hosts a escanear (uno por línea)
-eh, -exclude-hosts string[] hosts a excluir para escanear de la lista de entrada (ip, cidr, hostname)
-resume string reanudar el escaneo usando resume.cfg (la clusterización quedará inhabilitada)
-sa, -scan-all-ips escanear todas las IP asociadas al registro dns
-iv, -ip-version string[] versión IP a escanear del nombre de host (4,6) - (por defecto 4)
-u, -target string[] target URLs/hosts to scan
-l, -list string path to file containing a list of target URLs/hosts to scan (one per line)
-targets-inline string inline multiline target list (for use in template profiles)
-eh, -exclude-hosts string[] hosts to exclude to scan from the input list (ip, cidr, hostname)
-resume string resume scan from and save to specified file (clustering will be disabled)
-sa, -scan-all-ips scan all the IP's associated with dns record
-iv, -ip-version string[] IP version to scan of hostname (4,6) - (default 4)
TARGET-FORMAT:
-im, -input-mode string modo del archivo de entrada (list, burp, jsonl, yaml, openapi, swagger) (por defecto "list")
-ro, -required-only utilizar solo campos requeridos en el formato de entrada al generar peticiones
-sfv, -skip-format-validation saltar la validación de formato (como variables faltantes) al procesar el archivo de entrada
-llm-base-url string openai-compatible endpoint for semantic matching (overrides -llm-provider, e.g. a local model)
-llm-model string model used for semantic matching
-llm-timeout int time in seconds to wait for a single llm call (default 30)
-llm-max-calls int maximum llm calls per scan (0 for unlimited) (default 5000)
-llm-concurrency int maximum concurrent llm calls (default 4)
-llm-cache cache llm responses within a scan (default true)
FILTERING:
-a, -author string[] plantillas a ejecutar basadas en autores (separadas por comas, file)
-tags string[] plantillas a ejecutar basadas en etiquetas (separadas por comas, file)
-etags, -exclude-tags string[] plantillas a excluir basadas en etiquetas (separadas por comas, file)
-itags, -include-tags string[] etiquetas a ejecutar incluso si están excluidas ya sea por defecto o por configuración
-id, -template-id string[] plantillas a ejecutar basadas en IDs de plantilla (comma-separated, file, allow-wildcard)
-eid, -exclude-id string[] plantillas a excluir basadas en IDs de plantilla (separadas por comas, file)
-it, -include-templates string[] ruta al archivo de plantilla o directorio a ejecutar incluso si están excluidas ya sea por defecto o por configuración
-et, -exclude-templates string[] ruta al archivo de plantilla o directorio a excluir (separadas por comas, file)
-em, -exclude-matchers string[] matchers de plantilla a excluir en el resultado
-s, -severity value[] plantillas a ejecutar basadas en criticidad. Valores posibles: info, bajo, medio, alto, crítico, desconocido
-es, -exclude-severity value[] plantillas a excluir basadas en criticidad. Valores posibles: info, bajo, medio, alto, crítico, desconocido
-pt, -type value[] plantillas a ejecutar basadas en tipo de protocolo. Valores posibles: dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-ept, -exclude-type value[] plantillas a excluir basadas en tipo de protocolo. Valores posibles: dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-tc, -template-condition string[] plantillas a ejecutar basadas en condición de expresión
-a, -author string[] templates to run based on authors (comma-separated, file)
-tags string[] templates to run based on tags (comma-separated, file)
-etags, -exclude-tags string[] templates to exclude based on tags (comma-separated, file)
-itags, -include-tags string[] tags to be executed even if they are excluded either by default or configuration
-id, -template-id string[] templates to run based on template ids (comma-separated, file, allow-wildcard)
-eid, -exclude-id string[] templates to exclude based on template ids (comma-separated, file)
-it, -include-templates string[] path to template file or directory to be executed even if they are excluded either by default or configuration
-et, -exclude-templates string[] path to template file or directory to exclude (comma-separated, file)
-em, -exclude-matchers string[] template matchers to exclude in result
-s, -severity value[] templates to run based on severity. Possible values:info, low, medium, high, critical, unknown
-es, -exclude-severity value[] templates to exclude based on severity. Possible values:info, low, medium, high, critical, unknown
-pt, -type value[] templates to run based on protocol type. Possible values:dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-ept, -exclude-type value[] templates to exclude based on protocol type. Possible values:dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-tc, -template-condition string[] templates to run based on expression condition
OUTPUT:
-o, -output string archivo de salida donde guardar las incidencias/vulnerabilidades detectadas
-sresp, -store-resp almacenar todas las peticiones/respuestas enviadas por nuclei en el directorio de salida
-srd, -store-resp-dir string almacenar todas las peticiones/respuestas enviadas por nuclei en un directorio personalizado (por defecto "output")
-silent mostrar resultados únicamente
-nc, -no-color deshabilitar la coloración del contenido de salida (códigos de escape ANSI)
-j, -jsonl escribir la salida en formato JSONL(ines)
-irr, -include-rr -omit-raw incluir pares peticiones/respuesta en las salidas JSON, JSONL y Markdown (sólo para hallazgos) [OBSOLETO usar -omit-raw] (por defecto true)
-or, -omit-raw omitir los pares peticiones/respuesta en las salidas JSON, JSONL y Markdown (sólo para hallazgos)
-ot, -omit-template omitir plantilla codificada en la salida JSON, JSONL
-nm, -no-meta deshabilitar la impresión de metadatos de resultados en la salida cli
-ts, -timestamp habilitar la impresión de la marca de tiempo en la salida cli
-rdb, -report-db string base de datos de informes de nuclei (utilizarla siempre para persistir los datos de los informes)
-ms, -matcher-status mostrar el estado de fallo de coincidencia
-me, -markdown-export string directorio para exportar resultados en formato markdown
-se, -sarif-export string archivo para exportar resultados en formato SARIF
-je, -json-export string archivo para exportar resultados en formato JSON
-jle, -jsonl-export string archivo para exportar resultados en formato JSONL(ines)
-o, -output string output file to write found issues/vulnerabilities
-sresp, -store-resp store all request/response passed through nuclei to output directory
-srd, -store-resp-dir string store all request/response passed through nuclei to custom directory (default "output")
-irr, -include-rr -omit-raw include request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only) [DEPRECATED use -omit-raw] (default true)
-or, -omit-raw omit request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only)
-ot, -omit-template omit encoded template in the JSON, JSONL output
-nm, -no-meta disable printing result metadata in cli output
-ts, -timestamp enables printing timestamp in cli output
-rdb, -report-db string nuclei reporting database (always use this to persist report data)
-ms, -matcher-status display match failure status
-me, -markdown-export string directory to export results in markdown format
-se, -sarif-export string file to export results in SARIF format
-je, -json-export string file to export results in JSON format
-jle, -jsonl-export string file to export results in JSONL(ine) format
-pe, -pdf-export string file to export results in PDF format
-rd, -redact string[] redact given list of keys from query parameter, request header and body
CONFIGURATIONS:
-config string ruta al archivo de configuración de nuclei
-fr, -follow-redirects habilitar el seguimiento de redirecciones para plantillas http
-fhr, -follow-host-redirects seguir redirecciones en el mismo host
-mr, -max-redirects intnúmero máximo de redirecciones a seguir para plantillas http (por defecto 10)
-dr, -disable-redirects deshabilitar redirecciones para plantillas http
-rc, -report-config string archivo de configuración del módulo de informes de nuclei
-H, -header string[] encabezado/cookie personalizado a incluir en todas las peticiones http en formato header:value (cli, file)
-V, -var value variables personalizadas en formato key=value
-r, -resolvers string archivo que contiene lista de resolutores para nuclei
-sr, -system-resolvers utilizar resolución de DNS del sistema como fallback de error
-dc, -disable-clustering deshabilitar la clusterización de peticiones
-passive habilitar el modo de procesamiento pasivo de respuestas HTTP
-fh2, -force-http2 forzar la conexión http2 en las peticiones
-ev, -env-vars habilitar el uso de variables de entorno en la plantilla
-cc, -client-cert string archivo de certificado de cliente (codificado en PEM) utilizado para autenticarse contra los hosts escaneados
-ck, -client-key string archivo de clave de cliente (codificado en PEM) utilizado para autenticarse contra los hosts escaneados
-ca, -client-ca string archivo de autoridad de certificación de cliente (codificado en PEM) utilizado para autenticarse contra los hosts escaneados
-sml, -show-match-line mostrar líneas de coincidencia para plantillas de archivo, funciona solo con extractores
-ztls utilizar la biblioteca ztls con autofallback a estándar para tls13 [Obsoleto] autofallback a ztls está habilitado por defecto
-sni string nombre de host tls sni a usar (por defecto: nombre de dominio de entrada)
-dt, -dialer-timeout value tiempo de espera para peticiones de red
-dka, -dialer-keep-alive value duración de keep-alive para peticiones de red
-lfa, -allow-local-file-access permite el acceso a archivos (carga útil) en cualquier lugar del sistema
-lna, -restrict-local-network-access bloquea conexiones a la red local / privada
-i, -interface string interfaz de red a usar para el escaneo de red
-at, -attack-type string tipo de combinaciones de carga útil a realizar (batteringram, pitchfork, clusterbomb)
-sip, -source-ip string dirección ip de origen a usar para el escaneo de red
-rsr, -response-size-read inttamaño máximo de respuesta a leer en bytes (por defecto 10485760)
-rss, -response-size-save int tamaño máximo de respuesta a guardar en bytes (por defecto 1048576)
-reset reset elimina todos los archivos de configuración y datos de nuclei (incluidas las nuclei-templates)
-ul, -uncover-limit int resultados uncover a devolver (por defecto 100)
-ur, -uncover-ratelimit int sobrescribe el límite de velocidad de los motores con el límite de velocidad del motor uncover (por defecto 60 req/min) (por defecto 60)
-mhe, -max-host-error int errores máximos para un host antes de omitirlo del escaneo (por defecto 30)
-te, -track-error string[] agrega el error dado a la lista de seguimiento de errores máximos por host (standard, file)
-nmhe, -no-mhe deshabilita la omisión del host del escaneo basado en errores
-project utiliza una carpeta de proyecto para evitar enviar la misma petición varias veces
-project-path string establece una ruta de proyecto específica (por defecto "/tmp")
-spm, -stop-at-first-match detiene el procesamiento de las peticiones HTTP después de la primera coincidencia (puede romper la lógica de la plantilla/flujo de trabajo)
-stream modo transmisión - comienza a trabajar sin ordenar la entrada
-ss, -scan-strategy value estrategia a utilizar mientras se escanea (auto/host-spray/template-spray) (por defecto auto)
-irt, -input-read-timeout value tiempo de espera en la lectura de entrada (por defecto 3m0s)
-nh, -no-httpx deshabilita análisis httpx para entradas que no son URL
-no-stdin deshabilita el procesamiento de la entrada estándar
-timeout int time to wait in seconds before timeout (default 10)
-retries int number of times to retry a failed request (default 1)
-mhe, -max-host-error int max errors for a host before skipping from scan (default 30)
-te, -track-error string[] adds given error to max-host-error watchlist (standard, file)
-nmhe, -no-mhe disable skipping host from scan based on errors
-project use a project folder to avoid sending same request multiple times
-project-path string set a specific project path (default "/tmp")
-spm, -stop-at-first-match stop processing HTTP requests after the first match (may break template/workflow logic)
-stream stream mode - start elaborating without sorting the input
-ss, -scan-strategy value strategy to use while scanning(auto/host-spray/template-spray) (default auto)
-irt, -input-read-timeout value timeout on input read (default 3m0s)
-response-cache reuse identical safe GET/HEAD responses within a scan (lossless:skips requests with auth, cookies, body or custom headers)
-nh, -no-httpx disable httpx probing for non-url input
-stp, -strict-probe skip templates whose target service is unreachable:HTTP/headless on hosts httpx could not confirm and network templates on closed ports (lossless, no raw-input fallback)
-tf, -tech-filter opt-in:fingerprint HTTP targets and skip product/macro-tagged templates that cannot match (off by default; enables scan-scoped GET cache; fail-open; no-op if no tech-bound templates)
-preflight-portscan run preflight resolve + TCP portscan and filter targets before scanning (disabled by default)
-no-stdin disable stdin processing
HEADLESS:
-headless habilita las plantillas que requieren soporte de navegadores sin interfaz gráfica (headless browser) (el usuario root en Linux deshabilitará el sandbox)
-page-timeout int segundos para esperar cada página en modo sin interfaz (por defecto 20)
-sb, -show-browser muestra el navegador en la pantalla al ejecutar plantillas con modo sin interfaz
-ho, -headless-options string[] inicia Chrome en modo sin interfaz con opciones adicionales
-sc, -system-chrome utiliza el navegador Chrome instalado localmente en lugar del instalado por nuclei
-lha, -list-headless-action lista de acciones sin interfaz disponibles
-headless enable templates that require headless browser support (root user on Linux will disable sandbox)
-page-timeout int seconds to wait for each page in headless mode (default 20)
-sb, -show-browser show the browser on the screen when running templates with headless mode
-ho, -headless-options string[] start headless chrome with additional options
-sc, -system-chrome use local installed Chrome browser instead of nuclei installed
-cdpe, -cdp-endpoint string use remote browser via Chrome DevTools Protocol (CDP) endpoint
-lha, -list-headless-action list available headless actions
DEBUG:
-debug muestra todas las peticiones y respuestas
-dreq, -debug-req muestra todas las peticiones enviadas
-dresp, -debug-resp muestra todas las respuestas recibidas
-p, -proxy string[] lista de proxies http/socks5 a utilizar (separados por comas o archivo de entrada)
-pi, -proxy-internal proxy para todas las peticiones internas
-ldf, -list-dsl-function lista todas las firmas de función DSL admitidas
-tlog, -trace-log string archivo a escribir el registro de traza de peticiones enviadas
-elog, -error-log string archivo a escribir el registro de error de peticiones enviadas
-version muestra la versión de nuclei
-hm, -hang-monitor habilita la monitorización de bloqueos de nuclei
-v, -verbose muestra salida detallada
-profile-mem string archivo opcional de volcado de memoria de nuclei
-vv muestra las plantillas cargadas para el escaneo
-svd, -show-var-dump muestra el volcado de variables para depuración
-ep, -enable-pprof habilita el servidor de depuración pprof
-tv, -templates-version muestra la versión de las plantillas nuclei (nuclei-templates) instaladas
-hc, -health-check ejecuta comprobación de diagnóstico
-debug show all requests and responses
-dreq, -debug-req show all sent requests
-dresp, -debug-resp show all received responses
-p, -proxy string[] list of http/socks5 proxy to use (comma separated or file input)
-pi, -proxy-internal proxy all internal requests
-ldf, -list-dsl-function list all supported DSL function signatures
-tlog, -trace-log string file to write sent requests trace log
-elog, -error-log string file to write sent requests error log
Consulta https://docs.projectdiscovery.io/tools/nuclei/running para obtener detalles sobre cómo ejecutar Nuclei.
</details>
### Uso de Nuclei desde código Go
### Escaneo de un solo objetivo
La guía completa sobre cómo usar Nuclei como biblioteca/SDK está disponible en [godoc](https://pkg.go.dev/github.com/projectdiscovery/nuclei/v3/lib#section-readme).
Para realizar un escaneo rápido en una aplicación web:
```sh
nuclei -target https://example.com
```
### Escaneo de múltiples objetivos
Nuclei puede manejar escaneos en bloque proporcionando una lista de objetivos. Puedes usar un archivo que contenga múltiples URLs.
```sh
nuclei -list urls.txt
```
### Escaneo de red
Esto escaneará toda la subred en busca de problemas relacionados con la red, como puertos abiertos o servicios mal configurados.
```sh
nuclei -target 192.168.1.0/24
```
### Escaneo con tu plantilla personalizada
Para escribir y usar tu propia plantilla, crea un archivo `.yaml` con reglas específicas y luego úsalo como se muestra a continuación.
Puedes ejecutar los escaneos en tu máquina y subir los resultados a la plataforma cloud para análisis y remediación adicionales.
```sh
nuclei -target https://example.com -dashboard
```
> [!NOTE]
> Esta funcionalidad es totalmente gratuita y no requiere suscripción. Para una guía detallada, consulta la [**`documentación`**](https://docs.projectdiscovery.io/cloud/scanning/nuclei-scan?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme).
<br>
<br>
## Plantillas de Nuclei, Comunidad y Recompensas 💎
Las [**plantillas de Nuclei**](https://github.com/projectdiscovery/nuclei-templates) se basan en el concepto de archivos de plantilla YAML que definen cómo se enviarán y procesarán las peticiones. Esto aporta a nuclei capacidades de extensibilidad sencillas. Las plantillas se escriben en YAML, que especifica un formato simple y legible por humanos para definir rápidamente el proceso de ejecución.
**Pruébalo en línea con nuestro Editor de Plantillas de Nuclei gratuito y con IA** [**`haciendo clic aquí`**](https://cloud.projectdiscovery.io/templates).
Las Plantillas de Nuclei ofrecen una manera simplificada de identificar y comunicar vulnerabilidades, combinando detalles esenciales como clasificaciones de severidad y métodos de detección. Esta herramienta de código abierto desarrollada por la comunidad acelera la respuesta ante amenazas y es ampliamente reconocida en el mundo de la ciberseguridad. Miles de investigadores de seguridad de todo el mundo contribuyen activamente a las plantillas de Nuclei. Mantenemos dos programas para nuestros colaboradores: [**`Pioneers`**](https://projectdiscovery.io/pioneers) y [**`💎 bounties`**](https://github.com/projectdiscovery/nuclei-templates/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22%F0%9F%92%8E%20Bounty%22).
### Recursos
Puedes acceder a la documentación principal de Nuclei en https://docs.projectdiscovery.io/tools/nuclei/, y obtener más información sobre Nuclei en la nube con [ProjectDiscovery Cloud Platform](https://cloud.projectdiscovery.io).
¡Consulta https://docs.projectdiscovery.io/tools/nuclei/resources para obtener más recursos y videos sobre Nuclei!
### Créditos
Gracias a todos los increíbles [contribuyentes de la comunidad que enviaron PRs](https://github.com/projectdiscovery/nuclei/graphs/contributors) y mantienen este proyecto actualizado. :heart:
Si tienes una idea o algún tipo de mejora, eres bienvenido a contribuir y participar en el Proyecto, siéntete libre de enviar tu PR.
<a href="/static/nuclei-templates-teamcity.png" target="_blank"><img src="/static/nuclei-templates-teamcity.png" width="1200px" alt="Ejemplo de plantilla Nuclei para detectar una mala configuración de TeamCity" /></a>
</p>
#### Ejemplos
También echa un vistazo a los siguientes proyectos de código abierto similares que pueden adaptarse a tu flujo de trabajo:
Visita [**nuestra documentación**](https://docs.projectdiscovery.io/templates/introduction) para casos de uso e ideas.
Los escáneres de vulnerabilidades tradicionales fueron construidos hace décadas. Son de código cerrado, increíblemente lentos y dirigidos por proveedores. Los atacantes de hoy explotan masivamente CVEs recién publicadas en internet en cuestión de días, en lugar de los años que solía llevar. Este cambio requiere un enfoque completamente diferente para abordar los exploits emergentes en internet.
Construimos Nuclei para resolver este desafío. Hicimos que todo el framework del motor de escaneo fuera abierto y personalizable, permitiendo que la comunidad global de seguridad colabore y aborde los vectores de ataque y vulnerabilidades emergentes en internet. Nuclei es utilizado actualmente y recibe contribuciones de empresas Fortune 500, agencias gubernamentales y universidades.
Puedes participar contribuyendo a nuestro código, a la [**`biblioteca de plantillas`**](https://github.com/projectdiscovery/nuclei-templates) o [**`uniéndote a nuestro equipo`**](https://projectdiscovery.io/).
<br>
<br>
## Colaboradores :heart:
Gracias a todos los increíbles [**`colaboradores de la comunidad que envían PRs`**](https://github.com/projectdiscovery/nuclei/graphs/contributors) y mantienen este proyecto actualizado. :heart:
**Nuclei یک اسکنر آسیبپذیری مدرن و با کارایی بالاست که از قالبهای ساده بر پایه YAML استفاده میکند. این ابزار به شما امکان میدهد سناریوهای سفارشی برای شناسایی آسیبپذیریها طراحی کنید که شرایط واقعی را شبیهسازی میکنند و منجر به صفر شدن خطاهای مثبت کاذب (گزارشهای اشتباه) میشوند.**
- فرمت ساده YAML برای ساخت و سفارشیسازی قالبهای آسیبپذیری.
- مشارکت توسط هزاران متخصص امنیت جهت مقابله با آسیبپذیریهای نوظهور و رایج.
- کاهش خطاهای مثبت کاذب با شبیهسازی مراحل واقعی جهت تایید یک آسیبپذیری.
- پردازش موازی فوقسریع اسکنها و خوشهبندی درخواستها.
- قابلیت ادغام در خطوط لوله CI/CD برای شناسایی آسیبپذیریها و تستهای رگرسیون.
- پشتیبانی از پروتکلهای متعدد مانند TCP، DNS، HTTP، SSL، WHOIS، جاوااسکریپت، کد و موارد دیگر.
- قابلیت یکپارچهسازی با Jira، Splunk، GitHub، Elastic و GitLab.
<br>
<br>
## فهرست مطالب
- [**`شروع کار`**](#شروع-کار)
- [_`۱. ابزار خط فرمان Nuclei`_](#۱-ابزار-خط-فرمان-nuclei)
- [_`۲. نسخههای حرفهای و سازمانی`_](#۲-نسخههای-حرفهای-و-سازمانی)
- [**`مستندات`**](#مستندات)
- [_`دستورات خط فرمان`_](#دستورات-خط-فرمان)
- [_`اسکن یک هدف واحد`_](#اسکن-یک-هدف)
- [_`اسکن اهداف متعدد`_](#اسکن-چندین-هدف)
- [_`اسکن شبکه`_](#اسکن-شبکه)
- [_`اسکن با قالب سفارشی شما`_](#اسکن-با-استفاده-از-قالب-سفارشی-خودتان)
- [_`اتصال Nuclei به ProjectDiscovery`_](#اتصال-nuclei-به-projectdiscovery)
- [**`قالبهای Nuclei، جامعه کاربری و پاداشها`**](#قالبهای-nuclei-جامعه-و-پاداشها-) 💎
- [**`ماموریت ما`**](#ماموریت-ما)
- [**`مشارکتکنندگان`**](#مشارکتکنندگان-) ❤
- [**`مجوز استفاده`**](#license)
<br>
<br>
## شروع کار
### ۱. ابزار خط فرمان Nuclei
_ابزار Nuclei را روی سیستم خود نصب کنید. کار خود را با دنبال کردن راهنمای نصب در [**`اینجا`**](https://docs.projectdiscovery.io/tools/nuclei/install?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) آغاز کنید. علاوه بر این، ما [**`یک سطح ابری رایگان`**](https://cloud.projectdiscovery.io/sign-up) ارائه میدهیم که همراه با محدودیتهای رایگان ماهانه سخاوتمندانهای عرضه میشود:_
- ذخیرهسازی و بصریسازی یافتههای آسیبپذیری شما
- نوشتن و مدیریت قالبهای Nuclei شما
- دسترسی به آخرین قالبهای Nuclei
- شناسایی و ذخیرهسازی اهداف شما
> [!Important]
> |**این پروژه در حال توسعه فعال است**. انتظار تغییرات اساسی در نسخههای جدید را داشته باشید. لطفاً قبل از بهروزرسانی، لیست تغییرات نسخه (Changelog) را بررسی کنید.|
> |:--------------------------------|
> | این پروژه در درجه اول برای استفاده به عنوان یک ابزار خط فرمان (CLI) مستقل ساخته شده است. **اجرای Nuclei به عنوان یک سرویس ممکن است خطرات امنیتی به همراه داشته باشد.** توصیه میشود با احتیاط و با در نظر گرفتن تدابیر امنیتی اضافی از آن استفاده کنید. |
<br>
### ۲. نسخههای حرفهای و سازمانی
_برای تیمهای امنیتی و سازمانها، ما یک سرویس میزبانیشده در ابر بر پایه نسخه متنباز (OSS) ابزار Nuclei ارائه میدهیم؛ این سرویس بهطور دقیق بهینهسازی شده است تا به شما کمک کند اسکنهای آسیبپذیری را بهصورت مداوم، در مقیاس بزرگ و همراه با تیم و گردشهای کاری فعلی خود اجرا کنید:_
- اتصال به Jira، Slack، Linear، رابطهای برنامهنویسی (APIs) و وبهوکها (Webhooks)
- گزارشدهیهای مدیریتی و سازگاری با استانداردهای امنیتی (Compliance)
- بهعلاوه: اسکن بیدرنگ (Real-time)، پشتیبانی از SAML SSO، پلتفرم منطبق با استاندارد SOC 2 (همراه با گزینههای میزبانی در اتحادیه اروپا و آمریکا)، فضاهای کاری مشترک تیمی و موارد دیگر
- ما بهطور مداوم در حال [**`افزودن قابلیتهای جدید`**](https://feedback.projectdiscovery.io/changelog) هستیم!
- **ایدهآل برای:** نفوذگران قانونمند (Pentesters)، تیمهای امنیتی و سازمانها
در صورتی که سازمان بزرگی دارید و نیازمندیهای شما پیچیده است، میتوانید در [**`نسخه پرو ثبتنام کنید`**](https://projectdiscovery.io/pricing?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) یا [**`با تیم ما گفتگو کنید`**](https://projectdiscovery.io/request-demo?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme).
<br>
<br>
## مستندات
[**`مستندات کامل`**](https://docs.projectdiscovery.io/tools/nuclei/running) ابزار Nuclei را در اینجا مرور کنید. اگر بهتازگی کار با Nuclei را شروع کردهاید، [**`مجموعه ویدیوهای آموزشی پایهای ما در یوتیوب`**](https://www.youtube.com/playlist?list=PLZRbR9aMzTTpItEdeNSulo8bYsvil80Rl) را بررسی کنید.
<div align="center">
<a href="https://www.youtube.com/watch?v=b5qMyQvL1ZA&list=PLZRbR9aMzTTpItEdeNSulo8bYsvil80Rl&utm_source=github&utm_medium=web&utm_campaign=nuclei_readme" target="_blank"><img src="/static/nuclei-getting-started.png" width="350px" alt="Nuclei Getting Started Video Tutorial"></a> <a href="https://www.youtube.com/watch?v=nFXygQdtjyw&utm_source=github&utm_medium=web&utm_campaign=nuclei_readme" target="_blank"><img src="/static/nuclei-write-your-first-template.png" width="350px" alt="Writing Your First Nuclei Template Video Tutorial"></a>
</div>
<br>
### نصب
برای نصب موفقیتآمیز `nuclei` به نسخه **go >= 1.24.2** نیاز است. دستور زیر را برای دریافت مخزن اجرا کنید:
<div dir="ltr">
```sh
go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest
```
</div>
برای اطلاعات بیشتر درباره نحوه نصب nuclei، به آدرس `https://docs.projectdiscovery.io/tools/nuclei/install` مراجعه کنید.
### دستورات خط فرمان
برای نمایش تمامی پارامترها و سوییچهای این ابزار:
<div dir="ltr">
```sh
nuclei -h
```
</div>
<details>
<summary>گسترش تمام فلگهای راهنما</summary>
<div dir="ltr">
```yaml
Nuclei is a fast, template based vulnerability scanner focusing
onextensive configurability, massive extensibility and ease of use.
Usage:
./nuclei [flags]
Flags:
TARGET:
-u, -target string[] target URLs/hosts to scan
-l, -list string path to file containing a list of target URLs/hosts to scan (one per line)
-targets-inline string inline multiline target list (for use in template profiles)
-eh, -exclude-hosts string[] hosts to exclude to scan from the input list (ip, cidr, hostname)
-resume string resume scan from and save to specified file (clustering will be disabled)
-sa, -scan-all-ips scan all the IP's associated with dns record
-iv, -ip-version string[] IP version to scan of hostname (4,6) - (default 4)
-dun, -disable-url-normalization keep targets exactly as supplied instead of collapsing urls that address the same resource
-mup, -max-urls-per-pattern int scan at most this many urls sharing one structural shape, e.g. /user/1 and /user/2 (0 to scan all)
-llm-base-url string openai-compatible endpoint for semantic matching (overrides -llm-provider, e.g. a local model)
-llm-model string model used for semantic matching
-llm-timeout int time in seconds to wait for a single llm call (default 30)
-llm-max-calls int maximum llm calls per scan (0 for unlimited) (default 5000)
-llm-concurrency int maximum concurrent llm calls (default 4)
-llm-cache cache llm responses within a scan (default true)
FILTERING:
-a, -author string[] templates to run based on authors (comma-separated, file)
-tags string[] templates to run based on tags (comma-separated, file)
-etags, -exclude-tags string[] templates to exclude based on tags (comma-separated, file)
-itags, -include-tags string[] tags to be executed even if they are excluded either by default or configuration
-id, -template-id string[] templates to run based on template ids (comma-separated, file, allow-wildcard)
-eid, -exclude-id string[] templates to exclude based on template ids (comma-separated, file)
-it, -include-templates string[] path to template file or directory to be executed even if they are excluded either by default or configuration
-et, -exclude-templates string[] path to template file or directory to exclude (comma-separated, file)
-em, -exclude-matchers string[] template matchers to exclude in result
-s, -severity value[] templates to run based on severity. Possible values:info, low, medium, high, critical, unknown
-es, -exclude-severity value[] templates to exclude based on severity. Possible values:info, low, medium, high, critical, unknown
-pt, -type value[] templates to run based on protocol type. Possible values:dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-ept, -exclude-type value[] templates to exclude based on protocol type. Possible values:dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-tc, -template-condition string[] templates to run based on expression condition
OUTPUT:
-o, -output string output file to write found issues/vulnerabilities
-sresp, -store-resp store all request/response passed through nuclei to output directory
-srd, -store-resp-dir string store all request/response passed through nuclei to custom directory (default "output")
-irr, -include-rr -omit-raw include request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only) [DEPRECATED use -omit-raw] (default true)
-or, -omit-raw omit request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only)
-ot, -omit-template omit encoded template in the JSON, JSONL output
-nm, -no-meta disable printing result metadata in cli output
-ts, -timestamp enables printing timestamp in cli output
-rdb, -report-db string nuclei reporting database (always use this to persist report data)
-ms, -matcher-status display match failure status
-me, -markdown-export string directory to export results in markdown format
-se, -sarif-export string file to export results in SARIF format
-je, -json-export string file to export results in JSON format
-jle, -jsonl-export string file to export results in JSONL(ine) format
-pe, -pdf-export string file to export results in PDF format
-rd, -redact string[] redact given list of keys from query parameter, request header and body
CONFIGURATIONS:
-config string path to the nuclei configuration file
-tp, -profile string template profile config file to run
-tpl, -profile-list list community template profiles
-fr, -follow-redirects enable following redirects for http templates
-fhr, -follow-host-redirects follow redirects on the same host
-mr, -max-redirects int max number of redirects to follow for http templates (default 10)
-dr, -disable-redirects disable redirects for http templates
-mhe, -max-host-error int max errors for a host before skipping from scan (default 30)
-te, -track-error string[] adds given error to max-host-error watchlist (standard, file)
-nmhe, -no-mhe disable skipping host from scan based on errors
-project use a project folder to avoid sending same request multiple times
-project-path string set a specific project path (default "/tmp")
-spm, -stop-at-first-match stop processing HTTP requests after the first match (may break template/workflow logic)
-stream stream mode - start elaborating without sorting the input
-ss, -scan-strategy value strategy to use while scanning(auto/host-spray/template-spray) (default auto)
-irt, -input-read-timeout value timeout on input read (default 3m0s)
-response-cache reuse identical safe GET/HEAD responses within a scan (lossless:skips requests with auth, cookies, body or custom headers)
-nh, -no-httpx disable httpx probing for non-url input
-stp, -strict-probe skip templates whose target service is unreachable:HTTP/headless on hosts httpx could not confirm and network templates on closed ports (lossless, no raw-input fallback)
-tf, -tech-filter opt-in:fingerprint HTTP targets and skip product/macro-tagged templates that cannot match (off by default; enables scan-scoped GET cache; fail-open; no-op if no tech-bound templates)
-preflight-portscan run preflight resolve + TCP portscan and filter targets before scanning (disabled by default)
-no-stdin disable stdin processing
HEADLESS:
-headless enable templates that require headless browser support (root user on Linux will disable sandbox)
-page-timeout int seconds to wait for each page in headless mode (default 20)
-sb, -show-browser show the browser on the screen when running templates with headless mode
-ho, -headless-options string[] start headless chrome with additional options
-sc, -system-chrome use local installed Chrome browser instead of nuclei installed
-cdpe, -cdp-endpoint string use remote browser via Chrome DevTools Protocol (CDP) endpoint
-lha, -list-headless-action list available headless actions
DEBUG:
-debug show all requests and responses
-dreq, -debug-req show all sent requests
-dresp, -debug-resp show all received responses
-p, -proxy string[] list of http/socks5 proxy to use (comma separated or file input)
-pi, -proxy-internal proxy all internal requests
-rp, -replay-proxy string http/socks5 proxy to re-send requests that produced a finding through (e.g. burp)
-ldf, -list-dsl-function list all supported DSL function signatures
-tlog, -trace-log string file to write sent requests trace log
-elog, -error-log string file to write sent requests error log
Additional documentation is available at:https://docs.projectdiscovery.io/getting-started/running
```
</div>
مستندات تکمیلی در این آدرس در دسترس است: [**`docs.projectdiscovery.io/getting-started/running`**](https://docs.projectdiscovery.io/getting-started/running?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme)
</details>
### اسکن یک هدف
برای انجام یک اسکن سریع روی یک وباپلیکیشن:
<div dir="ltr">
```sh
nuclei -target https://example.com
```
</div>
### اسکن چندین هدف
Nuclei میتواند با ارائهٔ فهرستی از اهداف، اسکن گروهی را انجام دهد. میتوانید از فایلی استفاده کنید که شامل چندین URL است.
<div dir="ltr">
```sh
nuclei -list urls.txt
```
</div>
### اسکن شبکه
این کار کل زیرشبکه را برای مشکلات مرتبط با شبکه، مانند پورتهای باز یا سرویسهای پیکربندی نادرست، اسکن میکند.
<div dir="ltr">
```sh
nuclei -target 192.168.1.0/24
```
</div>
### اسکن با استفاده از قالب سفارشی خودتان
برای نوشتن و استفاده از قالب خودتان، یک فایل `.yaml` با قوانین مشخص ایجاد کنید، سپس آن را بهصورت زیر استفاده کنید.
میتوانید اسکنها را روی دستگاه خود اجرا کرده و نتایج را برای تحلیل و رفع مشکلات بیشتر، در پلتفرم ابری بارگذاری کنید.
<div dir="ltr">
```sh
nuclei -target https://example.com -dashboard
```
</div>
> [!NOTE]
> این قابلیت کاملاً رایگان است و به هیچگونه اشتراکی نیاز ندارد. برای راهنمایی دقیقتر، به [**`مستندات`**](https://docs.projectdiscovery.io/cloud/scanning/overview?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) مراجعه کنید.
<br>
<br>
## قالبهای Nuclei، جامعه و پاداشها 💎
[**قالبهای Nuclei**](https://github.com/projectdiscovery/nuclei-templates) بر اساس مفهوم فایلهای قالب مبتنی بر YAML طراحی شدهاند که نحوه ارسال و پردازش درخواستها را تعریف میکنند. این موضوع امکان توسعهپذیری آسان Nuclei را فراهم میکند. قالبها با استفاده از YAML نوشته میشوند که قالبی ساده و قابلخواندن برای انسان ارائه میدهد تا بتوان فرآیند اجرا را بهسرعت تعریف کرد.
**همین حالا بهصورت آنلاین با ویرایشگر رایگان قالبهای Nuclei مجهز به هوش مصنوعی ما امتحان کنید؛** [**`اینجا کلیک کنید`**](https://cloud.projectdiscovery.io/templates).
قالبهای Nuclei روشی ساده و یکپارچه برای شناسایی و گزارش آسیبپذیریها ارائه میدهند و جزئیات ضروری مانند سطح شدت و روشهای شناسایی را در بر میگیرند. این ابزار متنباز که توسط جامعه توسعه داده میشود، واکنش به تهدیدات را سرعت میبخشد و در دنیای امنیت سایبری بهطور گسترده شناخته شده است. قالبهای Nuclei بهطور فعال توسط هزاران پژوهشگر امنیتی در سراسر جهان توسعه داده میشوند. ما دو برنامه برای مشارکتکنندگان خود داریم: [**`Pioneers`**](https://projectdiscovery.io/pioneers) و [**`💎 پاداشها`**](https://github.com/projectdiscovery/nuclei-templates/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22%F0%9F%92%8E%20Bounty%22).
اسکنرهای سنتی آسیبپذیری دههها پیش ساخته شدهاند. آنها متنبسته، فوقالعاده کند و وابسته به فروشندگان هستند. مهاجمان امروزی، برخلاف گذشته که بهرهبرداری از آسیبپذیریها سالها طول میکشید، ظرف چند روز پس از انتشار CVEهای جدید، آنها را در سراسر اینترنت بهصورت گسترده مورد سوءاستفاده قرار میدهند. این تغییر، نیازمند رویکردی کاملاً متفاوت برای مقابله با اکسپلویتهای پرطرفدار در اینترنت است.
ما Nuclei را برای حل این چالش ساختیم. ما کل چارچوب موتور اسکن را متنباز و قابل سفارشیسازی کردیم تا جامعه امنیتی جهانی بتواند با یکدیگر همکاری کرده و با بردارهای حمله و آسیبپذیریهای پرطرفدار در اینترنت مقابله کند. امروزه Nuclei توسط شرکتهای Fortune 500، سازمانهای دولتی و دانشگاهها استفاده و توسعه داده میشود.
شما نیز میتوانید با مشارکت در کد ما، [**`کتابخانه قالبها`**](https://github.com/projectdiscovery/nuclei-templates)، یا [**`پیوستن به تیم ما`**](https://projectdiscovery.io/) مشارکت کنید.
<br>
<br>
## مشارکتکنندگان :heart:
از تمام مشارکتکنندگان فوقالعاده [**`جامعه که با ارسال PRها`**](https://github.com/projectdiscovery/nuclei/graphs/contributors) و بهروز نگهداشتن این پروژه از آن حمایت میکنند، سپاسگزاریم. :heart:
**Nuclei adalah pemindai kerentanan modern berkinerja tinggi yang memanfaatkan template berbasis YAML sederhana. Nuclei memungkinkan Anda merancang skenario deteksi kerentanan khusus yang meniru kondisi dunia nyata, sehingga menghasilkan nol false positive.**
Nuclei digunakan untuk mengirim permintaan lintas target berdasarkan templat, yang menghasilkan nol positif palsu dan menyediakan pemindaian yang cepat pada banyak host. Nuclei menawarkan pemindaian untuk berbagai protokol, termasuk TCP, DNS, HTTP, SSL, File, Whois, Websocket, Headless, dll. Dengan templating yang kuat dan fleksibel, Nuclei dapat digunakan untuk memodelkan semua jenis pemeriksaan keamanan.
- Format YAML sederhana untuk membuat dan menyesuaikan template kerentanan.
- Dikontribusikan oleh ribuan profesional keamanan untuk menangani kerentanan terkini.
- Mengurangi false positive dengan mensimulasikan langkah-langkah dunia nyata untuk memverifikasi kerentanan.
- Pemrosesan pemindaian paralel super cepat dan clustering permintaan.
- Terintegrasi ke dalam pipeline CI/CD untuk deteksi kerentanan dan pengujian regresi.
- Mendukung beragam protokol seperti TCP, DNS, HTTP, SSL, WHOIS, JavaScript, Code, dan lainnya.
- Terintegrasi dengan Jira, Splunk, GitHub, Elastic, GitLab.
Kami memiliki [repositori khusus](https://github.com/projectdiscovery/nuclei-templates) yang menampung berbagai jenis templat kerentanan yang disumbangkan oleh **lebih dari 300** peneliti dan teknisi keamanan.
<br>
<br>
## Daftar Isi
## Cara Kerja
- [**`Memulai`**](#memulai)
- [_`1. Nuclei CLI`_](#1-nuclei-cli)
- [_`2. Edisi Pro dan Enterprise`_](#2-edisi-pro-dan-enterprise)
_Instal Nuclei pada mesin Anda. Mulai dengan mengikuti panduan instalasi [**`di sini`**](https://docs.projectdiscovery.io/tools/nuclei/install?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme). Selain itu, kami menyediakan [**`tier cloud gratis`**](https://cloud.projectdiscovery.io/sign-up) yang dilengkapi batas bulanan gratis yang melimpah:_
Nuclei membutuhkan **go1.22** agar dapat diinstall. Jalankan perintah berikut untuk menginstal versi terbaru -
- Simpan dan visualisasikan temuan kerentanan Anda
- Tulis dan kelola template nuclei Anda
- Akses template nuclei terbaru
- Temukan dan simpan target Anda
> [!Important]
> |**Proyek ini sedang dalam pengembangan aktif**. Mengharapkan perubahan yang tidak kompatibel pada setiap rilis. Tinjau changelog rilis sebelum memperbarui.|
> |:--------------------------------|
> | Proyek ini terutama dibangun untuk digunakan sebagai alat CLI mandiri. **Menjalankan nuclei sebagai layanan dapat menimbulkan risiko keamanan.** Disarankan untuk menggunakannya dengan hati-hati dan langkah-langkah keamanan tambahan. |
<br>
### **2. Edisi Pro dan Enterprise**
_Untuk tim keamanan dan perusahaan, kami menyediakan layanan yang di-hosting di cloud yang dibangun di atas Nuclei OSS, disetel untuk membantu Anda menjalankan pemindaian kerentanan secara berkesinambungan dan dalam skala besar dengan tim dan alur kerja Anda yang sudah ada:_
- Pemindaian 50x lebih cepat
- Pemindaian berskala besar dengan akurasi tinggi
- Integrasi dengan layanan cloud (AWS, GCP, Azure, Cloudflare, Fastly, Terraform, Kubernetes)
- Jira, Slack, Linear, API, dan Webhook
- Pelaporan eksekutif dan kepatuhan
- Plus: Pemindaian real-time, SAML SSO, platform yang patuh SOC 2 (dengan opsi hosting UE dan AS), workspace tim bersama, dan lainnya
- Kami terus [**`menambahkan fitur baru`**](https://feedback.projectdiscovery.io/changelog)!
- **Ideal untuk:** Pentester, tim keamanan, dan perusahaan
[**`Daftar ke Pro`**](https://projectdiscovery.io/pricing?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) atau [**`bicara dengan tim kami`**](https://projectdiscovery.io/request-demo?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) jika Anda memiliki organisasi besar dan kebutuhan yang kompleks.
<br>
<br>
## Dokumentasi
Telusuri [**`dokumentasi Nuclei lengkap di sini`**](https://docs.projectdiscovery.io/tools/nuclei/running). Jika Anda baru mengenal Nuclei, lihat [**`seri pengantar YouTube kami`**](https://www.youtube.com/playlist?list=PLZRbR9aMzTTpItEdeNSulo8bYsvil80Rl).
`nuclei` memerlukan **go >= 1.27.3** agar dapat diinstal dengan sukses. Jalankan perintah berikut untuk mengambil repo:
```sh
go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest
```
**Metode [instalasi lain dapat ditemukan di sini](https://nuclei.projectdiscovery.io/nuclei/get-started/).**
Untuk informasi lebih lanjut tentang menginstal nuclei, lihat `https://docs.projectdiscovery.io/tools/nuclei/install`.
<table>
<tr>
<td>
### Flag Baris Perintah
### Nuclei Templates
Nuclei memiliki dukungan untuk unduhan/pembaruan templat otomatis sebagai bawaan sejak versi [v2.5.2](https://github.com/projectdiscovery/nuclei/releases/tag/v2.5.2). Proyek [**Nuclei-Templates**](https://github.com/projectdiscovery/nuclei-templates) menyediakan daftar template siap pakai yang dibuat oleh komunitas yang terus diperbarui.
Anda dapat menggunakan flag `-update-templates` untuk memperbarui templat inti kapan saja; Anda juga dapat menulis pemeriksaan Anda sendiri untuk alur kerja individu dan untuk kebutuhan Anda sendiri dengan mengikuti [panduan pembuatan templat Nuclei](https://nuclei.projectdiscovery.io/templating-guide/).
Untuk referensi penulisan sintaks DSL berbasis YAML tersedia [di sini](SYNTAX-REFERENCE.md).
</td>
</tr>
</table>
### Cara Pakai
Untuk menampilkan seluruh flag dari alat ini:
```sh
nuclei -h
```
Ini akan menampilkan bantuan untuk alat tersebut. Berikut adalah semua flag yang didukungnya.
<details>
<summary>Buka semua flag bantuan</summary>
```console
```yaml
Nuclei is a fast, template based vulnerability scanner focusing
onextensive configurability, massive extensibility and ease of use.
@@ -96,11 +139,20 @@ Usage:
Flags:
TARGET:
-u, -target string[] target URLs/hosts to scan
-l, -list string path to file containing a list of target URLs/hosts to scan (one per line)
-resume string resume scan using resume.cfg (clustering will be disabled)
-sa, -scan-all-ips scan all the IP's associated with dns record
-iv, -ip-version string[] IP version to scan of hostname (4,6) - (default 4)
-u, -target string[] target URLs/hosts to scan
-l, -list string path to file containing a list of target URLs/hosts to scan (one per line)
-targets-inline string inline multiline target list (for use in template profiles)
-eh, -exclude-hosts string[] hosts to exclude to scan from the input list (ip, cidr, hostname)
-resume string resume scan from and save to specified file (clustering will be disabled)
-sa, -scan-all-ips scan all the IP's associated with dns record
-iv, -ip-version string[] IP version to scan of hostname (4,6) - (default 4)
-llm-base-url string openai-compatible endpoint for semantic matching (overrides -llm-provider, e.g. a local model)
-llm-model string model used for semantic matching
-llm-timeout int time in seconds to wait for a single llm call (default 30)
-llm-max-calls int maximum llm calls per scan (0 for unlimited) (default 5000)
-llm-concurrency int maximum concurrent llm calls (default 4)
-llm-cache cache llm responses within a scan (default true)
FILTERING:
-a, -author string[] templates to run based on authors (comma-separated, file)
-tags string[] templates to run based on tags (comma-separated, file)
-etags, -exclude-tags string[] templates to exclude based on tags (comma-separated, file)
-itags, -include-tags string[] tags to be executed even if they are excluded either by default or configuration
-id, -template-id string[] templates to run based on template ids (comma-separated, file)
-id, -template-id string[] templates to run based on template ids (comma-separated, file, allow-wildcard)
-eid, -exclude-id string[] templates to exclude based on template ids (comma-separated, file)
-it, -include-templates string[] templates to be executed even if they are excluded either by default or configuration
-et, -exclude-templates string[] template or template directory to exclude (comma-separated, file)
-it, -include-templates string[] path to template file or directory to be executed even if they are excluded either by default or configuration
-et, -exclude-templates string[] path to template file or directory to exclude (comma-separated, file)
-em, -exclude-matchers string[] template matchers to exclude in result
-s, -severity value[] templates to run based on severity. Possible values:info, low, medium, high, critical, unknown
-es, -exclude-severity value[] templates to exclude based on severity. Possible values:info, low, medium, high, critical, unknown
-pt, -type value[] templates to run based on protocol type. Possible values: dns, file, http, headless, tcp, workflow, ssl, websocket, whois
-ept, -exclude-type value[] templates to exclude based on protocol type. Possible values: dns, file, http, headless, tcp, workflow, ssl, websocket, whois
-pt, -type value[] templates to run based on protocol type. Possible values:dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-ept, -exclude-type value[] templates to exclude based on protocol type. Possible values:dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-tc, -template-condition string[] templates to run based on expression condition
-irr, -include-rr include request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only) [DEPRECATED use -omit-raw] (default true)
-irr, -include-rr -omit-raw include request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only) [DEPRECATED use -omit-raw] (default true)
-or, -omit-raw omit request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only)
-ot, -omit-template omit encoded template in the JSON, JSONL output
-nm, -no-meta disable printing result metadata in cli output
-ts, -timestamp enables printing timestamp in cli output
-rdb, -report-db string nuclei reporting database (always use this to persist report data)
@@ -150,9 +217,13 @@ OUTPUT:
-se, -sarif-export string file to export results in SARIF format
-je, -json-export string file to export results in JSON format
-jle, -jsonl-export string file to export results in JSONL(ine) format
-pe, -pdf-export string file to export results in PDF format
-rd, -redact string[] redact given list of keys from query parameter, request header and body
CONFIGURATIONS:
-config string path to the nuclei configuration file
-tp, -profile string template profile config file to run
-tpl, -profile-list list community template profiles
-fr, -follow-redirects enable following redirects for http templates
-fhr, -follow-host-redirects follow redirects on the same host
-mr, -max-redirects int max number of redirects to follow for http templates (default 10)
@@ -172,16 +243,18 @@ CONFIGURATIONS:
-sml, -show-match-line show match lines for file templates, works with extractors only
-ztls use ztls library with autofallback to standard one for tls13 [Deprecated] autofallback to ztls is enabled by default
-sni string tls sni hostname to use (default:input domain name)
-lfa, -allow-local-file-access allows file (payload) access anywhere on the system
-dka, -dialer-keep-alive value keep-alive duration for network requests.
-lfa, -allow-local-file-access allow all templates in the run to read any file on the system (not just payloads)
-lna, -restrict-local-network-access blocks connections to the local / private network
-i, -interface string network interface to use for network scan
-at, -attack-type string type of payload combinations to perform (batteringram,pitchfork,clusterbomb)
-sip, -source-ip string source ip address to use for network scan
-config-directory string override the default config path ($home/.config)
-rsr, -response-size-read int max response size to read in bytes (default 10485760)
-rsr, -response-size-read int max response size to read in bytes
-rss, -response-size-save int max response size to read in bytes (default 1048576)
-rqss, -request-size-save int max request body size to save in bytes (0 to save the whole body) (default 32768)
-reset reset removes all nuclei configuration and data files (including nuclei-templates)
-mhe, -max-host-error int max errors for a host before skipping from scan (default 30)
-te, -track-error string[] adds given error to max-host-error watchlist (standard, file)
-nmhe, -no-mhe disable skipping host from scan based on errors
-project use a project folder to avoid sending same request multiple times
-project-path string set a specific project path (default "/tmp")
-spm, -stop-at-first-match stop processing HTTP requests after the first match (may break template/workflow logic)
-stream stream mode - start elaborating without sorting the input
-ss, -scan-strategy value strategy to use while scanning(auto/host-spray/template-spray) (default auto)
-irt, -input-read-timeout value timeout on input read (default 3m0s)
-response-cache reuse identical safe GET/HEAD responses within a scan (lossless:skips requests with auth, cookies, body or custom headers)
-nh, -no-httpx disable httpx probing for non-url input
-stp, -strict-probe skip templates whose target service is unreachable:HTTP/headless on hosts httpx could not confirm and network templates on closed ports (lossless, no raw-input fallback)
-tf, -tech-filter opt-in:fingerprint HTTP targets and skip product/macro-tagged templates that cannot match (off by default; enables scan-scoped GET cache; fail-open; no-op if no tech-bound templates)
-preflight-portscan run preflight resolve + TCP portscan and filter targets before scanning (disabled by default)
-no-stdin disable stdin processing
HEADLESS:
-headless enable templates that require headless browser support (root user on Linux will disable sandbox)
-page-timeout int seconds to wait for each page in headless mode (default 20)
-sb, -show-browser show the browser on the screen when running templates with headless mode
-sc, -system-chrome use local installed Chrome browser instead of nuclei installed
-lha, -list-headless-action list available headless actions
-headless enable templates that require headless browser support (root user on Linux will disable sandbox)
-page-timeout int seconds to wait for each page in headless mode (default 20)
-sb, -show-browser show the browser on the screen when running templates with headless mode
-ho, -headless-options string[] start headless chrome with additional options
-sc, -system-chrome use local installed Chrome browser instead of nuclei installed
-cdpe, -cdp-endpoint string use remote browser via Chrome DevTools Protocol (CDP) endpoint
-lha, -list-headless-action list available headless actions
DEBUG:
-debug show all requests and responses
-dreq, -debug-req show all sent requests
-dresp, -debug-resp show all received responses
-p, -proxy string[] list of http/socks5 proxy to use (comma separated or file input)
-pi, -proxy-internal proxy all internal requests
-ldf, -list-dsl-function list all supported DSL function signatures
-tlog, -trace-log string file to write sent requests trace log
-elog, -error-log string file to write sent requests error log
Additional documentation is available at: https://docs.nuclei.sh/getting-started/running
Additional documentation is available at:https://docs.projectdiscovery.io/getting-started/running
```
### Menjalankan Nuclei
Dokumentasi tambahan tersedia di: [**`docs.projectdiscovery.io/getting-started/running`**](https://docs.projectdiscovery.io/getting-started/running?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme)
Memindai domain target dengan templat Nuclei yang [dikurasi oleh komunitas](https://github.com/projectdiscovery/nuclei-templates).
</details>
### Pemindaian target tunggal
Untuk melakukan pemindaian cepat pada aplikasi web:
```sh
nuclei -u https://example.com
nuclei -target https://example.com
```
Memindai URL target dengan templat Nuclei yang [dikurasi oleh komunitas](https://github.com/projectdiscovery/nuclei-templates).
### Pemindaian beberapa target
Nuclei dapat menangani pemindaian massal dengan menyediakan daftar target. Anda dapat menggunakan file yang berisi banyak URL.
```sh
nuclei -list urls.txt
```
Contoh dari berkas `urls.txt`:
### Pemindaian jaringan
```yaml
http://example.com
http://app.example.com
http://test.example.com
http://uat.example.com
Ini akan memindai seluruh subnet untuk masalah terkait jaringan, seperti port terbuka atau layanan yang dikonfigurasi keliru.
```sh
nuclei -target 192.168.1.0/24
```
**Contoh lebih detil tentang menjalankan Nuclei dapat ditemukan [di sini](https://nuclei.projectdiscovery.io/nuclei/get-started/#running-nuclei).**
### Pemindaian dengan template kustom Anda
# Untuk Teknisi Keamanan
Untuk menulis dan menggunakan template Anda sendiri, buat file `.yaml` dengan aturan-aturan spesifik, lalu gunakan seperti berikut.
Nuclei menawarkan sejumlah besar fitur yang berguna bagi teknisi keamanan untuk menyesuaikan alur kerja di organisasi mereka. Dengan berbagai kemampuan pemindaian (seperti misalnya DNS, HTTP, TCP), teknisi keamanan dapat dengan mudah membuat rangkaian pemeriksaan khusus mereka dengan Nuclei.
- Berbagai protokol yang didukung: TCP, DNS, HTTP, File, dll
- Mencapai langkah-langkah kerentanan yang kompleks dengan alur kerja dan [permintaan dinamis](https://blog.projectdiscovery.io/nuclei-unleashed-quickly-write-complex-exploits/).
- Mudah diintegrasikan ke dalam CI/CD, dirancang agar mudah diintegrasikan ke dalam siklus regresi untuk secara aktif memeriksa perbaikan dan kemunculan kerentanan kembali.
Anda dapat menjalankan pemindaian di mesin Anda dan mengunggah hasilnya ke platform cloud untuk analisis lebih lanjut dan perbaikan.
<table>
<tr>
<td>
```sh
nuclei -target https://example.com -dashboard
```
**Untuk Pemburu Celah Berhadiah:**
> [!NOTE]
> Fitur ini sepenuhnya gratis dan tidak memerlukan langganan. Untuk panduan rinci, lihat [**`dokumentasi`**](https://docs.projectdiscovery.io/cloud/scanning/nuclei-scan?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme).
Nuclei memungkinkan Anda untuk menyesuaikan pendekatan pengujian Anda dengan rangkaian pemeriksaan Anda sendiri dan dengan mudah menjalankan program celah berhadiah Anda. Selain itu, Nuclei dapat dengan mudah diintegrasikan ke dalam alur kerja pemindaian berkelanjutan.
<br>
<br>
- Dirancang agar mudah diintegrasikan ke dalam alur kerja alat lainnya.
- Dapat memproses ribuan host hanya dalam beberapa menit.
- Mudah mengotomatiskan pendekatan pengujian khusus Anda dengan sintaks DSL berbasis YAML sederhana kami.
## Template Nuclei, Komunitas dan Hadiah 💎
[**Template Nuclei**](https://github.com/projectdiscovery/nuclei-templates) didasarkan pada konsep file template berbasis YAML yang mendefinisikan bagaimana permintaan dikirim dan diproses. Ini memberikan kemampuan ekstensibilitas yang mudah pada nuclei. Template ditulis dalam YAML yang menentukan format yang sederhana dan mudah dibaca manusia untuk dengan cepat mendefinisikan proses eksekusi.
Silakan periksa proyek sumber terbuka kami yang lain yang mungkin cocok dengan alur kerja celah berhadiah Anda: [github.com/projectdiscovery](http://github.com/projectdiscovery), kami juga menyediakan [penyegaran data DNS di Chaos setiap hari](http://chaos.projectdiscovery.io).
**Coba secara online dengan Editor Template Nuclei berbasis AI kami yang gratis dengan** [**`mengklik di sini`**](https://cloud.projectdiscovery.io/templates).
</td>
</tr>
</table>
Template Nuclei menawarkan cara yang efisien untuk mengidentifikasi dan mengomunikasikan kerentanan, menggabungkan detail penting seperti rating keparahan dan metode deteksi. Alat sumber terbuka yang dikembangkan oleh komunitas ini mempercepat respon ancaman dan diakui secara luas di dunia siber keamanan. Template Nuclei secara aktif dikontribusikan oleh ribuan peneliti keamanan di seluruh dunia. Kami menjalankan dua program untuk para kontributor: [**`Pioneers`**](https://projectdiscovery.io/pioneers) dan [**`💎 bounties`**](https://github.com/projectdiscovery/nuclei-templates/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22%F0%9F%92%8E%20Bounty%22).
Pemindai kerentanan tradisional dibangun puluhan tahun yang lalu. Mereka tertutup, sangat lambat, dan digerakkan oleh vendor. Penyerang masa kini secara massal mengeksploitasi CVE yang baru dirilis di seluruh internet dalam hitungan hari, berbeda dengan tahun-tahun yang dibutuhkan sebelumnya. Pergeseran ini membutuhkan pendekatan yang sangat berbeda untuk menangani eksploit yang sedang tren di internet.
Kami membangun Nuclei untuk menyelesaikan tantangan ini. Kami menjadikan seluruh framework mesin pemindai sebagai sumber terbuka dan dapat disesuaikan — memungkinkan komunitas keamanan global untuk berkolaborasi dan menangani vektor serangan dan kerentanan yang sedang tren di internet. Nuclei kini digunakan dan dikontribusikan oleh perusahaan Fortune 500, lembaga pemerintah, dan universitas.
Anda dapat berpartisipasi dengan berkontribusi pada kode kami, [**`library template`**](https://github.com/projectdiscovery/nuclei-templates), atau [**`bergabung dengan tim kami`**](https://projectdiscovery.io/).
<br>
<br>
## Kontributor :heart:
Terima kasih kepada semua [**`kontributor komunitas yang luar biasa yang telah mengirimkan PR`**](https://github.com/projectdiscovery/nuclei/graphs/contributors) dan terus memperbarui proyek ini. :heart:
<sub>**`nuclei`** didistribusikan di bawah [**Lisensi MIT**](https://github.com/projectdiscovery/nuclei/blob/main/LICENSE.md)</sub>
Nuclei sangat meningkatkan cara Anda mendekati penilaian keamanan dengan menambah proses manual yang berulang. Para konsultan sudah mengonversi langkah penilaian manual mereka dengan Nuclei, ini memungkinkan mereka untuk menjalankan serangkaian pendekatan penilaian khusus mereka di ribuan host secara otomatis.
Para penguji penetrasi mendapatkan kekuatan penuh dari templat publik dan kemampuan penyesuaian kami untuk mempercepat proses penilaian mereka, dan khususnya dengan siklus regresi di mana Anda dapat dengan mudah memverifikasi perbaikannya.
- Mudah untuk membuat daftar pemeriksa kepatuhan Anda, sederet standar (mis., OWASP 10 Teratas).
- Dengan kemampuan seperti [fuzz](https://nuclei.projectdiscovery.io/templating-guide/protocols/http-fuzzing/) dan [alur kerja](https://nuclei.projectdiscovery.io/templating-guide/workflows/), langkah manual yang rumit dan penilaian berulang dapat dengan mudah diotomatisasi dengan Nuclei.
- Mudah untuk menguji ulang perbaikan kerentanan hanya dengan menjalankan ulang template.
</td>
</tr>
</table>
# Untuk Pengembang dan Organisasi
Nuclei dibangun dengan kesederhanaan dalam pemikiran, dengan templat yang didukung komunitas oleh ratusan peneliti keamanan, memungkinkan Anda untuk tidak tertinggal dengan ancaman keamanan terbaru menggunakan pemindaian Nuclei terus menerus pada host. Ini dirancang agar mudah diintegrasikan ke dalam siklus pengujian regresi, untuk memverifikasi perbaikan dan menghilangkan kerentanan agar tidak terjadi di masa mendatang.
- **CI/CD:** Pengembang sudah memanfaatkan Nuclei dalam aliran CI/CD mereka, ini memungkinkan mereka untuk terus memantau lingkungan pementasan dan produksi mereka dengan templat yang disesuaikan.
- **Siklus Regresi Berkelanjutan:** Dengan Nuclei, Anda dapat membuat templat khusus pada setiap kerentanan baru yang teridentifikasi dan dimasukkan ke dalam mesin Nuclei untuk dihilangkan dalam siklus regresi berkelanjutan.
Kami memiliki [utas diskusi tentang ini](https://github.com/projectdiscovery/nuclei-templates/discussions/693), sudah ada beberapa program celah berhadiah yang memberikan insentif kepada peretas untuk menulis templat inti dengan setiap pengiriman, yang membantu mereka untuk menghilangkan kerentanan di semua aset mereka, serta untuk menghilangkan risiko masa depan yang muncul kembali pada lingkungan produksi. Jika Anda tertarik untuk menerapkannya di organisasi Anda, jangan ragu untuk [menghubungi kami](mailto:[email protected]). Kami akan dengan senang hati membantu Anda dalam proses memulai, atau Anda juga dapat memposting ke [utas diskusi](https://github.com/projectdiscovery/nuclei-templates/discussions/693) untuk bantuan apapun.
<h3 align="center">
<img src="static/regression-with-nuclei.jpg" alt="Siklus Regresi Berkelanjutan dengan Nuclei" width="1100px"></a>
- [Menemukan bug dengan menggunakan Nuclei dengan PinkDraconian (Robbe Van Roey)](https://www.youtube.com/watch?v=ewP0xVPW-Pk) oleh **[@PinkDraconian](https://twitter.com/PinkDraconian)**
- [Nuclei: Mengemas Pukulan dengan Pemindaian Kerentanan](https://bishopfox.com/blog/nuclei-vulnerability-scan) oleh **Bishopfox**
- [Kerangka kemanjuran WAF](https://www.fastly.com/blog/the-waf-efficacy-framework-measuring-the-effectiveness-of-your-waf) oleh **Fastly**
- [Memindai Aplikasi Web Langsung dengan Nuclei di Aliran CI/CD](https://blog.escape.tech/devsecops-part-iii-scanning-live-web-applications/) oleh **[@TristanKalos](https://twitter.com/TristanKalos)**
- [Pemindaian Bertenaga Komunitas dengan Nuclei](https://blog.projectdiscovery.io/community-powered-scanning-with-nuclei/)
- [Nuclei Unleashed - Menulis eksploitasi kompleks dengan cepat](https://blog.projectdiscovery.io/nuclei-unleashed-quickly-write-complex-exploits/)
- [Nuclei - Fuzz semua hal](https://blog.projectdiscovery.io/nuclei-fuzz-all-the-things/)
- [Integrasi Nuclei + Interactsh untuk Mengotomatiskan Pengujian OOB](https://blog.projectdiscovery.io/nuclei-interactsh-integration/)
- [Mempersenjatai Alur Kerja Nuclei untuk Menghancurkan Semua Hal](https://medium.com/@dwisiswant0/weaponizes-nuclei-workflows-to-pwn-all-the-things-cd01223feb77) oleh **[@dwisiswant0](https://github.com/dwisiswant0)**
- [Bagaimana Memindai Terus-menerus dengan Nuclei?](https://medium.com/@dwisiswant0/how-to-scan-continuously-with-nuclei-fcb7e9d8b8b9) oleh **[@dwisiswant0](https://github.com/dwisiswant0)**
- [Retas dengan Otomatisasi !!!](https://dhiyaneshgeek.github.io/web/security/2021/07/19/hack-with-automation/) oleh **[@DhiyaneshGeek](https://github.com/DhiyaneshGeek)**
### Kredit
Terima kasih kepada semua komunitas yang luar biasa yang [berkontribusi untuk mengirimkan PR](https://github.com/projectdiscovery/nuclei/graphs/contributors). Lihat juga proyek sumber-terbuka serupa di bawah ini yang mungkin sesuai dengan alur kerja Anda:
-a, -author string[] templates to run based on authors (comma-separated, file)
-tags string[] templates to run based on tags (comma-separated, file)
-etags, -exclude-tags string[] templates to exclude based on tags (comma-separated, file)
-itags, -include-tags string[] tags to be executed even if they are excluded either by default or configuration
-id, -template-id string[] templates to run based on template ids (comma-separated, file, allow-wildcard)
-eid, -exclude-id string[] templates to exclude based on template ids (comma-separated, file)
-it, -include-templates string[] path to template file or directory to be executed even if they are excluded either by default or configuration
-et, -exclude-templates string[] path to template file or directory to exclude (comma-separated, file)
-em, -exclude-matchers string[] template matchers to exclude in result
-s, -severity value[] templates to run based on severity. Possible values:info, low, medium, high, critical, unknown
-es, -exclude-severity value[] templates to exclude based on severity. Possible values:info, low, medium, high, critical, unknown
-pt, -type value[] templates to run based on protocol type. Possible values:dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-ept, -exclude-type value[] templates to exclude based on protocol type. Possible values:dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-tc, -template-condition string[] templates to run based on expression condition
-irr, -include-rr -omit-raw include request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only) [DEPRECATED use -omit-raw] (default true)
-or, -omit-raw omit request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only)
-ot, -omit-template omit encoded template in the JSON, JSONL output
-nm, -no-meta disable printing result metadata in cli output
-ts, -timestamp enables printing timestamp in cli output
-rdb, -report-db string nuclei reporting database (always use this to persist report data)
-ms, -matcher-status display match failure status
-me, -markdown-export string directory to export results in markdown format
-se, -sarif-export string file to export results in SARIF format
-je, -json-export string file to export results in JSON format
-jle, -jsonl-export string file to export results in JSONL(ine) format
-pe, -pdf-export string file to export results in PDF format
-rd, -redact string[] redact given list of keys from query parameter, request header and body
CONFIGURATIONS:
-config string path to the nuclei configuration file
-tp, -profile string template profile config file to run
-tpl, -profile-list list community template profiles
-fr, -follow-redirects enable following redirects for http templates
-fhr, -follow-host-redirects follow redirects on the same host
-mr, -max-redirects int max number of redirects to follow for http templates (default 10)
-dr, -disable-redirects disable redirects for http templates
-mhe, -max-host-error int max errors for a host before skipping from scan (default 30)
-te, -track-error string[] adds given error to max-host-error watchlist (standard, file)
-nmhe, -no-mhe disable skipping host from scan based on errors
-project use a project folder to avoid sending same request multiple times
-project-path string set a specific project path (default "/tmp")
-spm, -stop-at-first-match stop processing HTTP requests after the first match (may break template/workflow logic)
-stream stream mode - start elaborating without sorting the input
-ss, -scan-strategy value strategy to use while scanning(auto/host-spray/template-spray) (default auto)
-irt, -input-read-timeout value timeout on input read (default 3m0s)
-response-cache reuse identical safe GET/HEAD responses within a scan (lossless:skips requests with auth, cookies, body or custom headers)
-nh, -no-httpx disable httpx probing for non-url input
-stp, -strict-probe skip templates whose target service is unreachable:HTTP/headless on hosts httpx could not confirm and network templates on closed ports (lossless, no raw-input fallback)
-tf, -tech-filter opt-in:fingerprint HTTP targets and skip product/macro-tagged templates that cannot match (off by default; enables scan-scoped GET cache; fail-open; no-op if no tech-bound templates)
-preflight-portscan run preflight resolve + TCP portscan and filter targets before scanning (disabled by default)
-no-stdin disable stdin processing
HEADLESS:
-headless enable templates that require headless browser support (root user on Linux will disable sandbox)
-page-timeout int seconds to wait for each page in headless mode (default 20)
-sb, -show-browser show the browser on the screen when running templates with headless mode
-ho, -headless-options string[] start headless chrome with additional options
-sc, -system-chrome use local installed Chrome browser instead of nuclei installed
-cdpe, -cdp-endpoint string use remote browser via Chrome DevTools Protocol (CDP) endpoint
-lha, -list-headless-action list available headless actions
DEBUG:
-debug show all requests and responses
-dreq, -debug-req show all sent requests
-dresp, -debug-resp show all received responses
-p, -proxy string[] list of http/socks5 proxy to use (comma separated or file input)
-pi, -proxy-internal proxy all internal requests
-ldf, -list-dsl-function list all supported DSL function signatures
-tlog, -trace-log string file to write sent requests trace log
-elog, -error-log string file to write sent requests error log
**O Nuclei é um scanner de vulnerabilidades moderno e de alto desempenho que utiliza templates simples baseados em YAML. Ele permite projetar cenários personalizados de detecção de vulnerabilidades que simulam condições do mundo real, resultando em zero falsos positivos.**
---
- Formato YAML simples para criar e personalizar templates de vulnerabilidade.
- Contribuído por milhares de profissionais de segurança para lidar com vulnerabilidades em alta.
- Reduza falsos positivos simulando passos reais para verificar uma vulnerabilidade.
- Processamento paralelo de scan ultrarrápido e agrupamento de requisições.
- Integre em pipelines de CI/CD para detecção de vulnerabilidades e testes de regressão.
- Suporta múltiplos protocolos como TCP, DNS, HTTP, SSL, WHOIS, JavaScript, Code e mais.
- Integra-se com Jira, Splunk, GitHub, Elastic, GitLab.
O Nuclei é utilizado para enviar solicitações para vários alvos baseados em um modelo, resultando em zero falsos positivos e proporcionando uma varredura rápida em um grande número de hosts. O Nuclei oferece suporte a uma variedade de protocolos, incluindo TCP, DNS, HTTP, SSL, Arquivo, Whois, Websocket, Headless, Código, entre outros. Com modelos poderosos e flexíveis, o Nuclei pode ser usado para modelar todos os tipos de verificações de segurança.
<br>
<br>
Temos um [repositório dedicado](https://github.com/projectdiscovery/nuclei-templates) que abriga vários tipos de modelos de vulnerabilidades, contribuídos por **mais de 300** pesquisadores e engenheiros de segurança.
## Índice
## Como funciona
- [**`Primeiros Passos`**](#primeiros-passos)
- [_`1. Nuclei CLI`_](#1-nuclei-cli)
- [_`2. Edições Pro e Enterprise`_](#2-edições-pro-e-enterprise)
- [**`Documentação`**](#documentação)
- [_`Flags de Linha de Comando`_](#flags-de-linha-de-comando)
- [_`Scan em alvo único`_](#scan-em-alvo-único)
- [_`Scan em múltiplos alvos`_](#scan-em-múltiplos-alvos)
- [_`Scan de rede`_](#scan-de-rede)
- [_`Scan com seu template personalizado`_](#scan-com-seu-template-personalizado)
- [_`Conectar o Nuclei ao ProjectDiscovery`_](#conectar-o-nuclei-ao-projectdiscovery)
- [**`Templates do Nuclei, Comunidade e Recompensas`**](#templates-do-nuclei-comunidade-e-recompensas-) 💎
| **Este projeto está em desenvolvimento ativo**. Alterações significativas são esperadas em versões futuras. Consulte o changelog antes de atualizar. |
| Este projeto foi desenvolvido principalmente para ser usado como uma ferramenta CLI independente. **Executar o Nuclei como um serviço pode implicar riscos de segurança.** É recomendável utilizá-lo com precaução e medidas de segurança adicionais. |
_Instale o Nuclei na sua máquina. Comece seguindo o guia de instalação [**`aqui`**](https://docs.projectdiscovery.io/tools/nuclei/install?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme). Além disso, oferecemos [**`um plano gratuito na nuvem`**](https://cloud.projectdiscovery.io/sign-up) com limites mensais gratuitos generosos:_
# Instalação do Nuclei
- Armazene e visualize suas descobertas de vulnerabilidades
- Escreva e gerencie seus templates do nuclei
- Acesse os templates mais recentes do nuclei
- Descubra e armazene seus alvos
O Nuclei requer **go1.22** para ser instalado corretamente. Execute o seguinte comando para instalar a versão mais recente:
> [!Important]
> |**Este projeto está em desenvolvimento ativo**. Espere mudanças incompatíveis entre versões. Revise o changelog antes de atualizar.|
> |:--------------------------------|
> | Este projeto foi construído principalmente para ser utilizado como ferramenta CLI standalone. **Executar o nuclei como serviço pode trazer riscos de segurança.** Recomenda-se usá-lo com cautela e medidas de segurança adicionais. |
<br>
### **2. Edições Pro e Enterprise**
_Para times de segurança e empresas, oferecemos um serviço hospedado na nuvem construído sobre o Nuclei OSS, ajustado para ajudá-lo a executar continuamente scans de vulnerabilidade em escala com seu time e fluxos de trabalho existentes:_
- Scans 50x mais rápidos
- Scans em larga escala com alta precisão
- Integrações com serviços de nuvem (AWS, GCP, Azure, Cloudflare, Fastly, Terraform, Kubernetes)
- Jira, Slack, Linear, APIs e Webhooks
- Relatórios executivos e de conformidade
- Adicionalmente: Scan em tempo real, SAML SSO, plataforma compatível com SOC 2 (com opções de hospedagem na UE e EUA), workspaces de equipe compartilhados e mais
- **Ideal para:** Pentesters, times de segurança e empresas
[**`Cadastre-se no Pro`**](https://projectdiscovery.io/pricing?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) ou [**`fale com nosso time`**](https://projectdiscovery.io/request-demo?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) se você tem uma organização grande e requisitos complexos.
<br>
<br>
## Documentação
Acesse a [**`documentação completa do Nuclei aqui`**](https://docs.projectdiscovery.io/tools/nuclei/running). Se você é novo no Nuclei, confira nossa [**`série introdutória no YouTube`**](https://www.youtube.com/playlist?list=PLZRbR9aMzTTpItEdeNSulo8bYsvil80Rl).
O `nuclei` requer **go >= 1.27.3** para instalar com sucesso. Execute o seguinte comando para obter o repositório:
```sh
go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest
```
<details>
<summary>Brew</summary>
```sh
brew install nuclei
```
</details>
<details>
<summary>Docker</summary>
```sh
docker pull projectdiscovery/nuclei:latest
```
</details>
Para saber mais sobre como instalar o nuclei, consulte `https://docs.projectdiscovery.io/tools/nuclei/install`.
**Mais métodos de instalação [podem ser encontrados aqui](https://docs.projectdiscovery.io/tools/nuclei/install).**
### Flags de Linha de Comando
<table>
<tr>
<td>
### Modelos do Nuclei
O Nuclei possui suporte integrado para download/atualização automática de modelos a partir da versão [v2.5.2](https://github.com/projectdiscovery/nuclei/releases/tag/v2.5.2). O projeto [**Nuclei-Templates**](https://github.com/projectdiscovery/nuclei-templates) fornece uma lista de modelos prontos para uso, atualizados constantemente pela comunidade.
Você também pode usar a flag `update-templates` para atualizar os modelos do Nuclei a qualquer momento; também pode criar seus próprios testes para seu fluxo de trabalho e necessidades específicas seguindo o [guia de modelos](https://docs.projectdiscovery.io/templates/) do Nuclei.
A referência de sintaxe YAML DSL está disponível [aqui](SYNTAX-REFERENCE.md).
</td>
</tr>
</table>
### Uso
Para exibir todas as flags da ferramenta:
```sh
nuclei -h
```
Isso mostrará ajuda sobre a ferramenta. Aqui estão todas as opções que ela suporta.
<details>
<summary>Expandir todas as flags de ajuda</summary>
```console
Nuclei é um scanner de vulnerabilidades rápido e baseado em templates
que se concentra em sua ampla configurabilidade, extensibilidade e facilidade de uso.
```yaml
Nuclei is a fast, template based vulnerability scanner focusing
onextensive configurability, massive extensibility and ease of use.
Usage:
./nuclei [flags]
Flags:
TARGET:
-u, -target string[] URLs/hosts a serem escaneados
-l, -list string caminho do arquivo contendo a lista de URLs/hosts a serem escaneados (um por linha)
-eh, -exclude-hosts string[] hosts a serem excluídos do escaneamento na lista de entrada (ip, cidr, hostname)
-resume string retomar o escaneamento usando resume.cfg (a clusterização será desabilitada)
-sa, -scan-all-ips escanear todos os IPs associados ao registro DNS
-iv, -ip-version string[] versão de IP a escanear do nome do host (4,6) - (padrão 4)
-u, -target string[] target URLs/hosts to scan
-l, -list string path to file containing a list of target URLs/hosts to scan (one per line)
-targets-inline string inline multiline target list (for use in template profiles)
-eh, -exclude-hosts string[] hosts to exclude to scan from the input list (ip, cidr, hostname)
-resume string resume scan from and save to specified file (clustering will be disabled)
-sa, -scan-all-ips scan all the IP's associated with dns record
-iv, -ip-version string[] IP version to scan of hostname (4,6) - (default 4)
TARGET-FORMAT:
-im, -input-mode string modo do arquivo de entrada (list, burp, jsonl, yaml, openapi, swagger) (padrão "list")
-ro, -required-only usar apenas campos obrigatórios no formato de entrada ao gerar requisições
-sfv, -skip-format-validation pular a validação de formato (como variáveis ausentes) ao processar o arquivo de entrada
-llm-base-url string openai-compatible endpoint for semantic matching (overrides -llm-provider, e.g. a local model)
-llm-model string model used for semantic matching
-llm-timeout int time in seconds to wait for a single llm call (default 30)
-llm-max-calls int maximum llm calls per scan (0 for unlimited) (default 5000)
-llm-concurrency int maximum concurrent llm calls (default 4)
-llm-cache cache llm responses within a scan (default true)
FILTERING:
-a, -author string[] templates a serem executados com base nos autores (separados por vírgulas, arquivo)
-tags string[] templates a serem executados com base em tags (separados por vírgulas, arquivo)
-etags, -exclude-tags string[] templates a excluir com base em tags (separados por vírgulas, arquivo)
-itags, -include-tags string[] tags a executar mesmo que estejam excluídas por padrão ou configuração
-id, -template-id string[] templates a serem executados com base em IDs de template (separados por vírgulas, arquivo, permitem curingas)
-eid, -exclude-id string[] templates a excluir com base em IDs de template (separados por vírgulas, arquivo)
-it, -include-templates string[] caminho do arquivo de template ou diretório a executar mesmo que estejam excluídos por padrão ou configuração
-et, -exclude-templates string[] caminho do arquivo de template ou diretório a excluir (separados por vírgulas, arquivo)
-em, -exclude-matchers string[] matchers de template a excluir no resultado
-s, -severity value[] templates a executar com base na criticidade. Valores possíveis: info, baixo, médio, alto, crítico, desconhecido
-es, -exclude-severity value[] templates a excluir com base na criticidade. Valores possíveis: info, baixo, médio, alto, crítico, desconhecido
-pt, -type value[] templates a executar com base no tipo de protocolo. Valores possíveis: dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-ept, -exclude-type value[] templates a excluir com base no tipo de protocolo. Valores possíveis: dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-tc, -template-condition string[] templates a executar com base em condição de expressão
-a, -author string[] templates to run based on authors (comma-separated, file)
-tags string[] templates to run based on tags (comma-separated, file)
-etags, -exclude-tags string[] templates to exclude based on tags (comma-separated, file)
-itags, -include-tags string[] tags to be executed even if they are excluded either by default or configuration
-id, -template-id string[] templates to run based on template ids (comma-separated, file, allow-wildcard)
-eid, -exclude-id string[] templates to exclude based on template ids (comma-separated, file)
-it, -include-templates string[] path to template file or directory to be executed even if they are excluded either by default or configuration
-et, -exclude-templates string[] path to template file or directory to exclude (comma-separated, file)
-em, -exclude-matchers string[] template matchers to exclude in result
-s, -severity value[] templates to run based on severity. Possible values:info, low, medium, high, critical, unknown
-es, -exclude-severity value[] templates to exclude based on severity. Possible values:info, low, medium, high, critical, unknown
-pt, -type value[] templates to run based on protocol type. Possible values:dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-ept, -exclude-type value[] templates to exclude based on protocol type. Possible values:dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-tc, -template-condition string[] templates to run based on expression condition
OUTPUT:
-o, -output string arquivo de saída para salvar as ocorrências/vulnerabilidades detectadas
-sresp, -store-resp armazenar todas as solicitações/respostas enviadas pelo nuclei no diretório de saída
-srd, -store-resp-dir string armazenar todas as solicitações/respostas enviadas pelo nuclei em um diretório personalizado (padrão "output")
-silent exibir apenas os resultados
-nc, -no-color desativar a coloração do conteúdo de saída (códigos de escape ANSI)
-j, -jsonl salvar a saída no formato JSONL(ines)
-irr, -include-rr -omit-raw incluir pares solicitação/resposta nas saídas JSON, JSONL e Markdown (apenas para achados) [OBSOLETO usar -omit-raw] (padrão true)
-or, -omit-raw omitir os pares solicitação/resposta nas saídas JSON, JSONL e Markdown (apenas para achados)
-ot, -omit-template omitir o template codificado na saída JSON, JSONL
-nm, -no-meta desativar a exibição de metadados dos resultados na saída CLI
-ts, -timestamp ativar a exibição do carimbo de data/hora na saída CLI
-rdb, -report-db string banco de dados de relatórios do nuclei (usar sempre para persistir os dados dos relatórios)
-ms, -matcher-status exibir o estado de falha de correspondência
-me, -markdown-export string diretório para exportar resultados no formato Markdown
-se, -sarif-export string arquivo para exportar resultados no formato SARIF
-je, -json-export string arquivo para exportar resultados no formato JSON
-jle, -jsonl-export string arquivo para exportar resultados no formato JSONL(ines)
-o, -output string output file to write found issues/vulnerabilities
-sresp, -store-resp store all request/response passed through nuclei to output directory
-srd, -store-resp-dir string store all request/response passed through nuclei to custom directory (default "output")
-irr, -include-rr -omit-raw include request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only) [DEPRECATED use -omit-raw] (default true)
-or, -omit-raw omit request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only)
-ot, -omit-template omit encoded template in the JSON, JSONL output
-nm, -no-meta disable printing result metadata in cli output
-ts, -timestamp enables printing timestamp in cli output
-rdb, -report-db string nuclei reporting database (always use this to persist report data)
-ms, -matcher-status display match failure status
-me, -markdown-export string directory to export results in markdown format
-se, -sarif-export string file to export results in SARIF format
-je, -json-export string file to export results in JSON format
-jle, -jsonl-export string file to export results in JSONL(ine) format
-pe, -pdf-export string file to export results in PDF format
-rd, -redact string[] redact given list of keys from query parameter, request header and body
CONFIGURATIONS:
-config string caminho do arquivo de configuração do nuclei
-fr, -follow-redirects ativar o acompanhamento de redirecionamentos para templates HTTP
-fhr, -follow-host-redirects seguir redirecionamentos no mesmo host
-mr, -max-redirects intnúmero máximo de redirecionamentos a seguir para templates HTTP (padrão 10)
-dr, -disable-redirects desativar redirecionamentos para templates HTTP
-rc, -report-config string arquivo de configuração do módulo de relatórios do nuclei
-H, -header string[] cabeçalho/cookie personalizado a incluir em todas as solicitações HTTP no formato header:value (CLI, arquivo)
-V, -var value variáveis personalizadas no formato key=value
-r, -resolvers string arquivo contendo uma lista de resolvers para o nuclei
-sr, -system-resolvers usar resolução DNS do sistema como fallback em caso de erro
-dc, -disable-clustering desativar o agrupamento de solicitações
-passive ativar o modo de processamento passivo de respostas HTTP
-fh2, -force-http2 forçar conexões HTTP2 nas solicitações
-ev, -env-vars ativar o uso de variáveis de ambiente no template
-cc, -client-cert string arquivo de certificado de cliente (codificado em PEM) usado para autenticar-se contra os hosts escaneados
-ck, -client-key string arquivo de chave de cliente (codificado em PEM) usado para autenticar-se contra os hosts escaneados
-ca, -client-ca string arquivo de autoridade de certificação de cliente (codificado em PEM) usado para autenticar-se contra os hosts escaneados
-sml, -show-match-line exibir linhas de correspondência para templates de arquivo, funciona apenas com extratores
-ztls usar a biblioteca ztls com fallback automático para padrão no tls13 [OBSOLETO] fallback automático para ztls já está ativado por padrão
-sni string nome de host tls sni a ser usado (padrão: nome de domínio de entrada)
-dt, -dialer-timeout value tempo limite para solicitações de rede
-dka, -dialer-keep-alive value duração do keep-alive para solicitações de rede
-lfa, -allow-local-file-access permitir acesso a arquivos (payload) em qualquer lugar do sistema
-lna, -restrict-local-network-access bloquear conexões à rede local/privada
-i, -interface string interface de rede a ser usada para o escaneamento de rede
-at, -attack-type string tipo de combinações de payload a realizar (batteringram, pitchfork, clusterbomb)
-sip, -source-ip string endereço IP de origem a ser usado para o escaneamento de rede
-rsr, -response-size-read int tamanho máximo de resposta a ser lido em bytes (padrão 10485760)
-rss, -response-size-save int tamanho máximo de resposta a ser salvo em bytes (padrão 1048576)
-reset remove todos os arquivos de configuração e dados do nuclei (incluindo os nuclei-templates)
-tlsi, -tls-impersonate ativar randomização experimental do client hello (ja3) tls
-config string path to the nuclei configuration file
-tp, -profile string template profile config file to run
-tpl, -profile-list list community template profiles
-fr, -follow-redirects enable following redirects for http templates
-fhr, -follow-host-redirects follow redirects on the same host
-mr, -max-redirects int max number of redirects to follow for http templates (default 10)
-dr, -disable-redirects disable redirects for http templates
-cs, -fuzz-scope string[] in scope url regex to be followed by fuzzer
-cos, -fuzz-out-scope string[] out of scope url regex to be excluded by fuzzer
UNCOVER:
-uc, -uncover ativa o motor uncover
-uq, -uncover-query string[] consulta de busca uncover
-ue, -uncover-engine string[] motor de busca uncover (shodan,censys,fofa,shodan-idb,quake,hunter,zoomeye,netlas,criminalip,publicwww,hunterhow) (padrão shodan)
-rlm, -rate-limit-minute int maximum number of requests to send per minute (DEPRECATED)
-bs, -bulk-size int maximum number of hosts to be analyzed in parallel per template (default 25)
-c, -concurrency int maximum number of templates to be executed in parallel (default 25)
-hbs, -headless-bulk-size int maximum number of headless hosts to be analyzed in parallel per template (default 10)
-headc, -headless-concurrency int maximum number of headless templates to be executed in parallel (default 10)
-jsc, -js-concurrency int maximum number of javascript runtimes to be executed in parallel (default 120)
-pc, -payload-concurrency int max payload concurrency for each template (default 25)
-prc, -probe-concurrency int http probe concurrency with httpx (default 50)
-tlc, -template-loading-concurrency int maximum number of concurrent template loading operations (default 50)
OPTIMIZATIONS:
-timeout int tempo limite em segundos (padrão 10)
-retries int número de tentativas para solicitações com falha (padrão 1)
-ldp, -leave-default-ports manter as portas HTTP/HTTPS padrão (exemplo: host:80,host:443)
-mhe, -max-host-error int número máximo de erros para um host antes de ignorá-lo no scan (padrão 30)
-te, -track-error string[] adiciona o erro especificado à lista de rastreamento de erros máximos por host (standard, file)
-nmhe, -no-mhe desativa a exclusão de hosts do scan com base em erros
-project utiliza uma pasta de projeto para evitar enviar a mesma solicitação várias vezes
-project-path string define um caminho específico para o projeto (padrão "/tmp")
-spm, -stop-at-first-match interrompe o processamento de solicitações HTTP após a primeira correspondência (pode quebrar a lógica de templates/fluxos de trabalho)
-stream modo de transmissão - começa a trabalhar sem ordenar a entrada
-ss, -scan-strategy value estratégia a ser usada durante o scan(auto/host-spray/template-spray) (padrão auto)
-irt, -input-read-timeout value tempo limite para leitura da entrada (padrão 3m0s)
-nh, -no-httpx desativa a análise httpx para entradas que não sejam URLs
-no-stdin desativa o processamento de entrada padrão
-timeout int time to wait in seconds before timeout (default 10)
-retries int number of times to retry a failed request (default 1)
-mhe, -max-host-error int max errors for a host before skipping from scan (default 30)
-te, -track-error string[] adds given error to max-host-error watchlist (standard, file)
-nmhe, -no-mhe disable skipping host from scan based on errors
-project use a project folder to avoid sending same request multiple times
-project-path string set a specific project path (default "/tmp")
-spm, -stop-at-first-match stop processing HTTP requests after the first match (may break template/workflow logic)
-stream stream mode - start elaborating without sorting the input
-ss, -scan-strategy value strategy to use while scanning(auto/host-spray/template-spray) (default auto)
-irt, -input-read-timeout value timeout on input read (default 3m0s)
-response-cache reuse identical safe GET/HEAD responses within a scan (lossless:skips requests with auth, cookies, body or custom headers)
-nh, -no-httpx disable httpx probing for non-url input
-stp, -strict-probe skip templates whose target service is unreachable:HTTP/headless on hosts httpx could not confirm and network templates on closed ports (lossless, no raw-input fallback)
-tf, -tech-filter opt-in:fingerprint HTTP targets and skip product/macro-tagged templates that cannot match (off by default; enables scan-scoped GET cache; fail-open; no-op if no tech-bound templates)
-preflight-portscan run preflight resolve + TCP portscan and filter targets before scanning (disabled by default)
-no-stdin disable stdin processing
HEADLESS:
-headless habilita templates que requerem suporte para navegadores sem interface gráfica (headless browser) (o usuário root no Linux desativará o sandbox)
-page-timeout int segundos para esperar cada página no modo headless (padrão 20)
-sb, -show-browser exibe o navegador na tela ao executar templates no modo headless
-ho, -headless-options string[] inicia o Chrome no modo headless com opções adicionais
-sc, -system-chrome utiliza o navegador Chrome instalado localmente em vez do instalado pelo nuclei
-lha, -list-headless-action lista ações disponíveis para o modo headless
-headless enable templates that require headless browser support (root user on Linux will disable sandbox)
-page-timeout int seconds to wait for each page in headless mode (default 20)
-sb, -show-browser show the browser on the screen when running templates with headless mode
-ho, -headless-options string[] start headless chrome with additional options
-sc, -system-chrome use local installed Chrome browser instead of nuclei installed
-cdpe, -cdp-endpoint string use remote browser via Chrome DevTools Protocol (CDP) endpoint
-lha, -list-headless-action list available headless actions
DEBUG:
-debug exibe todas as solicitações e respostas
-dreq, -debug-req exibe todas as solicitações enviadas
-dresp, -debug-resp exibe todas as respostas recebidas
-p, -proxy string[] lista de proxies HTTP/SOCKS5 a serem usados (separados por vírgulas ou arquivo de entrada)
-pi, -proxy-internal proxy para todas as solicitações internas
-ldf, -list-dsl-function lista todas as assinaturas de funções DSL suportadas
-tlog, -trace-log string arquivo para gravar o log de rastreamento de solicitações enviadas
-elog, -error-log string arquivo para gravar o log de erros de solicitações enviadas
-version exibe a versão do nuclei
-hm, -hang-monitor ativa o monitoramento de travamentos do nuclei
-v, -verbose exibe saída detalhada
-profile-mem string arquivo opcional para despejo de memória do nuclei
-vv exibe os templates carregados para o scan
-svd, -show-var-dump exibe o dump de variáveis para depuração
-ep, -enable-pprof ativa o servidor de depuração pprof
-tv, -templates-version exibe a versão dos templates do nuclei (nuclei-templates) instalados
-hc, -health-check executa verificações de diagnóstico
-debug show all requests and responses
-dreq, -debug-req show all sent requests
-dresp, -debug-resp show all received responses
-p, -proxy string[] list of http/socks5 proxy to use (comma separated or file input)
-pi, -proxy-internal proxy all internal requests
-ldf, -list-dsl-function list all supported DSL function signatures
-tlog, -trace-log string file to write sent requests trace log
-elog, -error-log string file to write sent requests error log
Consulte https://docs.projectdiscovery.io/tools/nuclei/running para obter detalhes sobre como executar o Nuclei.
</details>
### Uso de Nuclei com código Go
### Scan em alvo único
O guia completo sobre como usar o Nuclei como biblioteca/SDK está disponível em [godoc](https://pkg.go.dev/github.com/projectdiscovery/nuclei/v3/lib#section-readme).
Para realizar um scan rápido em uma aplicação web:
```sh
nuclei -target https://example.com
```
### Scan em múltiplos alvos
O Nuclei pode lidar com scans em massa fornecendo uma lista de alvos. Você pode usar um arquivo contendo múltiplas URLs.
```sh
nuclei -list urls.txt
```
### Scan de rede
Isso fará scan de toda a subrede em busca de problemas relacionados à rede, como portas abertas ou serviços mal configurados.
```sh
nuclei -target 192.168.1.0/24
```
### Scan com seu template personalizado
Para escrever e usar seu próprio template, crie um arquivo `.yaml` com regras específicas e use-o como mostrado abaixo.
Você pode executar os scans na sua máquina e enviar os resultados para a plataforma na nuvem para análise e remediação adicionais.
```sh
nuclei -target https://example.com -dashboard
```
> [!NOTE]
> Este recurso é totalmente gratuito e não requer assinatura. Para um guia detalhado, consulte a [**`documentação`**](https://docs.projectdiscovery.io/cloud/scanning/nuclei-scan?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme).
<br>
<br>
## Templates do Nuclei, Comunidade e Recompensas 💎
Os [**templates do Nuclei**](https://github.com/projectdiscovery/nuclei-templates) são baseados no conceito de arquivos de template em YAML que definem como as requisições serão enviadas e processadas. Isso fornece capacidades de extensibilidade simples ao nuclei. Os templates são escritos em YAML, que especifica um formato simples e legível por humanos para definir rapidamente o processo de execução.
**Experimente online com nosso Editor de Templates do Nuclei gratuito e com IA** [**`clicando aqui`**](https://cloud.projectdiscovery.io/templates).
Os Templates do Nuclei oferecem uma forma simplificada de identificar e comunicar vulnerabilidades, combinando detalhes essenciais como classificações de severidade e métodos de detecção. Esta ferramenta open-source desenvolvida pela comunidade acelera a resposta a ameaças e é amplamente reconhecida no mundo da cibersegurança. Os templates do Nuclei recebem contribuições ativas de milhares de pesquisadores de segurança no mundo todo. Mantemos dois programas para nossos contribuidores: [**`Pioneers`**](https://projectdiscovery.io/pioneers) e [**`💎 bounties`**](https://github.com/projectdiscovery/nuclei-templates/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22%F0%9F%92%8E%20Bounty%22).
### Recursos
Você pode acessar a documentação principal do Nuclei em https://docs.projectdiscovery.io/tools/nuclei/ e obter mais informações sobre o Nuclei na nuvem com a [ProjectDiscovery Cloud Platform](https://cloud.projectdiscovery.io).
Consulte https://docs.projectdiscovery.io/tools/nuclei/resources para acessaar mais recursos e vídeos sobre o Nuclei!
### Créditos
Obrigado a todos os incríveis [contribuidores da comunidade que enviaram em PRs](https://github.com/projectdiscovery/nuclei/graphs/contributors) e mantêm este projeto atualizado. :heart:
Se você tem uma ideia ou algum tipo de melhoria, sinta-se à vontade para contribuir e participar do projeto. Envie seu PR!
Os scanners de vulnerabilidades tradicionais foram construídos há décadas. Eles são de código fechado, incrivelmente lentos e orientados por fornecedores. Os atacantes de hoje exploram em massa CVEs recém-publicadas pela internet em poucos dias, ao contrário dos anos que isso costumava levar. Essa mudança exige uma abordagem completamente diferente para enfrentar exploits em alta na internet.
Construímos o Nuclei para resolver esse desafio. Tornamos todo o framework do mecanismo de scan aberto e personalizável — permitindo que a comunidade global de segurança colabore e enfrente os vetores de ataque e vulnerabilidades em alta na internet. O Nuclei agora é usado e recebe contribuições de empresas Fortune 500, agências governamentais e universidades.
Você pode participar contribuindo com nosso código, com a [**`biblioteca de templates`**](https://github.com/projectdiscovery/nuclei-templates) ou [**`juntando-se ao nosso time`**](https://projectdiscovery.io/).
<br>
<br>
## Contribuidores :heart:
Obrigado a todos os incríveis [**`contribuidores da comunidade que enviaram PRs`**](https://github.com/projectdiscovery/nuclei/graphs/contributors) e mantêm este projeto atualizado. :heart:
**Nuclei, basit YAML tabanlı şablonlardan yararlanan modern, yüksek performanslı bir zafiyet tarayıcısıdır. Gerçek dünya koşullarını taklit eden özel zafiyet tespit senaryoları tasarlamanıza olanak tanıyarak sıfır hatalı pozitif sonuç sağlar.**
- Zafiyet şablonları oluşturmak ve özelleştirmek için basit YAML formatı.
- Trend olan zafiyetleri ele almak için binlerce güvenlik uzmanı tarafından katkıda bulunulmuştur.
- Bir zafiyeti doğrulamak için gerçek dünya adımlarını simüle ederek hatalı pozitifleri azaltır.
- Ultra hızlı paralel tarama işleme ve istek kümeleme.
- Zafiyet tespiti ve regresyon testi için CI/CD hatlarına entegre edilebilir.
- TCP, DNS, HTTP, SSL, WHOIS, JavaScript, Code ve daha fazlası gibi birçok protokolü destekler.
- Jira, Splunk, GitHub, Elastic, GitLab ile entegre olur.
<br>
<br>
## İçindekiler
- [**`Başlarken`**](#başlarken)
- [_`1. Nuclei CLI`_](#1-nuclei-cli)
- [_`2. Pro ve Kurumsal Sürümler`_](#2-pro-ve-kurumsal-sürümler)
_Nuclei'yi makinenize kurun. [**`Buradaki`**](https://docs.projectdiscovery.io/tools/nuclei/install?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) kurulum kılavuzunu takip ederek başlayın. Ayrıca, [**`ücretsiz bir bulut katmanı`**](https://cloud.projectdiscovery.io/sign-up) sağlıyoruz ve cömert aylık ücretsiz limitlerle birlikte geliyor:_
- Zafiyet bulgularınızı saklayın ve görselleştirin
- nuclei şablonlarınızı yazın ve yönetin
- En son nuclei şablonlarına erişin
- Hedeflerinizi keşfedin ve saklayın
> [!Important]
> |**Bu proje aktif geliştirme aşamasındadır**. Sürümlerle birlikte kırılma değişiklikleri bekleyin. Güncellemeden önce sürüm değişiklik günlüğünü inceleyin.|
> |:--------------------------------|
> | Bu proje öncelikle bağımsız bir CLI aracı olarak kullanılmak üzere oluşturulmuştur. **Nuclei'yi bir servis olarak çalıştırmak güvenlik riskleri oluşturabilir.** Dikkatli kullanılması ve ek güvenlik önlemleri alınması önerilir. |
<br>
### **2. Pro ve Kurumsal Sürümler**
_Güvenlik ekipleri ve kuruluşlar için, ekibiniz ve mevcut iş akışlarınızla ölçekli olarak sürekli zafiyet taramaları yapmanıza yardımcı olmak üzere ince ayarlanmış, Nuclei OSS üzerine inşa edilmiş bulut tabanlı bir hizmet sunuyoruz:_
- Artı: Gerçek zamanlı tarama, SAML SSO, SOC 2 uyumlu platform (AB ve ABD barındırma seçenekleri ile), paylaşılan ekip çalışma alanları ve daha fazlası
- Sürekli olarak [**`yeni özellikler ekliyoruz`**](https://feedback.projectdiscovery.io/changelog)!
- **Şunlar için ideal:** Sızma testi yapanlar, güvenlik ekipleri ve kuruluşlar
Büyük bir organizasyonunuz ve karmaşık gereksinimleriniz varsa [**`Pro'ya kaydolun`**](https://projectdiscovery.io/pricing?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) veya [**`ekibimizle konuşun`**](https://projectdiscovery.io/request-demo?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme).
<br>
<br>
## Dokümantasyon
Nuclei'nin tam [**`dokümantasyonuna buradan`**](https://docs.projectdiscovery.io/tools/nuclei/running) göz atın. Nuclei'de yeniyseniz, [**`temel YouTube serimize`**](https://www.youtube.com/playlist?list=PLZRbR9aMzTTpItEdeNSulo8bYsvil80Rl) göz atın.
-llm-base-url string openai-compatible endpoint for semantic matching (overrides -llm-provider, e.g. a local model)
-llm-model string model used for semantic matching
-llm-timeout int time in seconds to wait for a single llm call (default 30)
-llm-max-calls int maximum llm calls per scan (0 for unlimited) (default 5000)
-llm-concurrency int maximum concurrent llm calls (default 4)
-llm-cache cache llm responses within a scan (default true)
FILTERING:
-a, -author string[] templates to run based on authors (comma-separated, file)
-tags string[] templates to run based on tags (comma-separated, file)
-etags, -exclude-tags string[] templates to exclude based on tags (comma-separated, file)
-itags, -include-tags string[] tags to be executed even if they are excluded either by default or configuration
-id, -template-id string[] templates to run based on template ids (comma-separated, file, allow-wildcard)
-eid, -exclude-id string[] templates to exclude based on template ids (comma-separated, file)
-it, -include-templates string[] path to template file or directory to be executed even if they are excluded either by default or configuration
-et, -exclude-templates string[] path to template file or directory to exclude (comma-separated, file)
-em, -exclude-matchers string[] template matchers to exclude in result
-s, -severity value[] templates to run based on severity. Possible values:info, low, medium, high, critical, unknown
-es, -exclude-severity value[] templates to exclude based on severity. Possible values:info, low, medium, high, critical, unknown
-pt, -type value[] templates to run based on protocol type. Possible values:dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-ept, -exclude-type value[] templates to exclude based on protocol type. Possible values:dns, file, http, headless, tcp, workflow, ssl, websocket, whois, code, javascript
-tc, -template-condition string[] templates to run based on expression condition
OUTPUT:
-o, -output string output file to write found issues/vulnerabilities
-sresp, -store-resp store all request/response passed through nuclei to output directory
-srd, -store-resp-dir string store all request/response passed through nuclei to custom directory (default "output")
-irr, -include-rr -omit-raw include request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only) [DEPRECATED use -omit-raw] (default true)
-or, -omit-raw omit request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only)
-ot, -omit-template omit encoded template in the JSON, JSONL output
-nm, -no-meta disable printing result metadata in cli output
-ts, -timestamp enables printing timestamp in cli output
-rdb, -report-db string nuclei reporting database (always use this to persist report data)
-ms, -matcher-status display match failure status
-me, -markdown-export string directory to export results in markdown format
-se, -sarif-export string file to export results in SARIF format
-je, -json-export string file to export results in JSON format
-jle, -jsonl-export string file to export results in JSONL(ine) format
-pe, -pdf-export string file to export results in PDF format
-rd, -redact string[] redact given list of keys from query parameter, request header and body
CONFIGURATIONS:
-config string path to the nuclei configuration file
-tp, -profile string template profile config file to run
-tpl, -profile-list list community template profiles
-fr, -follow-redirects enable following redirects for http templates
-fhr, -follow-host-redirects follow redirects on the same host
-mr, -max-redirects int max number of redirects to follow for http templates (default 10)
-dr, -disable-redirects disable redirects for http templates
-mhe, -max-host-error int max errors for a host before skipping from scan (default 30)
-te, -track-error string[] adds given error to max-host-error watchlist (standard, file)
-nmhe, -no-mhe disable skipping host from scan based on errors
-project use a project folder to avoid sending same request multiple times
-project-path string set a specific project path (default "/tmp")
-spm, -stop-at-first-match stop processing HTTP requests after the first match (may break template/workflow logic)
-stream stream mode - start elaborating without sorting the input
-ss, -scan-strategy value strategy to use while scanning(auto/host-spray/template-spray) (default auto)
-irt, -input-read-timeout value timeout on input read (default 3m0s)
-response-cache reuse identical safe GET/HEAD responses within a scan (lossless:skips requests with auth, cookies, body or custom headers)
-nh, -no-httpx disable httpx probing for non-url input
-stp, -strict-probe skip templates whose target service is unreachable:HTTP/headless on hosts httpx could not confirm and network templates on closed ports (lossless, no raw-input fallback)
-tf, -tech-filter opt-in:fingerprint HTTP targets and skip product/macro-tagged templates that cannot match (off by default; enables scan-scoped GET cache; fail-open; no-op if no tech-bound templates)
-preflight-portscan run preflight resolve + TCP portscan and filter targets before scanning (disabled by default)
-no-stdin disable stdin processing
HEADLESS:
-headless enable templates that require headless browser support (root user on Linux will disable sandbox)
-page-timeout int seconds to wait for each page in headless mode (default 20)
-sb, -show-browser show the browser on the screen when running templates with headless mode
-ho, -headless-options string[] start headless chrome with additional options
-sc, -system-chrome use local installed Chrome browser instead of nuclei installed
-cdpe, -cdp-endpoint string use remote browser via Chrome DevTools Protocol (CDP) endpoint
-lha, -list-headless-action list available headless actions
DEBUG:
-debug show all requests and responses
-dreq, -debug-req show all sent requests
-dresp, -debug-resp show all received responses
-p, -proxy string[] list of http/socks5 proxy to use (comma separated or file input)
-pi, -proxy-internal proxy all internal requests
-ldf, -list-dsl-function list all supported DSL function signatures
-tlog, -trace-log string file to write sent requests trace log
-elog, -error-log string file to write sent requests error log
Additional documentation is available at:https://docs.projectdiscovery.io/getting-started/running
```
Ek dokümantasyon şu adreste mevcuttur: [**`docs.projectdiscovery.io/getting-started/running`**](https://docs.projectdiscovery.io/getting-started/running?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme)
</details>
### Tek hedef tarama
Web uygulamasında hızlı bir tarama yapmak için:
```sh
nuclei -target https://example.com
```
### Çoklu hedef tarama
Nuclei, bir hedef listesi sağlayarak toplu taramayı gerçekleştirebilir. Birden fazla URL içeren bir dosya kullanabilirsiniz.
```sh
nuclei -list urls.txt
```
### Ağ taraması
Bu, açık portlar veya yanlış yapılandırılmış servisler gibi ağla ilgili sorunlar için tüm alt ağı tarayacaktır.
```sh
nuclei -target 192.168.1.0/24
```
### Özel şablonunuzla tarama
Kendi şablonunuzu yazmak ve kullanmak için, belirli kurallara sahip bir `.yaml` dosyası oluşturun ve ardından aşağıdaki gibi kullanın.
Taramaları makinenizde çalıştırabilir ve sonuçları daha fazla analiz ve düzeltme için bulut platformuna yükleyebilirsiniz.
```sh
nuclei -target https://example.com -dashboard
```
> [!NOTE]
> Bu özellik tamamen ücretsizdir ve herhangi bir abonelik gerektirmez. Ayrıntılı bir kılavuz için [**`dokümantasyona`**](https://docs.projectdiscovery.io/cloud/scanning/nuclei-scan?utm_source=github&utm_medium=web&utm_campaign=nuclei_readme) bakın.
<br>
<br>
## Nuclei Şablonları, Topluluk ve Ödüller 💎
[**Nuclei şablonları**](https://github.com/projectdiscovery/nuclei-templates), isteklerin nasıl gönderileceğini ve işleneceğini tanımlayan YAML tabanlı şablon dosyaları kavramına dayanır. Bu, nuclei'ye kolay genişletilebilirlik yetenekleri sağlar. Şablonlar, yürütme sürecini hızlı bir şekilde tanımlamak için insan tarafından okunabilir basit bir format belirten YAML ile yazılmıştır.
Nuclei Şablonları, önem dereceleri ve tespit yöntemleri gibi temel ayrıntıları birleştirerek güvenlik açıklarını tanımlamak ve iletmek için akıcı bir yol sunar. Bu açık kaynaklı, topluluk tarafından geliştirilen araç, tehdit yanıtını hızlandırır ve siber güvenlik dünyasında geniş çapta tanınmaktadır. Nuclei şablonları, dünya çapında binlerce güvenlik araştırmacısı tarafından aktif olarak katkıda bulunulmaktadır. Katılımcılarımız için iki program yürütüyoruz: [**`Öncüler (Pioneers)`**](https://projectdiscovery.io/pioneers) ve [**`💎 ödüller`**](https://github.com/projectdiscovery/nuclei-templates/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22%F0%9F%92%8E%20Bounty%22).
<p align="left">
<a href="/static/nuclei-templates-teamcity.png" target="_blank"><img src="/static/nuclei-templates-teamcity.png" width="1200px" alt="TeamCity yanlış yapılandırmasını tespit etmek için Nuclei şablon örneği" /></a>
</p>
#### Örnekler
Kullanım durumları ve fikirler için [**dokümantasyonumuzu**](https://docs.projectdiscovery.io/templates/introduction) ziyaret edin.
| Varsayılan veya zayıf şifreler | **[Default Credentials Check](https://cloud.projectdiscovery.io/public/airflow-default-login)** |
| Gizli dosyalar veya veri ifşası | **[Sensitive File Disclosure](https://cloud.projectdiscovery.io/public/airflow-configuration-exposure)** |
| Açık yönlendirmeleri (open redirects) belirle| **[Open Redirect Detection](https://cloud.projectdiscovery.io/public/open-redirect)** |
| Alt alan adı devralmalarını (takeover) tespit et | **[Subdomain Takeover Templates](https://cloud.projectdiscovery.io/public/azure-takeover-detection)** |
| Güvenlik yanlış yapılandırmaları | **[Unprotected Jenkins Console](https://cloud.projectdiscovery.io/public/unauthenticated-jenkins)** |
| Zayıf SSL/TLS yapılandırmaları | **[SSL Certificate Expiry](https://cloud.projectdiscovery.io/public/expired-ssl)** |
| Dosya dahil etme (file inclusion) zafiyetleri| **[Local/Remote File Inclusion](https://cloud.projectdiscovery.io/public/CVE-2023-6977)** |
<br>
<br>
## Misyonumuz
Geleneksel zafiyet tarayıcıları on yıllar önce inşa edildi. Kapalı kaynaklıdırlar, inanılmaz derecede yavaştırlar ve satıcı odaklıdırlar. Günümüzün saldırganları, eskiden yıllar süren süreçlerin aksine, yeni yayınlanan CVE'leri günler içinde internet genelinde kitlesel olarak istismar ediyor. Bu değişim, internetteki trend olan istismarlarla mücadele etmek için tamamen farklı bir yaklaşım gerektiriyor.
Bu zorluğu çözmek için Nuclei'yi inşa ettik. Tüm tarama motoru çerçevesini açık ve özelleştirilebilir hale getirdik; bu sayede küresel güvenlik topluluğunun işbirliği yapmasına ve internet üzerindeki trend saldırı vektörlerini ve zafiyetlerini ele almasına olanak tanıdık. Nuclei artık Fortune 500 şirketleri, devlet kurumları ve üniversiteler tarafından kullanılmakta ve katkıda bulunulmaktadır.
Kodumuza, [**`şablon kitaplığımıza`**](https://github.com/projectdiscovery/nuclei-templates) katkıda bulunarak veya [**`ekibimize katılarak`**](https://projectdiscovery.io/) siz de yer alabilirsiniz.
<br>
<br>
## Katkıda Bulunanlar :heart:
Projeyi güncel tuttukları ve [**`PR gönderdikleri için harika topluluk katkıda bulunanlara`**](https://github.com/projectdiscovery/nuclei/graphs/contributors) teşekkür ederiz. :heart:
<!-- Generated by securitycontext.dev. Source HEAD: 3e1e0e81f091c7817bbf7af64bb8eec6e8c2bac1. -->
# Security Context: projectdiscovery/nuclei @ dev
> Reference context for editing projectdiscovery/nuclei. Before changing any component below, **preserve the listed guards and do not reintroduce these fixed issues**. Each fingerprint is a regression check, and each shared attack surface is a guard that must keep holding on every path.
_17 of 30 historical fixes have no remaining unguarded variant; 368 open remediation leads to verify. Measures fix consistency, not a vulnerability verdict._
- Commits analyzed: **4814**
- Commits flagged for review: **235**
- Confirmed historical security fixes: **32**
- Known published CVEs: **0**
## Summary
Nuclei's historical security posture is dominated by sandbox escapes and code execution via unsigned or unverified templates, with recurring SSRF, path traversal, and auth bypass issues across JS libraries, loaders, and workflow paths. The most critical theme is inconsistent enforcement of signature verification and local-file-access (-lfa) guards across direct, workflow, DAST, and JS-sandbox entry points, enabling variant attacks. A second theme is network policy (host allowlist) gaps in LDAP dialing and proxy handling. The security context also includes dependency upgrades (Alpine, go-git) and output file permission hardening, but the highest-value focus is on template trust boundaries and sandbox enforcement parity.
## Recurring Security Patterns
**15.6% of classified fixes repeat a previously fixed pattern** (5 recurring, 27 first-seen). A recurring pattern means this repository fixed a similar issue before — not that the code is currently vulnerable.
Unsigned templates can execute code through direct loading, workflows, and DAST branches; signature verification was bypassed via cache poisoning and missing guards on specific paths.
Signature verification can be bypassed via cached metadata, improper signature extraction, or missing checks on specific load paths, and cookie jar bypass via disabled cookie handling.
SSRF via LDAP dialing to internal hosts and via proxy configuration; host allowlist checks were missing or applied to the wrong target (domain vs controller).
Path traversal via lexical prefix checks, zip-slip in template extraction, and file:// scheme in headless mode; canonicalization and containment checks are required.
Capabilities guarded by more than one past fix on different code paths. A guard enforced on one entry point is often missing on a sibling; verify each alternate path before assuming it's covered.
### 1. Template signature verification and unsigned-template opt-in enforcement across all load paths
- Guard that should hold everywhere: signature verification (template.Verified, Verify), DisableUnsignedTemplates flag, -code flag for code templates, cache invalidation on verification status/fingerprint/digest
- Check: Inspect the DAST and workflow sub-loaders: they must enforce the same DisableUnsignedTemplates and -code checks as the direct loader, and must not rely on cached verification results without re-checking signatures.
### 2. Local file access (read/write) outside the sandbox, gated by -lfa flag
- Guard that should hold everywhere: -lfa flag enforcement, path canonicalization and containment (sandbox directory), file:// scheme blocking, allowAllFiles stripping, require() registry rebuild
- Check: Verify that every JS library and protocol helper (krbforge, mysql, require, headless file://, payload loaders) enforces the -lfa flag and path containment; a sibling path that skips the -lfa check is a sandbox escape.
### 3. Network policy (host allowlist) enforcement before outbound connections
- Guard that should hold everywhere: IsHostAllowed check on the actual target host (controller, not domain), proxy validation and connectivity check, ProxyInternal gate for HTTP_PROXY env
- Check: Inspect other dialing paths (e.g., HTTP, headless) to ensure they apply the same host allowlist check on the resolved IP/host, not just a user-supplied domain, and that proxy settings cannot redirect traffic to internal hosts.
- Check: Audit all file-write and file-read paths that accept template-controlled paths (e.g., template extraction, payload loading) to ensure they use canonical containment, not lexical prefix checks, and apply the same sandbox directory restriction.
These are real security fixes mined from git history. Use them as regression checks.
- **Auth Bypass** (high) [CWE-287]: Honors disable-cookie by preventing the shared cookie jar from being applied when cookie handling is disabled, closing a path where cookies could be reused across requests.
- sink: `SetCookieJar(input.CookieJar)`
- fix: Adds !request.DisableCookie check before applying shared cookie jar
- **Code Execution** (high) [CWE-347]: This commit fixes a cache poisoning vulnerability where unsigned templates could bypass signature verification and execute malicious code during compilation or request execution.
- sink: `template compilation and execution of JavaScript`
- fix: cache invalidation based on verification status, verifier fingerprint, and content digest
- **Code Execution via Unsigned Template** (high) [CWE-347]: Enforces signature verification on JavaScript templates, preventing execution of unsigned templates that could lead to arbitrary code execution.
- sink: `loading unsigned javascript templates into execution paths`
- fix: Require signature verification for javascript templates in direct loading and workflows when signing is enforced
- **Arbitrary File Read** (high) [CWE-22]: Gates MySQL's allowAllFiles option behind the -lfa flag, preventing arbitrary local file reads via LOAD DATA LOCAL INFILE.
- sink: `sql.Open("mysql", dsn) with AllowAllFiles=true`
- fix: DSN sandbox that strips allowAllFiles unless -lfa is set
- **Code Execution** (critical) [CWE-94]: Moves the unsigned code-template guard ahead of the DAST branch, preventing unsigned code templates from being loaded and executed under DAST, which previously bypassed the signature check.
- sink: `Template loading and execution`
- fix: Hoisting unsigned code-template guard before DAST branch to ensure it applies on all load paths
- **Information Disclosure** (medium) [CWE-200]: This commit fixes a data leakage issue in workflows where sibling state could leak across concurrent executions, and race requests ignored dynamic values, by syncing context and cloning inputs.
- **Race Condition** (medium) [CWE-362]: Fixes a race condition in workflow execution caused by shared context callbacks, which could lead to data corruption or crashes; the primary impact is reliability, not a direct security breach.
- sink: `shared context callbacks in workflow execution`
- fix: fix race condition by making workflow execution sequential
- **Auth Bypass** (high) [CWE-347]: Fixes template signature verification by centralizing signature extraction and requiring the signature to be at the end of the template, preventing bypass.
- **Dependency Vulnerability** (medium) [CWE-1104]: Upgrades Alpine base image from 3.18.5 to 3.18.6 to fix known security vulnerabilities in bundled packages.
- **Dependency Vulnerability** (medium) [CWE-1104]: Upgrades Alpine base image from 3.18.2 to 3.18.5 to fix known security vulnerabilities in bundled packages.
- **Dependency Vulnerability** (high) [CWE-1035]: Updates go-git to fix known vulnerabilities (CVE-2023-49569, CVE-2023-49568), which could be exploited when processing untrusted git data.
- **Code Execution via Unsigned Template** (high) [CWE-347]: Introduces a flag to disable unsigned templates, preventing execution of unverified templates that could lead to arbitrary code execution.
- sink: `loading unsigned templates when -dut flag is set`
- fix: Adds -disable-unsigned-templates flag to skip unsigned templates and report them separately
- **Auth Bypass** (medium) [CWE-347]: This commit introduces a flag to skip unsigned templates, closing a path where an attacker could execute untrusted templates by bypassing signature verification.
- sink: `parsed.Verified`
- fix: skip unverified templates when DisableUnsignedTemplates is set
- **Deserialization of Untrusted Data** (medium) [CWE-502]: Fixes JSON deserialization by adding explicit UnmarshalJSON methods and correcting tags, preventing type confusion and potential logic bypasses.
- sink: `UnmarshalJSON on user-controlled fields like Type and Name`
- fix: Adds proper UnmarshalJSON implementations and corrects json tags to prevent type confusion
- **Sandbox Escape** (medium) [CWE-22]: The commit adds sandbox mode that restricts payload file paths to the template directory, preventing arbitrary file reads when sandbox is enabled.
- sink: `loadPayloadsFromFile`
- fix: path prefix validation against template directory and template path directory
- **Sandbox Escape** (high) [CWE-250]: The commit restricts the use of the --no-sandbox flag to Linux root users, preventing sandbox escape vulnerabilities in other environments.
- sink: `NoSandbox(true)`
- fix: Conditionally disable sandbox only on Linux as root
- **Path Traversal** (high) [CWE-22]: This commit fixes a zip-slip path traversal vulnerability by validating the extracted file path against the configured template directory.
- **SSRF** (high) [CWE-918]: Adds validation and connectivity checks for SOCKS5 proxies before launching a scan, preventing SSRF through proxy configuration.
- sink: `Proxy connection validation and loading`
- fix: Proxy server validation and connectivity check before scan launch
- **Sandbox Escape** (high) [CWE-284]: This commit adds a sandbox flag that, when enabled, restricts the tengo scripting engine to safe modules, preventing sandbox escape and arbitrary command execution.
- **Sandbox Escape** (high) [CWE-284]: This commit restricts the tengo scripting engine to a safe module list, preventing sandbox escape and arbitrary command execution via workflow templates.
returnfmt.Errorf("incorrect number of results: %d (actual) vs %v (expected) \nResults:\n\t%s\n",len(results),expectedNumbers,strings.Join(results,"\n\t"))// nolint:all
}
returnnil
}
funcnormalizeSplit(strstring)[]string{
returnstrings.FieldsFunc(str,func(rrune)bool{
returnr==','
})
}
// filterLines applies all filtering functions to the results
funcfilterLines(results[]string)[]string{
results=filterHeadlessLogs(results)
results=filterUnsignedTemplatesWarnings(results)
returnresults
}
// if chromium is not installed go-rod installs it in .cache directory
// this function filters out the logs from download and installation
flagSet.SetDescription(`Nuclei is a fast, template based vulnerability scanner focusing
on extensive configurability, massive extensibility and ease of use.`)
// Shared PD flags (e.g. -max-time soft-kill via interrupt).
flagSet.AddCommonFlags()
/* TODO Important: The defined default values, especially for slice/array types are NOT DEFAULT VALUES, but rather implicit values to which the user input is appended.
This can be very confusing and should be addressed
*/
@@ -253,16 +270,21 @@ on extensive configurability, massive extensibility and ease of use.`)
flagSet.CreateGroup("input","Target",
flagSet.StringSliceVarP(&options.Targets,"target","u",nil,"target URLs/hosts to scan",goflags.CommaSeparatedStringSliceOptions),
flagSet.StringVarP(&options.TargetsFilePath,"list","l","","path to file containing a list of target URLs/hosts to scan (one per line)"),
flagSet.StringVarP(&options.InlineTargetsList,"targets-inline","","","inline multiline target list (for use in template profiles)"),
flagSet.StringSliceVarP(&options.ExcludeTargets,"exclude-hosts","eh",nil,"hosts to exclude to scan from the input list (ip, cidr, hostname)",goflags.FileCommaSeparatedStringSliceOptions),
flagSet.StringVar(&options.Resume,"resume","","resume scan using resume.cfg (clustering will be disabled)"),
flagSet.StringVar(&options.Resume,"resume","","resume scan from and save to specified file (clustering will be disabled)"),
flagSet.BoolVarP(&options.ScanAllIPs,"scan-all-ips","sa",false,"scan all the IP's associated with dns record"),
flagSet.StringSliceVarP(&options.IPVersion,"ip-version","iv",nil,"IP version to scan of hostname (4,6) - (default 4)",goflags.CommaSeparatedStringSliceOptions),
flagSet.BoolVarP(&options.DisableURLNormalization,"disable-url-normalization","dun",false,"keep targets exactly as supplied instead of collapsing urls that address the same resource"),
flagSet.IntVarP(&options.MaxURLsPerPattern,"max-urls-per-pattern","mup",0,"scan at most this many urls sharing one structural shape, e.g. /user/1 and /user/2 (0 to scan all)"),
flagSet.StringVarP(&options.InputFileMode,"input-mode","im","list",fmt.Sprintf("mode of input file (%v)",provider.SupportedInputFormats())),
flagSet.BoolVarP(&options.FormatUseRequiredOnly,"required-only","ro",false,"use only required fields in input format when generating requests"),
flagSet.BoolVarP(&options.SkipFormatValidation,"skip-format-validation","sfv",false,"skip format validation (like missing vars) when parsing input file"),
flagSet.BoolVarP(&options.VarsTextTemplating,"vars-text-templating","vtt",false,"enable text templating for vars in input file (only for yaml input mode)"),
flagSet.StringSliceVarP(&options.VarsFilePaths,"var-file-paths","vfp",nil,"list of yaml file contained vars to inject into yaml input",goflags.CommaSeparatedStringSliceOptions),
)
flagSet.CreateGroup("templates","Templates",
@@ -277,7 +299,7 @@ on extensive configurability, massive extensibility and ease of use.`)
flagSet.BoolVar(&options.Validate,"validate",false,"validate the passed templates to nuclei"),
flagSet.BoolVarP(&options.NoStrictSyntax,"no-strict-syntax","nss",false,"disable strict syntax check on templates"),
flagSet.BoolVarP(&options.TemplateDisplay,"template-display","td",false,"displays the templates content"),
flagSet.BoolVar(&options.TemplateList,"tl",false,"list all available templates"),
flagSet.BoolVar(&options.TemplateList,"tl",false,"list all templates matching current filters"),
flagSet.BoolVar(&options.TagList,"tgl",false,"list all available tags"),
flagSet.StringSliceVarConfigOnly(&options.RemoteTemplateDomainList,"remote-template-domain",[]string{"cloud.projectdiscovery.io"},"allowed domain list to load remote templates from"),
flagSet.BoolVar(&options.SignTemplates,"sign",false,"signs the templates with the private key defined in NUCLEI_SIGNATURE_PRIVATE_KEY env variable"),
@@ -286,6 +308,14 @@ on extensive configurability, massive extensibility and ease of use.`)
flagSet.StringVar(&options.LLMBaseURL,"llm-base-url","","openai-compatible endpoint for semantic matching (overrides -llm-provider, e.g. a local model)"),
flagSet.StringVar(&options.LLMModel,"llm-model","","model used for semantic matching"),
flagSet.IntVar(&options.LLMTimeout,"llm-timeout",30,"time in seconds to wait for a single llm call"),
flagSet.IntVar(&options.LLMMaxCalls,"llm-max-calls",5000,"maximum llm calls per scan (0 for unlimited)"),
flagSet.BoolVarP(&options.JSONL,"jsonl","j",false,"write output in JSONL(ines) format"),
flagSet.BoolVarP(&options.JSONRequests,"include-rr","irr",true,"include request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only) [DEPRECATED use `-omit-raw`]"),
flagSet.BoolVarP(&options.OmitRawRequests,"omit-raw","or",false,"omit request/response pairs in the JSON, JSONL, and Markdown outputs (for findings only)"),
flagSet.BoolVarP(&options.OmitRawRequests,"omit-raw","or",false,"omit request/response pairs in the JSON, JSONL, Markdown, and PDF outputs (for findings only)"),
flagSet.BoolVarP(&options.OmitTemplate,"omit-template","ot",false,"omit encoded template in the JSON, JSONL output"),
flagSet.BoolVarP(&options.NoMeta,"no-meta","nm",false,"disable printing result metadata in cli output"),
flagSet.BoolVarP(&options.Timestamp,"timestamp","ts",false,"enables printing timestamp in cli output"),
@@ -323,12 +353,13 @@ on extensive configurability, massive extensibility and ease of use.`)
flagSet.StringVarP(&options.SarifExport,"sarif-export","se","","file to export results in SARIF format"),
flagSet.StringVarP(&options.JSONExport,"json-export","je","","file to export results in JSON format"),
flagSet.StringVarP(&options.JSONLExport,"jsonl-export","jle","","file to export results in JSONL(ine) format"),
flagSet.StringVarP(&options.PDFExport,"pdf-export","pe","","file to export results in PDF format"),
flagSet.StringSliceVarP(&options.Redact,"redact","rd",nil,"redact given list of keys from query parameter, request header and body",goflags.CommaSeparatedStringSliceOptions),
)
flagSet.CreateGroup("configs","Configurations",
flagSet.StringVar(&cfgFile,"config","","path to the nuclei configuration file"),
flagSet.StringVarP(&templateProfile,"profile","tp","","template profile config file to run"),
flagSet.StringVar(&selectedFiles.Config,"config","","path to the nuclei configuration file"),
flagSet.StringVarP(&selectedFiles.Profile,"profile","tp","","template profile config file to run"),
flagSet.BoolVarP(&options.ListTemplateProfiles,"profile-list","tpl",false,"list community template profiles"),
flagSet.BoolVarP(&options.FollowRedirects,"follow-redirects","fr",false,"enable following redirects for http templates"),
flagSet.BoolVarP(&options.FollowHostRedirects,"follow-host-redirects","fhr",false,"follow redirects on the same host"),
@@ -350,14 +381,16 @@ on extensive configurability, massive extensibility and ease of use.`)
flagSet.BoolVar(&options.ZTLS,"ztls",false,"use ztls library with autofallback to standard one for tls13 [Deprecated] autofallback to ztls is enabled by default"),//nolint:all
flagSet.StringVar(&options.SNI,"sni","","tls sni hostname to use (default: input domain name)"),
flagSet.DurationVarP(&options.DialerKeepAlive,"dialer-keep-alive","dka",0,"keep-alive duration for network requests."),
flagSet.BoolVarP(&options.AllowLocalFileAccess,"allow-local-file-access","lfa",false,"allows file (payload) access anywhere on the system"),
flagSet.BoolVarP(&options.AllowLocalFileAccess,"allow-local-file-access","lfa",false,"allow all templates in the run to read any file on the system (not just payloads)"),
flagSet.BoolVarP(&options.RestrictLocalNetworkAccess,"restrict-local-network-access","lna",false,"blocks connections to the local / private network"),
flagSet.StringVarP(&options.Interface,"interface","i","","network interface to use for network scan"),
flagSet.StringVarP(&options.AttackType,"attack-type","at","","type of payload combinations to perform (batteringram,pitchfork,clusterbomb)"),
flagSet.BoolVarP(&options.PayloadRandomOrder,"payload-random-order","pro",false,"iterate payload combinations in a random order instead of sequentially"),
flagSet.StringVarP(&options.SourceIP,"source-ip","sip","","source ip address to use for network scan"),
flagSet.IntVarP(&options.ResponseReadSize,"response-size-read","rsr",0,"max response size to read in bytes"),
flagSet.IntVarP(&options.ResponseSaveSize,"response-size-save","rss",unitutils.Mega,"max response size to read in bytes"),
flagSet.CallbackVar(resetCallback,"reset","reset removes all nuclei configuration and data files (including nuclei-templates)"),
flagSet.IntVarP(&options.RequestSaveSize,"request-size-save","rqss",32*unitutils.Kilo,"max request body size to save in bytes (0 to save the whole body)"),
flagSet.CallbackVar(func(){resetRequested=true},"reset","reset removes all nuclei configuration and data files (including nuclei-templates)"),
flagSet.StringVarP(&options.DASTProxyAuth,"dast-proxy-auth","dtpau","","dast proxy basic auth in user:pass format (required for non-loopback address)"),
flagSet.BoolVarP(&options.DisplayFuzzPoints,"display-fuzz-points","dfp",false,"display fuzz points in the output for debugging"),
flagSet.IntVar(&options.FuzzParamFrequency,"fuzz-param-frequency",10,"frequency of uninteresting parameters for fuzzing before skipping"),
flagSet.IntVarP(&options.RateLimitMinute,"rate-limit-minute","rlm",0,"maximum number of requests to send per minute (DEPRECATED)"),
flagSet.IntVarP(&options.BulkSize,"bulk-size","bs",25,"maximum number of hosts to be analyzed in parallel per template"),
flagSet.IntVarP(&options.TemplateThreads,"concurrency","c",25,"maximum number of templates to be executed in parallel"),
@@ -408,6 +447,7 @@ on extensive configurability, massive extensibility and ease of use.`)
flagSet.IntVarP(&options.JsConcurrency,"js-concurrency","jsc",120,"maximum number of javascript runtimes to be executed in parallel"),
flagSet.IntVarP(&options.PayloadConcurrency,"payload-concurrency","pc",25,"max payload concurrency for each template"),
flagSet.IntVarP(&options.ProbeConcurrency,"probe-concurrency","prc",50,"http probe concurrency with httpx"),
flagSet.IntVarP(&options.TemplateLoadingConcurrency,"template-loading-concurrency","tlc",types.DefaultTemplateLoadingConcurrency,"maximum number of concurrent template loading operations"),
flagSet.DurationVarP(&options.InputReadTimeout,"input-read-timeout","irt",time.Duration(3*time.Minute),"timeout on input read"),
flagSet.BoolVar(&options.ResponseCache,"response-cache",false,"reuse identical safe GET/HEAD responses within a scan (lossless: skips requests with auth, cookies, body or custom headers)"),
flagSet.BoolVarP(&options.DisableHTTPProbe,"no-httpx","nh",false,"disable httpx probing for non-url input"),
flagSet.BoolVarP(&options.StrictProbe,"strict-probe","stp",false,"skip templates whose target service is unreachable: HTTP/headless on hosts httpx could not confirm and network templates on closed ports (lossless, no raw-input fallback)"),
flagSet.BoolVarP(&options.TechFilter,"tech-filter","tf",false,"opt-in: fingerprint HTTP targets and skip product/macro-tagged templates that cannot match (off by default; enables scan-scoped GET cache; fail-open; no-op if no tech-bound templates)"),
flagSet.BoolVar(&options.PreflightPortScan,"preflight-portscan",false,"run preflight resolve + TCP portscan and filter targets before scanning (disabled by default)"),
flagSet.BoolVar(&options.EnableHTTPCache,"http-cache",false,"enable HTTP cache (RFC 9111) for HTTP requests"),
)
flagSet.CreateGroup("headless","Headless",
@@ -436,6 +481,7 @@ on extensive configurability, massive extensibility and ease of use.`)
flagSet.BoolVarP(&options.ShowBrowser,"show-browser","sb",false,"show the browser on the screen when running templates with headless mode"),
flagSet.StringSliceVarP(&options.HeadlessOptionalArguments,"headless-options","ho",nil,"start headless chrome with additional options",goflags.FileCommaSeparatedStringSliceOptions),
flagSet.BoolVarP(&options.UseInstalledChrome,"system-chrome","sc",false,"use local installed Chrome browser instead of nuclei installed"),
flagSet.StringVarP(&options.CDPEndpoint,"cdp-endpoint","cdpe","","use remote browser via Chrome DevTools Protocol (CDP) endpoint"),
flagSet.BoolVarP(&options.ShowActions,"list-headless-action","lha",false,"list available headless actions"),
)
@@ -445,6 +491,7 @@ on extensive configurability, massive extensibility and ease of use.`)
flagSet.BoolVarP(&options.DebugResponse,"debug-resp","dresp",false,"show all received responses"),
flagSet.StringSliceVarP(&options.Proxy,"proxy","p",nil,"list of http/socks5 proxy to use (comma separated or file input)",goflags.FileCommaSeparatedStringSliceOptions),
flagSet.BoolVarP(&options.ProxyInternal,"proxy-internal","pi",false,"proxy all internal requests"),
flagSet.StringVarP(&options.ReplayProxy,"replay-proxy","rp","","http/socks5 proxy to re-send requests that produced a finding through (e.g. burp)"),
flagSet.BoolVarP(&options.ListDslSignatures,"list-dsl-function","ldf",false,"list all supported DSL function signatures"),
flagSet.StringVarP(&options.TraceLogFile,"trace-log","tlog","","file to write sent requests trace log"),
flagSet.StringVarP(&options.ErrorLogFile,"error-log","elog","","file to write sent requests error log"),
@@ -463,8 +510,15 @@ on extensive configurability, massive extensibility and ease of use.`)
flagSet.CreateGroup("update","Update",
flagSet.BoolVarP(&updateNucleiBinary,"update","up",false,"update nuclei engine to the latest released version"),
flagSet.BoolVarP(&options.UpdateTemplates,"update-templates","ut",false,"update nuclei-templates to latest released version"),
@@ -545,7 +619,7 @@ Additional documentation is available at: https://docs.nuclei.sh/getting-started
h:=&pdcp.PDCPCredHandler{}
_,err:=h.GetCreds()
iferr!=nil{
options.Logger.Fatal().Msg("To utilize the `-ai` flag, please configure your API key with the `-auth` flag or set the `PDCP_API_KEY` environment variable")
fatalf("To utilize the `-ai` flag, please configure your API key with the `-auth` flag or set the `PDCP_API_KEY` environment variable")
}
}
@@ -564,69 +638,34 @@ Additional documentation is available at: https://docs.nuclei.sh/getting-started
Loaded 100 of 1266 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.