defences

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: AGPL-3.0 Imports: 15 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 defences describes what Vulnetix has built to protect a vulnerability that has no fix: virtual patches, which block a request at the edge, and countermeasures, which detect the exploit on a host.

The two are different promises and never share a line of output. A virtual patch stops the request; a countermeasure tells you it happened. Everything in this package keeps that distinction in the type, so a renderer cannot blur it by accident.

The data comes from the Vulnetix vulnerability database:

GET /v2/vuln/{id}/virtual-patches
GET /v2/vuln/{id}/countermeasures
GET /v2/virtual-patches/{uuid}/archive      (Pro)
GET /v2/countermeasures/{uuid}/archive      (Pro)

Every tier receives counts and the per-kind breakdown. Rule bodies and the archive URLs are Pro. "A defence exists for your vulnerability" is the warning and is not withheld; the rule is the product. Summary reflects that split.

The fetch is stubbed. Source is the seam: DefaultSource returns StateUnavailable for everything until the CLI wiring lands, and renderers treat that as "say nothing" rather than as "none exist". StaticSource is a working in-memory implementation for tests and previews.

Index

Constants

View Source
const ControlsFile = ".vulnetix/controls.json"

ControlsFile is where recorded compensating controls live, relative to the project root.

View Source
const DefaultControlLife = 90 * 24 * time.Hour

DefaultControlLife is how long a recorded control lasts when --until is not given. A compensating control is a loan against a patch that has not arrived, so it expires; the licence exception file works the same way.

Variables

View Source
var ErrNotAvailable = errors.New("defence lookup is not available in this build yet")

ErrNotAvailable is returned by the stub source. It means "this build cannot fetch defences yet", which is different from an API failure.

Functions

func FileName

func FileName(artifactID string, k Kind) string

FileName is the conventional name a rule of this kind is saved under.

func Flag

func Flag(k Kind) string

Flag is the `defend --for` spelling of a kind.

func Indexed

func Indexed(id string) bool

Indexed reports whether id has the shape of an advisory identifier.

The database looks up any advisory family and widens each id through its alias group, so a PYSEC or GO id finds defences filed under its CVE or GHSA. This used to allow only CVE, GHSA and CNVD, which under-reported; it now only refuses what is plainly not an identifier, and the server answers a malformed one per item.

func InferStack

func InferStack(root string) map[Kind]Hint

InferStack looks for evidence in the repository of which enforcement points are in front of the application, so the formats that fit can be listed first. The walk is bounded in both file count and file size.

func Name

func Name(k Kind) string

Name is the display name of a kind.

func Resolve

func Resolve(id string, aliases ...string) (string, bool)

Resolve picks the identifier to look up for a finding: its own if indexed, otherwise the first indexed alias. It reports false when none is.

func SetClientFactory

func SetClientFactory(f func() API)

SetClientFactory registers how the default source gets its client. It is a factory, not a client, because credentials are resolved after packages initialise: the source asks for one when it is first used.

func SetSource

func SetSource(s Source) (restore func())

SetSource replaces the default Source and returns a function that restores it. It exists for tests.

Types

type API

type API interface {
	// V2DefenceCounts is POST /v2/defences/counts: counts for every plan, the
	// defences with their console links for Pro. It chunks by 100 items.
	V2DefenceCounts(items []vdb.DefenceCountsItem) (*vdb.DefenceCountsResponse, error)
	// V2VulnDefences is GET /v2/vuln/{id}/{lane}: the full records, Pro only.
	V2VulnDefences(lane, identifier string) (map[string]interface{}, error)
	// V2DefenceArchive is GET /v2/{lane}/{uuid}/archive: one rule body, Pro only.
	V2DefenceArchive(lane, uuid string) ([]byte, error)
}

API is the part of the vulnerability database client the source uses. It is an interface so the source can be tested with a fake that answers as the API does.

type Body

type Body struct {
	Kind     Kind
	FileName string
	Content  []byte
	// SHA256 is the checksum the server sent with the body.
	SHA256 string
}

Body is a downloaded rule.

type Control

type Control struct {
	VulnID  string `json:"vulnId"`
	Package string `json:"package"`
	Version string `json:"version,omitempty"`
	// Ecosystem is optional context for the VEX statement.
	Ecosystem string `json:"ecosystem,omitempty"`
	Lane      Lane   `json:"lane"`
	Kind      Kind   `json:"kind,omitempty"`
	// Where is the person's own description: "ModSecurity, prod-eu ingress".
	Where      string    `json:"where"`
	RecordedAt time.Time `json:"recordedAt"`
	RecordedBy string    `json:"recordedBy,omitempty"`
	Until      time.Time `json:"until"`
	// Mode is the mode the rule states it is safe to start in, copied from the
	// rule so the PROTECTED line can repeat it ("log only" protects nothing).
	Mode       string `json:"mode,omitempty"`
	RuleSHA256 string `json:"ruleSha256,omitempty"`
}

Control is a statement by a person that a defence is in place for a finding that has no fix. The CLI cannot verify it is deployed: this is a record of a claim, with an expiry, and every renderer says so.

func (Control) Active

func (c Control) Active(now time.Time) bool

Active reports whether the control is still in date.

func (Control) Blocks

func (c Control) Blocks() bool

Blocks reports whether the control stops the request. A detection alone does not, and a rule still in log-only mode does not either.

func (Control) Expired

func (c Control) Expired(now time.Time) bool

Expired reports whether the control has lapsed.

type ControlSet

type ControlSet struct {
	Version  int       `json:"version"`
	Controls []Control `json:"controls"`
}

ControlSet is the loaded set of controls.

func LoadControls

func LoadControls(root string) (ControlSet, error)

LoadControls reads the controls file under root. A missing file is an empty set, not an error.

func (ControlSet) For

func (s ControlSet) For(vulnID, pkg string) []Control

For returns every control recorded for a vulnerability on a package, regardless of expiry, so a renderer can tell "none" from "lapsed".

func (ControlSet) Save

func (s ControlSet) Save(root string) error

Save writes the set back, sorted so the file diffs cleanly.

func (*ControlSet) Upsert

func (s *ControlSet) Upsert(c Control)

Upsert adds a control, replacing any earlier record for the same vulnerability, package and lane.

type Hint

type Hint struct {
	File string
	Line int
	// What is the token that matched, e.g. "aws_wafv2_web_acl".
	What string
}

Hint says where in a repository evidence of a given enforcement point was found. It is inference from files, not knowledge of what is deployed, and every renderer says so.

func (Hint) Where

func (h Hint) Where() string

Where renders the hint as file:line.

type Kind

type Kind string

Kind is the rule format. The values are the database's own.

const (
	KindSnort      Kind = "SNORT"
	KindSuricata   Kind = "SURICATA"
	KindModSec     Kind = "MODSECURITY"
	KindNginx      Kind = "NGINX"
	KindAWSWAF     Kind = "AWS_WAF"
	KindCloudflare Kind = "CLOUDFLARE_WAF"
	KindRegexL7    Kind = "REGEX_L7"
	KindSigma      Kind = "SIGMA"
	KindYARA       Kind = "YARA"
	KindSTIX       Kind = "STIX"
	KindOpenIOC    Kind = "OPENIOC"
)

func ParseFlag

func ParseFlag(s string) (Kind, bool)

ParseFlag resolves a `defend --for` value to a kind.

type Lane

type Lane string

Lane is which of the two promises a defence makes.

const (
	// LaneBlock is a virtual patch: it stops the request.
	LaneBlock Lane = "block"
	// LaneDetect is a countermeasure: it tells you it happened.
	LaneDetect Lane = "detect"
)

func LaneOf

func LaneOf(k Kind) Lane

LaneOf returns the lane a kind belongs to. An unknown kind is reported as detect: that is the weaker claim, so a format we do not recognise is never presented as something that blocks.

type LaneSummary

type LaneSummary struct {
	// Count is the total published, which every tier receives.
	Count int
	// ByKind is the per-format breakdown, which every tier receives.
	ByKind map[Kind]int
	// Rules carries the details, for Pro callers only.
	Rules []Rule
}

LaneSummary is what is known about one lane for one vulnerability.

func (LaneSummary) Kinds

func (l LaneSummary) Kinds() []Kind

Kinds returns the formats present in the lane, in a stable order.

type LookupOptions

type LookupOptions struct {
	// Pro is true when the caller's plan includes rule bodies and downloads. The
	// server decides what a plan receives; this only decides whether to ask for
	// detail.
	Pro bool
	// Detail asks for the full records (coverage notes, checksum, the exploit each
	// rule came from). It costs a request per lane per advisory, so a scan leaves
	// it off and `defend` turns it on.
	Detail bool
}

LookupOptions describes the caller.

type Rule

type Rule struct {
	UUID              string
	ArtifactID        string
	Kind              Kind
	Title             string
	Confidence        string // HIGH | MEDIUM | LOW
	DeployMode        string // the mode the rule says it is safe to start in, e.g. "log" or "block"
	FalsePositiveRisk string
	CoverageNotes     string
	MitreTechIDs      []string
	ExploitID         string
	ExploitSource     string
	ExploitURL        string
	// ArchiveURL is the relative path of the rule body, e.g.
	// /v2/virtual-patches/{uuid}/archive. Empty when the caller is not Pro.
	ArchiveURL string
	// ConsoleURL is the page for this rule in the Vulnetix console. The counts
	// endpoint returns it for Pro callers only.
	ConsoleURL string
	// SHA256 is the body checksum the archive endpoint also sends in
	// X-Vulnetix-Sha256, used to verify a download.
	SHA256 string
}

Rule is one defence artefact. ArchiveURL is set only for Pro callers.

type Source

type Source interface {
	// Lookup returns a Summary for each identifier it was able to look up.
	// Identifiers missing from the result were not looked up; Lookup does not
	// guess. It is called once per scan, with every no-fix identifier, so an
	// implementation is free to batch or to fan out under its own concurrency.
	Lookup(ctx context.Context, ids []string, opts LookupOptions) (map[string]Summary, error)

	// Download fetches one rule body. Pro only.
	Download(ctx context.Context, rule Rule) (Body, error)
}

Source is the seam between the CLI and the vulnerability database.

var Unavailable Source = &vdbSource{offline: true}

Unavailable is a Source that cannot ask: every lookup is StateUnavailable. It is what a test uses to be certain it never reaches the network.

func DefaultSource

func DefaultSource() Source

DefaultSource returns the Source the CLI uses.

func NewVDBSource

func NewVDBSource(api API) Source

NewVDBSource returns a Source backed by api.

type State

type State string

State is what the CLI can truthfully say about a finding's defences. The five "no rules to show" states are separate on purpose: collapsing them would let "we did not ask" read as "there is nothing".

const (
	// StateAvailable means rules exist and their details came back (Pro).
	StateAvailable State = "available"
	// StateGated means rules exist and only their counts came back.
	StateGated State = "gated"
	// StateNone means the database was asked and has nothing published yet. It
	// never means "cannot be defended": the database does not record that an
	// exploit was judged unobservable, only that nothing was built.
	StateNone State = "none"
	// StateNotIndexed means the identifier is not one that can be looked up: it is
	// not shaped like an advisory id, or the database refused it as input.
	StateNotIndexed State = "not_indexed"
	// StateNotChecked means the lookup was skipped: offline, or hidden by flag.
	StateNotChecked State = "not_checked"
	// StateFailed means the lookup ran and errored.
	StateFailed State = "failed"
	// StateUnavailable means this build cannot look defences up at all yet.
	// Renderers print nothing for it unless explicitly asked.
	StateUnavailable State = "unavailable"
)

type StaticSource

type StaticSource struct {
	// Summaries is keyed by upper-case identifier.
	Summaries map[string]Summary
	// Bodies is keyed by rule UUID.
	Bodies map[string]Body
}

StaticSource is an in-memory Source. It is a complete implementation, not a mock: it answers exactly as the API would, including withholding rule details from a caller that is not Pro.

func (StaticSource) Download

func (s StaticSource) Download(_ context.Context, rule Rule) (Body, error)

func (StaticSource) Lookup

func (s StaticSource) Lookup(_ context.Context, ids []string, opts LookupOptions) (map[string]Summary, error)

type Summary

type Summary struct {
	// ID is the identifier that was looked up.
	ID    string
	State State
	// Reason is a short explanation for the not-checked and failed states.
	Reason string
	Block  LaneSummary
	Detect LaneSummary
}

Summary is everything the CLI knows about the defences for one vulnerability.

func (*Summary) Classify

func (s *Summary) Classify()

Classify settles the state from the lane contents. A source calls this after filling the lanes so the rule is applied in one place.

func (Summary) HasAny

func (s Summary) HasAny() bool

HasAny reports whether any defence is known to exist, whether or not its details were returned.

func (Summary) Rules

func (s Summary) Rules() []Rule

Rules returns every rule with details, block first, in a stable order.

func (Summary) Total

func (s Summary) Total() int

Total is the number of defences across both lanes.

Jump to

Keyboard shortcuts

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