secscan

package
v1.0.406 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 24 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 secscan is the security-scan orchestrator: it ties ClamAV, YARA, the threat feed, the hash cache, and the admin hash allowlist into the single pipeline the proxy hot path calls. Extracted from package main per ADR-0006 Slice 2; the collaborators arrive as constructor-injected interfaces (Deps), so the engines stay decoupled and the decision tree is unit-testable with fakes. package main keeps the free-function glue (safeScanBody, scanBlock*, bodyNeedsBuffering, the status map) and the production adapters (security_scan.go shim).

Pipeline for every proxied request/response:

  1. URL / domain threat-feed check (CheckURL / CheckDomain) Instant, in-memory lookup against URLhaus + OpenPhish data. Applied in handleRequest before the request is forwarded upstream.

  2. Response body scan (ScanBody) a. SHA-256 hash looked up in cache → return cached verdict immediately. b. ClamAV INSTREAM scan (binary + text content). c. YARA rule matching (all loaded *.yar / *.yara rules). d. Result stored in hash cache. Applied in handleHTTP and handleTunnelInspect after reading the body.

All components are optional:

  • ClamAV is skipped when no address is configured or daemon is unreachable.
  • YARA is skipped when no matcher is injected or it reports not loaded.
  • Threat feeds are skipped when no checker is injected or it is disabled.

Index

Constants

View Source
const (
	ProbeReasonNotConfigured = "not_configured"
	ProbeReasonInvalidURL    = "invalid_url"
	ProbeReasonTimeout       = "timeout"
	ProbeReasonConnectFailed = "connect_failed"
	ProbeReasonTLSFailed     = "tls_failed"
	ProbeReasonBadResponse   = "bad_response"
	ProbeReasonUnavailable   = "unavailable"
)

Bounded probe reason classes.

View Source
const (
	DefaultDecompressRatioLimit = 64
	DecompressFloorBytes        = 1 << 20
)

DefaultDecompressRatioLimit is the shipped expansion ratio (see the block above). It is what applies whenever no operator override is set. DecompressFloorBytes is the small-response floor; exported for the admin surface that reports it, and deliberately not tunable.

View Source
const (
	MinDecompressRatioLimit = 16
	MaxDecompressRatioLimit = 256
)

MinDecompressRatioLimit and MaxDecompressRatioLimit bound the operator override. Validated here, in the owner, so no caller can install a value the bound was not designed for.

WHY 16 AT THE BOTTOM. Lowering the factor is a legitimate memory-tightening choice on a small node (the per-response expansion is ratio x compressed bytes), but HTML/JS/CSS already sits at 3-10:1 and JSON at 10-20:1. 16 is the lowest value that still admits all ordinary markup; below it the bound would refuse ordinary pages and stop being a bomb detector at all. Values between 16 and ~32 can already refuse very repetitive JSON — that is the operator's explicit, audited trade.

WHY 256 AT THE TOP, NOT 1024. The measured CHAOS-106 bomb expanded at 408:1 and a gzip of zeros reaches ~1030:1. A ceiling at or above ~400 would let an operator set a value at which the measured attack shape is admitted again, i.e. switch the protection off while the UI still shows it as on. 256 is 4x the default — room for CSV/log exports up to 256:1 — and still sits below every bomb ratio CHAOS-106 measured, so the bound keeps refusing that shape at the maximum. Content more repetitive than 256:1 is indistinguishable from a bomb by ratio, which is exactly the signal the bound uses; it stays refused. Raising the factor still lowers an attacker's cost per refused-byte (64 MiB of expansion for 256 KiB of wire at the maximum instead of 1 MiB), so the admin plane reports any value above the default as a relaxed posture.

View Source
const MaxDecompressBytes = 64 << 20

MaxDecompressBytes limits decompressed data to 64 MB to guard against gzip bombs.

View Source
const ScanBodyTimeout = 10 * time.Second

ScanBodyTimeout caps the total time for all body scanners (ClamAV + YARA). If the combined scan doesn't finish in time, the content is blocked (fail-closed).

Variables

View Source
var ErrNotConfigured = errors.New("remote scanner not configured")

ErrNotConfigured is the sentinel for a probe attempted while remote mode is off, so the classifier never has to match on message text.

Functions

func AddRemoteScanFail

func AddRemoteScanFail()

AddRemoteScanFail records a remote scan sidecar failure (incremented by the remote scanner client in package main).

func AddScanSkipped

func AddScanSkipped()

AddScanSkipped records a response forwarded unscanned because it exceeded the scan buffer limit. Two writers, deliberately sharing one counter: package main's logScanLimitExceeded for the in-process window, and remoteScanOversize for the SIDECAR's own window (CHAOS-101). It is one phenomenon — bytes were forwarded unscanned because the object was larger than the window — so it gets one counter and one alert class regardless of which deployment clipped it.

func DecompressBombs added in v1.0.375

func DecompressBombs() int64

DecompressBombs reports responses refused by the scan-path expansion ratio bound. A non-zero value means content was blocked for declaring an expansion disproportionate to what it transferred.

func DecompressForScan

func DecompressForScan(data []byte, contentEncoding string) (out []byte, bomb bool)

DecompressForScan transparently decompresses a response body based on its Content-Encoding header so that ClamAV/YARA signatures can match the actual content. Supports gzip, deflate, brotli, zstd and identity (no-op).

The expansion is bounded TWICE (CHAOS-106): by MaxDecompressBytes, and by expandBound's ratio allowance relative to the compressed bytes actually transferred. bomb reports that the ratio allowance was exceeded, i.e. the origin declared an encoding whose expansion is wildly disproportionate to what it sent; the caller must refuse the response (fail closed) and out is nil. See expandBound for why that is a refusal rather than a truncation.

Every other failure keeps the pre-CHAOS-106 posture verbatim: if the encoding is unknown, the reader cannot be constructed, the stream is truncated or corrupt, or the expansion is empty, the ORIGINAL data is returned with bomb false — the scan still runs on compressed bytes (fail-open for availability, but the signature gap is closed for the common case). Reaching MaxDecompressBytes is likewise unchanged: the prefix that fits is returned and scanned.

func DecompressRatioLimit added in v1.0.377

func DecompressRatioLimit() int64

DecompressRatioLimit returns the ratio scan-path expansions are bounded by.

func ProbeFailureReason added in v1.0.219

func ProbeFailureReason(err error) string

ProbeFailureReason maps a Health/Status error to a bounded class safe to render on a viewer surface. It never returns caller- or far-end-controlled text. A nil error is "" (the caller reports success).

func ReadScanBuffer added in v1.0.207

func ReadScanBuffer(r io.Reader, limit, contentLength int64) ([]byte, error)

ReadScanBuffer reads from r until EOF or limit bytes, whichever comes first, and returns the bytes read. It is a drop-in replacement for io.ReadAll(io.LimitReader(r, limit)) that uses contentLength — the origin's declared body size, or a value <= 0 when it declared none (chunked) — to allocate the destination buffer once instead of growing it.

contentLength is a HINT ONLY and is never trusted for correctness: the read still runs to EOF or to limit, so an origin that under-declares its body does not get the tail past its declaration forwarded unscanned, and one that over-declares simply yields a shorter buffer.

func RemoteScanFailTotal added in v1.0.211

func RemoteScanFailTotal() int64

RemoteScanFailTotal reports fail-OPEN sidecar faults so far. Used by the rate-limited degradation log, where the counter carries the magnitude the suppressed lines would have.

func RemoteScanInflight added in v1.0.211

func RemoteScanInflight() int64

RemoteScanInflight reports remote scan round trips currently in flight.

func ScanInflight added in v1.0.209

func ScanInflight() int64

ScanInflight reports body scans currently running (abandoned ones included). It is a saturation gauge: a value that stays near or above the ClamAV concurrency limit means scans are queueing, which is the leading indicator of the timeout-and-abandon regime.

func SetDecompressRatioLimit added in v1.0.377

func SetDecompressRatioLimit(n int64) error

SetDecompressRatioLimit installs n as the scan-path expansion ratio. An out-of-range value is refused and the current ratio is kept (fail closed: a bad value never widens the bound). Setting the default clears the override, so an untouched node and a node reset to the default behave identically.

func SigDBInvalidations added in v1.0.382

func SigDBInvalidations() int64

SigDBInvalidations reports verdict-cache flushes forced by a signature-set change (CHAOS-107).

func ValidateDecompressRatioLimit added in v1.0.377

func ValidateDecompressRatioLimit(n int64) error

ValidateDecompressRatioLimit reports whether n may be installed as the expansion ratio.

Types

type ClamScanner

type ClamScanner interface {
	Ping() error
	Scan(data []byte) (name string, found bool, err error)
}

ClamScanner is the ClamAV surface ScanBody/ClamAVStatus need.

type CounterSnapshot

type CounterSnapshot struct {
	ClamBlocked       int64
	YARABlocked       int64
	ThreatFeedBlocked int64
	ScanTimeout       int64
	ScanSkipped       int64
	RemoteScanFail    int64
	ClamScanError     int64
	ClamSaturated     int64
	ScanLateDiscarded int64
	ScanInflight      int64

	// DecompressBombs counts responses refused by the scan-path expansion
	// ratio bound (CHAOS-106). Fail-CLOSED, like ScanTimeout and
	// ClamSaturated, and separate from ScanSkipped, which is fail-OPEN.
	DecompressBombs int64

	// SigDBInvalidations counts verdict-cache flushes forced by an observed
	// ClamAV engine/signature-database change (CHAOS-107). A RECOVERY signal:
	// it rises when new definitions are adopted, and staying at zero while the
	// reported signature counter advances is itself the alarm.
	SigDBInvalidations int64

	// Remote (sidecar) deployment. Every counter above except RemoteScanFail is
	// structurally zero there, so before CHAOS-53 a sidecar node exported no
	// scanning signal at all.
	RemoteScanSaturated int64
	RemoteScanInflight  int64
}

CounterSnapshot is a point-in-time copy of the scan counters.

func Counters

func Counters() CounterSnapshot

Counters returns a snapshot of all scan counters.

type Deps

type Deps struct {
	Clam     ClamScanner
	Yara     YARAMatcher
	Feed     ThreatChecker
	Excl     HashExcluder
	Cache    *hashcache.HashCache
	MaxBytes int64
}

Deps carries the injectable collaborators for New. Nil collaborators behave as absent (that engine/check is skipped), so partial injection is fine.

type HTTPStatusError added in v1.0.219

type HTTPStatusError struct{ Code int }

HTTPStatusError reports a probe answered with a non-200 status. The code is a small integer the far end cannot use to smuggle text, so it is safe to render and is worth keeping for diagnosis.

func (*HTTPStatusError) Error added in v1.0.219

func (e *HTTPStatusError) Error() string

type HashExcluder

type HashExcluder interface{ IsHashExcluded(hash string) bool }

HashExcluder is the admin hash-allowlist surface ScanBody needs.

type RemoteScanner

type RemoteScanner struct {
	// contains filtered or unexported fields
}

RemoteScanner sends scan requests to a scan microservice.

func (*RemoteScanner) Enabled

func (rs *RemoteScanner) Enabled() bool

Enabled reports whether remote scanning is configured.

Lock-free by contract — see the enabled field. TestRemoteScannerEnabled_IsLockFree pins the property.

func (*RemoteScanner) Health

func (rs *RemoteScanner) Health() error

Health checks the remote scan service liveness.

func (*RemoteScanner) Init

func (rs *RemoteScanner) Init(baseURL string)

Init configures the remote scanner client.

The client timeout is a BACKSTOP only. Every request this client makes now carries its own context deadline — the shared scan budget for /scan, five seconds for the admin probes — and those always fire first. It used to be the only bound on a scan, at 60 s, i.e. six times the budget the local path gives the identical decision.

func (*RemoteScanner) ScanBody

func (rs *RemoteScanner) ScanBody(data []byte, contentType string) *Result

ScanBody sends data to the remote scan service and returns the result.

POSTURE — the whole point of this function, and previously the thing it got wrong. Three outcomes, not two:

  • VERDICT: the sidecar answered. Blocked → block, clean → forward. The answer must be AFFIRMATIVE; see the Clean check below.
  • BUDGET or CAPACITY: the scan did not finish in time, or the sidecar reported itself full. Fail CLOSED, exactly as the local path does for the identical condition. This is the inversion CHAOS-53 exists to fix: the deadline was private (30 s, three times the local budget), so exceeding it surfaced as an ordinary transport error, was classified as a sidecar fault, and took the fail-OPEN branch — a security control switched off by SLOWNESS, on healthy infrastructure, with the process's own fail-closed budget never consulted. It is the same defect CHAOS-52 fixed in the local path (WK-15), left standing in the deployment the CHAOS-52 runbook RECOMMENDS as the remedy for it.
  • FAULT: the sidecar is unreachable, erroring, or unintelligible. Fail OPEN, counted and alerted. This posture is unchanged and remains the recorded owner decision (WK-2b, the sibling of the local path's WK-1b); what changes is that it is now reached only by an actual fault.

func (*RemoteScanner) SetExclusions added in v1.0.211

func (rs *RemoteScanner) SetExclusions(excl HashExcluder)

SetExclusions injects the admin-managed hash allowlist so the remote path honours it exactly as Scanner.ScanBody does.

Without this the allowlist was structurally dead in sidecar deployments: an admin clearing a false positive by hash saw the entry accepted, persisted and audited, and the object kept being blocked, with nothing anywhere saying the setting did not apply to this deployment.

func (*RemoteScanner) Status

func (rs *RemoteScanner) Status() (map[string]interface{}, error)

Status fetches the remote scanner status (mirrors /api/security-scan/status).

func (*RemoteScanner) URL

func (rs *RemoteScanner) URL() string

URL returns the configured base URL.

type Result

type Result struct {
	Blocked bool
	Reason  string // virus name, YARA rule name, or feed source
	Source  string // "clamav", "yara", or "threatfeed"
	Hash    string // SHA-256 hex of scanned content (body scans only)
}

Result describes the outcome of a scan that triggered a block.

type ScanResponse

type ScanResponse struct {
	Clean      bool   `json:"clean"`
	Blocked    bool   `json:"blocked"`
	Reason     string `json:"reason,omitempty"`
	Source     string `json:"source,omitempty"`      // "clamav", "yara", "dpi"
	Hash       string `json:"hash,omitempty"`        // SHA-256 of scanned content
	DPIPattern string `json:"dpi_pattern,omitempty"` // matched DPI pattern
	ElapsedMS  int64  `json:"elapsed_ms"`
}

ScanResponse is the JSON wire type between the scan sidecar and this client. The sidecar server (package main, scan_svc.go) produces it; keep the field set in sync with the server handler.

type Scanner

type Scanner struct {
	// contains filtered or unexported fields
}

Scanner ties together ClamAV, YARA, the threat feed, and the hash cache into a single, easy-to-use interface for the proxy pipeline.

func New

func New(deps Deps) *Scanner

New builds a scanner from injected collaborators (ADR-0006). The scanner starts DISABLED — call Init to enable it — mirroring the pre-extraction package-main singleton (a struct literal with cache+maxBytes defaults that only Init flipped on). Collaborators are fixed at construction and never mutated afterwards (Init only touches clam/cache/maxBytes/enabled).

func (*Scanner) BodyScanEnabled

func (ss *Scanner) BodyScanEnabled() bool

BodyScanEnabled reports whether body scanning (ClamAV and/or YARA) is active. Unlike Enabled it still takes mu: the clam/yara collaborators are ordinary mu-guarded fields and this is a response-stage check, not the request gate.

func (*Scanner) CacheClear

func (ss *Scanner) CacheClear()

CacheClear empties the scan hash cache.

func (*Scanner) CacheEvict

func (ss *Scanner) CacheEvict(hash string) bool

CacheEvict removes a single hash from the scan cache, reporting whether it was present.

func (*Scanner) CacheGet

func (ss *Scanner) CacheGet(hash string) (hashcache.ScanCacheResult, bool)

CacheGet looks up a scan verdict (test support).

func (*Scanner) CacheReady

func (ss *Scanner) CacheReady() bool

CacheReady reports whether the scan hash cache is initialised.

func (*Scanner) CacheSet

func (ss *Scanner) CacheSet(hash string, r hashcache.ScanCacheResult)

CacheSet stores a scan verdict directly (test support and remote-scan result adoption).

func (*Scanner) CacheStats

func (ss *Scanner) CacheStats() (hits, misses int64, size int)

CacheStats returns hash-cache hit/miss counters and current size.

func (*Scanner) CheckDomain

func (ss *Scanner) CheckDomain(domain string) *Result

CheckDomain checks a bare hostname against the threat feed. Returns nil when no threat is found.

func (*Scanner) CheckRequestURL added in v1.0.247

func (ss *Scanner) CheckRequestURL(u *url.URL) *Result

CheckRequestURL is CheckURL for a URL the request path has already parsed. The verdict is identical; it just does not serialise the URL so the feed can parse it back. This is the form the proxy's per-request call site uses.

func (*Scanner) CheckURL

func (ss *Scanner) CheckURL(rawURL string) *Result

CheckURL checks a full URL against the threat feed. Returns nil when no threat is found.

func (*Scanner) ClamAVStatus

func (ss *Scanner) ClamAVStatus() string

ClamAVStatus returns a human-readable daemon connectivity string. Tier 2.3: Result is cached for clamStatusTTL to avoid hammering the ClamAV daemon on every admin dashboard poll. Cache is invalidated on Init().

func (*Scanner) ClamAVVersion added in v1.0.22

func (ss *Scanner) ClamAVVersion() (clamav.Version, bool)

ClamAVVersion returns the ClamAV engine + signature database version, so operators can see whether virus definitions are current. Returns ok=false when ClamAV is disabled, the client does not support VERSION, or the daemon is unreachable. Cached for clamVersionTTL (definitions change rarely) and invalidated on Init, mirroring ClamAVStatus.

func (*Scanner) Enabled

func (ss *Scanner) Enabled() bool

Enabled reports whether the scanner has been initialised.

Lock-free by contract — see the enabled field. This is the gate the proxy consults before any threat check, so it must stay free of mu. TestScannerEnabled_IsLockFree pins the property.

func (*Scanner) Init

func (ss *Scanner) Init(clamAddr string, maxBytes int64, cache *hashcache.HashCache)

Init configures the scanner.

clamAddr — ClamAV address string (see clamav.New); "" disables ClamAV.
maxBytes — maximum bytes to buffer per response (0 = use default 5 MiB).
cache    — hash cache to adopt; nil keeps the current one (ADR-0006: the
           cache is handed over here instead of being poked from outside).

func (*Scanner) MaxBytes

func (ss *Scanner) MaxBytes() int64

MaxBytes returns the buffer limit for body scanning.

func (*Scanner) RefreshSignatures added in v1.0.382

func (ss *Scanner) RefreshSignatures() bool

RefreshSignatures re-reads the ClamAV signature identity and reconciles the verdict cache against it, reporting whether an observation succeeded.

It exists because the reconciliation must not depend on somebody WATCHING. ClamAVVersion is otherwise called only by the dashboard metrics payload, so on a node whose dashboard nobody has open the signature change would never be noticed and the stale-clean window would run the full CacheTTL. The background poller in package main drives this on a fixed cadence; the 10-minute VERSION cache means a tick that lands inside the previous window is free.

func (*Scanner) ScanBody

func (ss *Scanner) ScanBody(data []byte) *Result

ScanBody scans a response body with ClamAV and YARA. Results are cached by SHA-256 to avoid redundant work. The entire scan is bounded by ScanBodyTimeout (fail-closed: blocks on timeout). Returns nil when the content is clean (or no scanner is enabled).

func (*Scanner) SignatureGeneration added in v1.0.382

func (ss *Scanner) SignatureGeneration() (string, bool)

SignatureGeneration reports the signature identity the cached verdicts were computed under, and whether one has been observed at all. Test/diagnostic accessor; the reconciliation is automatic.

type ThreatChecker

type ThreatChecker interface {
	Enabled() bool
	CheckURL(rawURL string) (bool, string)
	// CheckRequestURL is CheckURL for a URL the caller has already parsed —
	// same verdict, without the serialise-and-reparse round trip. See the
	// contract on threatfeed.Feed.CheckRequestURL.
	CheckRequestURL(u *url.URL) (bool, string)
	CheckDomain(domain string) (bool, string)
}

ThreatChecker is the threat-feed surface CheckURL/CheckDomain need.

type YARAMatcher

type YARAMatcher interface {
	Loaded() bool
	Enabled() bool
	Match(data []byte) []string
}

YARAMatcher is the YARA surface the scan pipeline needs. Loaded and Enabled are deliberately distinct to preserve pre-ADR-0006 behavior verbatim: BodyScanEnabled keys on rules-present only (Loaded), while the body scan additionally honors the runtime enable toggle (Enabled).

Jump to

Keyboard shortcuts

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