Documentation
¶
Overview ¶
Package scanner implements HTTP-based black-box security checks. Each check is a function that takes a scan config and endpoint, sends HTTP requests, and returns findings based on the responses.
Index ¶
- Constants
- Variables
- func CheckAuth(ctx context.Context, cfg *models.ScanConfig, endpoint Endpoint) []ev.Evidence
- func CheckCORS(ctx context.Context, cfg *models.ScanConfig, endpoint Endpoint) []ev.Evidence
- func CheckConfigLeak(ctx context.Context, cfg *models.ScanConfig, endpoint Endpoint) []ev.Evidence
- func CheckExposure(ctx context.Context, cfg *models.ScanConfig, endpoint Endpoint) []ev.Evidence
- func CheckHeaders(ctx context.Context, cfg *models.ScanConfig, endpoint Endpoint) []ev.Evidence
- func CheckIDOR(ctx context.Context, cfg *models.ScanConfig, endpoint Endpoint) []ev.Evidence
- func CheckInjection(ctx context.Context, cfg *models.ScanConfig, endpoint Endpoint) []ev.Evidence
- func CheckInjectionWithAudit(ctx context.Context, cfg *models.ScanConfig, endpoint Endpoint, ...) []ev.Evidence
- func CheckRateLimit(ctx context.Context, cfg *models.ScanConfig, endpoint Endpoint) []ev.Evidence
- func PrintDisclaimer()
- func ProbeExcerpt(body string) string
- func ProbeTimingExcerpt(elapsed, threshold time.Duration) string
- func ResetGlobalAuditLog()
- type Check
- type CheckContext
- type CheckFn
- type Crawler
- type Endpoint
- type ProbeAuditLog
- type ProbeLocation
- type ProbeRecord
- type ProbeType
- type SSRFCheck
- type Tier
Constants ¶
const ActiveDisclaimer = `` /* 257-byte string literal not displayed */
ActiveDisclaimer is printed to stderr when --enable-active is used.
const MaxProbesPerEndpoint = 20
MaxProbesPerEndpoint is the default cap on active probes per endpoint when ScanConfig.MaxProbesPerEndpoint is unset (zero). The cap is overridable via the --max-probes-per-endpoint CLI flag (TASK-086).
Variables ¶
var CommonPaths = []string{}/* 117 elements not displayed */
CommonPaths is a hardcoded list of frequently found API paths to brute-force. Curated for high signal — admin surfaces, source-control leakage, common dev tooling. Override with --wordlist for custom lists. ~100 entries.
Functions ¶
func CheckAuth ¶
CheckAuth runs authentication checks on an endpoint. When auth is configured, it tests: unauthenticated access, malformed JWT, expired JWT, and alg:none JWT confusion.
func CheckCORS ¶
CheckCORS sends a request with an evil Origin header and checks for CORS misconfigurations. Covers 4 scenarios:
- Wildcard ACAO + credentials → CRITICAL
- Wildcard ACAO without credentials → MEDIUM
- Reflected arbitrary origin → HIGH
- Non-standard methods allowed → LOW
func CheckConfigLeak ¶
CheckConfigLeak hits the endpoint and emits a CRITICAL "exposed config file" finding when (a) the endpoint's path matches a known config-file leak pattern AND (b) the response is 200-series (the server is actually serving the file).
Cheap to run — single HEAD-style GET, no probes, no body parse beyond a length check. Designed to slot into the worker pool as the first check so noisier downstream checks (headers / cors / ratelimit) can be deduped naturally by the existing pipeline when they fire on the same path.
func CheckExposure ¶
CheckExposure scans response bodies for sensitive data patterns.
func CheckHeaders ¶
CheckHeaders sends a GET request and checks for missing/misconfigured security headers.
func CheckIDOR ¶
CheckIDOR performs Insecure Direct Object Reference detection using two authenticated accounts. It sends the endpoint request with user1 and user2 credentials and flags broken object-level authorization.
Two detection modes:
- id-mutation (cross-tenant): when the endpoint carries an object identifier (numeric/UUID path segment or id-shaped query value), user2 hitting user1's identifier and getting 2xx is a direct access-control bypass → HIGH confidence (body emptiness is not the signal; access is).
- same-URL fallback: when no identifier is detectable, two identical /structurally-equivalent 2xx responses suggest a shared/global resource or missing authz → MEDIUM confidence (heuristic).
Requires cfg.AuthUser2 to be set (--auth-user2 flag).
func CheckInjection ¶
CheckInjection runs active injection probes on an endpoint. This function MUST only be called when cfg.EnableActive is true. It runs SQLi (time/error/boolean), CMDi, and CRLF probes across each declared query/header/body parameter.
func CheckInjectionWithAudit ¶
func CheckInjectionWithAudit(ctx context.Context, cfg *models.ScanConfig, endpoint Endpoint, auditLog *ProbeAuditLog) []ev.Evidence
CheckInjectionWithAudit runs active injection probes with a provided audit log. Iterates over (param, location) pairs returned by targetsForEndpoint — query params, header params, and (for POST/PUT/PATCH) body fields — and runs all configured probe types against each. The per-endpoint probe budget (cfg.MaxProbesPerEndpoint, default 20) caps total probe count.
func CheckRateLimit ¶
CheckRateLimit sends multiple rapid requests to detect rate limiting. If all requests succeed with no 429 or rate-limit headers, it reports a finding.
func PrintDisclaimer ¶
func PrintDisclaimer()
PrintDisclaimer writes the active scanning disclaimer to stderr.
func ProbeExcerpt ¶
ProbeExcerpt returns a bounded, control-character-free excerpt of what an active probe observed, for storage on evidence.Evidence.Response.
WHY THIS EXISTS: confidence.payloadValidated requires BOTH Payload and Response, and the decision layer counts "payload-validated probe" as an INDEPENDENT corroborating signal. No production producer set Response, so both were dead — and the decision layer had been leaning on a tautology ("Source is blackbox") in their place, which is the RC-1 defect. Recording what came back is what makes the honest signal real.
Response is Evidence-INTERNAL: evidence.ToFinding drops it, so it never reaches models.Finding, the JSON report or SARIF. It exists to justify a decision, not to be published.
Deterministic by construction — a pure function of the input string — because it feeds a confidence score that must be reproducible across runs.
func ProbeTimingExcerpt ¶
ProbeTimingExcerpt renders the timing differential that confirmed a timing-based probe (blind SQLi, SSRF hang detection) as the response observation.
For a timing check the confirming observation is NOT the body — the body proves nothing and is often empty. It is the elapsed time relative to the threshold the check tested against. Recording that is truthful; recording an unread body would be fabrication, and recording nothing would leave the check unable to corroborate a differential it genuinely measured.
func ResetGlobalAuditLog ¶
func ResetGlobalAuditLog()
ResetGlobalAuditLog clears the per-scan audit log. Call this at the top of every scan run; otherwise records leak across runs in long-running processes (tests, future server mode).
It also clears any per-origin once-per-scan guards (e.g. the GraphQL origin sweep) so that origin-scoped checks start fresh each scan and do not leak "already swept" state across runs/tests.
Types ¶
type Check ¶
type Check interface {
Name() string // stable id, e.g. "configleak"
Category() string // ev.Evidence.Category bucket
Tier() Tier // intrusiveness / input class
Enabled(cfg *models.ScanConfig) bool // tier-implied gate
Run(ctx context.Context, cc *CheckContext, ep Endpoint) []ev.Evidence
}
Check is the unit of black-box detection. Implementations are stateless adapter structs registered in DefaultChecks().
func AsCheck ¶
func AsCheck(name, category string, tier Tier, enabled func(*models.ScanConfig) bool, fn CheckFn) Check
AsCheck adapts an existing free CheckFn into the Check interface so the engine worker-pool tests (which pass []scanner.CheckFn) keep compiling. The adapter reads cfg/audit from the CheckContext.
func DefaultChecks ¶
func DefaultChecks() []Check
DefaultChecks returns the full ordered check registry. configleak is first so its CRITICAL "exposed config file" finding lands before noisier per-endpoint checks on the same path (dedup ordering). The orchestrator filters this slice by Enabled(cfg) at scan time.
type CheckContext ¶
type CheckContext struct {
Cfg *models.ScanConfig
Client *http.Client
NoFollow *http.Client
Audit *ProbeAuditLog
}
CheckContext is the per-scan execution context handed to every Check.Run.
Client and NoFollow share ONE guarded transport (budget over netguard SSRF policy), so the SSRF egress guard + budget counting are identical on both. Client follows redirects and re-validates the resolved IP on every hop; NoFollow returns the raw 3xx (a redirect IS the signal for auth/idor/ open-redirect/host-header). Checks MUST use one of these — never build their own transport. This is how the historical raw-budget.Transport() SSRF bypass is closed structurally.
Audit is the scan-wide probe log; it aliases the package-global currentAuditLog() so GlobalAuditRecords()/--debug-bundle keep working.
func NewCheckContext ¶
func NewCheckContext(cfg *models.ScanConfig) *CheckContext
NewCheckContext builds the shared context once per scan. The shared clients set Timeout:0 — per-(endpoint,check) deadlines come from a context.WithTimeout inside the worker pool's runCheck, so one global Timeout cannot cap the whole scan under connection reuse.
type CheckFn ¶
CheckFn is the signature for all scanner check functions. Each check receives a context, config, and endpoint, and returns findings.
type Crawler ¶
type Crawler struct {
// Discovered is the number of unique endpoints found BEFORE the
// --max-endpoints cap truncated the returned slice. Equal to len(result)
// when no cap fired. Read by the orchestrator after CrawlEndpoints to
// surface coverage (endpoints_discovered / endpoints_truncated in the
// report) instead of leaving the truncation a silent slog.Warn.
Discovered int
// SpecErr is the error fromSpec returned, when --spec was given and the
// document could not be parsed. Discovery continues with the other
// strategies (unchanged), but the orchestrator reads this to record the
// `spec` analyzer as failed/input_error instead of leaving a silent WARN.
SpecErr error
// contains filtered or unexported fields
}
Crawler discovers API endpoints using multiple strategies.
func NewCrawler ¶
func NewCrawler(cfg *models.ScanConfig) *Crawler
NewCrawler creates a Crawler with an HTTP client configured from scan config.
The transport raises MaxIdleConnsPerHost from Go's default of 2 to a value large enough to keep the brute-force phase reusing one keep-alive connection per host. With the default, ~115 sequential requests against the same host would churn TCP setup/teardown, and on macOS that reliably exhausts ephemeral ports when multiple httptest servers run in parallel — the e2e suite was flaky at exactly that boundary before this fix.
The SSRF egress guard (internal/netguard) is composed UNDERNEATH the budget counter via budget.WrapTransportGuarded, preserving the keep-alive transport fields. CheckRedirect caps redirect hops and re-applies the IP policy per hop. This matters for the crawler specifically because robots.txt / sitemap.xml are fetched at the very start of discovery — before any same-host filter runs — so an attacker-controlled --url could otherwise 30x-redirect those early fetches into the metadata IP or the host's own network. AllowPrivate (operator flag + auto-allow for private --url targets) makes the guard a passthrough.
func (*Crawler) CrawlEndpoints ¶
CrawlEndpoints discovers endpoints using all available strategies in priority order:
- OpenAPI spec parsing (--spec)
- robots.txt parsing (--url) — Disallow/Allow + Sitemap directives
- sitemap.xml parsing (--url) — <loc> entries + sitemapindex recursion
- JavaScript source analysis (--url)
- HTML link parsing with recursive depth (--url, --crawl-depth)
- Common-path brute-force, optionally from --wordlist (--url)
Result is deduplicated, sorted, and capped at --max-endpoints.
type Endpoint ¶
type Endpoint struct {
Method string
Path string
FullURL string
Params []string
Headers []string
BodyParams []string
// AuthExpectation is what a source of truth (today: the OpenAPI spec)
// declares about authentication for this operation. Zero value = unknown,
// which is what every non-spec discovery source (crawl, brute-force,
// robots.txt, JS extraction) leaves it as — correctly, since those observe
// that a path EXISTS and nothing about whether it should be gated.
//
// The auth check reads it to distinguish "this endpoint is public" from
// "this endpoint's authentication requirement was bypassed"; without it,
// checkUnauthenticated could only see a status code and called every 2xx
// CRITICAL (RC-2).
AuthExpectation models.AuthExpectation
}
Endpoint represents a discovered API endpoint to scan.
Params holds query and path parameter names (covered by TASK-081). Headers holds OpenAPI `in: header` parameter names with standard auth headers (Authorization, Cookie, X-Api-Key, ...) filtered out — those are the auth scanner's job, and probing them with malicious payloads risks breaking the test session for downstream endpoints. BodyParams holds JSON body field names extracted from `requestBody` (OpenAPI 3) or `in: body` schema (Swagger 2). Probing them requires emitting a JSON body on POST/PUT/PATCH; see CheckInjectionWithAudit.
type ProbeAuditLog ¶
type ProbeAuditLog struct {
// contains filtered or unexported fields
}
ProbeAuditLog records every active probe for accountability and debugging.
func NewProbeAuditLog ¶
func NewProbeAuditLog() *ProbeAuditLog
NewProbeAuditLog creates a new audit log that writes to stderr.
func NewProbeAuditLogWithWriter ¶
func NewProbeAuditLogWithWriter(w io.Writer) *ProbeAuditLog
NewProbeAuditLogWithWriter creates an audit log with a custom writer (for testing).
func (*ProbeAuditLog) Count ¶
func (a *ProbeAuditLog) Count(endpoint string) int
Count returns the number of probes recorded for a given endpoint.
func (*ProbeAuditLog) Record ¶
func (a *ProbeAuditLog) Record(r ProbeRecord)
Record adds a probe record to the audit log and writes it to the log writer.
func (*ProbeAuditLog) Records ¶
func (a *ProbeAuditLog) Records() []ProbeRecord
Records returns a copy of all recorded probe entries.
type ProbeLocation ¶
type ProbeLocation string
ProbeLocation identifies where in the HTTP request a probe payload is placed. Different vulnerabilities surface in different locations: query params get reflected into URLs and SQL, body params reach the same handlers but bypass query-string-only WAFs, and custom headers (X-Trace-Id, X-User-Role, etc.) often flow into logs and SQL queries.
const ( LocQuery ProbeLocation = "query" LocHeader ProbeLocation = "header" LocBody ProbeLocation = "body" )
type ProbeRecord ¶
type ProbeRecord struct {
Timestamp time.Time `json:"timestamp"`
Endpoint string `json:"endpoint"`
ProbeType ProbeType `json:"probe_type"`
Payload string `json:"payload"`
Parameter string `json:"parameter"`
Method string `json:"method"`
Status int `json:"status_code"`
Duration string `json:"duration"`
Finding bool `json:"finding_generated"`
}
ProbeRecord captures a single probe sent during active scanning.
func GlobalAuditRecords ¶
func GlobalAuditRecords() []ProbeRecord
GlobalAuditRecords returns a snapshot of every probe recorded by the scan-wide audit log. Safe to call after the scan has finished.
type ProbeType ¶
type ProbeType string
ProbeType identifies the kind of active probe.
const ( ProbeSQLi ProbeType = "sqli" ProbeCMDi ProbeType = "cmdi" ProbeCRLF ProbeType = "crlf" ProbeRedirect ProbeType = "redirect" ProbeXSS ProbeType = "xss" ProbeSSRF ProbeType = "ssrf" ProbeHostHeader ProbeType = "host_header" ProbeGraphQL ProbeType = "graphql" ProbeMethodTamper ProbeType = "method_tamper" )
type SSRFCheck ¶
type SSRFCheck struct{}
SSRFCheck is the active in-band SSRF (CWE-918) check. For each URL-shaped target it sends canary fetch probes and classifies the target's response via three in-band signals with precedence (a) error-leak > (b) reflected-fetch > (c) timing. At most one finding is emitted per (param, location).
func (SSRFCheck) Run ¶
Run probes every URL-shaped (param, location) target. Active discipline mirrors probeCMDi / reflectedXSSCheck: a ctx.Done()/budget check before each probe, a ProbeRecord per probe, and auth applied via cfg.Auth.ApplyToRequest. Skips non-2xx/3xx baseline endpoints (a 404 surface is not a feature, same as headers/cors). At most one finding per target, precedence (a)>(b)>(c).
type Tier ¶
type Tier int
Tier classifies a check by intrusiveness and required scan inputs. The orchestrator filters DefaultChecks() by Enabled(cfg) and prints the active-scanning disclaimer iff any enabled check is TierActive.
Tier values are append-only: the iota int is never persisted, but renumbering existing values is a needless footgun. Add new tiers at the end.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
deps
|
|
|
applicability
Package applicability answers one narrow question about a dependency finding: is the sub-component the advisory is actually scoped to ever imported by the scanned tree?
|
Package applicability answers one narrow question about a dependency finding: is the sub-component the advisory is actually scoped to ever imported by the scanned tree? |
|
govulncheck
Package govulncheck runs the upstream govulncheck logic in-process and emits fendix Findings for Go-module CVEs that the user's code actually calls.
|
Package govulncheck runs the upstream govulncheck logic in-process and emits fendix Findings for Go-module CVEs that the user's code actually calls. |
|
neterr
Package neterr types the transport failures the dependency scanners see so the orchestrator can classify them as network_error or timeout without reading error prose.
|
Package neterr types the transport failures the dependency scanners see so the orchestrator can classify them as network_error or timeout without reading error prose. |
|
npm
Package npm runs an in-process npm dependency CVE scan against package-lock.json v2/v3 manifests and emits fendix Findings for any resolved version that matches an OSV.dev vulnerability record.
|
Package npm runs an in-process npm dependency CVE scan against package-lock.json v2/v3 manifests and emits fendix Findings for any resolved version that matches an OSV.dev vulnerability record. |
|
pip
Package pip queries the OSV.dev /v1/query API to find vulnerabilities in Python dependencies declared in requirements.txt manifests.
|
Package pip queries the OSV.dev /v1/query API to find vulnerabilities in Python dependencies declared in requirements.txt manifests. |
|
Package secrets detects hardcoded secrets in source code via regex pattern matching, ported in-process from python/analyzers/secrets.py (TASK-115).
|
Package secrets detects hardcoded secrets in source code via regex pattern matching, ported in-process from python/analyzers/secrets.py (TASK-115). |
|
Package semgrep shells out to a host-installed semgrep binary, running fendix's bundled rule pack and mapping every match to a fendix Finding (TASK-116).
|
Package semgrep shells out to a host-installed semgrep binary, running fendix's bundled rule pack and mapping every match to a fendix Finding (TASK-116). |
|
Package textscan ships a regex-based SAST engine that drives the Sprint-04 (Go), Sprint-05 (JS/TS), and Sprint-06 (Dockerfile + k8s YAML) rulesets in one unified scanner.
|
Package textscan ships a regex-based SAST engine that drives the Sprint-04 (Go), Sprint-05 (JS/TS), and Sprint-06 (Dockerfile + k8s YAML) rulesets in one unified scanner. |