feeds

package
v0.1.10 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 71 Imported by: 1 module, 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 feeds is the pure library behind the feeds module: parsing of untrusted feed data, boundary validation, the HTTP fetcher, scheduling rules and the IOC verdict. It has no database, no events and no job registration; the module wiring calls into it.

Everything that reads feed data is fail-closed (SYS-6): size and row limits, bad rows are rejected and counted, never half-accepted.

Index

Constants

View Source
const (
	OriginNVD = "nvd"
	OriginCNA = "cna" // the CNA's affected[] list of the CVE record
	OriginADP = "adp" // an Authorized Data Publisher's (CISA) list of the CVE record
)

The origins of a range (feeds_cve_range.origin).

View Source
const (
	RecordPublished = "PUBLISHED"
	RecordRejected  = "REJECTED"
)

The states of a CVE record.

View Source
const (
	DefaultAffected   = "affected"   // versions the entry does not list are affected
	DefaultUnaffected = "unaffected" // versions the entry does not list are not affected
	DefaultUnknown    = "unknown"    // the entry does not say (absent, or another word)
)

The defaultStatus words of an affected entry, as feeds_cve_range.default_status keeps them (NVD's rows: "").

View Source
const (
	MetricNVD = "nvd" // NVD's own score ("Primary" in NVD's record)
	MetricCNA = "cna" // the CVE Numbering Authority's
	MetricADP = "adp" // CISA's Authorized Data Publisher (Vulnrichment)
)

The scorers of a CVSS score (feeds_cve_metric.source), in the order PickCVSS prefers them within one CVSS version.

View Source
const (
	DistroUbuntu = "ubuntu"
	DistroDebian = "debian"
	DistroAlpine = "alpine"

	DistroFixed       = "fixed"
	DistroNotAffected = "not_affected"
	// DistroOpen is the distribution's word "affected, no fix yet" (Debian's open entries, an Ubuntu release with no fixed event):
	// kept for every CVE of the CISA list (the matcher judges a package the distribution built by its word alone) and for the tier
	// CVEs of the devices' packages (DistroWant.Row), for "Updates to plan".
	DistroOpen = "open"
)

Distribution backport data. Ubuntu and Debian fix their packages without changing the upstream version, so a patched OpenSSH stays inside NVD's affected range. Three built-in feeds say, for the CVEs of the CISA list, which source package of which release is fixed in which distribution version, or not affected; ubuntu-osv and debian-tracker also keep the fixed versions of the tier CVEs for the packages the devices run (DistroWant), for findings' "Updates to plan":

  • ubuntu-osv: Canonical's osv-all.tar.xz, every Ubuntu release in one file; a "fixed" event is the first fixed version.
  • ubuntu-vex: Canonical's vex-all.tar.xz; only its not_affected statements are kept (its "fixed" statements name the archive's current version, not the first fixed one, so they would keep a patched device suspected).
  • debian-tracker: the Debian Security Tracker JSON, every Debian release in one file: resolved with a fixed version, or resolved with fixed version "0" (not affected).
  • alpine-osv: OSV.dev's Alpine ecosystem (all.zip, one OSV record per CVE converted from Alpine's secdb), every Alpine branch OSV lists in one file: a "fixed" event is the first fixed apk release of the source package on that branch, "0" not affected. KEV CVEs only (no tier rows), and pulled only while a device states Alpine (the inventory gate without a first pull).

Each file covers every release, so a pull names none of the releases the customer runs. Open, needs-triage, deferred and ignored entries are not kept: they change nothing about a finding.

View Source
const (
	DistroReasonPostponed   = "postponed"   // fixed in a later point release instead
	DistroReasonIgnored     = "ignored"     // Debian decided not to fix it in this release
	DistroReasonMinor       = "minor"       // a minor issue: no security advisory, a later point release fixes it
	DistroReasonUnimportant = "unimportant" // Debian rates it unimportant for its packages
	DistroReasonEndOfLife   = "end_of_life" // the release no longer gets security support for the package
)

Why Debian publishes no security update for an entry it lists as affected (DistroFix.Reason, feeds_distro_fix.reason).

View Source
const (
	ListCISA      = "cisa"
	ListVulnCheck = "vulncheck"
)

The lists of feeds_kev.list.

View Source
const (
	SignalExploited     = "exploited"      // on an exploited list, or a vendor says it is exploited
	SignalPublicExploit = "public_exploit" // a public exploit or a scan template exists
)

The signal kinds (feeds_signal.kind) this module writes now. Open vocabulary: decoders of other sources add kinds of their own.

View Source
const (
	// BackoffBase is the first retry delay after a failed pull.
	BackoffBase = 5 * time.Minute
	// BackoffMax caps the retry delay (never longer than the feed's own interval).
	BackoffMax = 6 * time.Hour
	// MaxDataAge is INV-9: data should be at most 60 minutes old beyond the
	// moment its pull was due.
	MaxDataAge = 60 * time.Minute
)

The back-off after a failed pull and the staleness rule, as pure functions of an injected clock (INV-8, INV-9). When a feed is pulled regularly is its schedule (feedschedule.go).

View Source
const (
	EventNewKEV        = "feeds.vuln.new_kev"
	EventVulnUpdated   = "feeds.vuln.updated"
	EventSyncBaseline  = "feeds.sync.baseline"
	EventRangesUpdated = "feeds.ranges.updated"
)

Event names and payloads (CONTRACT "Events"). Consumers: inventory, scan, notify.

View Source
const (
	AnsweredCISA   = "CISA"
	AnsweredMirror = "CISA GitHub mirror"
)

What a pull of the CISA list records as the address that answered (feeds_source.answered_by, Feed.answered_by).

View Source
const (
	MaxBodyBytes = 5_000_000 // bigger input is ErrTooLarge (413 too_large)
	MaxRows      = 50_000    // more rows stops parsing and sets Truncated
	PreviewRows  = 20        // records kept by Result.Preview
	MaxRejects   = 20        // rejected rows listed individually
	MaxRegexLen  = 200
	MaxPathLen   = 200
	MaxURLLen    = 500
	MaxNameLen   = 60
)

Limits (INV-2).

View Source
const DefaultCustomHours = 6

DefaultCustomHours is how often a new custom feed pulls until someone changes it.

View Source
const (
	DefaultFetchTimeout = 60 * time.Second
)

Fetch limits.

View Source
const DistroGiveUpFailures = KEVStaleChecks

DistroGiveUpFailures is how many pulls in a row may fail, with none ever completed, before the plan stops waiting for a distribution feed (KEVStaleChecks: the same count of checks after which the exploited list is called stale).

View Source
const (

	// EPSSLikely is the score from which a CVE is "likely to be exploited" (tier 2): FIRST's own example
	// threshold, 17,562 CVEs on 2026-11-14.
	EPSSLikely = 0.1
)

The EPSS score of every CVE: FIRST publishes the scores of all CVEs once a day as one gzip CSV ("#model_version:…,score_date:…", "cve,epss,percentile", then one row per CVE). Measured 2026-11-15: 2,849,094 bytes for 406,543 CVEs, about 12 MB once unpacked; 15.5 MB in SQLite. The scores feed tier 2 (EPSS at or above EPSSLikely, published in the last 12 months) and are kept for every CVE (CVE pages, scan-found older CVEs).

View Source
const HaveWindow = 7 * 24 * time.Hour

HaveWindow is how far before the answered entry "I have this" reaches back: the 7 days of "This week" on Home, so the other entries of that product the same week also become findings.

View Source
const KEVMirrorURL = "https://raw.githubusercontent.com/cisagov/kev-data/develop/known_exploited_vulnerabilities.json"

KEVMirrorURL is CISA's own GitHub mirror of the KEV catalog (the cisagov/kev-data repository). Every check of the CISA list at its built-in address asks it as well as cisa.gov and keeps the newer catalog. Same file, same parser, same limits.

View Source
const KEVStaleChecks = 6

KEVStaleChecks is how many checks of the CISA list may pass without a good pull before the admins are told.

View Source
const MaxNewKEVPage = 500

MaxNewKEVPage bounds one NewKEVSince read.

View Source
const (
	// NVDPageSize keeps one hasKev answer under MaxBodyBytes: the largest 100 consecutive KEV records measured 1.9 MB on 2026-11-13
	// (one record alone is 1 MB), against 3.1 MB for 200.
	NVDPageSize = 100
)

The NVD CVE API 2.0 decoder. One decoder reads every NVD answer the box asks for (the exploited-list selector ?hasKev of nvd-kev, the date windows and the whole-set walk of nvd-recent, one CVE by id) and writes one catalogue (writeNVDRecords). Nothing of the customer is in a request: only a page index, a date window, or the id of a CVE a public list names.

View Source
const (
	// PullEvery is how often the pull job looks for feeds that are due. Each feed keeps its own interval and
	// back-off (State); this only bounds how late a due pull can start, so INV-9 (interval + 60 min) holds.
	PullEvery = 5 * time.Minute
)

Pull schedule.

View Source
const (

	// RecentPageSize records per request: about 5 MB of JSON at the measured 5.2 KB a record.
	RecentPageSize = 1000
)

The catalogue pull of NVD records (nvd-recent): every CVE published in the window, then the records NVD changes, and, when many are missing, one pass over the whole NVD set for the older CVEs the retention rule keeps (an exploited-list entry, a signal of any age). Measured 2026-11-15 without a key: 104,135 CVEs in 12 months (19,630 + 26,874 + 57,631 in three 120-day windows); a page of 2,000 records was 1.2 MB on the wire (gzip) and 10.4 MB of JSON, answered in 13 s; NVD changes about 1,700 records a day. The fill of the window is about 105 requests of RecentPageSize records (about 60 MB on the wire, about 25 minutes with nvdPause between requests), spread over pulls of at most pullBudget: each page is stored as it comes and feeds_nvd_cursor says where the next pull goes on. After a good pull, a daily update asks only for the records NVD changed since one day before it, and keeps those the retention rule keeps, whatever their age. Nothing of the customer is in a request: only the date window, the record number it starts at, or the id of a CVE a public list names.

View Source
const (
	// RecordMaxBytes bounds one record. The largest records (Linux kernel, products with thousands of builds) are a few MB;
	// a larger one is skipped and counted, never read.
	RecordMaxBytes = 4 << 20
)

CVE records. The CVE Program publishes every CVE record (CVE JSON 5) in its public cvelistV5 repository: the CNA's own words (most often the vendor's: affected versions, title, solutions, workarounds, references with tags, weaknesses) and the ADPs' additions (CISA's Vulnrichment: SSVC decision points, CWE, CPE names; suppliers' own affected lists). NVD lags behind the CNA, often by weeks, and defers most CVEs: the record is the first and often the only structured statement of which versions are affected. ParseCVERecord reads one record whole; recordRanges turns its affected lists into catalogue ranges.

View Source
const RecordTextType = VendorNotation + "record-text"

RecordTextType is the version_type of a row read from a CVE record's words (esxiTextRows), and of a row a reader adds from it (esxiLaterTrains): kept in the vendor's notation, read only by the product's version scheme.

View Source
const RefOther = "other"

RefOther is the group of a reference with no tag of refGroups.

View Source
const RefsNVD = "nvd"

RefsNVD is the source of a reference NVD lists (feeds_cve_ref.source); the CVE record's are OriginCNA and OriginADP.

View Source
const UnaffectedNotation = VendorNotation + "unaffected"

UnaffectedNotation is the version_type of a row that states versions the vendor says are NOT affected ("unaffected" from 0 before 24.4R1: Juniper's statement that releases before 24.4 do not have the flaw; unaffectedRows). Kept in the vendor's notation, so no reader of affected ranges reads it (Range.Generic, RangeScheme); StatementScheme reads it for a product's version scheme.

View Source
const VendorNotation = "vendor:"

VendorNotation is the prefix of the version_type of a row kept as the vendor states it (display-only for the generic comparison).

Variables

View Source
var (
	ErrInvalidURL       = errors.New("feeds: invalid feed address")
	ErrHTTPSRequired    = fmt.Errorf("%w: use https:// (http:// is only allowed for internal addresses)", ErrInvalidURL)
	ErrInvalidFormat    = errors.New("feeds: format does not fit the feed kind")
	ErrInvalidName      = errors.New("feeds: invalid feed name")
	ErrDuplicateName    = errors.New("feeds: duplicate feed name")
	ErrDuplicateURL     = errors.New("feeds: another feed already uses this address")
	ErrBlockedHost      = errors.New("feeds: the address is the box itself, loopback, link-local or cloud metadata")
	ErrInvalidAuth      = errors.New("feeds: invalid authentication settings")
	ErrInvalidSecret    = errors.New("feeds: invalid secret")
	ErrInvalidWhitelist = errors.New("feeds: invalid whitelist entry")

	ErrTooLarge  = errors.New("feeds: data too large")
	ErrBadConfig = errors.New("feeds: bad parser configuration")
	ErrBadSample = errors.New("feeds: data could not be parsed")
)

Sentinel errors. Callers map them to API codes (invalid_url, too_large, ...).

View Source
var BodyLimits = map[string]int64{"feeds_post_feeds_parse_test": 8 << 20}

BodyLimits is the per-operation request cap this module needs above the server default (operationId → bytes). cmd/vedette hands it to server.Config through moduleWiring.BodyLimits.

parse-test takes a sample of up to 5 000 000 characters (contract.ts, INV-2) inside a JSON body: newlines and quotes grow by one byte each when escaped, so 8 MiB holds any real sample. A bigger body is refused before it is read.

DistroReasons lists every reason.

View Source
var ErrAlertOff = errors.New("feeds: alerts are off")

ErrAlertOff is what Deps.Alert answers while nothing can be sent (the notify module is off): the watch tries again at its next run, quietly, and records nothing as sent.

View Source
var ErrBlockedAddress = errors.New("feeds: connection to this address is refused")

ErrBlockedAddress is a connection the dialer refuses by address.

View Source
var ErrBoxAddrsUnknown = errors.New("feeds: the box's own addresses are not known yet")

ErrBoxAddrsUnknown means the box does not know its own addresses yet (vedette-host has not answered since the start), so no destination can be checked against them: the connection is refused, as notify does. The next pull retries.

View Source
var ErrFeedDisabled = errors.New("feeds: the feed is turned off")

ErrFeedDisabled is returned by Fetch for a feed that is turned off (INV-8, FORBID-3).

View Source
var ErrFileChanged = errors.New("feeds: the file changed since the part already read")

ErrFileChanged is a resumed download whose file changed since the part already read (Request.WantTotal).

View Source
var ErrNotFound = errors.New("feeds: not found")

ErrNotFound is returned when a feed or a record does not exist.

View Source
var ErrOwnAddress = fmt.Errorf("%w: it is Vedette itself", ErrBlockedAddress)

ErrOwnAddress is ErrBlockedAddress for Vedette itself: loopback, an address of core's own container, or one of Vedette's own ports on the machine's addresses (vedette-host's, the container's gateway). userError says so in plain words.

View Source
var ErrRedirect = errors.New("feeds: redirect refused")

ErrRedirect is a redirect the fetcher refuses.

View Source
var Migrations = mustSub(migrationFiles, "migrations/sqlite")

Migrations holds the SQLite migrations of the feeds module, rooted at the directory that holds the NNNN_*.sql files. Pass it to store.Migrate(ctx, db, "feeds", feeds.Migrations) after core's.

Functions

func Backoff

func Backoff(failures int) time.Duration

Backoff is the retry delay after n consecutive failures: 5 min doubling, capped at BackoffMax.

func CVEIDURL

func CVEIDURL(base, cve string) (string, error)

CVEIDURL builds the request of one CVE's record: base?cveId=CVE-…. Only for a CVE a public list names (an exploited-list entry or a signal), never for one only the customer's devices make interesting.

func CVERecordURL

func CVERecordURL(base, cve string) (string, error)

CVERecordURL is the address of one record under base (the cves directory of cvelistV5): base/<year>/<number/1000>xxx/<CVE>.json, as the repository lays them out ("CVE-2024-3400" -> "2024/3xxx"). Only the CVE ID is in the request.

func CheckAuth

func CheckAuth(t AuthType, headerName, username string, newSecret *string, hasStored bool) error

CheckAuth validates the auth settings of a feed (INV-6). newSecret is the secret typed by the user, nil when editing and keeping the stored one; hasStored says a secret is already stored.

func CheckDest

func CheckDest(raw string, own ownAddrs) error

CheckDest is the save-time half of INV-17: an address whose host is a literal IP the pull would refuse (link-local, cloud metadata, unspecified, multicast, in any transition form: blockedText; Vedette itself: loopback, an address of own.self, or one of own.machine on a port of vedettePorts: ownText) or a loopback name (localhost, *.localhost: ownText) is refused when the feed is saved, with the pull's sentence. Other names are not resolved here (no DNS lookup in a request; the answer could change before the pull anyway): a name that resolves to a refused address is still refused by the dialer at every pull (guardedDial, destControl).

func CheckKindFormat

func CheckKindFormat(k Kind, f Format) error

CheckKindFormat is INV-5: the format must fit the kind.

func CheckName

func CheckName(name string, others []string) error

CheckName is INV-5: a non-empty name of at most 60 characters, unique case-insensitively among the built-in feed names and `others` (the names of the other custom feeds; leave out the feed being edited).

func CheckParser

func CheckParser(kind Kind, p Parser) error

CheckParser validates the rules before a run (parsers.ts checkParser) so a bad configuration is a clear error: format fits the kind, only known fields, JSONPaths compile, regexes compile (RE2 syntax, at most 200 chars), the delimiter is one ordinary character, and the required field is mapped.

func CheckSecret

func CheckSecret(s string) error

CheckSecret is the INV-6 rule on its own (for API validation).

func CheckURL

func CheckURL(raw string) error

CheckURL is the INV-2 address rule: https, or http for internal hosts only. Credentials in the address are refused (they belong in the auth settings).

func DisplayOf

func DisplayOf(vendor, product string) string

DisplayOf is the name people recognise for a vendor and product.

func FieldIDs

func FieldIDs(k Kind) []string

FieldIDs lists the record fields of a kind, in order.

func FormatAllowed

func FormatAllowed(k Kind, f Format) bool

FormatAllowed reports whether a custom feed of this kind may use the format.

func IOCConfidence

func IOCConfidence(gs []IOCSighting) (conf float64, c2 bool)

IOCConfidence is how sure the switched-on feeds that list an indicator are, together, that it is bad (0 to 1, two decimals), and whether one of them lists it as a botnet command-and-control server. A switched-off feed's listing is stale and does not count. The sightings are those of IOCLookup (a built-in list's Confidence is its weight there).

func IOCKey

func IOCKey(kind, value string) (string, bool)

IOCKey is the canonical identity of an IOC value: an IP is its exact address (never widened to a /24 or any range), a domain is lower-case without a trailing dot. ok is false for a value that is neither, and for a private, reserved or special-purpose address or a local, reserved or public-suffix name, which are never IOCs.

func IsInternalHost

func IsInternalHost(host string) bool

IsInternalHost is the INV-2 list of hosts that may use plain http.

func IsStale

func IsStale(now, lastSuccess time.Time, intervalHours int) bool

IsStale is the INV-9 check: an enabled feed is stale when its data is older than its interval plus MaxDataAge (the pull is overdue by more than an hour). A feed that never succeeded is stale.

func KindOf

func KindOf(key string) string

KindOf is the device type suggested when someone answers "I have it" (S-FEED-2): a hint for the manual device, not a classification.

func MatchName

func MatchName(vendor, product string, record bool) (string, string)

MatchName is the vendor and product a range names, as the matcher compares them with a device's software: a CPE's own names; for a CVE record's product key (record), the product the catalogue knows by that name (core/productid ByRangeName), by its NVD name when it has one, else by its own normalised name; a record key the catalogue does not know stays as it is. So a record that names "Palo Alto Networks" "PAN-OS" reaches the device NVD's paloaltonetworks:pan-os names.

func NVDPageURL

func NVDPageURL(base string, start int, from, to time.Time) (string, error)

NVDPageURL builds one request of the exploited-list selector: base?hasKev&resultsPerPage=N&startIndex=I, plus the lastMod window for an incremental pull (from and to non-zero).

func NewClient

func NewClient(timeout time.Duration) *http.Client

NewClient returns an http.Client with explicit timeouts (never DefaultClient) whose connections go through the address guard: link-local and metadata addresses are refused for every feed, plain http only reaches private or loopback addresses, and the host is resolved once per connection (no DNS rebinding). Environment proxies are not used. A Client supplied to Fetcher instead of this one is the caller's responsibility (tests only).

func RangeScheme

func RangeScheme(r Range) (s *versionscheme.Scheme, sp versionscheme.Span, fixed *versionscheme.Version, ok bool)

RangeScheme is the version scheme of the product a range names (core/productid's catalogue product of its CPE or of its record key, ByRangeName), with the range read in it: its bounds as a versionscheme.Span, and its fixed release when it states one. ok is false when the product has no scheme, a bound does not read in it, the row names one version in its CPE (pinnedInCPE), or it is a CVE record's row that states no version at all (recordBounded): then the row says only what its words say. The matcher reads a row kept in a vendor's notation (Range.Generic false) only through this; the brief shows each row's train and fixed release. A row that states unaffected versions (Range.Unaffected) or holds only on some models (Range.ModelLimited) is no affected range: false, StatementScheme reads those.

func ReadSourceNames

func ReadSourceNames(ctx context.Context, q *sql.DB) (map[string]string, error)

ReadSourceNames reads the name people see of every feed (feeds_source.name), by id: a reasons line names its sources this way, never by id.

func ReadUrgencyFacts

func ReadUrgencyFacts(ctx context.Context, q *sql.DB, cves []string) (map[string]UrgencyFacts, error)

ReadUrgencyFacts reads the urgency facts of these CVEs through q once (NewUrgencyReader(q).Facts).

func RecentPageURL

func RecentPageURL(base string, byPublished bool, from, to time.Time, start, size int) (string, error)

RecentPageURL builds one request of a date window: base?pubStartDate=…&pubEndDate=… (byPublished, the fill of the window) or lastModStartDate=…&lastModEndDate=… (an update), &resultsPerPage=size&startIndex=start.

func RefGroups

func RefGroups() []string

RefGroups is the groups a reference can be shown under, in order, RefOther last.

func SampleFor

func SampleFor(k Kind, f Format) (text, label string, ok bool)

SampleFor returns the built-in sample of a kind and format, with its label.

func SchemeProduct

func SchemeProduct(r Range) bool

SchemeProduct says the range names a product whose versions the product catalogue declares a version scheme for (core/productid ByRangeName, field "scheme"): its CVE record rows are read through that scheme only (RangeScheme).

func Severity

func Severity(score float64, version string) string

Severity is the band of a CVSS base score as FIRST and NVD write it: CVSS 3.x and 4.0 NONE (0), LOW (0.1–3.9), MEDIUM (4.0–6.9), HIGH (7.0–8.9), CRITICAL (9.0–10.0); CVSS 2.0 LOW (0–3.9), MEDIUM (4.0–6.9), HIGH (7.0–10.0), with no CRITICAL.

func StatementScheme

func StatementScheme(r Range) (s *versionscheme.Scheme, sp versionscheme.Span, unaffected, ok bool)

StatementScheme reads, in its product's version scheme, a CVE record row that only supports a "not affected" verdict: a range the vendor states unaffected (unaffected true: Juniper's "0 lessThan 24.4R1", whatever the model) or an affected range that holds only on some models (ModelLimited, unaffected false: a version outside every such range of a product whose unlisted versions are unaffected is not affected, one inside it is not known to be). ok is false for any other row, and as RangeScheme's for one that does not read.

func VulnCheckPageURL

func VulnCheckPageURL(base, cursor string) (string, error)

VulnCheckPageURL is the address of one page of the list under base (the built-in address or a mirror's). The list is read with VulnCheck's cursor paging: the first page opens a session (start_cursor), every next one sends back the cursor the page before gave (_meta.next_cursor) until a page has none. Page numbers are not used: the number of pages grows with the list (62 at 6,136 entries in November 2026), and the cursor is VulnCheck's documented way to read a whole index.

func WalkPageURL

func WalkPageURL(base string, start, size int) (string, error)

WalkPageURL builds one request of the walk over the whole NVD set: base?resultsPerPage=size&startIndex=start.

Types

type AffectedRow

type AffectedRow struct {
	CPE                                    string
	StartIncl, StartExcl, EndIncl, EndExcl string
}

AffectedRow is one vulnerable CPE match entry of a CVE: the CPE 2.3 criteria and its version range (empty bounds are absent).

func KEVRecordRows

func KEVRecordRows(ranges []Range, vendor, product string) ([]AffectedRow, string)

KEVRecordRows is the view of kevRecordView for one CVE: of its record ranges, the CNA's rows of the product an exploited-list entry names (vendor, product), as the matcher's CPE entries, with "cve.org" for a complete list or "cve.org-partial"; none for a vendor of recordSkipVendors or a "Multiple Products" entry.

type AnnouncedKEV

type AnnouncedKEV struct {
	NewKEVEvent
	At time.Time
}

AnnouncedKEV is one feeds.vuln.new_kev as the box recorded it: the entry and when feeds announced it.

type Auth

type Auth struct {
	Type       AuthType
	HeaderName string // AuthHeader
	Username   string // AuthBasic
	Secret     Secret
}

Auth is the credential set the fetcher injects.

type AuthType

type AuthType string

AuthType is how a feed authenticates.

const (
	AuthNone   AuthType = "none"
	AuthHeader AuthType = "header"
	AuthBearer AuthType = "bearer"
	AuthBasic  AuthType = "basic"
)

Authentication types.

type Brief

type Brief struct {
	CVE                string
	Title, Description string // the CNA's title ("" when it gives none); NVD's English description, else the CNA's
	// Display is the product in plain words: the exploited-list entry's when the CVE is on a list, else the first of Products.
	Display string
	// Products is the vendor and product of the ranges that count, "vmware esxi", distinct, sorted, at most briefMaxProducts.
	Products            []string
	Published, Modified *time.Time
	NVDStatus           string     // NVD's vulnStatus ("Analyzed", "Deferred" …); "" until NVD answered
	NVDAt, RecordAt     *time.Time // when NVD answered and when the CVE record was read; nil: never
	CWE                 []Weakness
	CVSS                *BriefCVSS // PickCVSS of Scores; nil when the CVE has no score
	Scores              []Metric   // every stored score, newest CVSS version first, then NVD, the CNA, CISA's ADP
	Lists               []ListEntry
	Signals             []BriefSignal
	// Ranges is every affected-versions row, with Counts set on the rows the matcher reads (rangeOrigin: NVD's when NVD gives any,
	// else the CVE record's); the other origin's rows stay for what they say (a CNA's fixed release beside NVD's exact versions).
	Ranges []BriefRange
	// RangesFrom is the origin of the rows that count (OriginNVD, OriginCNA, OriginADP; "" when none); RangesComplete says, for the
	// CVE record's rows, whether every product's list says what an unlisted version is.
	RangesFrom     string
	RangesComplete bool
	// Fixes is the fixed release of each release train the ranges state, as the product's version scheme reads them (RangeScheme):
	// VMware's 8.0 U3d (build 24585383) for train 8.0 U3. One per product and train, the vendor's (CNA, ADP) before NVD's; none for a
	// product without a scheme. A row a scheme does not read keeps its fixed release in Ranges.
	Fixes                []BriefFix
	References           []Reference // grouped: ordered by Group (refGroups), then by address
	Solution, Workaround string      // the CNA's text; "" when the record has none
	SSVC                 SSVC
	EPSS                 *BriefEPSS // nil when epss-all holds no score for the CVE
	NVDURL, RecordURL    string     // the CVE's pages at NVD and at the CVE Program
}

Brief is everything the box knows about one CVE, in one read model: the CVE page, the summary card of a finding, the AI context, notices and reports all read it, and none assembles CVE data of its own. Every value comes from the stored catalogue and is read by one function each (PickCVSS, Severity, rangeOrigin, ReadVector, refGroup); nothing is fetched to answer it.

type BriefCVSS

type BriefCVSS struct {
	CVSS
	Severity string         // Severity(Score, Version): "CRITICAL", "HIGH" …
	Reading  *VectorReading // nil when the vector cannot be read
}

BriefCVSS is the picked CVSS score with its band and its vector read into words.

type BriefEPSS

type BriefEPSS struct {
	Score, Percentile float64
	Day               string // FIRST's score date; "" when the file gave none
	WeekAgo           *float64
	History           []EPSSDay
}

BriefEPSS is FIRST's EPSS score of the CVE: today's, the day FIRST scored it, the score of a week before and the days the box kept (feeds_epss_hist, only for CVEs on a list or with a signal), oldest first.

type BriefFix

type BriefFix struct {
	Vendor, Product string // the range's product, as stored ("vmware", "esxi")
	Origin          string // who stated it (OriginCNA, OriginADP, OriginNVD)
	Train           string // "8.0 U3"
	Release         string // "8.0 U3d (build 24585383)"
}

BriefFix is the fixed release a vendor states for one release train of a product, as its version scheme reads the CVE's ranges.

type BriefRange

type BriefRange struct {
	Range
	Counts              bool
	Versions            string
	Train, FixedRelease string
}

BriefRange is one affected-versions row read for people: Versions says which versions in words ("from 2.0 before 2.4.58", "7.0 update_1", "every version"; a row its product's version scheme reads in the scheme's words: "from 8.0 before 8.0 U3d (build 24585383)"). Train is the release train the row's end belongs to ("8.0 U3") and FixedRelease its fixed release ("8.0 U3d (build 24585383)"), as the scheme reads them; "" when no scheme reads the row.

type BriefSignal

type BriefSignal struct {
	Signal
	SourceName string // the feed's name ("Metasploit"); the source id when no feed of that id exists
}

BriefSignal is one feeds_signal row of the CVE with the name of the feed that wrote it. Kinds and sources are read as stored, so a new kind or source appears here without a change.

type CVERecord

type CVERecord struct {
	CVE   string
	State string // RecordPublished or RecordRejected
	// Assigner is the CNA's short name ("oracle", "vmware"): the vendor of an affected entry that names none.
	Assigner  string
	Published time.Time // cveMetadata.datePublished; zero when the record gives none or one that is not a time
	Updated   time.Time // cveMetadata.dateUpdated
	// Title is the CNA's title; Description its English description; Solution and Workaround the English text of its solutions
	// and workarounds (several joined by a blank line). Each capped at the catalogue's column size, control characters removed.
	Title, Description   string
	Solution, Workaround string
	CWE                  []string // "CWE-787", the CNA's then the ADPs', in that order, without repeats
	// SSVC is CISA's decision points (Vulnrichment): exploitation none|poc|active, automatable yes|no, technical impact
	// partial|total. Empty when no ADP gave them.
	SSVC   SSVC
	Refs   []RecordRef
	Ranges []Range // the affected versions Vedette can compare (recordRanges); CVE and Origin set
	// Skipped is the affected entries whose versions could not be read without guessing (git commits, wildcards, text, holes);
	// their product has no range from this record.
	Skipped int
	// StatedDropped is the products of Skipped whose versions are not kept as the vendor states them either: more rows than
	// recordMaxStatedProduct, or past recordMaxStated for the record.
	StatedDropped int
	// contains filtered or unexported fields
}

CVERecord is what Vedette keeps of one CVE record.

func ParseCVERecord

func ParseCVERecord(data []byte, cve string) (CVERecord, error)

ParseCVERecord reads one CVE JSON 5.x record of cve. A record that is not CVE JSON 5.x (one JSON value, nothing after it), is not cve's, has another state than published or rejected, or is larger than RecordMaxBytes fails the parse. A rejected record keeps only its state: no product is affected. Everything else is read as the record gives it, within the caps above, and the affected lists become ranges only where they can be compared without guessing (recordRanges).

type CVSS

type CVSS struct {
	Score   float64 // 0.0 … 10.0, one decimal
	Version string  // "4.0", "3.1", "3.0" or "2.0"
	Source  string  // MetricNVD, MetricCNA or MetricADP
	Vector  string  // the vector string of that score ("CVSS:3.1/AV:N/…", v2 "AV:N/AC:L/…")
}

CVSS is the CVSS base score every page shows for a CVE (PickCVSS): one scorer's score of one CVSS version, always with its vector (FIRST: a score is shown with its vector). The band follows from Score and Version (Severity), so it is not kept.

func PickCVSS

func PickCVSS(ms []Metric) (CVSS, bool)

PickCVSS is the one rule that chooses the CVSS score of a CVE, for every reader (findings, the plan, the CVE page, reports): the newest CVSS version present (4.0, 3.1, 3.0, then 2.0), and within it NVD's own score before the CNA's before CISA's ADP. ok is false when the CVE has no score.

type CatalogueEntry

type CatalogueEntry struct {
	CVE                 string
	Published, Modified *time.Time
	NVDStatus           string     // "" until NVD answered
	NVDAt, RecordAt     *time.Time // when NVD answered, when the CVE record was read; nil: never
	Title, Description  string
	CVSS                *CVSS // PickCVSS of the stored scores; nil when none
	Severity            string
	EPSS, Percentile    *float64
	// RangesFrom is the origin of the ranges that count (rangeOrigin): OriginNVD, OriginCNA, OriginADP, or "" when none;
	// RangesComplete says, for the CVE record's rows, whether they make a complete list: every row's entry says
	// affected or unaffected for the versions it does not list.
	RangesFrom     string
	RangesComplete bool
}

CatalogueEntry is one CVE of the catalogue as the matcher and the pages read it.

type DROPList

type DROPList struct {
	Prefixes []string
	Stats
}

DROPList is a parsed Spamhaus DROP list: its networks in canonical form ("192.0.2.0/24"; a network of one address as the address), each once, in list order, with the accounting of the rows dropped (INV-3).

func ParseSpamhausDROP

func ParseSpamhausDROP(data []byte, maxRows int) (DROPList, error)

ParseSpamhausDROP reads a Spamhaus DROP list, in the JSON form or the text form, and fails closed: a row that is not a canonical public network within the length bounds is rejected and counted by reason, and the whole list is refused when it is larger than MaxBodyBytes, holds more than maxRows rows, has no accepted network, or, in the JSON form, does not end with exactly one metadata record whose count equals the rows read (a list cut short in transit).

type DateFormat

type DateFormat string

DateFormat tells the date normaliser how to read a date field.

const (
	DateAuto  DateFormat = "auto"
	DateDMY   DateFormat = "dmy"
	DateMDY   DateFormat = "mdy"
	DateEpoch DateFormat = "epoch"
)

Date formats of a date field.

type Decoder

type Decoder string

Decoder says which parser a built-in feed needs.

const (
	DecoderMetasploit Decoder = "metasploit"    // parseMetasploitModules: Metasploit's db/modules_metadata_base.json
	DecoderExploitDB  Decoder = "exploit-db"    // parseExploitDBIndex: Exploit-DB's files_exploits.csv
	DecoderPoCGitHub  Decoder = "poc-in-github" // parsePoCInGitHub: the PoC-in-GitHub repository as one tar.gz archive
)

The decoders of the public-exploit feeds.

const (
	DecoderChrome  Decoder = "chrome-releases"  // parsePostFeed (Atom), then chromeForms on each post
	DecoderAndroid Decoder = "android-bulletin" // androidNotes of this month's and last month's bulletin pages, then androidForms
	DecoderRapid7  Decoder = "rapid7-blog"      // parsePostFeed (RSS), then rapid7Forms on each post
	DecoderGTI     Decoder = "gti-blog"         // parsePostFeed (RSS), then gtiForms on each post
)

The decoders of the prose feeds.

const (
	DecoderMSRC     Decoder = "msrc"           // parseMSRCExploited: the Security Update Guide's CVEs with exploited = Yes
	DecoderCisco    Decoder = "cisco-psirt"    // parseCiscoFeed, then parseCSAF of each advisory (ciscoClaims)
	DecoderFortinet Decoder = "fortinet-psirt" // parseFortiGuardFeed, then parseCSAF of each advisory (fortinetClaims)
)

The decoders of the vendor feeds.

const (
	DecoderParser    Decoder = "parser"    // the generic custom-format parser with Source.Parser
	DecoderKEV       Decoder = "kev"       // ParseKEV
	DecoderNuclei    Decoder = "nuclei"    // ParseNucleiCVEs
	DecoderNVD       Decoder = "nvd"       // NVDPageURL and ParseNVD (NVD CVE API 2.0, ?hasKev: the exploited-list selector)
	DecoderCVEOrg    Decoder = "cveorg"    // the CVE Program's records (cvelistV5): the daily archive, its changes, CVERecordURL; ParseCVERecord
	DecoderVulnCheck Decoder = "vulncheck" // VulnCheckPageURL and ParseVulnCheckPage (the customer's own key)
	// The distribution backport data: ParseUbuntuOSV, ParseUbuntuVEX, ParseDebianTracker, read as a stream.
	DecoderUbuntuOSV     Decoder = "ubuntu-osv"
	DecoderUbuntuVEX     Decoder = "ubuntu-vex"
	DecoderDebianTracker Decoder = "debian-tracker"
	DecoderAlpineOSV     Decoder = "alpine-osv" // ParseAlpineOSV: OSV.dev's Alpine all.zip
	// The data of CVE tiers 2 and 3.
	DecoderEPSSAll   Decoder = "epss-all"   // ParseEPSSCSV: FIRST's daily file of every EPSS score
	DecoderNVDRecent Decoder = "nvd-recent" // RecentPageURL, WalkPageURL and ParseNVD: the catalogue's NVD records
	// Microsoft's Windows release information pages (parseWinRelPage): the releases core/winrel learns.
	DecoderWinRel Decoder = "windows-releases"
	// ParseSpamhausDROP: the networks of the Spamhaus DROP list.
	DecoderSpamhausDROP Decoder = "spamhaus-drop"
)

Built-in decoders.

type Deps

type Deps struct {
	DB      *store.DB
	Secrets *secrets.Store
	Audit   *audit.Log
	Modules ModuleGate
	Log     *slog.Logger
	// Inventory is optional: nil, or the inventory module being off, means INV-10 (you_have null).
	Inventory Inventory
	// Events is optional (nil drops events).
	Events Publisher
	// Fetcher does every pull; the zero value works (guarded client). Set Version for the User-Agent.
	Fetcher Fetcher
	// KEVPrimary and KEVFallback are the two addresses of the CISA list; empty means the built-in CISA address and
	// KEVMirrorURL. Tests point them at fake servers. The fallback applies only while the feed still uses KEVPrimary.
	KEVPrimary, KEVFallback string
	// Clock is time.Now when nil; tests inject a fake.
	Clock func() time.Time
	// Zone is the organization's time zone the times of alerts are written in (orgtime); nil: UTC.
	Zone orgtime.Source
	// Pins lists the CVEs an open finding references: the catalogue keeps them whatever their age (the retention rule). nil: none.
	// They are only kept, never asked of a source by id.
	Pins func(ctx context.Context) ([]string, error)
	// DataDir is where the module keeps work files (the CVE Program's daily archive while it downloads); "": the system's
	// temporary folder.
	DataDir string
	// Alert sends a notice to the admins through notify (the CISA list cannot be updated, critical; it is up to date again, not
	// critical). id names the alert; notify does not dedupe such notices once sent, so the watch records an alert before it queues it.
	// ErrAlertOff (notify off) makes the watch try again later. nil: no alerts (tests, a box without notify).
	Alert func(ctx context.Context, id, title, text string, critical bool) error
	// Schedules saves a source's schedule when it is created (core/schedule Service.EnsureTx). nil: sources have none, so only the
	// first pull and the retries after a failure pull them (tests).
	Schedules SchedulePort
}

Deps is what the module needs from the rest of the box.

type DistroFix

type DistroFix struct {
	Distro  string // DistroUbuntu, DistroDebian or DistroAlpine
	Release string // "24.04", "12", "3.23" (an Alpine branch)
	Package string // the source package
	CVE     string
	Status  string // DistroFixed or DistroNotAffected
	Fixed   string // the first fixed version (DistroFixed), "" otherwise
	Pro     bool   // the fix is in Ubuntu Pro (ESM) only
	Reason  string // DistroOpen from Debian: why no security update comes (DistroReason*), "" when one is expected
}

DistroFix is what one distribution says about one CVE in one source package of one release.

type DistroLister

type DistroLister interface {
	Distros(ctx context.Context) (map[string]map[string]bool, error)
}

DistroLister is an optional extension of Inventory: the distributions ("ubuntu", "debian") of the devices the distribution feeds can answer for (an Ubuntu or Debian device with deb packages an agent read), each with the source packages of those devices as the security data names them (findings.DevicePackages): the tier rows are kept for them only. Without it, or with the inventory module off, feeds pulls every enabled distribution feed as before and keeps no tier row.

type DistroPackage

type DistroPackage struct{ Distro, Release, Package string }

DistroPackage is a source package of one release as the distributions' security data names it ("ubuntu", "24.04", "openssl"). Release "" asks for every release of the distribution.

type DistroResult

type DistroResult struct {
	Rows []DistroFix
	Stats
}

DistroResult is one parsed pull.

func ParseAlpineOSV

func ParseAlpineOSV(r io.Reader, want DistroWant) (DistroResult, error)

ParseAlpineOSV reads OSV.dev's Alpine all.zip and keeps, for the CVEs of want (DistroWant.Row: every row of a CVE of the CISA list, and of a tier CVE the rows of the packages the Alpine devices run), the first fixed release of each source package of each Alpine branch ("Alpine:v3.23" → release "3.23"): a "fixed" event, the highest of several; "0" is Alpine's "not affected" (secdb's convention). secdb lists fixed releases only: a CVE it does not list for a package has no fix from Alpine yet. The record must be about its file's CVE; a record with a bad package name, no affected package of an Alpine branch or too many rows is rejected whole, and a withdrawn record keeps nothing. A release apkver cannot read ("1.9.5p2-r0", in old branches of two KEV CVEs on 2026-11-17) drops that branch's row only, counted with its value (also one longer than 100 characters or with spaces): a branch without a row never proves "not affected" in findings, so the other branches stay usable.

func ParseDebianTracker

func ParseDebianTracker(r io.Reader, want DistroWant) (DistroResult, error)

ParseDebianTracker reads the Debian Security Tracker JSON ({source: {CVE: {releases: {codename: {status, fixed_version}}}}}) as a stream and keeps, for the CVEs in want, each release's "resolved" status: fixed in its fixed_version, or not affected when that version is "0". sid has no release number and is skipped; a codename this Vedette does not know is rejected with its name. A bad package name or version rejects that package's CVE entry.

func ParseUbuntuOSV

func ParseUbuntuOSV(r io.Reader, want DistroWant) (DistroResult, error)

ParseUbuntuOSV reads Canonical's osv-all.tar.xz and keeps, for the CVEs in want (DistroWant.Row), the first fixed version of each source package of each Ubuntu release. A fix of a release only Ubuntu Pro has is kept with Pro set unless the release also has a public fix; of several fixed versions the highest is kept. A CVE file with a bad package name, version or too many rows is rejected whole (fail closed: findings never decide on half an entry).

func ParseUbuntuVEX

func ParseUbuntuVEX(r io.Reader, want DistroWant) (DistroResult, error)

ParseUbuntuVEX reads Canonical's vex-all.tar.xz and keeps the not_affected statements of the CVEs in want: each source product ("pkg:deb/ubuntu/<source>@<version>?arch=source&distro=<codename>") of a plain release. Products of a pocket (esm-infra/focal, fips/jammy) and binary products are left out. A codename this Vedette does not know is rejected with its name; a malformed product rejects the CVE file whole.

type DistroWant

type DistroWant struct {
	KEV      map[string]bool // CVEs whose every row is kept
	Tier     map[string]bool // CVEs whose fixed rows of Packages are kept
	Packages map[string]bool // source packages as the security data names them (findings.DevicePackages)
}

DistroWant says which rows a pull keeps: every row of a CVE of the CISA list, as before; of a tier CVE (nvd-recent's last 12 months) only the "fixed" rows of a source package some device runs, since the plan lists only packages below their fix and the parse of every package of every tier CVE held 434,162 rows (418k of them kernel flavours no device runs) and 366 MB of peak RSS for Ubuntu's file on 2026-11-15 (KEV only: 2,131 rows, 159 MB).

func (DistroWant) CVE

func (w DistroWant) CVE(c string) bool

CVE says whether some row of the CVE may be kept: its entry is read.

func (DistroWant) Row

func (w DistroWant) Row(cve, pkg, _ string) bool

Row says whether the row of the CVE for the source package with this status is kept: every row of a CVE of the CISA list (the matcher's: fixed, not affected, or open), and every row of a tier CVE for a package some device runs (the plan's).

type EPSSAllData

type EPSSAllData struct {
	Model, ScoreDate string // from the first line, "" when absent
	Scores           []EPSSAllScore
	Stats
}

EPSSAllData is the parsed daily file.

func ParseEPSSCSV

func ParseEPSSCSV(r io.Reader) (EPSSAllData, error)

ParseEPSSCSV reads FIRST's daily file of every EPSS score, gzip or plain CSV, as it downloads. The header must be cve,epss,percentile; a row with a bad CVE id or a value outside 0..1 is rejected and counted. A damaged gzip stream, a file that unpacks past epssAllMaxUnpacked or has more than epssAllMaxRows rows fails the parse (fail closed: the scores stored before stay).

type EPSSAllScore

type EPSSAllScore struct {
	CVE        string
	Score, Pct float64
}

EPSSAllScore is one row of the daily file.

type EPSSDay

type EPSSDay struct {
	Day   string
	Score float64
}

EPSSDay is one kept day of a CVE's EPSS score.

type Error

type Error struct {
	Err    error
	Detail string
}

Error carries a sentinel plus a sentence that is safe to show to the user.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type FeedHandlers

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

FeedHandlers implements the operations of the feeds module (S-FEED-1..5) of oas.Handler. Embed it in the composite handler (cmd/vedette/handler.go); it implements no other operation. Roles, the module gate, CSRF and schema validation run before these methods (core/server), so no handler checks a role.

func NewHandlers

func NewHandlers(s *Service) *FeedHandlers

NewHandlers returns the handlers of a service.

func (*FeedHandlers) FeedsDeleteFeedsCustomID

func (h *FeedHandlers) FeedsDeleteFeedsCustomID(ctx context.Context, params oas.FeedsDeleteFeedsCustomIDParams) error

FeedsDeleteFeedsCustomID implements DELETE /feeds/custom/{id} (INV-4): the feed, its secret and everything it loaded go. A built-in feed answers 404, like the GUI mock.

func (*FeedHandlers) FeedsGetFeedsCveID

func (h *FeedHandlers) FeedsGetFeedsCveID(ctx context.Context, params oas.FeedsGetFeedsCveIDParams) (*oas.FeedsGetFeedsCveIDOK, error)

FeedsGetFeedsCveID implements GET /feeds/cve/{id} (PRE-3, POST-3): the brief of a CVE the catalogue holds (Store.Brief), and the devices whose product matches its exploited-list entry; 404 not_in_data when the catalogue does not hold the CVE.

func (*FeedHandlers) FeedsGetFeedsCveIDTier

FeedsGetFeedsCveIDTier implements GET /feeds/cve/{id}/tier (S-TIER-1): a CVE on no exploited list, from the tier data of the feeds that are on (epss-all, nvd-recent); 404 not_in_data when neither holds it.

func (*FeedHandlers) FeedsGetFeedsHot

func (h *FeedHandlers) FeedsGetFeedsHot(ctx context.Context, params oas.FeedsGetFeedsHotParams) (*oas.FeedsGetFeedsHotOK, error)

FeedsGetFeedsHot implements GET /feeds/hot (S-FEED-1, PRE-2, POST-2): the vulnerabilities added in the window, grouped by product; rows are ordered you_have=yes first, then the number of CVEs, then the top EPSS.

func (*FeedHandlers) FeedsGetFeedsSearch

FeedsGetFeedsSearch implements GET /feeds/search (S-FEED-3, PRE-4, POST-4): one of cve, ioc or text, answered from the data on the box, never from the network.

func (*FeedHandlers) FeedsGetFeedsSources

func (h *FeedHandlers) FeedsGetFeedsSources(ctx context.Context) (*oas.FeedsGetFeedsSourcesOK, error)

FeedsGetFeedsSources implements GET /feeds/sources: the built-in feeds in display order, then the custom ones.

func (*FeedHandlers) FeedsGetFeedsStatus

func (h *FeedHandlers) FeedsGetFeedsStatus(ctx context.Context) (*oas.FeedsGetFeedsStatusOK, error)

FeedsGetFeedsStatus implements GET /feeds/status: when the data was pulled and from where.

func (*FeedHandlers) FeedsGetFeedsWeekly

func (h *FeedHandlers) FeedsGetFeedsWeekly(ctx context.Context) (*oas.FeedsGetFeedsWeeklyOK, error)

FeedsGetFeedsWeekly implements GET /feeds/weekly.

func (*FeedHandlers) FeedsPostFeedsCustom

FeedsPostFeedsCustom implements POST /feeds/custom (PRE-5, POST-5).

func (*FeedHandlers) FeedsPostFeedsParseTest

FeedsPostFeedsParseTest implements POST /feeds/parse-test (S-FEED-5, INV-7): the rules run on the caller's sample, or on the built-in sample of the format. It reads and writes nothing: no database, no network.

func (*FeedHandlers) FeedsPostFeedsSourcesIDFetch

FeedsPostFeedsSourcesIDFetch implements POST /feeds/sources/{id}/fetch (INV-8): pull the feed now, straight from its source. A feed that is off is 409 feed_disabled; a pull that fails is a 200 with status error on the feed.

func (*FeedHandlers) FeedsPostFeedsWeeklyID

FeedsPostFeedsWeeklyID implements POST /feeds/weekly/{id}: "I have it" or "Not relevant" (INV-14). "I have it" declares one manual device through the inventory (once per product) when the inventory is on; with the inventory off only the answer is stored, as in the GUI mock.

func (*FeedHandlers) FeedsPutFeedsCustomID

FeedsPutFeedsCustomID implements PUT /feeds/custom/{id}. Changing the kind removes what the feed loaded.

func (*FeedHandlers) FeedsPutFeedsSourcesID

FeedsPutFeedsSourcesID implements PUT /feeds/sources/{id}: on or off, the schedule, a mirror address. A built-in feed with an empty url goes back to its default address.

type Fetcher

type Fetcher struct {
	Client  *http.Client // nil uses NewClient(DefaultFetchTimeout)
	Version string       // product version for the User-Agent
	// BoxAddrs lists the machine's addresses (vedette-host), asked again at every connection: a pull never connects to Vedette's
	// own ports on one of them, nor to loopback or the container's own interfaces on any port. known false
	// (vedette-host has never answered) allows only global unicast destinations. nil: none.
	BoxAddrs func() (addrs []netip.Addr, known bool)

	// Gateway is the container's default gateway, which is the machine too (set by wiring; nil: not asked).
	Gateway func() (netip.Addr, bool)

	// Self lists addresses that are Vedette itself beyond this process's own interfaces (the honeypot's decoys): refused on every
	// port, like loopback. nil: none.
	Self func() []netip.Addr
	// contains filtered or unexported fields
}

Fetcher performs the HTTPS GET of a feed. The zero value works.

func (Fetcher) Fetch

func (f Fetcher) Fetch(ctx context.Context, req Request) (*Response, error)

Fetch does one GET to exactly req.URL: no body, no customer data, fixed User-Agent, size cap enforced while reading, conditional headers when given, 304 reported as NotModified. Without a context deadline it applies DefaultFetchTimeout.

func (Fetcher) UserAgent

func (f Fetcher) UserAgent() string

UserAgent is the fixed identity of every pull: no box id, no host name (FORBID-2).

type FieldMap

type FieldMap struct {
	Source     string     `json:"source"`
	Regex      string     `json:"regex"`
	Trim       bool       `json:"trim"`
	Lowercase  bool       `json:"lowercase"`
	DateFormat DateFormat `json:"date_format"`
}

FieldMap is the per-field rule of a custom parser. JSON tags match api/openapi.json.

type Format

type Format string

Format is how a custom feed is encoded.

const (
	FormatJSON  Format = "json"
	FormatCSV   Format = "csv"
	FormatRSS   Format = "rss"
	FormatSTIX  Format = "stix"
	FormatLines Format = "lines"
)

Formats of a custom feed.

func FormatsFor

func FormatsFor(k Kind) []Format

FormatsFor is the INV-5 compatibility table.

type Have

type Have struct {
	Key   string
	Since time.Time
}

Have is the "I have this" scope of one declared device: its version-less software of KEV key Key is matched from the CISA date Since on.

type IOCRecord

type IOCRecord struct {
	Type, Value string
	FirstSeen   time.Time
	LastSeen    time.Time
	Sightings   []IOCSighting
}

IOCRecord is an indicator with the feeds that list it now.

type IOCSighting

type IOCSighting struct {
	SourceID   string
	SourceName string
	// Confidence is how sure this feed's listing is that the value is bad (0 to 1): for a built-in indicator list its weight
	// (Source.Weight, IPsum by the level its address names) whatever was stored, as such a list carries no confidence per line;
	// for a custom feed the stored value (what the feed said, or 0.5).
	Confidence float64
	// Enabled is whether the feed is switched on now: a switched-off feed is never pulled and its listings are not pruned, so they go stale (logs ignores them).
	Enabled bool
	// Subdomains is whether the feed lists a name for itself and all of its subdomains (a built-in source with Source.Subdomains);
	// false for a custom feed, which lists names exactly.
	Subdomains bool
	// Builtin is whether the feed is a built-in one; C2 is whether it lists confirmed botnet command-and-control servers (Source.C2).
	Builtin bool
	C2      bool
	// FetchedAt is the feed's last good pull (feeds_source.last_success; a 304 Not Modified pull confirms the list it holds), zero
	// before the first. CreditName shows it for a list whose terms ask for it.
	FetchedAt time.Time
}

IOCSighting is one feed's listing of an indicator.

type Impact

type Impact struct{ Confidentiality, Integrity, Availability string }

Impact is an impact on confidentiality, integrity and availability: none | low | high each.

type Inventory

type Inventory interface {
	// MatchProducts returns, for each product, the devices that run it (how is yes) or may run it (maybe).
	// The map is keyed by Product.Key(); a product with no device has no entry.
	MatchProducts(ctx context.Context, products []Product) (map[string][]MatchedAsset, error)
	// AddManualDevice declares one manually added device that runs the product. It runs inside the caller's
	// write transaction (tx) so the device, the audit row of the inventory and the answer commit together. It
	// returns the new device's id, or "" when the inventory does not say it: then "I have this" scopes no device
	// (HaveSince) and findings match it like any other device.
	AddManualDevice(ctx context.Context, tx *sql.Tx, actor string, d ManualDevice) (deviceID string, err error)
}

Inventory is what feeds needs from the inventory module (FORBID-4: feeds never reads inv_* itself). The inventory module implements it and the wiring passes it in Deps; when it is nil or the module is off, feeds answers with you_have null and no matched devices (INV-10).

type KEVCatalog

type KEVCatalog struct {
	Version  string // catalogVersion, "" when absent or odd
	Released string // dateReleased as YYYY-MM-DD, "" when absent or odd
	// ReleasedAt is dateReleased to the second (zero when absent or odd): the tie-breaker of two copies with one catalogVersion
	ReleasedAt time.Time
	Vulns      []Vuln
	Stats
}

KEVCatalog is a parsed CISA KEV JSON catalog.

func ParseKEV

func ParseKEV(data []byte) (KEVCatalog, error)

ParseKEV parses the CISA Known Exploited Vulnerabilities JSON catalog, fail-closed per entry (INV-3): a bad entry is rejected and counted, the rest are kept. Syntax errors, a missing "vulnerabilities" array or input over MaxBodyBytes fail the whole parse so the caller keeps the data it has. Keys are matched exactly and the last duplicate key wins, as JSON.parse in the SPA does. Duplicate CVE ids keep the first entry.

type KevIndex

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

KevIndex holds the CVEs of the exploited lists (CISA, VulnCheck) by the product key of their owner entry (productid.Key). It is never changed once built, so callers share it and look up many keys in it without reading the database again.

func (*KevIndex) CVEs

func (x *KevIndex) CVEs(keys []string) []string

CVEs returns the sorted CVEs listed for any of keys (productid.Key form, lower case). A "Multiple products" entry of a vendor matches every key of that vendor (INV-11). Never nil.

type Kind

type Kind string

Kind is what a feed carries.

const (
	KindVulnerabilities Kind = "vulnerabilities"
	KindIOC             Kind = "ioc"
)

Kinds of feed.

type ListEntry

type ListEntry struct {
	List, Source, SourceName       string // "cisa", the feed "cisa-kev", the feed's name "CISA KEV"
	Vendor, Product, Display, Name string
	Description, RequiredAction    string
	Links                          []string
	DateAdded, DueDate             string // days; DueDate "" when the list gives none
	Ransomware                     bool
}

ListEntry is one exploited-list entry of the CVE in the list's own words (feeds_kev), the owner entry first (listRank).

type ManualDevice

type ManualDevice struct {
	Kind    string // a hint (nas, firewall, router, camera, web, server, unknown)
	Vendor  string
	Product string
	Display string // the name people recognise
	Key     string // productid.Key of vendor and product, the KEV matching key
}

ManualDevice is the device "I have it" declares (S-FEED-2, INV-14): one device that runs the product.

type MatchedAsset

type MatchedAsset struct {
	ID       string  `json:"id"`
	Hostname *string `json:"hostname"` // the name a person gave the device in Vedette, else its host name; nil when neither
	IP       string  `json:"ip"`
	Display  string  `json:"display"`
	How      YouHave `json:"how"` // yes or maybe, never no
}

MatchedAsset is a device that matches a vulnerable product.

type Metric

type Metric struct {
	Source  string // MetricNVD, MetricCNA, MetricADP
	Version string
	Score   float64
	Vector  string
}

Metric is one stored CVSS base score of a CVE (feeds_cve_metric): one per scorer and version.

type ModuleGate

type ModuleGate interface {
	Enabled(id string) bool
}

ModuleGate says whether a module is on; modreg.Registry satisfies it.

type NVDPage

type NVDPage struct {
	Total, Returned int // totalResults, and the records in this answer
	Records         []NVDRecord
	Stats
}

NVDPage is one parsed answer of the NVD CVE API 2.0.

func ParseNVD

func ParseNVD(data []byte) (NVDPage, error)

ParseNVD reads one NVD CVE API 2.0 answer. A record with a bad id, dates or status is rejected and counted, as is one with an unusable vulnerable entry (a criteria that is not a CPE 2.3 name, a version too long or not printable): fail closed, a CVE that lost an entry is dropped whole, so findings never decide on half a configuration. A damaged answer fails the parse.

type NVDRecord

type NVDRecord struct {
	CVE                     string
	Published, LastModified time.Time
	Status                  string // NVD's vulnStatus ("Analyzed", "Deferred", "Rejected" …)
	Description             string // NVD's English description, capped
	Metrics                 []Metric
	Affected                []AffectedRow // the vulnerable entries of nodes that are not negated
	// Platforms is, per entry of Affected, the operating systems ("microsoft:windows", vendor and product of the CPE) of NVD's "running
	// on" condition of its configuration (an AND of the vulnerable entries with non-vulnerable operating-system entries); nil for an
	// entry without one.
	Platforms [][]string
	// CWE is the weaknesses NVD lists ("CWE-787"), NVD's own and the ones it carries from the CNA and CISA's ADP, in NVD's order,
	// without repeats; NVD's placeholders ("NVD-CWE-Other", "NVD-CWE-noinfo") are not weaknesses and are left out.
	CWE []string
	// Refs is the references NVD lists, with NVD's tags in the words of the CVE record ("Vendor Advisory" is vendor-advisory:
	// nvdTag), source "nvd". NVD tags the references when it analyses a CVE; before that they carry none.
	Refs []RecordRef
}

NVDRecord is one CVE as NVD's record gives it, as the catalogue keeps it.

func (NVDRecord) CVSS

func (r NVDRecord) CVSS() (CVSS, bool)

CVSS is the picked score of the record (PickCVSS).

func (NVDRecord) Tagged

func (r NVDRecord) Tagged() bool

Tagged says whether NVD gave any of the references a tag: NVD has analysed them.

type NewKEVEvent

type NewKEVEvent struct {
	CVE         string `json:"cve"`
	Vendor      string `json:"vendor"`
	Product     string `json:"product"`
	HasTemplate bool   `json:"has_template"`
	DateAdded   string `json:"date_added"`
}

NewKEVEvent is published once for each CVE the box has never seen before (POST-1).

type NucleiCVEs

type NucleiCVEs struct {
	CVEs      []string   // sorted, unique
	Templates []Template // the same CVEs, each with the address of its template ("" when the index gives no usable path)
	Stats
}

NucleiCVEs is the set of CVEs that have a nuclei template: a public-exploit signal of each (feeds_signal).

func ParseNucleiCVEs

func ParseNucleiCVEs(data []byte) (NucleiCVEs, error)

ParseNucleiCVEs reads the nuclei-templates cves.json index, JSON Lines: one object per line with "ID" (like CVE-2024-1234), "Info" and "file_path". The key is matched exactly. A line that is not such an object is rejected and counted; a line over 1 MiB fails the parse. Duplicates collapse.

type Parser

type Parser struct {
	Format      Format              `json:"format"`
	RecordsPath string              `json:"records_path"`
	Delimiter   string              `json:"delimiter"`
	HasHeader   bool                `json:"has_header"`
	Fields      map[string]FieldMap `json:"fields"`
}

Parser is the stored parsing rule set of a feed (feeds_source.parser).

func DefaultParser

func DefaultParser(kind Kind, format Format) Parser

DefaultParser returns the starting rules for a kind and format; they match the built-in sample of that format (defaults.ts).

type PlatformChecker

type PlatformChecker interface {
	NotAffected(ctx context.Context, cve, vendor, product string, distro []DistroFix, ids []string) (map[string]bool, error)
}

PlatformChecker is an optional extension of Inventory (KF-CVEPAGE): among ids, the devices that the findings matcher's platform rules prove are not affected by the CVE (an Ubuntu box for an Alpine-only OpenSSH flaw), so "Do you have it?" on the CVE page agrees with the device's findings. distro is what the distribution feeds that are on say about the CVE (DistroFixesOf): a package release a person gave is read against it. Without it the page answers by product only, as before.

type Product

type Product struct{ Vendor, Product string }

Product is a vendor and product pair as KEV writes them.

func (Product) Key

func (p Product) Key() string

Key is productid.Key of the pair.

type ProductCount

type ProductCount struct {
	Vendor, Product string
	Count           int
}

ProductCount is a vendor and product pair of the CISA list with the number of its CVEs.

type ProductKey

type ProductKey struct{ Vendor, Product string }

ProductKey names a product as the catalogue's ranges do: CPE vendor and product, lower case ("apache", "http_server").

func RecordProductKey

func RecordProductKey(vendor, product string) ProductKey

RecordProductKey is the product key of a CVE record's affected entry that names no CPE, as feeds_cve_range stores it: the vendor without its company words and the product without the vendor's name in front, each [a-z0-9] only ("Palo Alto Networks", "PAN-OS" is "paloalto", "panos"; "Oracle Corporation", "Oracle Java SE" is "oracle", "javase"). A matcher asks Store.Ranges with this key of a product's names beside its NVD CPE names.

type Publisher

type Publisher interface {
	Publish(ctx context.Context, e events.Event) error
}

Publisher puts a module event on the bus: *events.Bus satisfies it, so wiring passes the real bus; nil drops events.

type Range

type Range struct {
	CVE, Origin                            string
	Part, Vendor, Product, CPE             string
	StartIncl, StartExcl, EndIncl, EndExcl string
	Fixed, VersionType                     string
	// DefaultStatus is the CVE record entry's defaultStatus of a CNA or ADP row (DefaultAffected, DefaultUnaffected, DefaultUnknown);
	// "" for NVD's rows.
	DefaultStatus string
	Platforms     []string // NVD's "running on" operating systems ("microsoft:windows"); empty for none
}

Range is one affected-versions row of the catalogue.

func CutCatchAll

func CutCatchAll(rows []Range) []Range

CutCatchAll reads a CVE record's open-ended row the way its vendor means it when the same product also has bounded rows above the row's start. Some vendors list each release train they evaluated with its fixed release and add one row "affected from X, every later version" for the trains they no longer evaluate (F5's NGINX records: 1.31.0 before 1.31.7, 1.30.0 before 1.30.6, and 1.25.0 with no end, next to the note that end-of-support versions are not evaluated). Read literally, that row says the fixed releases the same record names are affected, so no release would ever fix the flaw and a device stays affected after the update. The row is cut where the lowest bounded row above its start begins: 1.25.0 before 1.30.0. Versions below the first evaluated train stay affected with no fix named; the evaluated trains keep their own rows and fixes. A cut row's default status is unknown: a version above the cut that no bounded row names was called affected by the record, so outside the rows proves nothing (a question, never closed).

Only the rows of a CVE record (origin cna or adp) are read so; NVD writes its own ranges. Rows of one product are those of one origin, part, vendor, product and CPE. A row is open-ended when it has a start and no end; a bounded row has a start and an end that differ (an exact version is not a train). Starts that cannot be compared leave the row as it is. The rows are not changed in place: a cut row is a copy.

func (Range) AffectedRow

func (r Range) AffectedRow() AffectedRow

AffectedRow is the range as the matcher's CPE entry.

func (Range) Generic

func (r Range) Generic() bool

Generic says the generic comparison reads the row: an NVD row, or a record row it can order (not one kept as the vendor states it).

func (Range) MatchRow

func (r Range) MatchRow() (AffectedRow, bool)

MatchRow is the range as the matcher's CPE entry: NVD's and a record's CPE as stated, a record's product without a CPE as "cpe:2.3:*:<vendor>:<product>:…" of the name the catalogue knows it by (MatchName, kevRecordRow). ok is false for a record row the generic comparison does not read (recordSkipped: a product with a version scheme, a vendor whose versions findings compares with rules of its own).

func (Range) ModelLimited

func (r Range) ModelLimited() bool

ModelLimited says the row is a CVE record's affected range that holds only on the devices its platforms name (Juniper's "EX4000-48T", "EX Series"): Vedette does not know a device's model for certain, so the row can only tell that versions outside it are not affected, never that a version inside it is (StatementScheme). NVD's rows keep their own platforms (running-on CPEs).

func (Range) Unaffected

func (r Range) Unaffected() bool

Unaffected says the row states versions the vendor says are not affected (UnaffectedNotation), not affected ones.

type RangeProduct

type RangeProduct struct {
	Vendor, Product string
	Record          bool
}

RangeProduct is a product a catalogue range names: a CPE's vendor and product, or, Record set, a CVE record's product key (no CPE).

type RangesUpdatedEvent

type RangesUpdatedEvent struct {
	CVEs  []string `json:"cves"`
	First bool     `json:"first"`
	// Catalogue: the pull also changed the ranges of a CVE on no exploited list (NVD's or a CVE record's): CVEs names none of them,
	// and findings' match pass, the one reader of those CVEs, runs again. CVEs may be empty then.
	Catalogue bool `json:"catalogue,omitempty"`
}

RangesUpdatedEvent is published after a pull of the NVD affected versions (nvd-kev) changed the entries of some CVEs: findings must match the devices again. First is true when the table was empty before (the first fill: like the baseline, nothing it causes is news).

type Reason

type Reason struct {
	Reason  string `json:"reason"`
	Count   int    `json:"count"`
	Example string `json:"-"`
}

Reason counts rejected rows with the same cause (quoted values masked). Example is the first of those rows with its value shown (quoteVal), for the status line of a pull (note, accepted); it is not part of the API.

type Record

type Record map[string]any

Record is a normalised row: values are string, float64 (confidence) or nil.

type RecordRef

type RecordRef struct {
	URL    string
	Tags   []string
	Source string
}

RecordRef is one reference of a record: its URL, the tags its publisher gave it (vendor-advisory, patch, mitigation, exploit …) and who gave it (cna or adp).

type Reference

type Reference struct {
	URL    string
	Tags   []string
	Source string
	Group  string
}

Reference is one reference of the CVE: its address, its tags in the CVE record's words, who gave it (nvd, cna, adp) and the one group it is shown under (refGroup).

type Reject

type Reject struct {
	Row    int    `json:"row"`
	Reason string `json:"reason"`
}

Reject is one rejected row. Row is the line of the input for a plain list and for CSV (comments, blank lines and the header counted; a record that spans lines is at the line it starts); for the other formats the record number (from 1). Reason shows the value (quoteVal); only parse-test returns Rejects over the API; a pull keeps the masked Reasons (INV-3).

type Request

type Request struct {
	URL          string
	Auth         Auth
	ETag         string // sent as If-None-Match
	LastModified string // sent as If-Modified-Since
	MaxBytes     int64  // 0 means MaxBodyBytes
	// HeaderTimeout, when longer than the client's, is how long the source may take before it starts to answer
	// (NVD). The whole request is then bounded by the context deadline only.
	HeaderTimeout time.Duration
	// Stream, when set, reads the body as it arrives instead of Response.Body (when it fails, Fetch returns its error with the Response
	// of the answer's headers) (the distribution archives are
	// tens of megabytes and are parsed while they download). The reader stops with ErrTooLarge past MaxBytes, counted
	// after the transport's gzip decoding; the client's whole-request timeout is lifted, so the context deadline is the
	// bound. Its error is the error of the fetch.
	Stream func(io.Reader) error `json:"-"`
	// RedirectHosts are the other hosts a redirect may lead to (exact names, lower case): a source that serves its files from a
	// storage host of its own (GitHub's release files). Every hop still passes the address guard and never leaves https.
	RedirectHosts []string
	// From, when above zero, asks for the body from that byte on (Range: bytes=From-), to resume a download: Response.Partial says
	// the source answered with that part. A source that answers the whole body (200) is read from that byte on too, the bytes before
	// it skipped, so the caller always gets the body from From on.
	From int64
	// WantTotal, when above zero, is the whole body's size a resumed download expects: a source whose file now has another size
	// fails with ErrFileChanged before anything is read, so a replaced file is never joined to the part read before.
	WantTotal int64
}

Request is one pull of one declared feed address (INV-1).

type Response

type Response struct {
	Body         []byte // nil when NotModified
	NotModified  bool
	ETag         string
	LastModified string
	FinalURL     string    // may carry a query string: do not log it
	Date         time.Time // the server's Date header (zero when missing or unreadable): its clock, for the CISA list's plausibility (#946 r2)
	// Partial: the source answered the part asked for by Request.From (206). Total is the whole body's size when the source said it
	// (Content-Range of a part, Content-Length of a whole answer), else -1.
	Partial bool
	Total   int64
}

Response is what came back.

type Result

type Result struct {
	Records []Record `json:"records"`
	Stats
}

Result is the outcome of ParseFeed. Records holds every accepted record (up to MaxRows); Preview gives the shape the SPA shows.

func ParseFeed

func ParseFeed(ctx context.Context, data []byte, kind Kind, p Parser) (Result, error)

ParseFeed parses untrusted feed data with a custom parser, fail-closed (INV-2, INV-3): input over MaxBodyBytes is ErrTooLarge; rows over MaxRows set Truncated; an invalid row is rejected and counted, never half-accepted. Configuration problems are ErrBadConfig, undecodable data is ErrBadSample. ctx is checked every few rows; on cancellation nothing is returned (ctx.Err()).

func ParseSource

func ParseSource(ctx context.Context, src Source, data []byte) (Result, error)

ParseSource parses the data of a built-in source with the source's own row limit.

func (Result) Preview

func (r Result) Preview() Result

Preview returns a copy limited to the first PreviewRows records (parse-test).

type SSVC

type SSVC struct{ Exploitation, Automatable, Impact string }

SSVC is CISA's SSVC decision points for a CVE, lower case as stored ("" = not given).

type SchedulePort

type SchedulePort interface {
	EnsureTx(ctx context.Context, tx *sql.Tx, key string, rule coreschedule.Rule, by string) error
}

SchedulePort is the part of core/schedule the module uses to give a source its schedule.

type Secret

type Secret struct{ secrets.Value }

Secret is a feed credential: a core/secrets.Value (which redacts itself in fmt, slog, JSON and text, and is read only through Reveal, SYS-4) plus the INV-6 validation and the 4-character hint the UI may show.

func NewSecret

func NewSecret(s string) (Secret, error)

NewSecret validates INV-6: 8..500 chars, no whitespace or control characters.

func (Secret) IsSet

func (s Secret) IsSet() bool

IsSet reports whether a value is held.

func (Secret) Last4

func (s Secret) Last4() string

Last4 is what the UI may show (secret_last4).

type Seed

type Seed struct {
	Claims []SeedClaim `json:"claims"`
}

Seed is the seed file.

func MergeSeed

func MergeSeed(prev Seed, reads []SeedRead) Seed

MergeSeed is the next seed: the previous one, without the claims a document read now no longer makes, plus the claims read now; of one (CVE, source), the earliest date and its link.

func ParseSeed

func ParseSeed(data []byte) (Seed, error)

ParseSeed reads a seed file: every claim must be whole and valid, and no (CVE, source) twice.

func (Seed) JSON

func (s Seed) JSON() []byte

JSON is the seed file: claims sorted by source, then CVE, one per line, so a release's change reads as lines added.

type SeedClaim

type SeedClaim struct {
	CVE    string `json:"cve"`
	Source string `json:"source"` // the feed whose decoder read it
	Date   string `json:"date"`   // the date of the claim, RFC 3339 UTC
	URL    string `json:"url"`    // the post, bulletin or advisory that says it
}

SeedClaim is one claim of the seed: facts only.

type SeedRead

type SeedRead struct {
	URL    string
	Claims []SeedClaim
}

SeedRead is what a decoder reads of one post, bulletin or advisory now: its link and the claims it makes.

func SeedFromAndroidPage

func SeedFromAndroidPage(ctx context.Context, pageURL string, page []byte, month time.Time) (SeedRead, error)

SeedFromAndroidPage reads one month's Android bulletin page (pageURL, its address) as the box does.

func SeedFromCSAF

func SeedFromCSAF(ctx context.Context, source string, doc []byte) (SeedRead, error)

SeedFromCSAF reads one Cisco or Fortinet CSAF document as the box does (advisories older than the vendor's feed reaches).

func SeedFromFeed

func SeedFromFeed(ctx context.Context, source string, body []byte) ([]SeedRead, error)

SeedFromFeed reads a blog feed (Chrome Releases, Rapid7, Google Threat Intelligence) as the box does: one SeedRead per post.

type Service

type Service struct {
	Deps
	// contains filtered or unexported fields
}

Service is the module: the pull logic, the jobs and the data the handlers read. Build it with NewService, call Seed once after the migrations, then hand FeedHandlers(s) to the composite handler and Jobs() to the scheduler.

func NewService

func NewService(d Deps) (*Service, error)

NewService checks the dependencies.

func (*Service) DeviceDeleted

func (s *Service) DeviceDeleted(ctx context.Context, tx *sql.Tx, d lifecycle.Delete) error

DeviceDeleted is feeds' part of a device delete (core/lifecycle, inside the inventory's write): an "I have this" answer that declared the deleted device stays, naming no device, so its scope (HaveSince) names no device that is gone.

func (*Service) DeviceMerged

func (s *Service) DeviceMerged(ctx context.Context, tx *sql.Tx, m lifecycle.Merge) error

DeviceMerged is feeds' part of a device merge (core/lifecycle, inside the inventory's write): an "I have this" answer that declared device m.From declares m.Into, the device it joined, so the answer's scope (HaveSince) follows the device.

func (*Service) Fetch

func (s *Service) Fetch(ctx context.Context, feedID string) error

Fetch pulls one feed now (PRE-1: the feed is on; its address passes INV-2 inside the fetcher). A failed pull is recorded on the feed (status error) and is not an error here; ErrFeedDisabled and ErrNotFound are.

func (*Service) Jobs

func (s *Service) Jobs() []jobs.Job

Jobs returns the pull job of the module for the scheduler. The scheduler runs it only while the module is on.

func (*Service) LearnWindowsReleases

func (s *Service) LearnWindowsReleases(ctx context.Context) error

LearnWindowsReleases hands the stored releases and monthly updates to core/winrel: when the service is built (cmd/vedette, before any match or agent report needs them), when it is first ready, and after every good pull. With the feed off the stored lists stay in use (the last good copy); they are never deleted by turning the feed off, only replaced by a good pull.

func (*Service) NewlyExploited

func (s *Service) NewlyExploited(ctx context.Context) (cves, productsInUse int, err error)

NewlyExploited is the Home headline as numbers, for the weekly report: the CVEs newly exploited in the last 7 days and how many of their products the inventory says are in use (you_have=yes; 0 while the inventory is off). One definition for both pages: the same board as GET /feeds/hot?window=7d.

func (*Service) RunPull

func (s *Service) RunPull(ctx context.Context) error

RunPull is one tick of the pull job: every enabled feed that is due (INV-8, INV-9: State.Due with the feed's interval and its back-off after errors; nvd-recent with an unfinished pull, only its back-off) is pulled in turn, vulnerabilities first. A failed pull is recorded on the feed and never fails the job; only a cancelled context or a database failure does.

func (*Service) ScheduleOwner

func (s *Service) ScheduleOwner() coreschedule.Owner

ScheduleOwner is what the sources register with core/schedule: one schedule per source (feeds.source:<id>), an interval only. When it comes due nothing starts here: the pull job pulls the source at its next tick (State.Due reads when the schedule last came due), because a pull asks the Internet and must not hold the schedule's transaction.

func (*Service) Seed

func (s *Service) Seed(ctx context.Context) error

Seed merges the built-in feeds into the database. Call it after the migrations, every start.

func (*Service) Store

func (s *Service) Store() *Store

Store gives other modules the read methods (VulnByCVE, VulnsByProductKey, HasTemplate, IOCLookup, KevPairs).

type Sighting

type Sighting struct {
	Source        string
	BlockClass    bool     // DROP/CC0-class list: one such source is enough to block
	Aggregate     bool     // the list is a merge of other lists: never block alone
	Informational bool     // describes the address, not malice (Tor exit): never counts toward block
	Upstreams     []string // ids of the sources an aggregate includes
}

Sighting says one source listed the IOC. Source is the feed id (compared trimmed and lower-case). The flags describe the source; for a built-in feed Judge takes them from the registry whatever the caller says (SightingOf fills them in).

func SightingOf

func SightingOf(s Source) Sighting

SightingOf describes a sighting by a built-in source.

type Signal

type Signal struct {
	CVE, Kind, Source             string
	FirstSeen, StoredAt, LastSeen time.Time
	Qualifies                     bool
	URL                           string
	Detail                        json.RawMessage // small, for display; nil when none
}

Signal is one feeds_signal row: why a CVE is urgent, from which source, since when.

type Source

type Source struct {
	ID            string
	Name          string
	Kind          Kind
	Format        Format
	URL           string // default address; Reset restores it
	License       string
	IntervalHours int // default schedule: 1 for the CISA list (S-FEED-1) and CVE.org, 24 for the other vulnerability feeds, 6 for IOC (24 for Spamhaus DROP, which asks for at most one download a day)
	Decoder       Decoder
	Parser        *Parser // set when Decoder == DecoderParser
	MaxRows       int     // row limit of this source; 0 means MaxRows (50,000)
	// BYOK: the customer's own API key is needed. The feed is off until one is saved, and what it loaded goes
	// when the key is removed or the feed is turned off.
	BYOK bool
	// DefaultOff: the feed is off on a new box until an administrator turns it on (Spamhaus DROP); the box contacts its host only then.
	DefaultOff bool

	// Aggregate: the list is itself a merge of other lists (IPsum, hagezi TIF).
	// It never reaches block alone, and counts with one of its Upstreams as one source.
	Aggregate bool
	Upstreams []string // ids of built-in feeds an aggregate is known to include
	// Informational: the list says what an address is, not that it is malicious
	// (Tor exit nodes). It never counts toward block.
	Informational bool
	// Subdomains: every name the list holds stands for itself and all of its subdomains (hagezi TIF, "Domains (without
	// subdomains)": a listed bad.example also means a.b.bad.example). A source without it lists each name exactly.
	Subdomains bool
	// Weight is how sure a listing by this built-in indicator list is that the value is bad, from 0 to 1 (IOCConfidence). The lists
	// carry no confidence per line, so the weight is what the list is: a confirmed command-and-control list near certain, a curated
	// compromised-host list high, an aggregate by how many lists agree, a list that only says what an address is (Tor exit relays)
	// low. Zero for every other kind of feed.
	Weight float64
	// LevelInURL: the list's address names its level, the number of blocklists an address is on at least (IPsum's levels/N.txt). A
	// listing weighs what that level says (levelWeight); an address that names no level keeps Weight.
	LevelInURL bool
	// C2: the list is of confirmed botnet command-and-control servers (abuse.ch Feodo Tracker). A device that reaches one runs
	// malware, so logs rates such an incident critical.
	C2 bool
	// DropClass: the list is meant to be dropped outright by whoever uses it (Spamhaus DROP, "Don't Route Or Peer"): one such source
	// is enough for the verdict block, as a CC0 list is (BlockClass).
	DropClass bool
	// CreditFetch: the list is credited with the time the box fetched it wherever a listing by it is named (CreditName).
	CreditFetch bool
	// MinHours: the source allows at most one download every MinHours hours (Spamhaus DROP: once a day). Its schedule cannot be set
	// shorter, and neither the pull job nor Fetch now pulls it sooner after a good pull, nor sooner than an hour after any attempt
	// (fetchFloor). 0 for every other source.
	MinHours int
}

Source is a built-in feed. Built-ins cannot be deleted (INV-4): the module stores only enabled, interval_hours and a mirror URL for them.

func BuiltinByID

func BuiltinByID(id string) (Source, bool)

BuiltinByID finds a built-in feed.

func BuiltinSources

func BuiltinSources() []Source

BuiltinSources returns the built-in feeds in display order. The slice is a copy; the Parser pointers are shared and must be treated as read-only.

func (Source) BlockClass

func (s Source) BlockClass() bool

BlockClass reports a CC0 IOC list or one meant to be dropped outright (Spamhaus DROP): one such source is enough for `block` (INV-12, "one DROP/CC0-class source").

type State

type State struct {
	LastSuccess time.Time // zero when never
	LastAttempt time.Time // zero when never
	Failures    int       // consecutive failures since the last success
}

State is what the module remembers about a feed's pulls (feeds_fetch rows).

func (State) Due

func (s State) Due(now time.Time, intervalHours int, lastDue *time.Time) bool

Due reports whether a pull should start at now. When the feed's last pull was a success the regular pull is the feed's schedule (core_schedule, feeds.source:<id>): lastDue is when it last came due, and the feed is due when that is after its last pull. A feed that never pulled is due at once, and one that failed is due when its back-off is over. A success or attempt time in the future (a clock that was wrong) counts as due, so pulls never wait for the clock.

func (State) Record

func (s State) Record(now time.Time, err error) State

Record returns the state after a pull finished at now (err == nil is success, which resets the back-off).

func (State) RetryAt

func (s State) RetryAt(intervalHours int) time.Time

RetryAt is when a feed that failed is tried again: the last attempt plus the back-off, which never exceeds the feed's interval.

type Stats

type Stats struct {
	Accepted  int      `json:"accepted"`
	Rejected  int      `json:"rejected"`
	Reasons   []Reason `json:"reasons"`
	Rejects   []Reject `json:"rejects"` // the first MaxRejects
	Truncated bool     `json:"truncated"`
}

Stats is the accounting shared by every parser (INV-3).

type StatusError

type StatusError struct {
	Code       int
	RetryAfter time.Duration
}

StatusError is a non-200 answer (other than a usable 304). RetryAfter is the answer's Retry-After (seconds or an HTTP date; 0 when absent or unreadable, at most maxRetryAfter).

func (*StatusError) Error

func (e *StatusError) Error() string

type Store

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

Store is the module's database access. Reads use the read-only pool; every write goes through DB.Write. A pull is one transaction, except an indicator list: that goes in chunks (applyIOCs).

func NewStore

func NewStore(db *store.DB) *Store

NewStore wraps a migrated database.

func (*Store) Brief

func (s *Store) Brief(ctx context.Context, cve string) (Brief, bool, error)

Brief reads the brief of one CVE (upper case); ok is false when the catalogue does not hold it.

func (*Store) CVSSOf

func (s *Store) CVSSOf(ctx context.Context, cves []string) (map[string]CVSS, error)

CVSSOf returns the CVSS base score of each of these CVEs that has one (PickCVSS of the catalogue's scores), with its version, source and vector. A CVE without a score is absent: the pages say "No CVSS score", never 0. The source is "nvd" or "cna" as the findings API names it: CISA's ADP, another scorer than NVD, reads as "cna" there.

func (*Store) Catalogue

func (s *Store) Catalogue(ctx context.Context, cves []string) (map[string]CatalogueEntry, error)

Catalogue returns the catalogue entries of these CVEs; a CVE the catalogue does not hold is absent.

func (*Store) CreditName

func (s *Store) CreditName(ctx context.Context, g IOCSighting) string

CreditName is creditName in the organization's zone as it is now.

func (*Store) DistroCVEs

func (s *Store) DistroCVEs(ctx context.Context, pkgs []DistroPackage) ([]string, error)

DistroCVEs returns the CVEs the enabled distribution feeds say something about (fixed or not affected) for these packages: a CVE a distribution has fixed in a package reaches the match pass before NVD names the upstream product. Sorted.

func (*Store) DistroFixes

func (s *Store) DistroFixes(ctx context.Context) (map[string][]DistroFix, error)

DistroFixes returns what the distributions say about the CVEs of the CISA list, by CVE, from the distribution feeds that are on: a feed an admin turned off is not used, its rows stay until it is on again. The tier rows are not read here: the KEV matcher sees exactly the rows it saw before them.

func (*Store) DistroFixesFor

func (s *Store) DistroFixesFor(ctx context.Context, cves []string) (map[string][]DistroFix, error)

DistroFixesFor is DistroFixes for these CVEs, on an exploited list or not: what the distributions say about the catalogue CVEs the match pass compares.

func (*Store) DistroFixesOf

func (s *Store) DistroFixesOf(ctx context.Context, cve string) ([]DistroFix, error)

DistroFixesOf is DistroFixes of one CVE (the CVE page's platform check); nil when none.

func (*Store) DistroLoading

func (s *Store) DistroLoading(ctx context.Context) (map[string]bool, error)

DistroLoading lists the distributions one of whose feeds is on but holds no row while a first pull can still come: never completed, not yet failed DistroGiveUpFailures times in a row, and the CISA list it waits for on the box or still coming (kevCanArrive). findings then keeps an Alpine CVE of the platform list a question ("not loaded yet") instead of letting NVD decide; a feed that is off is not loading (its distribution falls back to NVD), and one with rows from an earlier good pull decides with them.

func (*Store) DistroOn

func (s *Store) DistroOn(ctx context.Context) (map[string]bool, error)

DistroOn lists the distributions ("ubuntu", "debian") whose security data decides their own packages: the feed that says which packages are affected and fixed (debian-tracker, ubuntu-osv) is on and has rows or a completed pull, or is loading (as DistroLoading counts it). findings judges a package such a distribution built by its word alone; a distribution whose feeds are off, or were given up after failing, falls back to NVD's ranges. ubuntu-vex does not count: it keeps only "not affected", so with ubuntu-osv off no row could ever say an Ubuntu package is affected.

func (*Store) DistroPlanLoading

func (s *Store) DistroPlanLoading(ctx context.Context) (map[string]bool, error)

DistroPlanLoading lists the distributions the plan still waits for: a feed the plan reads (alpine-osv, debian-tracker, ubuntu-osv; ubuntu-vex is not read by the plan) is on, has never completed a pull and has not failed DistroGiveUpFailures times in a row. A pull that completed is loaded even if it stored no row; a feed that keeps failing is given up, so the plan falls back to "Check <distro>'s security updates" for its devices instead of leaving them unchecked for good.

func (*Store) HasTemplate

func (s *Store) HasTemplate(ctx context.Context, cve string) (bool, error)

HasTemplate reports whether nuclei has a template for the CVE (its public-exploit signal).

func (*Store) HaveSince

func (s *Store) HaveSince(ctx context.Context) (map[string]Have, error)

HaveSince maps each device an "I have this" answer declared (S-FEED-2) to its scope: the answered product and the date a week before the answered entry (HaveWindow), set by the first "have". Only answers that are still "have" and whose device the inventory named count; findings scopes that one device, never the product on other devices.

func (*Store) IOCCredits

func (s *Store) IOCCredits(ctx context.Context) (map[string]string, error)

IOCCredits is the name each switched-on built-in feed whose terms ask for credit with a time (Source.CreditFetch: Spamhaus DROP) is shown by, by its plain name: CreditName with the feed's last good pull. A feed never pulled is not in it (shown by its plain name). Logs stores the plain name on a hit and shows this one.

func (*Store) IOCListed

func (s *Store) IOCListed(ctx context.Context) (bool, error)

IOCListed says whether a switched-on feed lists at least one indicator now: false while every IOC feed is off or none has loaded yet, so logs' digest can say that no connection can be matched instead of "none of your devices connected to a listed address".

func (*Store) IOCLookup

func (s *Store) IOCLookup(ctx context.Context, kind, value string) (IOCRecord, bool, error)

IOCLookup returns an indicator by type ("ip", "domain", "url", "hash") and canonical value (see IOCKey). An indicator no feed lists any more is reported with no sightings. An address is also listed by every feed that lists a network holding it (Spamhaus DROP: networksAround), and a feed that lists the address and a network around it, or several networks around it, is one sighting. The first and last seen times span every stored row read (the address and its networks).

func (*Store) IOCSubdomainsOn

func (s *Store) IOCSubdomainsOn(ctx context.Context) (bool, error)

IOCSubdomainsOn says whether a switched-on built-in feed lists names with all of their subdomains (Source.Subdomains): logs looks up the parents of an unlisted name only then. A custom feed is always exact.

func (*Store) KevAffected

func (s *Store) KevAffected(ctx context.Context) (map[string][]AffectedRow, error)

KevAffected returns the affected entries of the exploited lists' CVEs, for findings: NVD's when NVD gives any, else those of the CNA's CVE record for the product the list's entry names (kevRecordView; RangesFromCVEOrg names them). A CVE NVD has not answered for and the record gave nothing for is absent; one NVD answered for without a vulnerable entry is present with an empty list.

func (*Store) KevCVEsByKeys

func (s *Store) KevCVEsByKeys(ctx context.Context, keys []string) ([]string, error)

KevCVEsByKeys returns the CVEs of the exploited lists for these product keys (productid.Key form, lower case). A "Multiple products" entry of a vendor matches every key of that vendor (INV-11). It is one lookup in KevIndex.

func (*Store) KevIndex

func (s *Store) KevIndex(ctx context.Context) (*KevIndex, error)

KevIndex returns the index of the exploited-list CVEs by product key. It is read again only when kevStamp moved: a device page or an agent report looks up all of its software in one index, and most calls cost one small stamp query instead of reading every entry of the lists.

func (*Store) KevPairs

func (s *Store) KevPairs(ctx context.Context) ([]Product, error)

KevPairs lists every vendor and product pair of the exploited lists (CISA, VulnCheck), for the inventory catalog. A custom feed's products are not KEV entries.

func (*Store) KevProducts

func (s *Store) KevProducts(ctx context.Context) (version string, list []ProductCount, err error)

KevProducts lists every vendor and product pair of the exploited lists with its CVE count, and a version that changes whenever the set of entries does (entry count and newest update).

func (*Store) KevPublished

func (s *Store) KevPublished(ctx context.Context) (map[string]time.Time, error)

KevPublished returns the day each CVE of the exploited lists was published (NVD's, else the CVE record's). A CVE that is absent has no known day: findings then treats it as recent and never closes a finding on it for its age.

func (*Store) KevPulledAt

func (s *Store) KevPulledAt(ctx context.Context) (time.Time, error)

KevPulledAt is when the CISA list was last pulled successfully (zero = never). The weekly report names it as the source time of its exploited-list figures.

func (*Store) KevVulns

func (s *Store) KevVulns(ctx context.Context) ([]VulnRow, error)

KevVulns returns the owner entry of every CVE of the exploited lists (CISA, VulnCheck), for matching.

func (*Store) KevVulnsByCVE

func (s *Store) KevVulnsByCVE(ctx context.Context, cves []string) ([]VulnRow, error)

KevVulnsByCVE returns the owner entries of the exploited lists for these CVEs (upper case); CVEs not on them are absent.

func (*Store) MatchStamp

func (s *Store) MatchStamp(ctx context.Context) (string, error)

MatchStamp changes whenever what KevVulns, KevAffected and DistroFixes return may have changed: the last pull time and rev (turned on or off) of the feeds that write them (each written in the pull's own transaction), and the count and newest change of the exploited-list entries and of their catalogue rows. findings (through cmd/vedette) keeps one read of the list per stamp, instead of reading the ranges once per device.

func (*Store) NewKEVSince

func (s *Store) NewKEVSince(ctx context.Context, at time.Time, cve string, limit int) ([]AnnouncedKEV, error)

NewKEVSince lists the entries of the CISA list and VulnCheck KEV that feeds announced as new (feeds.vuln.new_kev, POST-1) after the point (at, cve), oldest first, at most limit (1..MaxNewKEVPage). The bus is best-effort: a subscriber that may have missed events (its module off, or the box stopped between the pull's commit and the events) keeps the (At, CVE) of the last entry it handled and asks again. Entries of a first fill and the CVEs of custom feeds were never announced and are never listed. A CVE VulnCheck announced and the CISA list later named is listed twice, as the bus announced it twice. HasTemplate is today's value.

func (*Store) PublishedOf

func (s *Store) PublishedOf(ctx context.Context, cves []string) (map[string]string, error)

PublishedOf returns the day each of these CVEs was published ("2017-03-14"); a CVE with no known day is absent. One query per publishedChunk CVEs (the CVEs as one JSON array parameter, json_each), not one per CVE.

func (*Store) RangeProducts

func (s *Store) RangeProducts(ctx context.Context) ([]RangeProduct, error)

RangeProducts is every product a catalogue range names, each once: the match pass keeps those its devices run and reads only their ranges (Ranges). One walk of the (vendor, product, cpe) index.

func (*Store) Ranges

func (s *Store) Ranges(ctx context.Context, keys []ProductKey) ([]Range, error)

Ranges returns the ranges of every catalogue CVE that names one of these products, with the precedence of rangeOrigin applied per CVE (a CVE NVD gives ranges for counts only NVD's, also when NVD names other products). Sorted by CVE, then as stored.

func (*Store) RangesFromCVEOrg

func (s *Store) RangesFromCVEOrg(ctx context.Context) (map[string]string, error)

RangesFromCVEOrg returns the exploited-list CVEs whose affected versions (KevAffected) come from the CNA's CVE record, not from NVD, with their source as findings names it: "cve.org" (a complete list: every row says affected or unaffected) or "cve.org-partial" (findings may raise a match on it, never close one). kevRecordView decides both.

func (*Store) RangesOf

func (s *Store) RangesOf(ctx context.Context, cves []string) ([]Range, error)

RangesOf returns the ranges of these CVEs with the precedence of rangeOrigin applied per CVE, sorted by CVE, then as stored. A CVE the catalogue does not hold, or holds without ranges, is absent.

func (*Store) RecordStamps

func (s *Store) RecordStamps(ctx context.Context, cves []string) (map[string]string, error)

RecordStamps returns, for each CVE asked for that the catalogue holds, a stamp that changes whenever its record says something new: a hash of what the catalogue holds of it (NVD's change time and status, the description, every reference with its tags and every affected range of every origin). It never moves when the box only reads the same record again (nvd_at and record_at are read times: an exploited CVE without NVD ranges is read again every recordRecheck). findings keys a check of a CVE's advisories on it, so a changed record is checked again and an unchanged one never is.

func (*Store) SchemeCVEs

func (s *Store) SchemeCVEs(ctx context.Context, keys []ProductKey) ([]string, error)

SchemeCVEs returns the CVEs whose CVE record rows (origin cna or adp) name one of these products: a CVE a vendor states in its own notation reaches the match pass before NVD analyses it (Ranges returns only the rows the generic comparison reads). Sorted.

func (*Store) SchemeRangesOf

func (s *Store) SchemeRangesOf(ctx context.Context, cves []string) ([]Range, error)

SchemeRangesOf returns the ranges of these CVEs a product's version scheme reads (RangeScheme): the rows kept in their vendor's notation (Range.Generic false), the CVE records' rows of a product that has a scheme (SchemeProduct: the vendor's own word, read per release train, never by the generic comparison), and for a product whose vendor states its releases in the description (Described) the rows the description gives (describedRows, statedUnaffected). Sorted by CVE, then as stored.

func (*Store) SeedBuiltins

func (s *Store) SeedBuiltins(ctx context.Context, now time.Time) error

SeedBuiltins merges BuiltinSources() into feeds_source: new feeds are inserted (on, except a feed that needs the customer's key or is off by default: Source.BYOK, Source.DefaultOff); existing rows keep what the admin chose (enabled, schedule, a mirror address) while name, format, license and the default address follow the code. A feed whose address is still its old default moves to the new default.

func (*Store) Signals

func (s *Store) Signals(ctx context.Context, cves []string) (map[string][]Signal, error)

Signals returns the signal rows of these CVEs, each CVE's sorted by first sighting.

func (*Store) TierCVEOf

func (s *Store) TierCVEOf(ctx context.Context, cve string, now time.Time) (TierCVE, bool, error)

TierCVEOf reads one CVE from the tier data of the feeds that are on; found is false when neither holds it. Tier follows EPSS ≥ EPSSLikely and published in the last 365 days is likely, published in the last 365 days is recent.

func (*Store) TierStatus

func (s *Store) TierStatus(ctx context.Context, now time.Time) (TierStatus, error)

TierStatus reads the two feeds: epss-all is ready once it stored scores, nvd-recent once the fill of its window finished (its cursor left the fill mode) and the catalogue holds NVD records of the window.

func (*Store) VulnByCVE

func (s *Store) VulnByCVE(ctx context.Context, cve string) (VulnRow, bool, error)

VulnByCVE returns the owner entry of one CVE (upper case).

func (*Store) VulnsByProductKey

func (s *Store) VulnsByProductKey(ctx context.Context, key string) ([]VulnRow, error)

VulnsByProductKey returns the entries of one product key (productid.Key), newest first.

type SyncBaselineEvent

type SyncBaselineEvent struct {
	Source string `json:"source"` // "cisa-kev"
	Count  int    `json:"count"`  // CVEs the pull added
}

SyncBaselineEvent is published once, instead of one NewKEVEvent per CVE, when the first pull of the CISA list fills an empty database. Subscribers recompute everything once; notify sends nothing for it.

type Template

type Template struct{ CVE, URL string }

Template is one CVE of nuclei-templates' index, with the address of its template.

type TierCVE

type TierCVE struct {
	CVE                     string
	Tier                    string // "likely", "recent", or "" (older than 12 months, or no published day in the data)
	Published, LastModified *time.Time
	NVDStatus, Severity     *string
	Score, EPSS, Percentile *float64
	EPSSDate                *time.Time
	Products                []string // "vendor product" of NVD's affected entries, at most 10
	Ranges                  bool     // NVD gives affected entries
}

TierCVE is what the tier data says about one CVE (GET /feeds/cve/{id}/tier).

type TierFeed

type TierFeed string

TierFeed is the state of one tier feed for the pages that read it.

const (
	TierOff     TierFeed = "off"
	TierLoading TierFeed = "loading"
	TierReady   TierFeed = "ready"
)

The states of a tier feed: off (an admin has not turned it on), loading (on, its first fill is not finished), ready.

type TierStatus

type TierStatus struct {
	EPSS, Recent TierFeed
	EPSSDate     time.Time // FIRST's day of the stored scores (the file's score_date, 00:00 UTC); before a pull stored it, the UTC day of the last good pull; zero unless EPSS is ready
	RecentSince  time.Time // CVEs published on or after it are in nvd-recent's data; zero unless Recent is ready
}

TierStatus says what the tier data holds.

type TooSoonError

type TooSoonError struct {
	Name  string
	Hours int
	At    time.Time
	Zone  *time.Location // the organization's zone the time is written in (orgtime); nil: UTC
}

TooSoonError is a pull refused because the source allows fewer downloads (fetchFloor); nothing was asked. The text names the time the next pull is possible.

func (*TooSoonError) Error

func (e *TooSoonError) Error() string

type TxSettler

type TxSettler interface {
	Settle(ctx context.Context, tx *sql.Tx, committed bool)
}

TxSettler is optional on Inventory: AddManualDevice may leave work for after the caller's transaction (the inventory events), and Settle(ctx, tx, committed) tells it whether that transaction committed or rolled back.

type UrgencyFacts

type UrgencyFacts struct {
	Signals     []UrgencySignal
	CVSS        *CVSS
	Automatable string // "" when not given
	Published   *time.Time
}

UrgencyFacts is what the box holds about one CVE that the urgency of its findings reads: its signals of the feeds that are on (an exploited list's entry is one: the list writes its signal row with the entry), the CVSS score PickCVSS picks, CISA's SSVC "automatable" and the publication day.

type UrgencyReader

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

UrgencyReader reads urgency facts through q, the store's reader or a read-only handle on the same file (the selfcheck recomputes stored urgencies with it). It keeps what it reads of the sources until a feed pulls again or is switched (the sources' stamp).

func NewUrgencyReader

func NewUrgencyReader(q *sql.DB) *UrgencyReader

NewUrgencyReader returns a reader on q.

func (*UrgencyReader) CatalogueLoaded

func (r *UrgencyReader) CatalogueLoaded(ctx context.Context) (time.Time, error)

CatalogueLoaded is when the catalogue's first load ended: the later of the first good pulls of the catalogue's two feeds (NVD's CVEs of the last 12 months, the CVE records) that have one; zero before either has. A device's findings of old flaws appear then.

func (*UrgencyReader) Facts

func (r *UrgencyReader) Facts(ctx context.Context, cves []string) (map[string]UrgencyFacts, error)

Facts reads the urgency facts of these CVEs. A CVE the box holds nothing of is absent. The signals of a feed that is off are left out (an exploited list's own rows stay: the list's entries are what the match pass reads, whatever the switch).

type UrgencySignal

type UrgencySignal struct {
	Signal
	FirstLoad bool
	LoadedAt  time.Time
}

UrgencySignal is a signal row as the urgency of a finding reads it. FirstLoad says the row came with the first load of its source on this box (stored no later than the end of the source's first good pull, LoadedAt), so its date says nothing about when the box learned it.

type VectorReading

type VectorReading struct {
	AttackVector       string // network | adjacent | local | physical
	AttackComplexity   string // low | medium (2.0 only) | high
	AttackRequirements string // 4.0 only: none | present; "" otherwise
	// PrivilegesRequired is none | low | high; for CVSS 2.0 its Authentication read the same way (none, single, multiple).
	PrivilegesRequired string
	UserInteraction    string // none | required (3.x) | passive | active (4.0); "" for 2.0, which has no such metric
	Scope              string // 3.x only: unchanged | changed; "" otherwise
	// Confidentiality, Integrity and Availability are the impact on the vulnerable system: none | low | high (2.0's partial is low,
	// complete is high).
	Confidentiality, Integrity, Availability string
	Subsequent                               *Impact // 4.0 only: the impact on the systems beyond it; nil otherwise
	Summary                                  string
}

VectorReading is a CVSS base vector read into words: the attack conditions and the impact, one value per metric, the same words for CVSS 2.0, 3.x and 4.0 so a reader never decodes a vector itself. Summary says it in one sentence.

func ReadVector

func ReadVector(vector string) *VectorReading

ReadVector reads a CVSS base vector as the catalogue stores it ("CVSS:3.1/AV:N/…", "CVSS:4.0/…", 2.0 "AV:N/AC:L/Au:N/C:P/I:P/A:P"). It returns nil for a vector it cannot read whole: an unknown version, a base metric missing or given twice, or a value the version does not define. Metrics beyond the base ones (a 4.0 threat or environmental metric, 3.x temporal ones) are passed over.

type Verdict

type Verdict string

Verdict is the decision for an IOC (INV-12).

const (
	VerdictNone  Verdict = ""      // not judged: unknown value, special address, local name, whitelisted domain
	VerdictAlert Verdict = "alert" // one independent source, or only aggregate or informational sources
	VerdictBlock Verdict = "block" // two independent sources, or one DROP/CC0-class source
)

Verdicts.

func Judge

func Judge(kind, value string, sightings []Sighting, wl Whitelist) Verdict

Judge applies INV-12 (DATA_PIPELINE §3) to one IOC: whitelisted domains and values that are not a public IP or domain get no verdict; otherwise `block` for two independent sources or any block-class source, `alert` below that. Independence: ids are normalised; an informational source (Tor exit) never counts toward block; an aggregate (IPsum) never blocks alone, and with one of its upstreams present is not a second source; all aggregates together count as at most one source.

type Vuln

type Vuln struct {
	CVE            string   `json:"cve"`
	Vendor         string   `json:"vendor"`
	Product        string   `json:"product"`
	Name           string   `json:"name"`
	Description    string   `json:"description"`
	RequiredAction string   `json:"required_action"`
	Links          []string `json:"links"`
	DateAdded      string   `json:"date_added"` // YYYY-MM-DD
	DueDate        string   `json:"due_date"`   // YYYY-MM-DD, empty when KEV gives none
	Ransomware     bool     `json:"ransomware"`
}

Vuln is one entry of an exploited list, in the list's own words (a feeds_kev row).

func (Vuln) Key

func (v Vuln) Key() string

Key is the inventory matching key (productid.Key of vendor and product).

type VulnCheckPageResult

type VulnCheckPageResult struct {
	Vulns      []Vuln // entries CISA does not list and VulnCheck added inside the window
	Entries    int    // entries on the page, valid or not
	Total      int    // _meta.total_documents: the entries of the whole list (0 when not said)
	NextCursor string // _meta.next_cursor: "" on the last page
	Short      bool   // _meta.truncated: VulnCheck cut the page short
	Warning    string // _meta.warnings, as plain text (why VulnCheck cut the page short)
	FirstCVE   string // the first entry's CVE (a server that ignores the cursor repeats it)
	Stats
}

VulnCheckPageResult is one parsed page of the list.

func ParseVulnCheckPage

func ParseVulnCheckPage(data []byte, now time.Time, held map[string]bool) (VulnCheckPageResult, error)

ParseVulnCheckPage reads one page of the index answer ({"_meta":{...},"data":[...]}), fail-closed per entry (INV-3): a bad entry is rejected and counted, the rest are kept. A body that is not that envelope fails the page. now fixes the window of "recent", which only keeps a CVE the box does not hold yet: an entry already held stays while VulnCheck lists it and CISA does not (held: the CVEs of the box's vulncheck-kev rows).

type VulnRow

type VulnRow struct {
	Vuln
	EPSS        *float64
	EPSS7dAgo   *float64
	HasTemplate bool
	SourceID    string
}

VulnRow is an exploited-list entry as the pages read it: the owner entry of its CVE, with the EPSS score of the CVE (today's and the one of a week before, when the box holds it) and whether nuclei has a template for it.

type VulnUpdatedEvent

type VulnUpdatedEvent struct {
	CVEs []string `json:"cves"`
}

VulnUpdatedEvent lists CVEs whose stored data changed (vendor, product, dates, ransomware flag, template).

type Weakness

type Weakness struct{ ID, Name string }

Weakness is one CWE of a CVE with its name in MITRE's CWE List; Name is "" for an id the list does not hold.

type Whitelist

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

Whitelist is a validated set of domains that never get a verdict.

func NewWhitelist

func NewWhitelist(entries []string) (Whitelist, error)

NewWhitelist normalises entries ("Google.com.", "*.google.com" and ".google.com" all mean google.com and everything under it) and refuses any entry that is not a registrable domain, instead of ignoring it silently.

type YouHave

type YouHave string

YouHave is the answer of "Do you have it?" (INV-11).

const (
	HaveYes   YouHave = "yes"   // a device runs the product (confirmed match)
	HaveMaybe YouHave = "maybe" // only the vendor matches a "Multiple products" entry
	HaveNo    YouHave = "no"
)

Answers.

Jump to

Keyboard shortcuts

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