pentest

package
v0.115.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package pentest provides security-testing helpers: a bounded-concurrency worker pool for concurrent payload delivery and a result aggregator. Also exposes standard go test -fuzz corpus entrypoints so the Go fuzzer can drive the same payloads in CI.

Package pentest gives every fleet pentest detector ONE canonical way to declare its protocol with go-pentest-findings-store.

Background. Five detectors (cookie-pwn, js-bundle-scanner, wayback- urls, reflection-hunter, …) each used to ship ~150 lines of identical glue: a local Candidate struct, a /verify HTTP handler, a /selftest corpus-replay loop, an env-var "skipped" idiom. Every change to the protocol meant N PRs across N services and the shapes inevitably drifted.

This package collapses all of that into one Detector{...}.Mount (10 lines instead of 150). The /verify handler is uniform. The /selftest is built on top of the existing selftest.Suite, so the go-fleet-selftest-aggregator (ADR-0015) sees the SAME canonical shape detectors emit for any other check — one Check per owned vuln_class, named "corpus_replay/<vc>", that fails (non-nil error) the moment a single TP regresses.

What still lives in the detector:

  • The /detect handler. Detector inputs are unavoidably specific (cookie-pwn takes a URL, wayback takes a domain, js-bundle-scanner takes a target + optional max_js_bundles), so we don't pretend to unify them. Provide a ToCandidates(result) []pentest.Candidate helper in your service and mount your own /detect.

  • The Verify function itself. The detector knows its kinds; this package just dispatches on them.

Typical wiring (~10 lines in main.go):

det := pentest.Detector{
    Service:          serviceName,
    Version:          version,
    VulnClassesOwned: []string{"cookie.missing_flag"},
    Verify:           myverifier.Verify,
    StoreURL:         os.Getenv("FINDINGS_STORE_URL"),
    APIKey:           os.Getenv("FINDINGS_STORE_API_KEY"),
}
det.Mount(srv.Mux) // mounts /verify + /selftest

dedup_key contract is centralized too. Both detector and findings- store agree on identity via:

dedup_key = "<vuln_class>:<target>:<evidence_key>"
id        = "f_" + sha256(dedup_key)[:16]

Use pentest.DedupKey and pentest.ID to construct them — never hand- roll the concatenation, the next agent will get the separator wrong.

worker.go — VerifierWorker, the canonical polling-loop primitive for "a service that knows how to verify findings of certain kinds and wants to verify every new candidate that lands in findings-store".

go-pentest-exploit-verifier is the canonical consumer: it has per-class verifiers (SSRF via OOB, XSS via marker reflection, IDOR via session-stripped re-fetch, JWT alg-none, open-redirect, subdomain-takeover) and previously had no link to the candidate firehose findings-store collects. With VerifierWorker the wiring becomes ~15 lines in main.go:

w := &pentest.VerifierWorker{
    Service:  "go-pentest-exploit-verifier",
    Version:  version,
    StoreURL: os.Getenv("FINDINGS_STORE_URL"),
    APIKey:   os.Getenv("FINDINGS_STORE_API_KEY"),
    Verifiers: map[string]pentest.Verifier{
        "xss.confirmed":         verifyXSS,
        "ssrf.blind":            verifySSRF,
        "idor.session_stripped": verifyIDOR,
    },
}
go w.Run(ctx)

Each tick, the worker:

  1. GETs /findings?corpus_state=candidate&limit=100
  2. For each candidate whose vuln_class is in Verifiers, runs the verifier against it.
  3. POSTs the result to /verifications.

findings-store's recomputeCorpusState then transitions the row to "verified" or "rejected" — no human label, but enough for triage dashboards to filter by.

Failure-mode policy mirrors Detector:

  • findings-store unreachable / 5xx → log, skip tick, no panic
  • 4xx → log loudly (caller misuse)
  • per-candidate verify failure → log, continue with next

Concurrency: PollInterval bounds the loop. Within a tick, candidates run serially (Concurrency=1) by default — verifiers often hit OOB callbacks or rate-limited APIs and rarely benefit from parallelism. Bump Concurrency for verifiers that are pure-CPU.

Index

Constants

This section is empty.

Variables

View Source
var ErrUnsupportedKind = errors.New("no verifier registered for vuln_class")

ErrUnsupportedKind is the canonical error a Verifier should wrap when asked about a vuln_class outside its dispatch. Used so the /verify HTTP layer can render a consistent reason.

Functions

func DedupKey

func DedupKey(vulnClass, target, evidenceKey string) string

DedupKey constructs the canonical dedup_key for a (vuln_class, target, evidence_key) triple. Use this everywhere instead of hand- rolled string concatenation — the separator is "::". Wait no: the field separator is ":" but `evidence_key` may legitimately contain ":" (e.g. a URL like https://x.com/...). To stay unambiguous we keep the convention as documented but warn the caller via the const SeparatorRune.

Note. The historical convention (used by every detector that pre-dates this package) is single ":" — keeping it for backward compatibility. evidence_key containing ":" still works because findings-store treats dedup_key as opaque; only the hash matters. Don't try to "fix" the separator without bumping the dedup model.

func EnvOr

func EnvOr(key, def string) string

EnvOr is a tiny helper for the canonical "configured value or fallback" idiom every service repeats. Exported so detectors can use it in place of the inline two-liner.

func ID

func ID(dedupKey string) string

ID returns the stable finding id findings-store computes from a dedup_key. Detectors can pre-compute the id to correlate /detect emissions against /corpus rows without an extra round-trip.

This MUST stay in lockstep with go-pentest-findings-store's newID(). If you change either, change both AND run the replay-stability regression test.

func NormalizeSeverity

func NormalizeSeverity(s string) string

SeverityFromIssue is a soft helper for collapsing a detector's internal severity scale onto the findings-store severity scale (info|low|medium|high|critical). Detectors with custom levels should map them; this default just normalizes case + maps "med" → "medium".

Types

type Candidate

type Candidate struct {
	VulnClass string          `json:"vuln_class"`
	Target    string          `json:"target"`
	Program   string          `json:"program,omitempty"`
	Source    string          `json:"source"`             // typically the detector's service id
	Severity  string          `json:"severity,omitempty"` // info|low|medium|high|critical
	DedupKey  string          `json:"dedup_key"`
	Evidence  json.RawMessage `json:"evidence,omitempty"`
}

Candidate is what every detector emits and what findings-store /findings ingests. The wire shape is the contract; the fields here match findings-store's Finding minus the server-controlled bits (id / seen_count / created_at / corpus_state).

type CorpusFinding

type CorpusFinding struct {
	ID          string          `json:"id"`
	VulnClass   string          `json:"vuln_class"`
	Target      string          `json:"target"`
	Program     string          `json:"program"`
	DedupKey    string          `json:"dedup_key"`
	Severity    string          `json:"severity"`
	Evidence    json.RawMessage `json:"evidence"`
	CorpusState string          `json:"corpus_state"`
}

CorpusFinding mirrors the FindingWithCorpus shape returned by findings-store /corpus/{vc}. We only deserialize what replayCheck needs — keeps the package independent of findings-store schema additions.

type Detector

type Detector struct {
	// Service is the canonical fleet slug (e.g. "go-pentest-cookie-pwn").
	// Echoed in /verify and /selftest responses.
	Service string
	// Version is the running detector version (must match service.yaml).
	Version string
	// VulnClassesOwned is the set of finding-kinds this detector emits +
	// can verify. /selftest runs one corpus_replay check per kind.
	VulnClassesOwned []string
	// Verify is the kind-dispatched verifier (required).
	Verify Verifier
	// StoreURL is the base URL of go-pentest-findings-store. When empty,
	// /selftest reports "skipped" and returns 200 — the detector is
	// still deployable in environments without the store.
	StoreURL string
	// APIKey authenticates the corpus fetch. It must be explicitly set to a
	// service-specific key whenever StoreURL is configured.
	APIKey string
	// CorpusFetchTimeout bounds each /corpus/{vc} call. Defaults to 10s.
	CorpusFetchTimeout time.Duration
	// VerifyTimeout bounds each in-process Verify() call during replay.
	// Defaults to 5s (the same as selftest.DefaultCheckTimeout).
	VerifyTimeout time.Duration
	// CorpusRequired makes /selftest fail (503) when the corpus is
	// unreachable. Default (false) treats transient findings-store
	// outages as DEGRADED success — avoids making findings-store a
	// deploy-time SPOF for the entire detector fleet. Set true for
	// canary deploys where you want strict verification.
	CorpusRequired bool
	// contains filtered or unexported fields
}

Detector holds everything pentest.Mount needs to wire /verify + /selftest for one service.

func (*Detector) Mount

func (d *Detector) Mount(mux *http.ServeMux)

Mount installs /verify and /selftest on mux. /selftest delegates to a selftest.Suite with one check per VulnClassesOwned. Idempotent if called once; calling twice panics (net/http mux contract).

type Verifier

type Verifier func(ctx context.Context, c Candidate) VerifyResult

Verifier is the detector-side function the pentest package dispatches candidates to. Implement it once per service with a switch on c.VulnClass.

type VerifierWorker

type VerifierWorker struct {
	// Service is this worker's fleet slug — appears in every
	// Verification record so the audit trail tells you which worker
	// promoted a candidate.
	Service string
	// Version is propagated as verifier_version.
	Version string
	// StoreURL is the findings-store base URL.
	StoreURL string
	// APIKey is a service-specific findings-store credential and is required.
	APIKey string
	// Verifiers maps vuln_class → verifier func. Tick scans for any
	// candidate whose kind is in this map; everything else is ignored.
	Verifiers map[string]Verifier
	// Aliases maps an alternate vuln_class string to the canonical key
	// in Verifiers. Use this when a worker speaks one naming convention
	// (e.g. dot-separated "xss.confirmed") but the corpus carries
	// findings from detectors using another (e.g. dash-separated
	// "xss-reflected").
	//
	// Example: exploit-verifier's Registry uses "xss-reflected",
	// "jwt-alg-none", "idor"; the new detector pkg emits
	// "xss.confirmed", "xss.dom", "cookie.missing_flag". Wire:
	//
	//	Aliases: map[string]string{
	//	    "xss.confirmed": "xss-reflected",   // accept detector kind, route to canonical
	//	    "xss.dom":       "xss-dom",
	//	    "auth.idor":     "idor",
	//	}
	//
	// Resolution order on every candidate:
	//   1. exact match in Verifiers — use it
	//   2. alias hit — re-look up the aliased key in Verifiers
	//   3. neither — candidate ignored (not this worker's class)
	//
	// Aliases are one-way (candidate-kind → registered-key). The worker
	// does NOT rewrite the candidate's vuln_class — Verifications go
	// back to findings-store carrying the ORIGINAL kind, so the corpus
	// state machine resolves on the kind that was emitted, not the
	// canonical-side name. That keeps replay diffs and dedup stable
	// across the alias boundary.
	Aliases map[string]string
	// PollInterval defaults to 30s. Too aggressive and we hammer
	// findings-store; too slow and candidates pile up.
	PollInterval time.Duration
	// Concurrency bounds in-flight Verify calls per tick. Default 1
	// (serial) — most verifiers do OOB / rate-limited probing where
	// parallelism doesn't help. Bump for pure-CPU verifiers.
	Concurrency int
	// MaxPerTick caps candidates processed per tick (default 100) so
	// a large pending queue doesn't lock the worker for minutes on
	// a single tick.
	MaxPerTick int
	// contains filtered or unexported fields
}

VerifierWorker is the background poller that keeps findings-store's corpus_state column moving as candidates arrive.

func (*VerifierWorker) Run

func (w *VerifierWorker) Run(ctx context.Context) error

Run blocks until ctx is cancelled, ticking every PollInterval. Returns ctx.Err() on shutdown.

func (*VerifierWorker) SelftestHandler

func (w *VerifierWorker) SelftestHandler() http.HandlerFunc

SelftestHandler returns an http.HandlerFunc that surfaces worker liveness. Mount on the verifier service's /selftest or /worker-stats. Returns 200 with the WorkerStats JSON; returns 503 only if the worker has had consecutive fetch failures (signals findings-store outage or misconfiguration — needs operator attention).

func (*VerifierWorker) Stats

func (w *VerifierWorker) Stats() WorkerStats

Stats returns a snapshot of the worker's running state.

type VerifyResult

type VerifyResult struct {
	Method   string         `json:"method"`
	Promoted bool           `json:"promoted"`
	Reason   string         `json:"reason,omitempty"`
	Proof    map[string]any `json:"proof,omitempty"`
}

VerifyResult is what a Verifier returns. The detector decides whether promotion happened; this package just records and reports.

type WorkerStats

type WorkerStats struct {
	LastTickAt       time.Time `json:"last_tick_at"`
	LastTickPolled   int64     `json:"last_tick_polled"`
	LastTickVerified int64     `json:"last_tick_verified"`
	LastTickFailed   int64     `json:"last_tick_failed"`
	TotalVerified    int64     `json:"total_verified"`
	TotalFailed      int64     `json:"total_failed"`
	ConsecutiveFails int64     `json:"consecutive_fails"`
}

WorkerStats is the public snapshot.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL