Documentation
¶
Overview ¶
Package core contains the scan Executor — the central orchestrator of a native scan. The Executor receives HttpRequestResponse work items, dispatches them to registered active and passive modules through a bounded worker pool, and collects ResultEvent findings. It owns scope filtering, per-host rate limiting, pre/post hooks, per-module timeouts, context-based cancellation, and the post-EOF feedback drain that lets passive modules re-inject discovered requests. Subpackages provide the rate limiter, network dialer, service container, and scan statistics.
Index ¶
- Constants
- func IsExtensionModule(id string) bool
- func IsLevelDBClosed(err error) bool
- func SortedDropReasons(reasons map[string]int64) []string
- func WithExecutorObserver(ctx context.Context, fn ExecutorObserver) context.Context
- type BaselineFailure
- type DropSample
- type ExecutionReport
- type Executor
- func (e *Executor) BaselineFailures() []BaselineFailure
- func (e *Executor) ConsideredModuleCount() int64
- func (e *Executor) DropReasons() map[string]int64
- func (e *Executor) DropSamples() []DropSample
- func (e *Executor) Execute(ctx context.Context) (bool, error)
- func (e *Executor) FeedbackDropped() int64
- func (e *Executor) InFlight() int64
- func (e *Executor) KnownTotal() int64
- func (e *Executor) MethodPolicySkips() int64
- func (e *Executor) ModuleErrors() map[string]int64
- func (e *Executor) ModuleMetrics() map[string]stats.ModuleStatsSnapshot
- func (e *Executor) ModuleSkips() map[string]map[string]int64
- func (e *Executor) Processed() int64
- func (e *Executor) Report() ExecutionReport
- func (e *Executor) ResolveRequestUUID(requestHash string) string
- func (e *Executor) Responded() int64
- func (e *Executor) StoreFailed() int64
- func (e *Executor) Stored() int64
- func (e *Executor) SuppressedFindings() int64
- func (e *Executor) WriteTemplatesSkipped() int64
- type ExecutorConfig
- type ExecutorObserver
- type FindingAdmission
- type HookRunner
- type HostClaims
- type InsertionPointCache
- func (c *InsertionPointCache) Add(key string, points []httpmsg.InsertionPoint)
- func (c *InsertionPointCache) Get(key string) ([]httpmsg.InsertionPoint, bool)
- func (c *InsertionPointCache) GetOrCompute(raw []byte, requestID string, includeNested bool) ([]httpmsg.InsertionPoint, error)
- func (c *InsertionPointCache) GetOrComputeAll(raw []byte, requestID string, includeNested bool) ([]httpmsg.InsertionPoint, error)
- func (c *InsertionPointCache) Stats() InsertionPointCacheStats
- type InsertionPointCacheStats
- type LedgerSpec
- type OASTFlusher
- type PauseController
- func (p *PauseController) AcquireWorker()
- func (p *PauseController) IsPaused() bool
- func (p *PauseController) Pause()
- func (p *PauseController) Quiesced() bool
- func (p *PauseController) ReleaseWorker()
- func (p *PauseController) Resume()
- func (p *PauseController) WaitIfPaused(ctx context.Context) bool
- type QuarantinedHost
Constants ¶
const ( DropFetchError = "fetch_error" // the request failed in transport (DNS, connect, TLS, timeout) DropBlocked = "blocked" // the answer was a WAF / bot-wall page (see ExecutorConfig.KeepBlocked) DropBudget = "budget" // the request budget refused the send (--max-requests[-per-host]) DropQuarantined = "quarantined" // the host was quarantined as unresponsive DropStoreError = "store_error" // the database refused the write DropOutOfScope = "out_of_scope" // the answer was out of scope and scope applies on ingest )
Drop reasons: why an input item ended without its record in the store.
const ( ModuleErrorException = "exception" ModuleErrorTimeout = "timeout" ModuleErrorPanic = "panic" )
Module error kinds, the error_kind of a module.error event. "load" is the fourth value on the wire; it belongs to extension.failed's loader, not to a module call, so the executor never produces it.
const ( SkipReasonTechFilter = database.SkipTechFilter SkipReasonCannotProcess = database.SkipCannotProcess SkipReasonParamAlreadyFound = database.SkipParamAlreadyFound SkipReasonIPType = database.SkipIPType SkipReasonQuarantined = database.SkipQuarantined SkipReasonTimeout = database.SkipTimeout SkipReasonMethodPolicy = database.SkipMethodPolicy SkipReasonHeaderGated = database.SkipHeaderGated SkipReasonInconclusiveThrottled = database.SkipInconclusiveThrottled )
Module skip reasons, persisted to scans.module_stats. Each names why a module did NOT test something it was considered for — the "why was this not tested?" half of the module ledger. pkg/database owns the list.
const MaxDropSamples = 20
MaxDropSamples bounds the dropped items one run keeps as examples. Enough to name the pattern; the counts carry the size.
const SkipStaticFile = "static_file"
SkipStaticFile is the OnUnanswered reason for an item the static-file filter refused before the send. It is not a drop-ledger reason: the filter is policy, not a failure, and the ledger counts failures.
const SkipWriteTemplate = "write_template"
SkipWriteTemplate is the OnUnanswered reason for a stored request-only stub with a state-changing method that the write-template guard refused to send (ExecutorConfig.AllowWrites). Policy, like SkipStaticFile.
Variables ¶
This section is empty.
Functions ¶
func IsExtensionModule ¶ added in v0.5.3
IsExtensionModule reports whether a module id belongs to a user extension.
func IsLevelDBClosed ¶ added in v0.5.3
IsLevelDBClosed returns true if the error is caused by a closed LevelDB instance, which happens during shutdown when the dedup manager is closed before workers finish. The runner treats it as a fatal phase error.
The typed sentinel (errors.Is) is the primary check and survives any future change to goleveldb's error message, but we keep a string fallback because the error reaches us through module/storage call chains that may format it with %v (non-wrapping), which defeats errors.Is. Matching both is strictly more robust than either alone.
func SortedDropReasons ¶ added in v0.5.5
SortedDropReasons orders reasons most drops first, ties by name, so a report leads with the cause worth fixing.
func WithExecutorObserver ¶ added in v0.5.3
func WithExecutorObserver(ctx context.Context, fn ExecutorObserver) context.Context
WithExecutorObserver returns a context whose Execute calls report their executor to fn. A nil fn returns ctx unchanged.
Types ¶
type BaselineFailure ¶ added in v0.5.3
type BaselineFailure struct {
// Target is the request URL that was attempted.
Target string `json:"target"`
// Class is the transport error class, one of the http.TransportErr*
// constants (dns, refused, timeout, tls, reset, other).
Class string `json:"class"`
// Detail is the error text, truncated.
Detail string `json:"detail"`
}
BaselineFailure is one baseline fetch that got no HTTP answer.
type DropSample ¶ added in v0.5.5
type DropSample struct {
URL string `json:"url"`
Reason string `json:"reason"`
Detail string `json:"detail,omitempty"`
}
DropSample is one dropped item, for reporting.
type ExecutionReport ¶ added in v0.5.2
type ExecutionReport struct {
// StoppedEarly — the input source was not read to EOF (cancelled, deadline,
// or a paused scan that was stopped while waiting).
StoppedEarly bool
// DrainStalled — the feedback drain was abandoned with workers still in
// flight and making no progress.
DrainStalled bool
// WorkersAbandoned — one or more workers did not exit within the shutdown
// grace and were leaked.
WorkersAbandoned bool
// DeferredFlushSkipped — the end-of-run passive flush was skipped because a
// worker was abandoned, so deferred findings (secret detection, anomaly
// ranking) may be incomplete.
DeferredFlushSkipped bool
// Unacked counts work items a worker dequeued but deliberately did NOT
// acknowledge, because the context was already cancelled when it got them.
// Not acknowledging is what keeps the durable cursor behind them so a later
// run re-serves them; this number is how many that was.
Unacked int64
// ScopeRejected counts input items this run dropped as out of scope, before
// or after the baseline fetch. Not a coverage gap (scope is the operator's
// choice), so Clean ignores it; a consumer compares it with Responded to
// spot a run whose every input was rejected.
ScopeRejected int64
// ScopeRejectedBy splits ScopeRejected by the scope rule class that refused
// each item (host, path, static_file, status_code, …).
ScopeRejectedBy map[string]int64
// Responded counts input items this run got an HTTP response for.
Responded int64
// SkippedQuarantined counts input items this run dropped because their
// host:port was quarantined by the dead-host breaker — before dispatch, or
// when the baseline fetch was refused for the same reason. A coverage gap
// (the runner reports it as targets_unreachable), but not one Clean
// covers: it is the target's doing, not the executor's.
SkippedQuarantined int64
// QuarantinedHosts breaks SkippedQuarantined down per host:port, sorted
// by host and capped.
QuarantinedHosts []QuarantinedHost
// FindingsCapped counts, per module, the distinct findings the
// --max-findings-per-module cap dropped. With a FindingAdmission shared
// across executors (dynamic assessment's rounds) it is the running total of
// that shared state, so a caller summing reports must not add rounds.
FindingsCapped map[string]int64
// ModuleStats is this executor's per-module metrics (calls, requests,
// findings, errors) at report time.
ModuleStats map[string]stats.ModuleStatsSnapshot
// FeedbackDropped counts discovered requests modules fed back that were
// dropped because the feedback overflow list was full. A coverage gap the
// runner reports as feedback_dropped.
FeedbackDropped int64
// ModuleSkips is module id → skip reason → count (reasons: SkipReason*
// constants). Cumulative over the executor's lifetime; an executor normally
// runs one Execute. The runner persists it to scans.module_stats.
ModuleSkips map[string]map[string]int64
}
ExecutionReport says whether one Execute call processed its whole input, and what it gave up on if not.
Execute returns (bool, error) where the bool is "produced findings" and the error is nil on every one of these paths: a cancelled feed, an abandoned drain, abandoned workers, a skipped deferred flush. Each of those silently reduces coverage, and the caller had no way to learn about any of them — a scan whose workers were abandoned mid-flight reported exactly what a clean one did. This is that missing channel.
func (ExecutionReport) Clean ¶ added in v0.5.2
func (r ExecutionReport) Clean() bool
Clean reports whether the run covered its whole input with nothing abandoned.
A convenience for callers and tests that want the one-line question. The runner's own consumer (phaseTracker.noteExecution) deliberately does not use it: each flag maps to a distinct outcome reason code, so it has to read them individually.
type Executor ¶
type Executor struct {
// contains filtered or unexported fields
}
Executor orchestrates scanning with worker pool.
func NewExecutor ¶
func NewExecutor( cfg ExecutorConfig, src source.InputSource, activeModules []modules.ActiveModule, passiveModules []modules.PassiveModule, ) *Executor
NewExecutor creates a new Executor with the given configuration.
func (*Executor) BaselineFailures ¶ added in v0.5.3
func (e *Executor) BaselineFailures() []BaselineFailure
BaselineFailures returns the most recent baseline fetches that got no HTTP answer (at most 16), oldest first, each with its transport error class. With Responded() == 0 they are the explanation for an unreachable target. Fetches abandoned because the phase was cancelled are not included.
func (*Executor) ConsideredModuleCount ¶
ConsideredModuleCount returns the number of distinct modules whose CanProcess has been evaluated at least once during this scan. Reaches parity with the total enabled-module count once every module has been seen — including those whose CanProcess always rejects the input shape (e.g., POST-only modules in a GET-only scan). Use this for "modules scanned X/Y" status displays.
func (*Executor) DropReasons ¶ added in v0.5.5
DropReasons returns how many input items ended without a stored record, per reason (the Drop* constants). Reasons with no drops are absent.
func (*Executor) DropSamples ¶ added in v0.5.5
func (e *Executor) DropSamples() []DropSample
DropSamples returns the first few dropped items, in the order they dropped.
func (*Executor) Execute ¶
Execute runs the scan. Blocks until all inputs are processed or context is cancelled.
func (*Executor) FeedbackDropped ¶
FeedbackDropped returns the number of feedback items dropped due to channel capacity.
func (*Executor) InFlight ¶
InFlight returns the number of worker goroutines currently processing items. Zero means the executor is quiescent (all workers idle, no items in flight). Exposed for status reporting — callers typically combine this with source-level idle signals to distinguish "still doing work" from "waiting for input."
func (*Executor) KnownTotal ¶ added in v0.5.3
KnownTotal returns the number of items the executor's input source says it holds, or 0 when the source cannot say (it does not implement source.Countable).
Read live, not captured at construction: a database-backed source learns its count on its first Next, so a reading taken before the run starts is 0 and a later one is the real bound.
func (*Executor) MethodPolicySkips ¶ added in v0.5.7
MethodPolicySkips is how many records this executor kept out of the active stage because the traffic policy refused their method.
func (*Executor) ModuleErrors ¶ added in v0.5.3
ModuleErrors returns this executor's per-module error counts (exceptions, timeouts and panics), keyed by module id. Empty when no module failed.
func (*Executor) ModuleMetrics ¶
func (e *Executor) ModuleMetrics() map[string]stats.ModuleStatsSnapshot
ModuleMetrics returns a point-in-time snapshot of per-module performance metrics.
func (*Executor) ModuleSkips ¶ added in v0.5.7
ModuleSkips returns module → skip reason → count for this executor.
func (*Executor) Report ¶ added in v0.5.2
func (e *Executor) Report() ExecutionReport
Report returns this executor's coverage self-report. Call it after Execute has returned; before that the fields are still being written.
func (*Executor) ResolveRequestUUID ¶
ResolveRequestUUID resolves a request hash to its database record UUID. Implements modkit.RequestUUIDResolver.
func (*Executor) Responded ¶
Responded returns how many input items produced an HTTP response, which is always <= Processed(). Use this, not Processed(), to report how many targets answered: Processed() counts attempts, including the ones that never reached a server. See the responded field for why the two differ.
func (*Executor) StoreFailed ¶ added in v0.5.2
StoreFailed returns the number of input items whose primary record could not be written. Distinct from an item that was never stored because it got no response (Processed() minus Responded()) or because a filter dropped it: this one reached the database and the database refused it.
func (*Executor) Stored ¶ added in v0.5.2
Stored returns the number of input items whose primary record is in the database when this executor finished with them. Use this, not Processed(), to report how many records a run PERSISTED: Processed() counts attempts, and an attempt that never reached a host, or whose write failed, stores nothing.
func (*Executor) SuppressedFindings ¶
SuppressedFindings returns the number of candidate findings dropped by the body-differential safety net because a real payload-vs-baseline difference could not be re-confirmed.
func (*Executor) WriteTemplatesSkipped ¶ added in v0.5.8
WriteTemplatesSkipped is how many stored request-only stubs with a state-changing method the executor refused to send (ExecutorConfig.AllowWrites).
type ExecutorConfig ¶
type ExecutorConfig struct {
Workers int
OnResult func(*output.ResultEvent)
OnCandidate func(*output.ResultEvent)
OnObservation func(*output.ResultEvent)
OnTraffic func(method, url string, statusCode int, contentType string) // Optional: called for each processed item
// OnAuthWall is called once per item whose redirect chain the transport
// refused to follow into a login / SSO wall (http.StoppedAtAuthWall). It
// carries the target that bounced and the wall it bounced to.
//
// The executor only reports; the phase decides what to do. That split is
// deliberate: the wall host is a scan-wide fact (it feeds the fuzz-target
// exclusion the spidering phase already maintains) and the executor has no
// business owning scan-wide state, while re-deriving it later from stored
// records would mean re-parsing every 3xx in the corpus.
OnAuthWall func(target, wall string)
// KeepBlocked stores a response the block detector classified as a WAF or
// bot-wall page instead of dropping the item, with the remark
// "blocked:<reason>" on the record. Off for scans, where a block page is not
// the application's answer; an ingest asks for it with --keep-blocked.
KeepBlocked bool
// AllowWrites lets the executor send a stored request-only stub whose
// method is not GET/HEAD/OPTIONS. Off, such an item is refused before the
// send (SkipWriteTemplate): fetching its baseline would perform the write
// an ingested spec operation only describes. --allow-writes sets it.
AllowWrites bool
// NoRedirects stops the baseline fetch at the first response: a 3xx is
// stored as the answer. The fingerprint phase sets it — a 301 from
// /robots.txt to /login is itself the signal.
NoRedirects bool
// FetchStaticFiles keeps the pre-fetch scope check to its host and path
// rules, without the static-file carve-out: the fingerprint phase asks for
// a favicon on purpose.
FetchStaticFiles bool
// OnResponse is called with each item and the request/response pair its
// baseline fetch produced, before any module runs. The response buffer is
// pooled and reclaimed when the item completes, so a callback that keeps
// anything must copy it.
OnResponse func(item *work.WorkItem, rr *httpmsg.HttpRequestResponse)
// OnUnanswered is called once per input item that ends without a baseline
// response, with the reason it got none: DropFetchError, DropBlocked,
// DropBudget or DropQuarantined from the fetch, or DropOutOfScope,
// DropQuarantined or SkipStaticFile for an item refused before the send.
// err is the cause when there is one. An item a cancelled run never
// answered gets no call: cancellation says nothing about the item, and the
// caller can see its own context. Lets a phase that sends a fixed plan say
// why each missing answer is missing (the fingerprint phase's errors[]).
OnUnanswered func(item *work.WorkItem, reason string, err error)
// OnRecordStored is called once per input item whose primary record is in
// the store when the executor is done with it — newly written, or a dedup
// hit on an existing row — with that record's UUID. Lets a caller report
// WHICH records an ingest produced, not only how many.
OnRecordStored func(uuid string, rr *httpmsg.HttpRequestResponse)
Services *services.Services
HTTPRequester *http.Requester
Repository *database.Repository // Optional: database storage
RecordWriter *database.RecordWriter // Optional: batched record writer (preferred over Repository.SaveRecord)
FindingWriter *database.FindingWriter // Optional: batched finding writer (preferred over Repository.SaveFinding)
ScanUUID string
// ProjectUUID owns every record and finding this executor writes. An empty
// value is silently coerced to the DEFAULT project by the repository (see
// database.defaultProjectUUID), so a config carrying a Repository/
// RecordWriter/FindingWriter MUST set it or its output lands in a project
// nobody is reading. Enforced by TestExecutorConfigAlwaysSetsProjectUUID.
ProjectUUID string
Hooks HookRunner // Optional: pre/post hooks
ScopeMatcher *config.ScopeMatcher // Optional: scope filtering
ScopeOnIngest bool // When true, skip both save and scan for out-of-scope items
StaticFileMatcher *config.ScopeMatcher // Optional: always-on static file filtering (independent of ScopeMatcher)
FollowSubdomains bool // When true, subdomain_harvest adds discovered subdomains to scope and feeds them (needs ScopeMatcher + feedback)
SkipBaseline bool // When true, skip HTTP fetch if response already attached (Phase 3 DB source)
// RecordRedirectChain persists each followed redirect hop as its own record,
// chained through parent_uuid, and re-pairs the final response with the
// request that actually produced it. Off by default: it multiplies row
// counts on every redirecting URL, and only a host-sweep style phase wants
// the intermediate hops. See saveRedirectHops.
RecordRedirectChain bool
// RecordSource is the http_records.source label this executor stamps. Empty
// means "scanner", which is what every phase used before the label became
// configurable — so a phase that says nothing is unchanged.
RecordSource string
OASTProvider modkit.OASTProvider // Optional: OAST callback URL generator for blind vuln detection
OASTService OASTFlusher // Optional: OAST service to flush after scanning
PauseCtrl *PauseController // Optional: cooperative pause/resume controller
MaxFindingsPerModule int // When > 0, suppress findings after this many per module
// FindingAdmission optionally shares the per-module cap and the
// already-admitted identity set with other executors. nil = executor-local,
// which is right for a phase that runs exactly one Execute. The
// dynamic-assessment phase passes ONE admission to every feedback round, so
// the cap spans the phase and a root cause re-found in a later round does not
// re-fire its callbacks. See FindingAdmission.
FindingAdmission *FindingAdmission
MaxDuration time.Duration // When > 0, cancel execution after this duration
FeedbackDrainTimeout time.Duration // Idle timeout for draining feedback after source EOF (default: 100ms)
FeedbackDrainMaxStall time.Duration // Hard cap on draining with workers in-flight but making no progress (0 = 2x active module timeout). Guards against a module that ignores cancellation.
WorkerExitGrace time.Duration // Grace for worker goroutines to exit after the item channel is closed (0 = default 60s, capped at FeedbackDrainMaxStall). Kept short and separate from the drain-stall cap so shutdown stays responsive.
IPCacheSize int // LRU cache size for parsed insertion points (default: 4096)
IPCache *InsertionPointCache // Optional: shared IP cache (if nil, a new one is created)
ParallelPassive bool // When true, run passive per-request modules concurrently
PassiveModuleTimeout time.Duration // Timeout per passive module call (default: 5s). 0 uses default.
ActiveModuleTimeout time.Duration // Timeout per active module call (default: 300s). 0 uses default. Modules may raise via TimeoutHinter.
ActiveTaskLimit int // Max concurrent active module tasks across host/request/IP scopes
// HostTaskCap, when non-nil, overrides the per-host active-task cap the
// scheduler admits under (default: the host limiter's current per-host
// limit). Tests inject it; a value < 1 is treated as 1.
HostTaskCap func(hostPort string) int
// MaxOutstandingItems caps items that are dequeued but not yet finished —
// a worker dispatches an item's active tasks and moves on, and the item
// stays outstanding until its last task returns. Each one holds its live
// baseline response buffer, so this is also the buffer-memory bound.
// 0 = 4 x Workers. Values below Workers leave some workers idle.
MaxOutstandingItems int
OnStatus func(processed, total, findings, distinctModules, activeCount, passiveCount, timedOut int64, elapsed time.Duration) // Optional: periodic status callback
StatusInterval time.Duration // Interval for OnStatus callback (default: 30s)
// ModuleTimeouts, when non-nil, is an externally-owned counter the executor
// increments on each active-module timeout (instead of its own private one).
// A multi-round phase passes one shared counter so the timed-out total in the
// status line accumulates across the per-round executors it creates.
ModuleTimeouts *atomic.Int64
// OnModuleError, when non-nil, records one failed module call (kind is
// exception, timeout or panic) on an externally-owned ledger and returns
// that module's running error total. The runner passes one ledger to every
// executor of a scan, so the rate-limited module.error events count across
// phases and feedback rounds, and the totals reach scans.module_errors. nil
// = executor-local counting only.
OnModuleError func(moduleID, kind string) int64
// Phase is the canonical phase id this executor runs under, carried on the
// module.error events it emits. Empty leaves the field off.
Phase string
// FirstStatusInterval, when > 0 and shorter than StatusInterval, fires the
// very first status tick after this duration instead of waiting a full
// StatusInterval. Useful for long-cadence status (e.g., 2m) where users
// shouldn't have to stare at silence before the first line appears.
FirstStatusInterval time.Duration
// DisableFeedback drops every URL discovered by passive modules instead of
// re-injecting it into the scan. With this flag the executor scans exactly
// the items the input source delivers and nothing more — matching the
// shallow per-request semantics of `vigolium scan-request`. Used by
// scan-on-receive's default mode to avoid the cascade of new HTTP records
// that link extractors and redirect followers would otherwise generate.
DisableFeedback bool
// TechFilterDisabled bypasses the tech-stack allowlist gate (see modules.TechAware).
// Set by --no-tech-filter and automatically by --intensity=deep so deep scans
// run every module regardless of detected stack.
TechFilterDisabled bool
// OnTechDetected fires once per (host, tag) when a passive fingerprint
// module first publishes a stack detection.
OnTechDetected func(host, tag string)
// DeepScan mirrors --intensity=deep into ScanContext so modules can unlock
// heavier probing (e.g. dashboard_exposure's full mount-path sweep).
DeepScan bool
// ExternalFetcher is copied into ScanContext.ExternalFetcher;
// nil disables third-party lookups.
ExternalFetcher *nethttp.Client
// AllowRiskyPayloads mirrors --allow-risky-payloads (or config
// dynamic-assessment.allow_risky_payloads) into ScanContext, unlocking
// risk:high payloads below deep.
AllowRiskyPayloads bool
// NoParamDedup mirrors --no-param-dedup into ScanContext: modules sharing
// a vuln class stop skipping parameters another module already reported
// (dispatch-time, in-task and in-module checks alike).
NoParamDedup bool
// InsertionPointFilter, when non-nil, narrows the per-insertion-point stage
// to the points it accepts (`finding verify` re-runs a module on the one
// point a finding was found on). Host- and request-scope modules are not
// affected; their results carry FuzzingParameter for callers to filter on.
InsertionPointFilter func(httpmsg.InsertionPoint) bool
// ContentClassByHost seeds the per-host content-class registry from the
// heuristics root probe (host → modkit.ContentClass string). It is the
// fallback consulted by the content-class gate when a record's own
// Content-Type is indeterminate. Honors the same TechFilterDisabled switch.
ContentClassByHost map[string]string
// Phase-shared state. A multi-round phase builds one executor per feedback
// round; with per-executor registries round 2 would forget every tech-stack
// detection (and the tech gate would let every gated module run
// everywhere), every confirmed parameter (param dedup restarts) and every
// per-host claim (per-host modules re-fire each round). When a field is
// non-nil the executor uses it instead of creating its own; the phase
// creates them once (see SharePhaseState). nil = executor-local, which is
// right for a single-Execute phase.
//
// A supplied TechRegistry keeps its own OnDetect (OnTechDetected is not
// applied to it), and a supplied ContentClass is not re-seeded from
// ContentClassByHost — the phase does both once when it creates them.
TechRegistry *modkit.TechRegistry
WAFStack *modkit.WAFRegistry
ParamFindings *modkit.ParameterFindingRegistry
ContentClass *modkit.ContentClassRegistry
HostClaims *HostClaims
// HeaderClaims holds the once-per-host header-point claims.
HeaderClaims *modkit.HeaderClaims
// Ledger, when set, records per-record coverage in the scan's coverage
// ledger and skips modules / the passive stage a record already finished
// (WorkItem.Coverage). See LedgerSpec.
Ledger *LedgerSpec
// HeaderPointsAll turns the header insertion-point gate off
// (dynamic_assessment.header_points: all, --header-fuzz=all): every header
// point reaches every module that accepts headers, per path.
HeaderPointsAll bool
}
ExecutorConfig configures the Executor behavior.
func (*ExecutorConfig) SharePhaseState ¶ added in v0.5.7
func (c *ExecutorConfig) SharePhaseState()
SharePhaseState fills every nil phase-shared field (TechRegistry, WAFStack, ParamFindings, ContentClass, HostClaims) with a fresh instance, so every executor built from copies of this config shares them. The tech registry gets OnTechDetected as its OnDetect and the content-class registry is seeded from ContentClassByHost, once, here. Call it on the phase's base config before the first round.
type ExecutorObserver ¶ added in v0.5.3
type ExecutorObserver func(*Executor)
ExecutorObserver is told about every Executor that starts running under a context that carries it.
It exists so a caller that owns a whole stretch of work (the runner's phase tracker) can read progress off every executor that stretch builds, without each of the places that build one having to hand it over. A dynamic-assessment phase builds one executor per feedback round, deep inside its own loop; the phase's progress is the sum over all of them.
type FindingAdmission ¶ added in v0.5.2
type FindingAdmission struct {
// contains filtered or unexported fields
}
FindingAdmission is the state behind the per-module finding cap: how many findings each module has had admitted, and which root-cause identities have already been admitted.
It is a separate type so it can OUTLIVE one Executor. The dynamic-assessment phase builds a fresh executor per feedback round, so this state used to reset between rounds: a cap documented as holding "for the remainder of the scan" actually restarted every round, and a root cause re-found in round 2 re-fired every callback and notification for a finding already reported in round 1. Sharing one admission across the phase's rounds is what makes the documented contract true (triage C7: per dynamic-assessment phase, shared across rounds; other phases are uncapped).
The zero value is ready to use, so an Executor built without a shared one gets its own by construction and a literal &Executor{cfg: …} in a test still works. Safe for concurrent use: both fields are sync.Maps.
func NewFindingAdmission ¶ added in v0.5.2
func NewFindingAdmission() *FindingAdmission
NewFindingAdmission returns admission state a caller can share across several executors — one per dynamic-assessment phase, covering all of its rounds.
func (*FindingAdmission) Capped ¶ added in v0.5.7
func (a *FindingAdmission) Capped() map[string]int64
Capped returns, per module, how many distinct findings the per-module cap dropped (identities, so repeated evidence of one dropped finding counts once). Modules that dropped nothing are absent; nil when none did.
type HookRunner ¶
type HookRunner interface {
RunPreHooks(req *httpmsg.HttpRequestResponse) (*httpmsg.HttpRequestResponse, error)
RunPostHooks(result *output.ResultEvent) (*output.ResultEvent, error)
}
HookRunner transforms requests before scanning and filters results after scanning.
type HostClaims ¶ added in v0.5.7
type HostClaims struct {
// contains filtered or unexported fields
}
HostClaims holds the per-host run-once claims of ScanPerHost modules — one (module, origin) entry per claimed pair. Shared across a phase's executors via ExecutorConfig.HostClaims.
The caches are bounded LRUs rather than unbounded maps: in a long-lived scan-on-receive executor the (module, host) key space grows with every distinct host ingested. The LRU caps that growth and, by evicting the least-recently-claimed pairs, lets per-host modules re-fire for a host whose claim has aged out.
func NewHostClaims ¶ added in v0.5.7
func NewHostClaims() *HostClaims
NewHostClaims returns empty claim caches.
type InsertionPointCache ¶
type InsertionPointCache struct {
// contains filtered or unexported fields
}
InsertionPointCache is a byte-aware LRU of insertion-point sets, keyed by request hash. It bounds both entry count (via the underlying LRU) and total retained bytes, and rejects individual entries above a per-entry ceiling.
A nil *InsertionPointCache is usable: every method degrades to a miss, so a caller with no cache configured needs no branch of its own.
All access is serialized on one mutex. That is deliberate: the byte counter and the LRU must move together or the budget drifts, and the eviction callback updates the counter while the LRU's own lock is held — so it must not attempt to re-acquire this mutex. Because every caller path holds the mutex around the LRU call, the callback runs with exclusive access already and updates the counter directly. Contention is not a concern: lookups are per-request, not per-payload.
func NewInsertionPointCache ¶
func NewInsertionPointCache(entries int) *InsertionPointCache
NewInsertionPointCache creates a byte-aware insertion-point cache holding at most entries items. A non-positive entries value falls back to a safe default.
func (*InsertionPointCache) Add ¶
func (c *InsertionPointCache) Add(key string, points []httpmsg.InsertionPoint)
Add caches points under key unless the set is too large to be worth retaining. Oversized sets are counted as rejections and left uncached — the caller's copy is unaffected either way, so a rejection costs only a later re-derivation.
func (*InsertionPointCache) Get ¶
func (c *InsertionPointCache) Get(key string) ([]httpmsg.InsertionPoint, bool)
Get returns the cached insertion points for key.
func (*InsertionPointCache) GetOrCompute ¶
func (c *InsertionPointCache) GetOrCompute(raw []byte, requestID string, includeNested bool) ([]httpmsg.InsertionPoint, error)
GetOrCompute returns the insertion points for requestID, deriving and caching them on a miss.
This owns the cache-key convention (the includeNested variants are separate entries) so no caller has to reproduce it. Both the per-insertion-point scan stage and the module-facing provider go through here; deriving a key inline instead is how the two ends up disagreeing about which variant they stored.
func (*InsertionPointCache) GetOrComputeAll ¶ added in v0.5.7
func (c *InsertionPointCache) GetOrComputeAll(raw []byte, requestID string, includeNested bool) ([]httpmsg.InsertionPoint, error)
GetOrComputeAll is GetOrCompute including the opt-in parameter-name and entire-body points (ParamNames + EntireBody). Both views come from one parse and one cache entry.
func (*InsertionPointCache) Stats ¶
func (c *InsertionPointCache) Stats() InsertionPointCacheStats
Stats returns a snapshot of the cache's current size and cumulative counters.
type InsertionPointCacheStats ¶
type InsertionPointCacheStats struct {
Entries int
RetainedBytes int64
Hits int64
Misses int64
// Evictions counts only byte-budget evictions. Ordinary count-bound LRU
// evictions are not counted: they are the cache working as configured, while a
// byte eviction means the budget — not the entry cap — is the binding limit.
Evictions int64
// Rejected counts sets never cached because they exceeded the per-entry ceiling.
Rejected int64
}
InsertionPointCacheStats is a point-in-time snapshot of cache behaviour, for logging and metrics. Counters are cumulative for the cache's lifetime.
type LedgerSpec ¶ added in v0.5.7
type LedgerSpec struct {
// Writer persists the per-record rows (shared by the phase's passes).
Writer *database.ProgressWriter
// Ordinals maps every module of the phase (all passes) to its bit in
// done_bits — the order stored in scans.coverage_modules.
Ordinals map[string]int
// Tiers maps every active module of the phase to its pass (0, 1, …).
Tiers map[string]int
// MaxTier is the last pass's tier; tier_done reaching it means the record
// is fully covered.
MaxTier int
// RunsPassives reports whether this executor runs the passive stage (the
// first pass), so passive_done can be recorded.
RunsPassives bool
}
LedgerSpec wires an executor into the coverage ledger. The phase builds one per tier pass.
type OASTFlusher ¶
type OASTFlusher interface {
Flush()
Close()
}
OASTFlusher is implemented by the OAST service to allow the executor to flush pending interactions after scanning completes.
type PauseController ¶
type PauseController struct {
// contains filtered or unexported fields
}
PauseController provides cooperative pause/resume for workers and the active-task scheduler.
Pause never blocks: it flips the paused flag and returns. From then on workers stop dequeuing (WaitIfPaused between items) and the active-task scheduler stops admitting queued tasks. A worker that is mid-dispatch finishes its current item; Quiesced reports true once no worker is mid-dispatch, which is when a status display should say "paused" rather than "pausing". Tasks the scheduler already admitted run to completion — they may still send probe traffic, emit findings and acknowledge their item after Pause returns.
Pause must not wait for in-flight dispatch: the server handler calls it while holding the server-wide scan lock, so one stuck dispatch would hang stop and status for every project.
stateMu serializes the Pause/Resume transitions and guards pausedCh, so concurrent Pause+Resume — reachable, e.g. a stop-triggered Runner.Close resuming while an API pause request is in flight — can never close a nil or already-closed channel or leave pausedCh stale relative to the paused flag.
func NewPauseController ¶
func NewPauseController() *PauseController
NewPauseController creates a new PauseController in the unpaused state.
func (*PauseController) AcquireWorker ¶
func (p *PauseController) AcquireWorker()
AcquireWorker marks a worker as mid-dispatch (fetch, passive stage, task dispatch). Never blocks. Call ReleaseWorker when done.
func (*PauseController) IsPaused ¶
func (p *PauseController) IsPaused() bool
IsPaused returns the current pause state.
func (*PauseController) Pause ¶
func (p *PauseController) Pause()
Pause stops new dispatch and admission and returns at once. Safe to call multiple times (idempotent) and concurrently with Resume.
func (*PauseController) Quiesced ¶ added in v0.5.7
func (p *PauseController) Quiesced() bool
Quiesced reports whether the controller is paused AND no worker is still mid-dispatch.
func (*PauseController) ReleaseWorker ¶
func (p *PauseController) ReleaseWorker()
ReleaseWorker ends a worker's dispatch.
func (*PauseController) Resume ¶
func (p *PauseController) Resume()
Resume unblocks paused workers and admission. Safe to call when not paused and concurrently with Pause.
func (*PauseController) WaitIfPaused ¶
func (p *PauseController) WaitIfPaused(ctx context.Context) bool
WaitIfPaused blocks the caller if the controller is paused. Returns false if the context is cancelled while waiting. Workers should call this between processing items.
type QuarantinedHost ¶ added in v0.5.3
type QuarantinedHost struct {
// Host is the breaker key, "host:port".
Host string `json:"host"`
// Items is how many input items were dropped for it (skipped_quarantined).
Items int64 `json:"skipped_quarantined"`
// State is the breaker state at report time: open, half_open, dead, or
// closed when the host recovered after the skips.
State string `json:"state"`
// Class is the transport error class of the failure that quarantined it,
// one of the http.TransportErr* constants.
Class string `json:"class,omitempty"`
}
QuarantinedHost is one host:port whose input items this run dropped because the dead-host breaker had it quarantined.
Source Files
¶
- doc.go
- executor.go
- executor_active.go
- executor_adapters.go
- executor_admission.go
- executor_baseline_failures.go
- executor_buffers.go
- executor_config.go
- executor_corroboration.go
- executor_drops.go
- executor_eligibility.go
- executor_fetch.go
- executor_filters.go
- executor_item_tracker.go
- executor_ledger.go
- executor_module_errors.go
- executor_module_skips.go
- executor_passive.go
- executor_persist.go
- executor_progress.go
- executor_quarantine.go
- executor_report.go
- executor_results.go
- executor_scheduler.go
- executor_timeouts.go
- executor_worker.go
- ip_cache.go
- pause.go
- shardmap.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package egress is the single admission point for scan traffic aimed at a target: the global request-rate token bucket, the per-host concurrency slot, the dead-host breaker and the wire-attempt counter, applied in one order by one type.
|
Package egress is the single admission point for scan traffic aimed at a target: the global request-rate token bucket, the per-host concurrency slot, the dead-host breaker and the wire-attempt counter, applied in one order by one type. |
|
Package hosterrors is the scan-wide dead-host circuit breaker.
|
Package hosterrors is the scan-wide dead-host circuit breaker. |
|
networktest
Package networktest holds test helpers for transports built on pkg/core/network.
|
Package networktest holds test helpers for transports built on pkg/core/network. |