diff --git a/CHANGELOG.md b/CHANGELOG.md index d3f9a73..49afbf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,11 +4,72 @@ All notable changes to this project are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [0.4.2] ### Fixed +- Debian `--scope all` inventory strips the multiarch suffix (`libssl3:amd64` + is `libssl3`), so purls, report keys and library CVE matches are right. +- Running out of quota during the `?search=` fallback no longer discards the + batch results: the report is written, the unsearched assets are listed in + `errors`, and the run exits `4` at the end with the upgrade link from Radar. +- `errors` is keyed by asset (`name@version`), like every other map, instead + of by search term. +- SARIF validates against the 2.1.0 schema: `fixes` (which lacked + `artifactChanges`) is gone, remediation is in `properties.remediation`, and + artifact URIs are percent-encoded. +- Solaris/illumos: services are resolved from the processes `svcs -p` lists + (binary and PID) instead of the start method, so SMF method scripts under + `/lib/svc/method` are never probed and paths with escaped spaces resolve. +- Version probes run only `--version` and `-V`; `-v` and a bare `version` + started some daemons. +- BSD and SysV/OpenRC services get a PID from `pgrep`, and Solaris/illumos + from `svcs -p`, so their listeners and exposure are reported. +- `--sbom --severity` keeps every exploited finding below the floor, not just + KEV ones, as host scans do. +- Windows app names lose `(R)`, `(TM)`, `®` and `™`, and only trailing + parenthesised groups: "Intel(R) Management Engine" is no longer "Intel". +- SBOM findings without a remediation entry get an asset, so every SARIF result + has a location, and an absolute `--sbom` path inside the current directory is + made relative. +- OpenBSD binaries resolve to their package: `pkg_info -E` prints + "path: package", and the parser took the path for the package. +- A CVE confirmed for an asset is no longer repeated under `unconfirmed`. +- `byCve.*.epss` is the highest EPSS across the assets. +- The plan readout skips the monthly row when Radar sends no monthly limit. +- A `413 Payload too large` (the server's body limit) is reported as such, not + as a plan cap; batches still halve on it. +- The `/scan` body limit is 16 MiB, as on the server (was 10 MB). + +### Changed +- Truncation is split by cause. `truncated` lists only plan-capped assets (with + the upgrade hint). Assets the server's candidate cap cut short are re-queried + once in a smaller batch; any still capped are listed in the new `incomplete` + and fail a `--fail-on` run with exit `1`, as lookup errors do. `--sbom` reads + Radar's `truncated` (`candidate-cap` → `incomplete`) the same way. Report + `schemaVersion` is 4. +- At most 25 `?search=` fallback lookups per run; the rest are listed in + `rejected` as not searched (their hits would be unconfirmed, so they never + fail `--fail-on`). +- Running out of quota mid-run keeps everything already matched: the report is + written with the rest under `errors`, registration is skipped, and the run + exits `4`. +- API keys must match Radar's format (`tr_` and 64 hex characters): a malformed + `OFFSEQ_API_KEY` or saved key exits `2` before any request, and the setup + prompt rejects one. +- `--json` and `--output` conflict. +- Registration uses Radar's `monitoringAvailable` to say whether alerts are on, + and notes when the server could not evaluate every asset. +- The plan readout shows when the hourly and daily windows reset. + +### Removed +- Unused `homebrew_version`, `atom_version`, `MatchHit::epss_percentile`, + `InstalledPkg` and `Collector::name`. `list_installed` returns + `(name, version)` pairs. + +### CI and release - Linux release binaries link against glibc 2.28 instead of the build runner's 2.39, so they run on Debian 10+, Ubuntu 20.04+ and RHEL 8+. +- Dependencies updated to their latest compatible patch releases. ## [0.4.1] @@ -114,7 +175,7 @@ Brings the client in line with the current Radar API. Windows and is shared on Unix). - Version probing resolves symlinks and refuses binaries others can replace, cannot hang on a forked child holding the pipe, and kills the probe's process - group (including anything it daemonized). + group (a child that starts its own session escapes it). - Findings exploited per EUVD, Mirage or the in-the-wild flag survive `--severity`, like KEV ones. - The logger no longer panics when its directory is not writable. @@ -404,7 +465,33 @@ Brings the client in line with the current Radar API. ### Removed - Dead `ServiceEntry` / `SystemInfo` API types left over from the match migration. -## [Unreleased] +## [0.1.0-prev] + +### Added +- Network-exposure correlation: each running service is mapped to its listening + sockets (`/proc/net` on Linux, `lsof` elsewhere) and flagged when reachable + off-host. Findings rank exposed-first. +- Enriched findings: CISA-KEV (known-exploited) flag, EPSS score, CVSS vector, + full reference list, and match provenance (constraint vs free-text). +- `--fail-on ` for CI gating, with a + documented exit-code scheme (0–5). +- `--json`, `--severity`, `--quiet`, `--no-color`, `--yes`, `--reset` flags; + `OFFSEQ_API_KEY` environment variable; ranked, colored terminal summary. +- Per-OS package-database version sourcing (dpkg/rpm/pacman/apk/pkg/pkg_info/brew). + +### Fixed +- macOS/BSD/Solaris/SysV discovery (previously probed a service name/label as a + binary); FreeBSD empty-result bug; NetBSD scanner. +- Structured `affectedVersions` constraint matching (`*`, `=`, `<`, `<=`, `>`, + `>=`, compound AND, OR-across-array) with a correct version model. +- Pagination cap; deterministic (sorted) JSON output; transient-error retries + with backoff and `Retry-After` handling. + +### Security +- Hardened version probing (absolute paths only, sanitized env) and `0600`/`0700` + API-key storage. + +## [0.1.0] ### Changed - **Migrated to Radar exact-coordinate matching** (`POST /match/batch`). Each @@ -416,6 +503,8 @@ Brings the client in line with the current Radar API. - Findings now split into `confirmed` (reported) and `unconfirmed` (triage, excluded from the count / `byCve` / `--fail-on`); added `--strict`. `?search=` is retained only as a fallback for assets with no buildable coordinate. +- `ThreatError` now implements `std::error::Error`; single canonical + `severity_rank`; pure per-OS parse functions extracted and unit-tested. ### Added - Split into a reusable library crate (`find_threats`) + thin binary, with a @@ -425,8 +514,6 @@ Brings the client in line with the current Radar API. Assets are deduplicated and merged so a package backing a running, exposed process keeps its runtime exposure. Defaults to `--scope running` (quota-safe), with a warning when the inventory exceeds the free-tier budget. - -### Added (prior) - Reachability classification (loopback / private / public) for listeners, and UDP listener coverage in addition to TCP. - Cross-service CVE grouping (`byCve`) — one fix mapped to every affected service. @@ -439,35 +526,4 @@ Brings the client in line with the current Radar API. disabling the headline feature off-Linux. Now uses `lsof -Fn` field output, with a non-vacuous regression test. -### Changed -- `ThreatError` now implements `std::error::Error`; single canonical - `severity_rank`; pure per-OS parse functions extracted and unit-tested. - -## [0.1.0-prev] - -### Added -- Network-exposure correlation: each running service is mapped to its listening - sockets (`/proc/net` on Linux, `lsof` elsewhere) and flagged when reachable - off-host. Findings rank exposed-first. -- Enriched findings: CISA-KEV (known-exploited) flag, EPSS score, CVSS vector, - full reference list, and match provenance (constraint vs free-text). -- `--fail-on ` for CI gating, with a - documented exit-code scheme (0–5). -- `--json`, `--severity`, `--quiet`, `--no-color`, `--yes`, `--reset` flags; - `OFFSEQ_API_KEY` environment variable; ranked, colored terminal summary. -- Per-OS package-database version sourcing (dpkg/rpm/pacman/apk/pkg/pkg_info/brew). - -### Fixed -- macOS/BSD/Solaris/SysV discovery (previously probed a service name/label as a - binary); FreeBSD empty-result bug; NetBSD scanner. -- Structured `affectedVersions` constraint matching (`*`, `=`, `<`, `<=`, `>`, - `>=`, compound AND, OR-across-array) with a correct version model. -- Pagination cap; deterministic (sorted) JSON output; transient-error retries - with backoff and `Retry-After` handling. - -### Security -- Hardened version probing (absolute paths only, sanitized env) and `0600`/`0700` - API-key storage. - -## [0.1.0] - Initial release. diff --git a/Cargo.lock b/Cargo.lock index c5b5283..c19866e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -122,9 +122,9 @@ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "bumpalo" -version = "3.20.3" +version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" [[package]] name = "bytes" @@ -134,9 +134,9 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cc" -version = "1.11.0" +version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" dependencies = [ "find-msvc-tools", "jobserver", @@ -198,7 +198,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -288,9 +288,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.4" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" dependencies = [ "cfg-if", ] @@ -364,7 +364,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -399,9 +399,9 @@ checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "flate2" -version = "1.1.10" +version = "1.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" dependencies = [ "crc32fast", "miniz_oxide", @@ -749,9 +749,9 @@ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "itoa" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "jni" @@ -889,9 +889,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.4" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi", @@ -1198,9 +1198,9 @@ dependencies = [ [[package]] name = "rpassword" -version = "7.5.4" +version = "7.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196" +checksum = "1fa2c5d9304b618df61ff17f3d3485c6e1854a3d94902a49abbb8d43dfbe0464" dependencies = [ "libc", "rtoolbox", @@ -1260,9 +1260,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.15.1" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ "web-time", "zeroize", @@ -1297,9 +1297,9 @@ checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.16" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "aws-lc-rs", "ring", @@ -1393,7 +1393,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1411,9 +1411,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "1.1.2" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" dependencies = [ "serde_core", ] @@ -1475,9 +1475,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.4" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" [[package]] name = "socket2" @@ -1526,9 +1526,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.9" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -1552,7 +1552,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1572,7 +1572,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1586,7 +1586,7 @@ dependencies = [ [[package]] name = "threat-finder" -version = "0.4.1" +version = "0.4.2" dependencies = [ "clap", "dirs", @@ -1690,9 +1690,9 @@ dependencies = [ [[package]] name = "toml" -version = "1.2.0+spec-1.1.0" +version = "1.2.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5ffcdf8f50436dbbfd675c1fe1b8e0854f42b7defea8584bdebe1aee900e561" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" dependencies = [ "indexmap", "serde_core", @@ -1705,9 +1705,9 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.2+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" dependencies = [ "serde_core", ] @@ -1916,9 +1916,9 @@ checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" [[package]] name = "uuid" -version = "1.29.0" +version = "1.29.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" +checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" dependencies = [ "getrandom 0.4.3", "js-sys", @@ -1998,7 +1998,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "wasm-bindgen-shared", ] @@ -2033,9 +2033,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.11" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] @@ -2139,9 +2139,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" [[package]] name = "writeable" @@ -2168,7 +2168,7 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] @@ -2189,7 +2189,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] @@ -2229,7 +2229,7 @@ checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 23f5270..dbf8c2e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "threat-finder" -version = "0.4.1" +version = "0.4.2" edition = "2021" rust-version = "1.89" description = "Runtime vulnerability scanner: finds CVEs in the services and packages actually present on a host and flags which are network-exposed" diff --git a/README.md b/README.md index 8f874c7..6e81931 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ threat-finder [OPTIONS] | Flag | Description | |------|-------------| | `-o, --output ` | Write the JSON report to `PATH` (default: prompt, or `./threats.json`) | -| `--json` | Print the JSON report to stdout instead of a file | +| `--json` | Print the JSON report to stdout instead of a file (conflicts with `-o`) | | `--scope ` | `running` (default) or `all` (+ every installed OS package) | | `--severity ` | Only report findings at/above `critical\|high\|medium\|low` | | `--strict` | Drop coordinate-unconfirmed findings (report only confirmed) | @@ -90,11 +90,13 @@ OFFSEQ_API_KEY=… threat-finder --yes --json --severity high > report.json OFFSEQ_API_KEY=… threat-finder --yes --quiet --fail-on act-now ``` -**Exit codes:** `0` ok · `1` lookup/IO error · `2` no API key · `3` unsupported -OS · `4` rate limit/quota, or API access required (upgrade needed) · `5` -`--fail-on` threshold met. With `--fail-on`, a run where any lookup failed exits -`1` rather than passing; packages Radar could not evaluate (listed under -`rejected`) don't count as failed lookups. +**Exit codes:** `0` ok · `1` lookup/IO error · `2` no or malformed API key · `3` +unsupported OS · `4` rate limit/quota, or API access required (upgrade needed) · +`5` `--fail-on` threshold met. With `--fail-on`, a run where any lookup failed or +an asset was left `incomplete` exits `1` rather than passing; packages Radar could +not evaluate (listed under `rejected`) don't count as failed lookups. When the +quota runs out mid-run, the report is still written with what was matched (the +rest under `errors`), registration is skipped, and the run exits `4`. **API key** (get one from the [Radar Console](https://radar.offseq.com/console)), resolved in order: @@ -104,6 +106,8 @@ resolved in order: unless `--reset` is given. 3. An interactive, hidden prompt on a TTY — then saved for next time. +Keys have Radar's format, `tr_` followed by 64 hex characters; a malformed +`OFFSEQ_API_KEY` or saved key exits `2` before any request is made. Non-interactive (`--yes` / no TTY) with no key available exits `2`. Set `OFFSEQ_CONFIG_DIR` to override where the config lives (default: the OS @@ -121,6 +125,8 @@ there's no client-side version guessing. Findings are split by the API's `confirmed` flag: confirmed matches are reported; coordinate matches whose version can't be confirmed are surfaced separately as **unconfirmed / triage** (excluded from the count, `byCve`, and `--fail-on`; drop them with `--strict`). +Assets with no buildable coordinate fall back to a name search, at most 25 per +run; the rest are listed under `errors`. **Network-exposure correlation.** Manifest scanners (Trivy, Grype, osv-scanner) read package lists; external scanners (Nessus, OpenVAS) need a second host. This @@ -167,7 +173,8 @@ default in CI), `--no-register` opts out, `--host-name ` labels the host, `--unregister` removes it. A stable per-host id and your prompt preference live in `$XDG_CONFIG_HOME/offseq-rust/config.toml`. Registration never changes the exit code — a monitoring hiccup won't fail your scan. Every plan can register hosts -(Free: 2); alerts need a paid plan. +(Free: 2); alerts need a paid plan, and the confirmation says whether yours has +them. ## SBOM and lockfile scanning @@ -183,11 +190,13 @@ threat-finder --sbom package-lock.json --yes --fail-on high --sarif deps.sarif The report has the usual shape, keyed by purl; `assets.*.upgradeTo` comes from Radar's remediation and packages it couldn't check (no version, unsupported -ecosystem) are listed under `rejected`. A file has no network exposure, so +ecosystem) are listed under `rejected`, and capped packages Radar reports go to +`truncated` or `incomplete` as for a host scan. A file has no network exposure, so `riskScore`/`decision` are Radar's exposure-free score. `--severity`, `--strict`, `--fail-on`, `--json` and `--sarif` work as for a host scan; registration and -the monitoring prompt are skipped. The file must stay under 10 MB once -JSON-encoded, and non-JSON files can't have lines over 4,096 characters (checked +the monitoring prompt are skipped. SARIF locates findings at the file's path +relative to the current directory (or its name when it is elsewhere). The file +must stay under 16 MiB once JSON-encoded, and non-JSON files can't have lines over 4,096 characters (checked locally before sending). Packages per scan are capped by plan (the same as the batch size); a larger file exits `4` with the cap named. @@ -227,23 +236,26 @@ coordinate). The kernel is covered as its package (`linux-image…`) under > per plan (Free 50 per request at 20 requests/hour and 30/day; Base 200; Pro > 1,000; Enterprise 4,000), and the tool warns when an inventory needs many free > requests. Free plans also see at most 10 matches per package (riskiest first); -> capped assets are listed under `truncated`. +> capped assets are listed under `truncated`. Assets the server's per-request +> candidate cap cut short are re-queried once in a smaller batch; any still cut +> short are listed under `incomplete`. ## Per-OS support | OS | Discovery | Coordinate source | |----|-----------|-------------------| | Linux (systemd) | `systemctl list-units` / `show` → `/proc//exe` | dpkg / rpm / pacman / apk | -| Linux (SysV/OpenRC) | `service --status-all` / `rc-status` | package DB | +| Linux (SysV/OpenRC) | `service --status-all` / `rc-status` → `pgrep` | package DB | | macOS | `launchctl list` → `ps` (third-party only) | Homebrew | -| FreeBSD / DragonFly | `service -e` | `pkg` | -| OpenBSD | `rcctl ls started` | `pkg_info` | -| NetBSD | `/etc/rc.d` status | `pkg_info` | -| Solaris / illumos | `svcs` → `svcprop` | probe (`--version`) | +| FreeBSD / DragonFly | `service -e` → `pgrep` | `pkg` | +| OpenBSD | `rcctl ls started` → `pgrep` | `pkg_info` | +| NetBSD | `/etc/rc.d` status → `pgrep` | `pkg_info` | +| Solaris / illumos | `svcs` → `svcs -p` (process binary and PID) | probe (`--version`) | | Windows | `Win32_Service` → `Get-NetTCPConnection` / `netstat` | registry / winget / Appx / Chocolatey / Scoop → CPE; npm / pip / dotnet → purl; the OS build → CPE | Where no package owns a binary, the version falls back to a hardened `--version` -probe (absolute path only, sanitized env). On macOS, Apple system services +/ `-V` probe (absolute path only, sanitized env, trusted owner); SMF method +scripts are never probed. On macOS, Apple system services (`com.apple.*`, SIP-protected paths) are skipped — they're covered by the OS version, and probing hundreds of them is pointless. @@ -265,17 +277,22 @@ JSON, with deterministic (sorted) keys and no timestamp, so reports diff cleanly `remediation`, `cwes`, `references`, `radarUrl`, and with `--respect-decisions` `recordedDecision`), highest-risk first. - **`unconfirmed`** — coordinate matches whose version couldn't be confirmed (triage). -- **`assets`** — `pkg@version` → `{ exe, versionSource, exposed, reachability, listeners, upgradeTo }` +- **`assets`** — `pkg@version` → `{ exe, version, versionSource, exposed, reachability, listeners, upgradeTo, restartPending }` (`versionSource` = `package-db` | `probe`; `reachability` covers TCP **and** UDP). - **`byCve`** — each CVE rolled up across every affected asset ("patch once, fix many"). -- **`errors`** — per-asset lookup failures, so a failure never reads as "clean". -- **`rejected`** — packages Radar could not evaluate, and why (not a lookup failure). +- **`errors`** — per-asset lookup failures (including assets left unmatched when + the quota ran out), so a failure never reads as "clean". +- **`rejected`** — packages Radar could not evaluate, and assets past the per-run + `?search=` fallback limit, and why (not a lookup failure). - **`truncated`** — assets whose matches the plan's per-query result cap cut short. +- **`incomplete`** — assets Radar could not fully evaluate (server candidate cap); + they fail `--fail-on` like lookup errors. - **`registration`** — present when the run registered the host: `hostId`, `monitoring`, `assetCount`, `drift`, `summary`, `newSinceLastCount`, `resolvedCount`. -- **`meta`** — `{ tool, version, schemaVersion }` (`schemaVersion` 3). +- **`meta`** — `{ tool, version, schemaVersion }` (`schemaVersion` 4). -A SARIF 2.1.0 report (`--sarif`) is also available for code-scanning UIs. +A SARIF 2.1.0 report (`--sarif`) is also available for code-scanning UIs; each +result's `properties` carry the risk fields and Radar's `remediation`. ## The OffSeq ecosystem diff --git a/src/api.rs b/src/api.rs index 49576c1..f7308ad 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,5 +1,5 @@ use std::collections::{BTreeMap, HashSet}; -use std::sync::{Arc, Mutex}; +use std::sync::Mutex; use std::time::Duration; use reqwest::blocking::Client; @@ -26,6 +26,9 @@ const MAX_PAGES: u32 = 3; const USER_AGENT: &str = concat!("threat-finder/", env!("CARGO_PKG_VERSION")); const FREE_REQUESTS_PER_HOUR: u64 = 20; +/// Free-plan batch size and daily request quota (utils/planLimits.js). +pub const FREE_BATCH: usize = 50; +pub const FREE_REQUESTS_PER_DAY: u64 = 30; /// Plan label from the hourly quota, which is unique per plan (utils/planLimits.js). fn plan_name(limit_hourly: u64) -> String { @@ -48,6 +51,9 @@ pub struct RateLimitInfo { pub remaining_daily: u64, pub limit_monthly: u64, pub remaining_monthly: u64, + /// Window resets, in epoch seconds. + pub reset_hourly: u64, + pub reset_daily: u64, } fn parse_header(headers: &reqwest::header::HeaderMap, name: &str) -> Option { @@ -70,6 +76,8 @@ impl RateLimitInfo { ("X-RateLimit-Remaining-Daily", &mut self.remaining_daily), ("X-RateLimit-Limit-Monthly", &mut self.limit_monthly), ("X-RateLimit-Remaining-Monthly", &mut self.remaining_monthly), + ("X-RateLimit-Reset-Hourly", &mut self.reset_hourly), + ("X-RateLimit-Reset-Daily", &mut self.reset_daily), ] { if let Some(v) = parse_header(headers, name) { *slot = v; @@ -83,18 +91,26 @@ pub fn plan_info(info: &RateLimitInfo) -> Option { if info.limit_hourly == 0 { return None; } - let row = |label: &str, left: u64, limit: u64| { - format!("{label:<9} {:>6} / {:>6} remaining\n", format_num(left), format_num(limit)) + let row = |label: &str, left: u64, limit: u64, reset: u64| { + let reset = if reset > 0 { format!(", resets {} UTC", utc_hhmm(reset)) } else { String::new() }; + format!("{label:<9} {:>6} / {:>6} remaining{reset}\n", format_num(left), format_num(limit)) }; let mut out = format!("Plan: {}\n", plan_name(info.limit_hourly)); - out += &row("Hourly:", info.remaining_hourly, info.limit_hourly); + out += &row("Hourly:", info.remaining_hourly, info.limit_hourly, info.reset_hourly); if info.limit_daily > 0 { - out += &row("Daily:", info.remaining_daily, info.limit_daily); + out += &row("Daily:", info.remaining_daily, info.limit_daily, info.reset_daily); + } + if info.limit_monthly > 0 { + out += &row("Monthly:", info.remaining_monthly, info.limit_monthly, 0); } - out += &row("Monthly:", info.remaining_monthly, info.limit_monthly); Some(out) } +fn utc_hhmm(epoch: u64) -> String { + let day = epoch % 86_400; + format!("{:02}:{:02}", day / 3600, day % 3600 / 60) +} + fn format_num(n: u64) -> String { let s = n.to_string(); let mut result = String::new(); @@ -107,13 +123,22 @@ fn format_num(n: u64) -> String { result.chars().rev().collect() } +/// A spent quota: the server's message and its upgrade checkout link. +#[derive(Debug, Clone)] +pub struct QuotaExceeded { + pub message: String, + pub checkout: Option, +} + #[derive(Debug)] pub enum ThreatError { - RateLimitExceeded(String), + RateLimitExceeded(QuotaExceeded), /// HTTP 413 Payload Too Large: the batch exceeded the tier cap. Carries the /// server-advertised `data.maxBatch`, when present, so the caller can resize /// and retry instead of aborting. BatchTooLarge(Option), + /// HTTP 413 from the server's body-size limit, not a plan cap. + PayloadTooLarge, /// HTTP 403 where the body indicates the account lacks API access (no active /// subscription / Pro Console). Distinct from a generic 403 so the caller can /// surface upgrade guidance and a quota exit code instead of a network-style @@ -126,9 +151,10 @@ pub enum ThreatError { impl std::fmt::Display for ThreatError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - ThreatError::RateLimitExceeded(msg) => write!(f, "Rate limit exceeded: {msg}"), + ThreatError::RateLimitExceeded(q) => write!(f, "Rate limit exceeded: {}", q.message), ThreatError::BatchTooLarge(Some(n)) => write!(f, "Batch too large (max {n})"), ThreatError::BatchTooLarge(None) => write!(f, "Batch too large"), + ThreatError::PayloadTooLarge => write!(f, "Request body exceeds the server's size limit"), ThreatError::AccessDenied(msg) => write!(f, "{msg}"), ThreatError::Http(e) => write!(f, "HTTP error: {e}"), ThreatError::Other(msg) => write!(f, "{msg}"), @@ -350,10 +376,8 @@ impl ThreatEntry { } } -/// Per-service asset metadata: where the version came from, and — uniquely — the -/// network exposure of the running process (which listeners it holds and whether -/// any is reachable off-host). This is what turns a flat CVE list into a -/// prioritized attack-surface report. +/// Per-asset metadata: where the version came from, and the network exposure of +/// the running process (its listeners and whether any is reachable off-host). #[derive(Debug, Serialize)] pub struct AssetInfo { pub exe: String, @@ -384,9 +408,8 @@ pub struct Meta { impl Default for Meta { fn default() -> Self { - // 3: `kev` means KEV-listed only (in-the-wild moved to `exploited`), plus - // exploitation/patch fields, `assets.*.upgradeTo` and `truncated`. - Meta { tool: "threat-finder", version: env!("CARGO_PKG_VERSION"), schema_version: 3 } + // 4: `truncated` is plan caps only; candidate caps moved to `incomplete`. + Meta { tool: "threat-finder", version: env!("CARGO_PKG_VERSION"), schema_version: 4 } } } @@ -455,9 +478,13 @@ pub struct BatchResults { /// version), name -> reason. Unlike `errors`, these never fail --fail-on. #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub rejected: BTreeMap, - /// Assets whose matches the server capped; more findings exist than reported. + /// Assets whose matches the plan's per-query result cap cut short. #[serde(skip_serializing_if = "Vec::is_empty")] pub truncated: Vec, + /// Assets Radar could not fully evaluate (candidate cap, even on a retry). + /// Like `errors`, these fail --fail-on. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub incomplete: Vec, /// Inventory-server registration outcome, present only when this run /// registered the host for monitoring (drift + new-since-last summary). #[serde(skip_serializing_if = "Option::is_none")] @@ -492,6 +519,9 @@ impl BatchResults { assets: Vec::new(), }); g.kev |= t.kev; + if t.epss > g.epss { + g.epss = t.epss; + } if severity_rank(t.severity.as_deref()) > severity_rank(g.severity.as_deref()) { g.severity = t.severity.clone(); } @@ -544,15 +574,30 @@ pub struct BatchOutcome { pub rejected: BTreeMap, /// Asset key -> Radar's `upgradeTo`. pub upgrades: BTreeMap, - /// Asset keys whose matches the server capped (plan result cap or candidate cap). + /// Asset keys whose matches the plan's result cap cut short. pub truncated: Vec, + /// Asset keys the server's candidate cap left unevaluated, even on a retry. + pub incomplete: Vec, + /// Set when the quota ran out after the batch; the outcome is partial. + pub quota: Option, +} + +/// Drop an unconfirmed finding when the same id is already confirmed for that asset. +pub fn prune_unconfirmed(confirmed: &BTreeMap>, unconfirmed: &mut BTreeMap>) { + let id = |e: &ThreatEntry| e.cve_id.clone().or_else(|| e.id.clone()); + for (key, entries) in unconfirmed.iter_mut() { + let Some(have) = confirmed.get(key) else { continue }; + let have: HashSet = have.iter().filter_map(id).collect(); + entries.retain(|e| id(e).is_none_or(|i| !have.contains(&i))); + } + unconfirmed.retain(|_, v| !v.is_empty()); } pub struct ThreatClient { client: Client, base: String, api_key: String, - rate_limit: Arc>, + rate_limit: Mutex, } impl ThreatClient { @@ -560,7 +605,7 @@ impl ThreatClient { Self::with_base(api_key, BASE_URL) } - fn with_base(api_key: &str, base: &str) -> Self { + pub(crate) fn with_base(api_key: &str, base: &str) -> Self { let client = Client::builder() .timeout(Duration::from_secs(90)) .connect_timeout(Duration::from_secs(8)) @@ -572,7 +617,7 @@ impl ThreatClient { client, base: base.to_string(), api_key: api_key.to_string(), - rate_limit: Arc::new(Mutex::new(RateLimitInfo::default())), + rate_limit: Mutex::new(RateLimitInfo::default()), } } @@ -640,14 +685,20 @@ impl ThreatClient { attempt += 1; continue; } - _ => return Err(ThreatError::RateLimitExceeded(message)), + _ => { + let checkout = str_of(body.pointer("/upgrade/urls/checkout")); + return Err(ThreatError::RateLimitExceeded(QuotaExceeded { message, checkout })); + } } } if status.as_u16() == 413 { // Not retried: the caller resizes (match/batch) or reports the cap. - let cap = response.json::().ok().and_then(|b| advertised_cap(&b)); - return Err(ThreatError::BatchTooLarge(cap)); + let body = response.json::().unwrap_or(Value::Null); + if body.get("data").is_none() && body.get("error").and_then(Value::as_str) == Some("Payload too large") { + return Err(ThreatError::PayloadTooLarge); + } + return Err(ThreatError::BatchTooLarge(advertised_cap(&body))); } // A handler 500 has already been counted against the quota; only @@ -711,12 +762,13 @@ impl ThreatClient { } /// Match a whole inventory by exact coordinate in one POST per tier-sized - /// chunk. Results are positionally aligned to `queries` (guarded per chunk). + /// chunk. Results are positionally aligned to a prefix of `queries`; a quota + /// stop keeps the chunks already matched and returns why it stopped. pub fn match_batch( &self, queries: &[MatchQuery], strict: bool, - ) -> Result, ThreatError> { + ) -> Result<(Vec, Option), ThreatError> { let mut out: Vec = Vec::with_capacity(queries.len()); let mut cursor = 0usize; // The working cap can only shrink within a run (a 413 tells us the real @@ -743,12 +795,16 @@ impl ThreatClient { out.extend(parsed.data.results); cursor = end; } - Err(ThreatError::BatchTooLarge(max_batch)) => { + Err(e @ (ThreatError::BatchTooLarge(_) | ThreatError::PayloadTooLarge)) => { // A single item can't be split further; a 413 on it is a hard // error rather than something we can retry-shrink out of. if chunk.len() <= 1 { - return Err(ThreatError::BatchTooLarge(max_batch)); + return Err(e); } + let max_batch = match e { + ThreatError::BatchTooLarge(n) => n, + _ => None, + }; // Server rejected this chunk as too large. Shrink the working // cap to the advertised max (or halve it) and retry the SAME // slice — do not advance the cursor or abort the run. Always @@ -759,10 +815,11 @@ impl ThreatClient { }; cap_ceiling = new_cap.max(1); } + Err(ThreatError::RateLimitExceeded(q)) if !out.is_empty() => return Ok((out, Some(q))), Err(e) => return Err(e), } } - Ok(out) + Ok((out, None)) } /// Register (or refresh) this host's asset inventory for continuous @@ -975,6 +1032,9 @@ pub struct RegisterSummary { pub by_severity: BTreeMap, #[serde(rename = "byDecision", default, skip_serializing_if = "BTreeMap::is_empty")] pub by_decision: BTreeMap, + /// The server's candidate cap cut this host's findings short. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub truncated: bool, } /// A finding in the registration's `newSinceLast`, as far as the CLI prints it. @@ -1041,6 +1101,9 @@ pub struct RegisterResponse { pub host_id: String, #[serde(default)] pub monitoring: bool, + /// Whether the plan alerts on monitored hosts. + #[serde(rename = "monitoringAvailable", default)] + pub monitoring_available: Option, #[serde(default)] pub new: bool, #[serde(rename = "assetCount", default)] @@ -1067,7 +1130,7 @@ fn tier_batch_cap(limit_hourly: u64) -> usize { 1500 => 4000, // enterprise 375 => 1000, // pro 25 | 45 | 75 => 200, // individual / lifetime / base - _ => 50, // free / unknown + _ => FREE_BATCH, // free / unknown } } @@ -1157,11 +1220,26 @@ pub struct MatchResult { /// The candidate or per-plan result cap cut `matches` short. #[serde(default)] pub truncated: bool, + #[serde(rename = "totalMatches", default)] + pub total_matches: Option, + /// The server's candidate cap, rather than the plan's result cap, cut it short. + #[serde(rename = "candidatesTruncated", default)] + pub candidates_truncated: Option, /// The query was rejected or could not be evaluated. #[serde(default)] pub error: Option, } +impl MatchResult { + /// Not every candidate was evaluated. Without `candidatesTruncated`, a plan + /// cap is the only cap that leaves `totalMatches` above what was returned. + pub fn candidate_capped(&self) -> bool { + self.candidates_truncated.unwrap_or_else(|| { + self.truncated && self.total_matches.is_some_and(|t| t <= self.matches.len()) + }) + } +} + /// Tolerant EPSS model: the server sends `epss` as an object `{score, percentile}` /// (the common case), but defensively we also accept a bare number or null/absent. /// A wrong-typed *present* value here would otherwise fail the whole-chunk decode. @@ -1171,8 +1249,6 @@ enum EpssField { Object { #[serde(default)] score: Option, - #[serde(default)] - percentile: Option, }, Score(f64), Null, @@ -1181,17 +1257,11 @@ enum EpssField { impl EpssField { fn score(&self) -> Option { match self { - EpssField::Object { score, .. } => *score, + EpssField::Object { score } => *score, EpssField::Score(s) => Some(*s), EpssField::Null => None, } } - fn percentile(&self) -> Option { - match self { - EpssField::Object { percentile, .. } => *percentile, - _ => None, - } - } } /// One CVE match, as `formatHit` in server/services/packageMatchService.js. @@ -1232,16 +1302,12 @@ impl MatchHit { pub fn epss(&self) -> Option { self.epss.as_ref().and_then(EpssField::score) } - /// EPSS percentile, present only in the object shape. - pub fn epss_percentile(&self) -> Option { - self.epss.as_ref().and_then(EpssField::percentile) - } } // ── Scan API (SBOM / lockfile) ─────────────────────────────────────────────── -/// The server's `express.json` body limit (10 MB). -pub const MAX_SCAN_BODY: usize = 10 * 1024 * 1024; +/// The server's `express.json` body limit for `/api/v1/scan` (16 MiB). +pub const MAX_SCAN_BODY: usize = 16 * 1024 * 1024; /// `MAX_LINE` in server/utils/sbom: longer lines are rejected unless the file is JSON. pub const MAX_SCAN_LINE: usize = 4096; @@ -1286,6 +1352,8 @@ pub struct ScanReport { remediation: Vec, #[serde(rename = "notChecked", default)] not_checked: Vec, + #[serde(default)] + truncated: Vec, } #[derive(Debug, Default, Deserialize)] @@ -1338,7 +1406,7 @@ impl ScanFinding { kev_overdue: self.kev && kev_due_date.as_deref().is_some_and(is_past), kev_due_date, ransomware: self.ransomware, - exploited: self.exploited, + exploited: self.exploited || self.kev, exploit_maturity: self.exploit_maturity, confirmed: self.confirmed, matched_range: self.matched_range, @@ -1362,28 +1430,39 @@ impl ScanReport { pub fn into_results(self, source: &str, severity_floor: u8) -> BatchResults { let mut services: BTreeMap> = BTreeMap::new(); let mut unconfirmed: BTreeMap> = BTreeMap::new(); + let asset = |purl: &str, version: Option, upgrade_to: Option| AssetInfo { + exe: source.to_string(), + version: version.unwrap_or_else(|| purl_version(purl).to_string()), + version_source: self.format.clone(), + exposed: false, + reachability: "none".to_string(), + listeners: Vec::new(), + upgrade_to, + restart_pending: false, + }; + let mut assets: BTreeMap = self.remediation.into_iter() + .map(|r| (r.purl.clone(), asset(&r.purl, r.version, r.upgrade_to))) + .collect(); for f in self.findings { + if !assets.contains_key(&f.purl) { + assets.insert(f.purl.clone(), asset(&f.purl, None, None)); + } let key = f.purl.clone(); let e = f.into_entry(); - // KEV is never dropped by the severity floor, as in scan::run_scan. - if !e.kev && severity_rank(e.severity.as_deref()) < severity_floor { + // Exploited findings are never dropped by the severity floor, as in scan::run_scan. + if !e.exploited && severity_rank(e.severity.as_deref()) < severity_floor { continue; } let bucket = if e.confirmed { &mut services } else { &mut unconfirmed }; bucket.entry(key).or_default().push(e); } - let assets = self.remediation.into_iter() - .map(|r| (r.purl, AssetInfo { - exe: source.to_string(), - version: r.version.unwrap_or_default(), - version_source: self.format.clone(), - exposed: false, - reachability: "none".to_string(), - listeners: Vec::new(), - upgrade_to: r.upgrade_to, - restart_pending: false, - })) - .collect(); + prune_unconfirmed(&services, &mut unconfirmed); + + let (incomplete, truncated): (Vec, Vec) = + self.truncated.into_iter().partition(|t| t.reason == "candidate-cap"); + let mut incomplete: Vec = incomplete.into_iter().map(|t| t.purl).collect(); + incomplete.sort(); + incomplete.dedup(); BatchResults { meta: Meta::default(), services, @@ -1392,12 +1471,19 @@ impl ScanReport { assets, errors: BTreeMap::new(), rejected: self.not_checked.into_iter().map(|n| (n.purl, n.reason)).collect(), - truncated: Vec::new(), + truncated: truncated.into_iter().map(|t| t.purl).collect(), + incomplete, registration: None, } } } +/// The version of `pkg:type/name@version?qualifiers#subpath`. +fn purl_version(purl: &str) -> &str { + let base = purl.split(['?', '#']).next().unwrap_or_default(); + base.rsplit_once('@').map_or("", |(_, v)| v) +} + fn truthy(v: Option<&Value>) -> bool { matches!(v, Some(Value::Bool(true))) || v.and_then(|x| x.as_str()) == Some("true") } @@ -1562,6 +1648,44 @@ fn clean_date(value: Option<&Value>) -> String { } } +/// Loopback HTTP server answering one request per canned response, in order; +/// the handle yields the raw requests. +#[cfg(test)] +pub(crate) fn serve(responses: Vec) -> (ThreatClient, std::thread::JoinHandle>) { + use std::io::{Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let client = ThreatClient::with_base("k", &format!("http://{}", listener.local_addr().unwrap())); + let handle = std::thread::spawn(move || { + responses.into_iter().map(|response| { + let (mut sock, _) = listener.accept().unwrap(); + let (mut req, mut buf) = (Vec::new(), [0u8; 4096]); + let complete = |req: &[u8]| { + let Some(end) = req.windows(4).position(|w| w == b"\r\n\r\n") else { return false }; + let head = String::from_utf8_lossy(&req[..end]).to_ascii_lowercase(); + let len = head.lines() + .find_map(|l| l.strip_prefix("content-length:")) + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0); + req.len() >= end + 4 + len + }; + while !complete(&req) { + let n = sock.read(&mut buf).unwrap(); + if n == 0 { break; } + req.extend_from_slice(&buf[..n]); + } + sock.write_all(response.as_bytes()).unwrap(); + String::from_utf8_lossy(&req).into_owned() + }).collect() + }); + (client, handle) +} + +/// A JSON response with this status and body. +#[cfg(test)] +pub(crate) fn http(status: u16, body: &str) -> String { + format!("HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()) +} + #[cfg(test)] mod tests { use super::*; @@ -1641,8 +1765,7 @@ mod tests { assert!(e.exploited && !e.kev, "in-the-wild is exploited, not KEV"); } - /// A realistic server hit where `epss` and `kev` are OBJECTS (the common live - /// shape). Before the fix this failed the WHOLE-chunk decode. + /// A realistic server hit where `epss` and `kev` are objects (the live shape). fn realistic_hit() -> Value { json!({ "id": "abc", "cveId": "CVE-2024-1", "title": "t", "slug": "cve-2024-1", @@ -1670,7 +1793,6 @@ mod tests { let hit = resp.data.results.into_iter().next().unwrap() .matches.into_iter().next().unwrap(); assert_eq!(hit.epss(), Some(0.42)); - assert_eq!(hit.epss_percentile(), Some(0.97)); assert!(hit.kev.is_some(), "object kev present"); assert!(hit.confirmed); assert_eq!(hit.match_basis.as_deref(), Some("coordinate")); @@ -1694,7 +1816,6 @@ mod tests { }); let hit: MatchHit = serde_json::from_value(raw).unwrap(); assert_eq!(hit.epss(), None); - assert_eq!(hit.epss_percentile(), None); assert!(hit.kev.is_none(), "null kev => not listed"); let e = match_to_entry(hit); assert_eq!(e.epss, None); @@ -1716,7 +1837,6 @@ mod tests { let raw = json!({ "cveId": "CVE-2024-4", "epss": 0.5, "kev": true }); let hit: MatchHit = serde_json::from_value(raw).unwrap(); assert_eq!(hit.epss(), Some(0.5)); - assert_eq!(hit.epss_percentile(), None); assert!(match_to_entry(hit).kev, "bool kev => as-is"); } @@ -2109,13 +2229,14 @@ mod tests { } #[test] - fn scan_severity_floor_keeps_kev() { + fn scan_severity_floor_keeps_exploited() { let report: ScanReport = serde_json::from_value(json!({ "findings": [ { "purl": "pkg:npm/a@1", "severity": "low", "kev": true, "confirmed": true }, { "purl": "pkg:npm/b@1", "severity": "low", "kev": false, "confirmed": true }, + { "purl": "pkg:npm/c@1", "severity": "low", "exploited": true, "confirmed": true }, ] })).unwrap(); let r = report.into_results("f", severity_rank(Some("high"))); - assert_eq!(r.services.keys().collect::>(), ["pkg:npm/a@1"]); + assert_eq!(r.services.keys().collect::>(), ["pkg:npm/a@1", "pkg:npm/c@1"]); } #[test] @@ -2171,7 +2292,7 @@ mod tests { ("openssl@3.0.2".to_string(), vec![entry("CVE-2024-1")]), ]), by_cve: BTreeMap::new(), assets: BTreeMap::new(), unconfirmed: BTreeMap::new(), - errors: BTreeMap::new(), rejected: BTreeMap::new(), truncated: vec![], registration: None, + errors: BTreeMap::new(), rejected: BTreeMap::new(), truncated: vec![], incomplete: vec![], registration: None, }; let coords = BTreeMap::from([ ("nginx@1.24.0".to_string(), "pkg:deb/ubuntu/nginx@1.24.0".to_string()), @@ -2207,34 +2328,15 @@ mod tests { assert_eq!(f.radar_url.as_deref(), Some("https://radar.offseq.com/threat/x")); } - /// Serve one canned HTTP response on loopback; the handle yields the raw request. - fn serve_once(response: String) -> (ThreatClient, std::thread::JoinHandle) { - use std::io::{Read, Write}; - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let client = ThreatClient::with_base("k", &format!("http://{}", listener.local_addr().unwrap())); - let handle = std::thread::spawn(move || { - let (mut sock, _) = listener.accept().unwrap(); - let (mut req, mut buf) = (Vec::new(), [0u8; 4096]); - while !req.windows(4).any(|w| w == b"\r\n\r\n") { - let n = sock.read(&mut buf).unwrap(); - if n == 0 { break; } - req.extend_from_slice(&buf[..n]); - } - sock.write_all(response.as_bytes()).unwrap(); - String::from_utf8_lossy(&req).into_owned() - }); - (client, handle) - } - #[test] fn host_vex_returns_the_raw_document() { - let (client, server) = serve_once( + let (client, server) = serve(vec![ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 27\r\n\ X-RateLimit-Limit-Hourly: 375\r\nConnection: close\r\n\r\n{\n \"@context\": \"openvex\"\n}".to_string(), - ); + ]); let doc = client.host_vex("h-1", "cyclonedx").unwrap(); assert_eq!(doc, b"{\n \"@context\": \"openvex\"\n}"); - let req = server.join().unwrap(); + let req = server.join().unwrap().remove(0); assert!(req.starts_with("GET /inventory/h-1/vex?format=cyclonedx "), "{req}"); assert!(req.to_ascii_lowercase().contains("accept: */*"), "{req}"); assert_eq!(client.last_rate_limit().limit_hourly, 375); @@ -2243,10 +2345,7 @@ mod tests { #[test] fn host_vex_on_free_plan_is_access_denied() { let body = r#"{"success":false,"error":"pro_access_required","message":"The decision ledger needs a paid plan (Individual and up)."}"#; - let (client, server) = serve_once(format!( - "HTTP/1.1 403 Forbidden\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - )); + let (client, server) = serve(vec![http(403, body)]); match client.host_vex("h-1", "openvex") { Err(ThreatError::AccessDenied(msg)) => assert!(msg.contains("paid plan"), "{msg}"), other => panic!("expected AccessDenied, got {other:?}"), @@ -2267,4 +2366,109 @@ mod tests { assert_eq!(e.cwes, vec!["CWE-125".to_string()]); assert_eq!(e.remediation.as_deref(), Some("Upgrade OpenSSL.")); } + + #[test] + fn candidate_cap_is_told_apart_from_plan_cap() { + let r = |v: Value| serde_json::from_value::(v).unwrap(); + let hit = json!({ "cveId": "CVE-1" }); + assert!(r(json!({ "truncated": true, "candidatesTruncated": true, "totalMatches": 40, "matches": [hit] })).candidate_capped()); + assert!(!r(json!({ "truncated": true, "candidatesTruncated": false, "totalMatches": 1, "matches": [hit] })).candidate_capped()); + assert!(r(json!({ "truncated": true, "totalMatches": 1, "matches": [hit] })).candidate_capped()); + assert!(!r(json!({ "truncated": true, "totalMatches": 40, "matches": [hit] })).candidate_capped()); + assert!(!r(json!({ "truncated": false, "totalMatches": 0, "matches": [] })).candidate_capped()); + } + + #[test] + fn body_size_413_is_not_a_plan_cap_and_still_halves() { + let too_large = http(413, r#"{"success":false,"error":"Payload too large","message":"Request body exceeds the maximum allowed size."}"#); + let one = http(200, r#"{"data":{"results":[{"matches":[]}]}}"#); + let (client, server) = serve(vec![too_large.clone(), one.clone(), one]); + let q = [MatchQuery::purl("pkg:npm/a@1"), MatchQuery::purl("pkg:npm/b@1")]; + assert_eq!(client.match_batch(&q, false).unwrap().0.len(), 2); + assert_eq!(server.join().unwrap().len(), 3); + + let (client, server) = serve(vec![too_large]); + assert!(matches!(client.scan(b"{}".to_vec()), Err(ThreatError::PayloadTooLarge))); + server.join().unwrap(); + } + + #[test] + fn quota_429_carries_the_checkout_link() { + let body = r#"{"message":"Daily quota reached.","upgrade":{"reason":"api-day","urls":{"checkout":"https://radar.offseq.com/checkout?plan=base&interval=month"}}}"#; + let (client, server) = serve(vec![http(429, body)]); + match client.search_threats("x") { + Err(ThreatError::RateLimitExceeded(q)) => { + assert_eq!(q.message, "Daily quota reached."); + assert_eq!(q.checkout.as_deref(), Some("https://radar.offseq.com/checkout?plan=base&interval=month")); + } + other => panic!("expected RateLimitExceeded, got {other:?}"), + } + server.join().unwrap(); + } + + #[test] + fn plan_info_shows_resets_and_skips_unknown_windows() { + let info = RateLimitInfo { + limit_hourly: 75, remaining_hourly: 70, reset_hourly: 1_700_003_600, ..Default::default() + }; + let out = plan_info(&info).unwrap(); + assert!(out.contains("Hourly: 70 / 75 remaining, resets 23:13 UTC"), "{out}"); + assert!(!out.contains("Daily") && !out.contains("Monthly"), "{out}"); + } + + #[test] + fn scan_report_locates_every_finding_and_reads_caps() { + let report: ScanReport = serde_json::from_value(json!({ + "format": "cyclonedx-json", + "findings": [ + { "purl": "pkg:npm/a@1.2.3?x=y", "cveId": "CVE-1", "severity": "high", "confirmed": true }, + { "purl": "pkg:npm/a@1.2.3?x=y", "cveId": "CVE-1", "severity": "high", "confirmed": false }, + { "purl": "pkg:npm/a@1.2.3?x=y", "cveId": "CVE-2", "severity": "high", "confirmed": false } + ], + "truncated": [ + { "purl": "pkg:npm/b@1", "reason": "candidate-cap" }, + { "purl": "pkg:npm/c@1", "reason": "plan-cap" } + ], + "gate": { "failOn": "high", "tripped": true, "incomplete": true } + })).unwrap(); + let r = report.into_results("bom.json", 0); + assert_eq!(r.assets["pkg:npm/a@1.2.3?x=y"].version, "1.2.3"); + assert_eq!(r.assets["pkg:npm/a@1.2.3?x=y"].exe, "bom.json"); + let ids: Vec<_> = r.unconfirmed["pkg:npm/a@1.2.3?x=y"].iter().map(|e| e.cve_id.as_deref()).collect(); + assert_eq!(ids, [Some("CVE-2")], "confirmed CVE-1 drops its unconfirmed copy"); + assert_eq!(r.truncated, ["pkg:npm/c@1"]); + assert_eq!(r.incomplete, ["pkg:npm/b@1"]); + + let bare: ScanReport = serde_json::from_value(json!({ "findings": [] })).unwrap(); + let r = bare.into_results("f", 0); + assert!(r.truncated.is_empty() && r.incomplete.is_empty()); + } + + #[test] + fn register_response_reads_monitoring_available_and_truncation() { + let r: RegisterResponse = serde_json::from_value(json!({ + "monitoringAvailable": false, "summary": { "total": 1, "truncated": true } + })).unwrap(); + assert_eq!(r.monitoring_available, Some(false)); + assert!(r.summary.truncated); + let r: RegisterResponse = serde_json::from_value(json!({})).unwrap(); + assert_eq!(r.monitoring_available, None); + } + + #[test] + fn cve_groups_take_the_highest_epss() { + let e = |epss: Option| ThreatEntry { cve_id: Some("CVE-1".into()), epss, confirmed: true, ..Default::default() }; + let mut r = BatchResults { + meta: Meta::default(), + services: BTreeMap::from([ + ("a@1".to_string(), vec![e(None)]), + ("b@1".to_string(), vec![e(Some(0.7))]), + ("c@1".to_string(), vec![e(Some(0.2))]), + ]), + by_cve: BTreeMap::new(), assets: BTreeMap::new(), unconfirmed: BTreeMap::new(), + errors: BTreeMap::new(), rejected: BTreeMap::new(), truncated: vec![], incomplete: vec![], registration: None, + }; + r.compute_cve_groups(); + assert_eq!(r.by_cve["CVE-1"].epss, Some(0.7)); + } } diff --git a/src/auth.rs b/src/auth.rs index 5186e07..75703a3 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -49,29 +49,43 @@ const ENV_KEY: &str = "OFFSEQ_API_KEY"; /// of the OS's per-user directory resolution. const CONFIG_DIR_ENV: &str = "OFFSEQ_CONFIG_DIR"; +const MALFORMED: &str = "malformed API key (expected tr_ followed by 64 hex characters)"; + +/// Radar's key format, `^tr_[0-9a-f]{64}$`. +pub fn is_key_format(key: &str) -> bool { + key.strip_prefix("tr_") + .is_some_and(|h| h.len() == 64 && h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))) +} + /// Resolve an API key from, in order: the OFFSEQ_API_KEY env var, the saved /// config (unless `reset`), then interactive setup (only if `interactive`). -/// Returns None when no key can be obtained without prompting. -pub fn resolve_api_key(reset: bool, interactive: bool) -> Option { +/// Errs, before any request is made, when no well-formed key is available. +pub fn resolve_api_key(reset: bool, interactive: bool) -> Result { if let Ok(k) = std::env::var(ENV_KEY) { let k = k.trim().to_string(); if !k.is_empty() { - return Some(k); + return if is_key_format(&k) { Ok(k) } else { Err(format!("{ENV_KEY}: {MALFORMED}")) }; } } if !reset { if let Some(k) = saved_api_key() { - return Some(k); + return if is_key_format(&k) { + Ok(k) + } else { + Err(format!("{}: {MALFORMED}; re-run with --reset to re-enter it", config_path().display())) + }; } } if interactive { run_initial_setup(); - return saved_api_key(); + if let Some(k) = saved_api_key() { + return Ok(k); + } } - None + Err("No API key available. Set OFFSEQ_API_KEY, or run interactively to enter one.".to_string()) } fn saved_api_key() -> Option { @@ -239,8 +253,8 @@ fn prompt_for_key() -> Option { continue; } - if key.len() < 48 { - println!("That doesn't look like a valid API key (too short). Please try again."); + if !is_key_format(&key) { + println!("That is a {MALFORMED}. Please try again."); continue; } @@ -252,14 +266,15 @@ fn prompt_for_key() -> Option { /// the server's own message — it distinguishes an hourly burst from a daily or /// monthly quota and carries the reset time, so we surface it verbatim above the /// generic upgrade line rather than guessing. +/// `checkout` is the server's direct upgrade link, when it sent one. /// Printed to stderr so it can't corrupt JSON written to stdout. -pub fn prompt_upgrade(detail: Option<&str>) { +pub fn prompt_upgrade(detail: Option<&str>, checkout: Option<&str>) { eprintln!("\n┌─────────────────────────────────────────────┐"); eprintln!("│ Rate Limit Reached │"); eprintln!("└─────────────────────────────────────────────┘\n"); eprintln!("{}\n", upgrade_body_line(detail)); eprintln!("Upgrade your plan for higher limits:"); - eprintln!(" https://radar.offseq.com/console?tab=billing\n"); + eprintln!(" {}\n", checkout.unwrap_or("https://radar.offseq.com/console?tab=billing")); eprintln!("Compare plans: https://radar.offseq.com/pricing\n"); } @@ -441,6 +456,42 @@ mod tests { assert_eq!(fs::read_to_string(&path).unwrap(), corrupt, "config left untouched"); } + #[test] + fn key_format_matches_the_server() { + let hex = "0123456789abcdef".repeat(4); + assert!(is_key_format(&format!("tr_{hex}"))); + assert!(!is_key_format(&format!("tr_{}", hex.to_uppercase()))); + assert!(!is_key_format(&format!("tr_{}", &hex[1..]))); + assert!(!is_key_format(&format!("tr_{hex}0"))); + assert!(!is_key_format(&format!("tk_{hex}"))); + assert!(!is_key_format("")); + } + + #[test] + fn malformed_keys_are_rejected_before_use() { + let _g = ENV_LOCK.lock().unwrap(); + let _tmp = TempConfigHome::new(); + let prev = std::env::var_os(ENV_KEY); + let good = format!("tr_{}", "ab".repeat(32)); + + std::env::set_var(ENV_KEY, "not-a-key"); + assert!(resolve_api_key(false, false).unwrap_err().contains("malformed API key")); + std::env::set_var(ENV_KEY, format!(" {good}\n")); + assert_eq!(resolve_api_key(false, false), Ok(good.clone())); + + std::env::remove_var(ENV_KEY); + assert!(resolve_api_key(false, false).unwrap_err().starts_with("No API key")); + update_config(|c| c.api_key = "short".into()).unwrap(); + assert!(resolve_api_key(false, false).unwrap_err().contains("--reset")); + update_config(|c| c.api_key = good.clone()).unwrap(); + assert_eq!(resolve_api_key(false, false), Ok(good)); + + match prev { + Some(v) => std::env::set_var(ENV_KEY, v), + None => std::env::remove_var(ENV_KEY), + } + } + #[test] fn saved_api_key_is_trimmed() { let _g = ENV_LOCK.lock().unwrap(); diff --git a/src/cpe.rs b/src/cpe.rs index fa9c54d..d2d78f6 100644 --- a/src/cpe.rs +++ b/src/cpe.rs @@ -10,6 +10,10 @@ //! when there's no confident mapping. A wrong CPE produces wrong CVE //! attributions, which is worse than a gap the caller fills with `?search=`. +use std::sync::LazyLock; + +use regex::Regex; + use crate::engine::WinOs; /// Build an application CPE from an already-cleaned display name + version. @@ -127,26 +131,33 @@ pub fn escape_cpe(value: &str) -> String { out } -/// Strip version / architecture / locale / edition / marketing noise from a raw -/// registry or winget DisplayName, leaving a stable product phrase to look up -/// (and to use as the `?search=` term when unmapped). Conservative: only trims -/// trailing noise tokens, never interior words, so "7-Zip 23.01 (x64)" → "7-Zip" -/// but "Visual Studio Code" is untouched. -pub fn clean_app_name(raw: &str) -> String { - // Drop any parenthesised suffix: "(x64)", "(64-bit)", "(en-US)", "(KB...)". - let mut s = raw.trim(); - if let Some(idx) = s.find('(') { - s = s[..idx].trim(); - } +static TRADEMARKS: LazyLock = LazyLock::new(|| Regex::new(r"(?i)\((?:r|tm)\)|[®™]").unwrap()); - let tokens: Vec<&str> = s.split_whitespace().collect(); - // Trim trailing noise tokens (version-like, arch, locale, edition words). - let mut end = tokens.len(); - while end > 0 && is_trailing_noise(tokens[end - 1]) { - end -= 1; +/// Strip trademark marks and trailing version / architecture / locale noise from +/// a raw registry or winget DisplayName, leaving a stable product phrase to look +/// up (and to use as the `?search=` term when unmapped). Conservative: only +/// trailing tokens and parenthesised groups go, so "7-Zip 23.01 (x64)" → "7-Zip" +/// and "Intel(R) Management Engine" → "Intel Management Engine". +pub fn clean_app_name(raw: &str) -> String { + let unmarked = TRADEMARKS.replace_all(raw, ""); + let mut s = unmarked.trim(); + loop { + let before = s.len(); + // "(x64)", "(64-bit)", "(en-US)", "(KB...)" + if let Some(i) = s.strip_suffix(')').and_then(|h| h.rfind('(')) { + s = s[..i].trim_end(); + } + while let Some((head, last)) = s.rsplit_once(char::is_whitespace) { + if !is_trailing_noise(last) { + break; + } + s = head.trim_end(); + } + if s.len() == before { + break; + } } - let kept = if end == 0 { &tokens[..] } else { &tokens[..end] }; - kept.join(" ").trim().to_string() + s.split_whitespace().collect::>().join(" ") } fn is_trailing_noise(tok: &str) -> bool { @@ -274,6 +285,17 @@ mod tests { assert_eq!(clean_app_name("Mozilla Firefox Update"), "Mozilla Firefox Update"); } + #[test] + fn cleans_trademarks_and_only_trailing_groups() { + assert_eq!(clean_app_name("Intel(R) Management Engine Components 2406.5.5.0"), "Intel Management Engine Components"); + assert_eq!(clean_app_name("Intel® Graphics Driver"), "Intel Graphics Driver"); + assert_eq!(clean_app_name("Microsoft Office(TM) 2019 (x64)"), "Microsoft Office"); + assert_eq!(clean_app_name("NVIDIA™ Control Panel (tm)"), "NVIDIA Control Panel"); + assert_eq!(clean_app_name("Foo (Beta) Tool"), "Foo (Beta) Tool"); + assert_eq!(clean_app_name("Foo 1.2 (x64) (en-US)"), "Foo"); + assert_eq!(clean_app_name("x64"), "x64"); + } + #[test] fn app_cpe_from_alias() { assert_eq!( diff --git a/src/engine.rs b/src/engine.rs index eea1d13..cf81dea 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -454,7 +454,6 @@ pub fn parse_linux_distro_version(distro: &LinuxDistro) -> (String, String) { (name.to_string(), os_release_field("VERSION_ID").unwrap_or_default()) } - pub const SYSTEMD_ONE_SHOTS: &[&str] = &[ "systemd-journal-flush", "systemd-tmpfiles-setup", "systemd-tmpfiles-setup-dev", "systemd-tmpfiles-setup-dev-early", @@ -507,16 +506,9 @@ pub fn resolve_binary(name: &str) -> Option { None } -// "name-1.2.3-r0" / "nginx-1.26.2nb1" -> "1.2.3" / "1.26.2" -pub static ATOM_VER_RE: Lazy = +static ATOM_VER_RE: Lazy = Lazy::new(|| Regex::new(r"-(\d[0-9A-Za-z.+~]*)").unwrap()); -pub fn atom_version(atom: &str) -> Option { - ATOM_VER_RE.captures(atom.trim()).map(|c| c[1].to_string()) -} - -/// Ask the OS package database for the version that owns `exe`. Returns None when -/// no package owns it (e.g. a base-system binary) so the caller can fall back. /// Resolve the owning package's (name, full-version) for a binary, querying the /// OS package database. The package NAME is the real coordinate (e.g. a unit /// "ssh" resolves to "openssh-server"), so the purl is built from the true @@ -638,10 +630,6 @@ pub fn apk_of(path: &str) -> Option<(String, String)> { atom_split(out.split("owned by ").nth(1)?.trim()) } -pub fn homebrew_version(path: &str) -> Option { - homebrew_of(path).map(|(_, v)| v) -} - pub fn homebrew_of(path: &str) -> Option<(String, String)> { // canonicalized brew binaries live at .../Cellar///... let idx = path.find("/Cellar/")?; @@ -658,15 +646,23 @@ pub fn freebsd_of(path: &str) -> Option<(String, String)> { } pub fn pkg_info_of(path: &str, file_flag: bool) -> Option<(String, String)> { - // OpenBSD: pkg_info -E -> "nginx-1.26.2: /usr/local/sbin/nginx" - // NetBSD : pkg_info -Fe -> "nginx-1.26.2nb1" - let out = if file_flag { - run_cmd("pkg_info", &["-Fe", path])? + if file_flag { + // NetBSD: pkg_info -Fe -> "nginx-1.26.2nb1" + atom_split(run_cmd("pkg_info", &["-Fe", path])?.split_whitespace().next()?) } else { - run_cmd("pkg_info", &["-E", path])? - }; - let atom = out.split(':').next().unwrap_or(&out).split_whitespace().next()?; - atom_split(atom) + atom_split(openbsd_owner(&run_cmd("pkg_info", &["-E", path])?)?) + } +} + +/// The owning package from OpenBSD `pkg_info -E `, which prints +/// ": [,…]" followed by the package's description. +pub fn openbsd_owner(out: &str) -> Option<&str> { + out.lines() + .filter(|l| l.starts_with('/')) + .find_map(|l| l.rsplit_once(": ")) + .and_then(|(_, pkgs)| pkgs.split(',').next()) + .map(str::trim) + .filter(|p| !p.is_empty()) } /// Resolve (owning-package-name, version, source) for a binary: package DB @@ -704,14 +700,21 @@ fn exe_replaced(pid: u32) -> bool { /// Build a ServiceInfo from a service name by resolving its binary and version. pub fn service_from_name(display_name: &str, os: &OsType) -> Option { let exe = resolve_binary(display_name)?; - make_service(display_name, &exe, None, os) + make_service(display_name, &exe, running_pid(&exe), os) +} + +/// The oldest process running `exe`: by process name, then by command line. +fn running_pid(exe: &str) -> Option { + run_cmd("pgrep", &["-o", "-x", &binary_basename(exe)]) + .and_then(|o| first_pid(&o)) + .or_else(|| run_cmd("pgrep", &["-o", "-f", ®ex::escape(exe)]).and_then(|o| first_pid(&o))) +} + +pub fn first_pid(out: &str) -> Option { + out.split_whitespace().find_map(|t| t.parse().ok()) } // Network-exposure correlation -// -// Mapping each running service to the sockets it is LISTENING on — and whether -// any is reachable off-host — is the tool's signature capability: manifest -// scanners can't see runtime state, and external scanners need a second host. pub fn listening_endpoints(pid: u32) -> Vec { let mut eps = if cfg!(target_os = "linux") { @@ -758,10 +761,7 @@ pub fn parse_port_range(s: &str) -> Option> { (lo <= hi).then_some(lo..=hi) } -/// Listening endpoints via `lsof` (macOS/BSD/Solaris). Uses field output (`-Fn`) -/// so the address is a clean `n`-prefixed line — the human format suffixes each -/// row with "(LISTEN)", which the old `.last()` parser picked up instead of the -/// address, leaving exposure silently dead on every non-Linux platform. +/// Listening endpoints via `lsof -Fn` field output (macOS/BSD/Solaris). pub fn lsof_listeners(pid: u32) -> Vec { let mut out = Vec::new(); for ep in lsof_names(pid, &["-iTCP", "-sTCP:LISTEN"]) { @@ -813,10 +813,6 @@ pub fn linux_listeners(pid: u32) -> Vec { } let mut out = Vec::new(); - // Stream each /proc/net table line-by-line (BufReader) rather than slurping - // the whole file — peak memory is one line, not the full table, which can be - // large on hosts with many connections. - // TCP: state 0A = LISTEN. for (path, v6) in [("/proc/net/tcp", false), ("/proc/net/tcp6", true)] { let Ok(file) = fs::File::open(path) else { continue }; @@ -1054,8 +1050,6 @@ fn kill_tree(child: &mut std::process::Child) { let _ = child.wait(); } -// Extract a clean version token from raw `--version` output. - pub fn extract_version(text: &str) -> Option { const BAD: &[&str] = &[ "invalid", "unknown option", "usage:", "error:", @@ -1103,7 +1097,8 @@ pub const TIMEOUT: Duration = Duration::from_secs(2); pub fn probe_version(exe: &str) -> Option { let bin_name = exe.rsplit('/').next().unwrap_or(exe); - for flag in &["--version", "-V", "-v", "version"] { + // `-v` and a bare `version` start some daemons instead of printing a version. + for flag in &["--version", "-V"] { let Some((success, stdout, stderr)) = run_timed(exe, flag, TIMEOUT) else { continue }; let candidate = if success { @@ -1184,9 +1179,6 @@ pub fn macos_relevant_path(exe: &str) -> bool { pub fn scan_launchctl(os: &OsType) -> Vec { // `launchctl list` columns: PID Status Label. A numeric PID means running. - // Resolve the running process's absolute binary via `ps -o comm=` (the old - // code fed the reverse-DNS Label straight into Command::new, which never - // resolved a binary, so the macOS list was always empty). let output = run_cmd("launchctl", &["list"]).unwrap_or_default(); parse_launchctl_running(&output) @@ -1247,9 +1239,7 @@ pub fn friendly_label(label: &str) -> Option { } pub fn scan_bsd_rc(os: &OsType) -> Vec { - // `service -e` prints absolute rc.d script PATHS; the old code intersected - // those against the bare names from `service -l`, yielding the empty set. - // Take the basename of each enabled script instead. + // `service -e` prints the enabled rc.d scripts' paths. let enabled: Vec = run_cmd("service", &["-e"]) .unwrap_or_default() .lines() @@ -1271,8 +1261,6 @@ pub fn scan_bsd_rc(os: &OsType) -> Vec { } pub fn scan_openbsd(os: &OsType) -> Vec { - // `rcctl ls started` = currently running (the old `rcctl ls on` listed - // merely *enabled* services, including stopped ones). let names: Vec = run_cmd("rcctl", &["ls", "started"]) .unwrap_or_default() .lines().map(|l| l.trim().to_string()) @@ -1319,8 +1307,23 @@ pub fn parse_svcs_online(output: &str) -> Vec { .collect() } +/// (pid, command) of each process `svcs -H -p ` lists under the service +/// line ("STIME PID CMD"). +pub fn parse_svcs_procs(output: &str) -> Vec<(u32, String)> { + output.lines() + .filter_map(|l| { + let mut it = l.split_whitespace(); + let _stime = it.next()?; + let pid = it.next()?.parse().ok()?; + Some((pid, it.next()?.to_string())) + }) + .collect() +} + +/// SMF method scripts are shell scripts that start the daemon, never the daemon. +const SMF_METHOD_DIR: &str = "/lib/svc/method/"; + pub fn scan_smf(os: &OsType) -> Vec { - // svcs -H -o state,fmri (machine-readable, no header) let output = run_cmd("svcs", &["-H", "-o", "state,fmri"]).unwrap_or_default(); if output.is_empty() { eprintln!("[!] `svcs` returned nothing; SMF may be unavailable"); @@ -1329,21 +1332,20 @@ pub fn scan_smf(os: &OsType) -> Vec { parse_svcs_online(&output) .into_par_iter() .filter_map(|fmri| { - // svcprop start/exec gives the start method command line. - let exec = run_cmd("svcprop", &["-p", "start/exec", &fmri]) - .or_else(|| run_cmd("svcprop", &["-p", "method/exec", &fmri]))?; - // First absolute-path token is the binary. - let exe = exec.split_whitespace() - .find(|t| t.starts_with('/')) - .map(|s| s.to_string()) - .or_else(|| resolve_binary(exec.split_whitespace().next().unwrap_or("")))?; + let procs = run_cmd("svcs", &["-H", "-p", &fmri])?; + let (pid, exe) = parse_svcs_procs(&procs).into_iter().find_map(|(pid, cmd)| { + let exe = fs::read_link(format!("/proc/{pid}/path/a.out")).ok() + .map(|p| p.to_string_lossy().into_owned()) + .or_else(|| resolve_binary(&cmd))?; + (!exe.starts_with(SMF_METHOD_DIR)).then_some((pid, exe)) + })?; let display = fmri.trim_start_matches("svc:/") .split(':').next().unwrap_or(&fmri) .rsplit('/').next().unwrap_or(&fmri) .to_string(); - make_service(&display, &exe, None, os) + make_service(&display, &exe, Some(pid), os) }) .collect() } @@ -1435,20 +1437,26 @@ mod tests { use std::path::Path; use std::time::Duration; - #[test] - fn atom_version_extraction() { - assert_eq!(atom_version("nginx-1.26.2-r0").as_deref(), Some("1.26.2")); - assert_eq!(atom_version("nginx-1.26.2nb1").as_deref(), Some("1.26.2nb1")); - assert_eq!(atom_version("openssl-3.0.7").as_deref(), Some("3.0.7")); - assert_eq!(atom_version("no-version-here"), None); - } - #[test] fn homebrew_version_from_cellar_path() { let p = "/opt/homebrew/Cellar/nginx/1.27.0/bin/nginx"; - assert_eq!(homebrew_version(p).as_deref(), Some("1.27.0")); + assert_eq!(homebrew_of(p), Some(("nginx".into(), "1.27.0".into()))); assert_eq!(homebrew_formula(p), None); // needs a real canonicalize - assert_eq!(homebrew_version("/usr/sbin/sshd"), None); + assert_eq!(homebrew_of("/usr/sbin/sshd"), None); + } + + #[test] + fn openbsd_pkg_info_e_owner() { + let out = "/usr/local/sbin/nginx: nginx-1.26.2p0\nInformation for inst:nginx-1.26.2p0\n\nComment:\nrobust and small HTTP server\n"; + assert_eq!(openbsd_owner(out), Some("nginx-1.26.2p0")); + assert_eq!(openbsd_owner("/usr/local/lib/libx.so.1.0: a-1.0,b-2.0\n"), Some("a-1.0")); + assert_eq!(openbsd_owner(""), None); + } + + #[test] + fn first_pid_from_pgrep() { + assert_eq!(first_pid("812\n913\n"), Some(812)); + assert_eq!(first_pid(""), None); } #[test] @@ -1601,6 +1609,15 @@ mod tests { "svc:/system/system-log:default".to_string(), ]); } + + #[test] + fn parse_svcs_procs_fixture() { + let out = "online Aug_01 svc:/network/http:apache24\n\ + \x20 Aug_01 1021 httpd\n\ + \x20 10:23:45 1044 httpd\n"; + assert_eq!(parse_svcs_procs(out), vec![(1021, "httpd".to_string()), (1044, "httpd".to_string())]); + assert!(parse_svcs_procs("online Aug_01 svc:/network/ssh:default\n").is_empty()); + } } // ── Phase 1: full installed-package inventory ──────────────────────────────── @@ -1609,13 +1626,6 @@ mod tests { // so the scanner can match the full Radar catalog. Each list_* shells out once // and parses with a pure helper (fixture-tested below). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct InstalledPkg { - pub name: String, - pub version: String, - pub tool: &'static str, -} - /// Split a package atom like "nginx-1.26.2-r0" / "openssl-3.0.7" into /// (name, upstream-version). Names may contain hyphens, so anchor on the first /// "-" run. @@ -1635,7 +1645,7 @@ pub fn parse_dpkg_list(out: &str) -> Vec<(String, String)> { out.lines().filter_map(|l| { let mut c = l.split('\t'); let status = c.next()?; - let name = c.next()?; + let name = strip_dpkg_arch(c.next()?); let ver = c.next()?; // 2nd status char 'i' = installed/held; drops 'rc' config-only etc. if status.chars().nth(1) != Some('i') || name.is_empty() || ver.is_empty() { @@ -1703,38 +1713,28 @@ pub fn parse_pkg_info_list(out: &str) -> Vec<(String, String)> { out.lines().filter_map(|l| atom_split(l.split_whitespace().next()?)).collect() } -fn tagged(tool: &'static str, pairs: Vec<(String, String)>) -> Vec { - pairs.into_iter().map(|(name, version)| InstalledPkg { name, version, tool }).collect() -} - -/// Enumerate all installed packages for the host's OS. Empty when no supported -/// package manager is available (e.g. Solaris IPS — deferred). -pub fn list_installed(os: &OsType) -> Vec { - match os { +/// Every installed package as (name, version). Empty when no supported package +/// manager is available (e.g. Solaris IPS). +pub fn list_installed(os: &OsType) -> Vec<(String, String)> { + let listed = match os { OsType::Linux(distro) => match distro { LinuxDistro::Debian | LinuxDistro::Ubuntu | LinuxDistro::Kali => - tagged("dpkg", run_cmd("dpkg-query", &["-W", "-f=${db:Status-Abbrev}\t${binary:Package}\t${Version}\t${Architecture}\n"]).map(|o| parse_dpkg_list(&o)).unwrap_or_default()), + run_cmd("dpkg-query", &["-W", "-f=${db:Status-Abbrev}\t${binary:Package}\t${Version}\n"]).map(|o| parse_dpkg_list(&o)), LinuxDistro::Fedora | LinuxDistro::Rhel | LinuxDistro::CentOs | LinuxDistro::Rocky | LinuxDistro::Alma | LinuxDistro::OpenSuse => - tagged("rpm", run_cmd("rpm", &["-qa", "--qf", "%{NAME}\t%{EPOCH}\t%{VERSION}\t%{RELEASE}\t%{ARCH}\n"]).map(|o| parse_rpm_list(&o)).unwrap_or_default()), - LinuxDistro::Arch => - tagged("pacman", run_cmd("pacman", &["-Q"]).map(|o| parse_pacman_list(&o)).unwrap_or_default()), - LinuxDistro::Alpine => - tagged("apk", run_cmd("apk", &["info", "-v"]).map(|o| parse_apk_list(&o)).unwrap_or_default()), - _ => Vec::new(), + run_cmd("rpm", &["-qa", "--qf", "%{NAME}\t%{EPOCH}\t%{VERSION}\t%{RELEASE}\n"]).map(|o| parse_rpm_list(&o)), + LinuxDistro::Arch => run_cmd("pacman", &["-Q"]).map(|o| parse_pacman_list(&o)), + LinuxDistro::Alpine => run_cmd("apk", &["info", "-v"]).map(|o| parse_apk_list(&o)), + _ => None, }, - OsType::MacOs => - tagged("brew", run_cmd("brew", &["list", "--versions"]).map(|o| parse_brew_list(&o)).unwrap_or_default()), - OsType::FreeBsd | OsType::DragonFlyBsd => - tagged("pkg", run_cmd("pkg", &["query", "%n %v"]).map(|o| parse_pkg_query_list(&o)).unwrap_or_default()), - OsType::OpenBsd => - tagged("pkg_info", run_cmd("pkg_info", &["-q"]).map(|o| parse_pkg_info_list(&o)).unwrap_or_default()), - OsType::NetBsd => - tagged("pkg_info", run_cmd("pkg_info", &[]).map(|o| parse_pkg_info_list(&o)).unwrap_or_default()), - // Windows inventory is multi-ecosystem (registry/winget/appx/lang mgrs) - // and is produced as Assets directly by the WindowsCollector. - _ => Vec::new(), - } + OsType::MacOs => run_cmd("brew", &["list", "--versions"]).map(|o| parse_brew_list(&o)), + OsType::FreeBsd | OsType::DragonFlyBsd => run_cmd("pkg", &["query", "%n %v"]).map(|o| parse_pkg_query_list(&o)), + OsType::OpenBsd => run_cmd("pkg_info", &["-q"]).map(|o| parse_pkg_info_list(&o)), + OsType::NetBsd => run_cmd("pkg_info", &[]).map(|o| parse_pkg_info_list(&o)), + // Windows inventory is produced as Assets by the WindowsCollector. + _ => None, + }; + listed.unwrap_or_default() } #[cfg(test)] @@ -1743,11 +1743,13 @@ mod inventory_tests { #[test] fn dpkg_parse() { - let out = "ii \topenssl\t3.0.11-1~deb12u2\tamd64\n\ - rc \toldpkg\t1.0\tamd64\n\ - ii \tnginx\t1.22.1-9\tall\n"; + let out = "ii \topenssl\t3.0.11-1~deb12u2\n\ + rc \toldpkg\t1.0\n\ + ii \tlibssl3:amd64\t3.0.11-1~deb12u2\n\ + ii \tnginx\t1.22.1-9\n"; assert_eq!(parse_dpkg_list(out), vec![ ("openssl".into(), "3.0.11-1~deb12u2".into()), + ("libssl3".into(), "3.0.11-1~deb12u2".into()), ("nginx".into(), "1.22.1-9".into()), ]); } diff --git a/src/main.rs b/src/main.rs index 61e939b..45785a4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,8 +2,7 @@ use std::io::{self, IsTerminal, Write}; use std::process::ExitCode; use std::time::Duration; use std::fs; -use std::path::PathBuf; -use std::sync::Arc; +use std::path::{Path, PathBuf}; use clap::Parser; use indicatif::{ProgressBar, ProgressStyle}; @@ -25,6 +24,9 @@ use find_threats::{ Asset, plan_info, scan_body, + QuotaExceeded, + FREE_BATCH, + FREE_REQUESTS_PER_DAY, severity_rank as sev_rank, }; @@ -67,7 +69,7 @@ struct Cli { output: Option, /// Print the JSON report to stdout instead of writing a file - #[arg(long)] + #[arg(long, conflicts_with = "output")] json: bool, /// What to scan: running services only, or every installed OS package @@ -273,7 +275,6 @@ fn asset_allowed(names: &[&str], include: &[String], exclude: &[String]) -> bool !hits(exclude) && (include.is_empty() || hits(include)) } - fn severity_floor(s: Option) -> u8 { match s { Some(Severity::Critical) => 4, @@ -628,6 +629,9 @@ fn print_registration(resp: &RegisterResponse, alerts: bool, color: bool) { s.exposed, s.kev, ); + if s.truncated { + println!(" {}", paint("Radar could not evaluate every asset of this host; the summary may be incomplete.", "33", color)); + } if resp.resolved_count > 0 { println!( @@ -682,12 +686,10 @@ fn main() -> ExitCode { let interactive = !cli.yes && io::stdin().is_terminal(); let api_key = match auth::resolve_api_key(cli.reset, interactive) { - Some(k) => k, - None => { - error!("no API key available"); - eprintln!( - "No API key available. Set OFFSEQ_API_KEY, or run interactively to enter one." - ); + Ok(k) => k, + Err(msg) => { + error!("{msg}"); + eprintln!("{msg}"); return ExitCode::from(2); } }; @@ -738,10 +740,10 @@ fn main() -> ExitCode { ($($a:tt)*) => {{ if !cli.quiet { if to_stdout { eprintln!($($a)*) } else { println!($($a)*) } } }}; } - let client = Arc::new(ThreatClient::new(&api_key)); + let client = ThreatClient::new(&api_key); let sev_floor = severity_floor(cli.severity); - let (mut final_results, assets, system_info) = if let Some(path) = &cli.sbom { + let (mut final_results, assets, system_info, quota) = if let Some(path) = &cli.sbom { let content = match fs::read_to_string(path) { Ok(c) => c, Err(e) => { @@ -771,7 +773,7 @@ fn main() -> ExitCode { Err(e) => return lookup_failed(e, "SBOM scan"), }; say!("\nScanned {} package(s) from {} ({}).\n", report.packages, path.display(), report.format); - (report.into_results(&path.display().to_string(), sev_floor), Vec::new(), None) + (report.into_results(&sbom_location(path), sev_floor), Vec::new(), None, None) } else { say!("\nDetected OS: {}\n", os_label(&os)); @@ -849,12 +851,13 @@ fn main() -> ExitCode { errors: outcome.errors, rejected: outcome.rejected, truncated: outcome.truncated, + incomplete: outcome.incomplete, registration: None, }; // Exposure-aware risk score + SSVC decision per finding, computed from the // OWNING asset's reachability so local scores agree with the server's. score_findings(&mut results); - (results, assets, system_info) + (results, assets, system_info, outcome.quota) }; if let Some(info) = plan_info(&client.last_rate_limit()) { @@ -869,7 +872,7 @@ fn main() -> ExitCode { let human_output = !to_stdout && !cli.quiet; let interactive_human = interactive && human_output; let prompt_mode = auth::monitoring_prompt_mode(); - let mut action = register_action(cli.no_register || cli.sbom.is_some(), cli.register, &prompt_mode, interactive_human); + let mut action = register_action(cli.no_register || cli.sbom.is_some() || quota.is_some(), cli.register, &prompt_mode, interactive_human); // If we'd prompt, ask now and fold the answer back into the action. if action == RegisterAction::Prompt { @@ -1039,6 +1042,12 @@ fn main() -> ExitCode { final_results.truncated.len() ); } + if !final_results.incomplete.is_empty() { + eprintln!( + "[!] {} asset(s) were not fully evaluated: Radar's candidate cap was hit even on a retry (see \"incomplete\").", + final_results.incomplete.len() + ); + } if to_stdout { eprintln!("Found {total} {word}."); } else if !cli.quiet { @@ -1049,7 +1058,8 @@ fn main() -> ExitCode { // vulnerability summary. The network call itself already happened before // serialization so the response is captured in the JSON report too. if let (true, Some(resp)) = (human_output, ®istration) { - print_registration(resp, !client.last_rate_limit().is_free_plan(), color); + let alerts = resp.monitoring_available.unwrap_or_else(|| !client.last_rate_limit().is_free_plan()); + print_registration(resp, alerts, color); } // Opt-in Windows Update Agent advisory: pending (not-installed) security @@ -1067,13 +1077,17 @@ fn main() -> ExitCode { } } + if let Some(q) = quota { + return quota_exhausted(q, "Lookup"); + } + if let Some(f) = cli.fail_on { if fail_triggered(&final_results, f, cli.severity) { tracing::info!(threshold = ?f, "run finished; --fail-on threshold met"); return ExitCode::from(5); } // A gate that could not see every asset must not pass. - if !final_results.errors.is_empty() { + if !final_results.errors.is_empty() || !final_results.incomplete.is_empty() { eprintln!("[!] --fail-on could not evaluate every asset; failing the run."); return ExitCode::from(1); } @@ -1086,11 +1100,7 @@ fn main() -> ExitCode { /// Exit code for a failed Radar lookup: 4 when the plan or quota is the cause, else 1. fn lookup_failed(e: ThreatError, what: &str) -> ExitCode { match e { - ThreatError::RateLimitExceeded(msg) => { - warn!(message = %msg, "rate limit exceeded: {what}"); - auth::prompt_upgrade(Some(&msg)); - ExitCode::from(4) - } + ThreatError::RateLimitExceeded(q) => quota_exhausted(q, what), // A plan gate or incomplete profile: the server message says how to fix // it (with links), and exit 4 rather than 1, which reads as a network failure. ThreatError::AccessDenied(msg) => { @@ -1106,6 +1116,24 @@ fn lookup_failed(e: ThreatError, what: &str) -> ExitCode { } } +fn quota_exhausted(q: QuotaExceeded, what: &str) -> ExitCode { + warn!(message = %q.message, "rate limit exceeded: {what}"); + auth::prompt_upgrade(Some(&q.message), q.checkout.as_deref()); + ExitCode::from(4) +} + +/// Where SARIF locates SBOM findings: the path relative to the current directory +/// when the file is inside it, else its file name. +fn sbom_location(path: &Path) -> String { + if path.is_relative() { + return path.display().to_string(); + } + std::env::current_dir().ok() + .and_then(|cwd| path.strip_prefix(cwd).ok().map(|p| p.display().to_string())) + .or_else(|| path.file_name().map(|n| n.to_string_lossy().into_owned())) + .unwrap_or_else(|| path.display().to_string()) +} + /// Print the Windows Update Agent advisory (pending updates, most severe first). /// Goes to stderr when stdout is reserved for the JSON report, so piping stays /// clean. @@ -1157,10 +1185,6 @@ fn inventory_noun(scope: ScanScope, count: usize) -> &'static str { } } -/// Free-plan batch size and daily request quota (utils/planLimits.js). -const FREE_BATCH: usize = 50; -const FREE_REQUESTS_PER_DAY: usize = 30; - /// Shown before matching (the plan is unknown until the first response), so it /// is worded for the free plan rather than asserting the caller's limits. fn scope_all_budget_warning(count: usize) -> String { @@ -1250,7 +1274,23 @@ mod tests { ))); // Unrelated registration failures don't get the upgrade hint. assert!(!is_host_or_asset_cap(&ThreatError::Other("decode error".into()))); - assert!(!is_host_or_asset_cap(&ThreatError::RateLimitExceeded("slow down".into()))); + assert!(!is_host_or_asset_cap(&ThreatError::PayloadTooLarge)); + } + + #[test] + fn json_conflicts_with_output() { + assert!(Cli::try_parse_from(["threat-finder", "--json", "-o", "r.json"]).is_err()); + } + + #[test] + fn sbom_location_is_relative_to_cwd() { + let cwd = std::env::current_dir().unwrap(); + assert_eq!(sbom_location(&cwd.join("deps").join("bom.json")), Path::new("deps").join("bom.json").display().to_string()); + assert_eq!(sbom_location(Path::new("deps/bom.json")), "deps/bom.json"); + let outside = std::env::temp_dir().join("tf-elsewhere").join("bom.json"); + if !outside.starts_with(&cwd) { + assert_eq!(sbom_location(&outside), "bom.json"); + } } #[test] @@ -1374,7 +1414,7 @@ mod tests { unconfirmed: std::collections::BTreeMap::new(), assets: std::collections::BTreeMap::new(), errors: std::collections::BTreeMap::new(), rejected: std::collections::BTreeMap::new(), - truncated: vec![], registration: None, + truncated: vec![], incomplete: vec![], registration: None, }; results.sort_findings(); let v = &results.services["svc@1"]; @@ -1401,7 +1441,7 @@ mod tests { services: std::collections::BTreeMap::from([("svc@1".to_string(), vec![decided])]), by_cve: std::collections::BTreeMap::new(), unconfirmed: std::collections::BTreeMap::new(), assets: std::collections::BTreeMap::new(), errors: std::collections::BTreeMap::new(), - rejected: std::collections::BTreeMap::new(), truncated: vec![], registration: None, + rejected: std::collections::BTreeMap::new(), truncated: vec![], incomplete: vec![], registration: None, }; assert!(!fail_triggered(&results, FailOn::Kev, None)); let v: serde_json::Value = serde_json::from_str(&sarif::to_sarif(&results)).unwrap(); @@ -1436,6 +1476,7 @@ mod tests { errors: std::collections::BTreeMap::new(), rejected: std::collections::BTreeMap::new(), truncated: vec![], + incomplete: vec![], registration: None, }; let s = sarif::to_sarif(&results); diff --git a/src/sarif.rs b/src/sarif.rs index 8a44afc..8e3c6c0 100644 --- a/src/sarif.rs +++ b/src/sarif.rs @@ -15,16 +15,23 @@ fn level(sev: Option<&str>) -> &'static str { } } - /// GitHub code scanning drops results without a physical location and resolves -/// URIs against the repository root, so the asset's path is made relative. +/// URIs against the repository root, so the asset's path is made relative and +/// percent-encoded into a valid uri-reference. fn artifact_uri(exe: &str) -> String { let path = exe.replace('\\', "/"); let path = match path.as_bytes() { [d, b':', ..] if d.is_ascii_alphabetic() => &path[2..], _ => &path, }; - path.trim_start_matches('/').to_string() + let mut uri = String::with_capacity(path.len()); + for b in path.trim_start_matches('/').bytes() { + match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => uri.push(b as char), + _ => uri.push_str(&format!("%{b:02X}")), + } + } + uri } fn push_entry(rules: &mut BTreeMap, results: &mut Vec, asset: &str, exe: Option<&str>, t: &ThreatEntry) { @@ -92,6 +99,9 @@ fn push_entry(rules: &mut BTreeMap, results: &mut Vec, ass if !t.fixed_versions.is_empty() { props["fixedVersions"] = json!(t.fixed_versions); } + if let Some(rem) = &t.remediation { + props["remediation"] = json!(rem); + } let mut location = json!({ "logicalLocations": [{ "fullyQualifiedName": asset, "kind": "module" }] }); if let Some(exe) = exe { @@ -107,10 +117,6 @@ fn push_entry(rules: &mut BTreeMap, results: &mut Vec, ass "locations": [location], "properties": props, }); - if let Some(rem) = &t.remediation { - // A `fixes`-adjacent hint that SARIF viewers can surface as guidance. - result["fixes"] = json!([{ "description": { "text": rem } }]); - } if let Some(d) = t.recorded_decision.as_ref().filter(|d| d.suppressing) { result["suppressions"] = json!([{ "kind": "external", "status": "accepted", "justification": d.verdict }]); } @@ -145,3 +151,16 @@ pub fn to_sarif(results: &BatchResults) -> String { serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".to_string()) } + +#[cfg(test)] +mod tests { + use super::artifact_uri; + + #[test] + fn artifact_uri_is_a_relative_uri_reference() { + assert_eq!(artifact_uri("/usr/sbin/nginx"), "usr/sbin/nginx"); + assert_eq!(artifact_uri("C:\\Program Files\\App (x86)\\a#b.exe"), "Program%20Files/App%20%28x86%29/a%23b.exe"); + assert_eq!(artifact_uri("deps/pkg:lock?.json"), "deps/pkg%3Alock%3F.json"); + assert_eq!(artifact_uri("/opt/caf\u{e9}/x"), "opt/caf%C3%A9/x"); + } +} diff --git a/src/scan.rs b/src/scan.rs index 28dffd6..ec7447d 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -10,8 +10,8 @@ use std::collections::BTreeMap; use crate::api::{ - match_to_entry, search_to_entry, severity_rank, BatchOutcome, MatchQuery, ThreatClient, - ThreatEntry, ThreatError, + match_to_entry, prune_unconfirmed, search_to_entry, severity_rank, BatchOutcome, MatchQuery, + ThreatClient, ThreatEntry, ThreatError, }; use crate::cpe::escape_cpe; use crate::engine::{ @@ -118,7 +118,6 @@ impl Asset { } pub trait Collector: Sync { - fn name(&self) -> &'static str; /// Never panics; returns an empty Vec on an unhandled OS. fn collect(&self, os: &OsType) -> Vec; } @@ -128,9 +127,6 @@ pub trait Collector: Sync { pub struct RunningServiceCollector; impl Collector for RunningServiceCollector { - fn name(&self) -> &'static str { - "running-services" - } fn collect(&self, os: &OsType) -> Vec { let mut services = scan_services(os); enrich_exposure(&mut services); @@ -163,18 +159,15 @@ fn service_to_asset(s: ServiceInfo, eco: Ecosystem) -> Asset { pub struct OsPackageCollector; impl Collector for OsPackageCollector { - fn name(&self) -> &'static str { - "os-packages" - } fn collect(&self, os: &OsType) -> Vec { let eco = Ecosystem::for_os(os); list_installed(os) .into_iter() - .map(|p| Asset { + .map(|(name, version)| Asset { ecosystem: eco, - name: p.name.clone(), - pkg_name: Some(p.name), // inventory names ARE the package coordinate - version: p.version, + name: name.clone(), + pkg_name: Some(name), // inventory names ARE the package coordinate + version, sources: vec![Source::PackageDb], locations: Vec::new(), runtime: None, @@ -202,9 +195,6 @@ pub struct WindowsCollector { } impl Collector for WindowsCollector { - fn name(&self) -> &'static str { - "windows" - } fn collect(&self, os: &OsType) -> Vec { match os { OsType::Windows(w) => crate::windows::collect_windows(w, self.full), @@ -426,9 +416,19 @@ fn dedup_by_cve(entries: &mut Vec) { }); } +/// `?search=` lookups per run; each costs up to `MAX_PAGES` requests of quota. +pub const MAX_FALLBACK_SEARCHES: usize = 25; + +fn note(errors: &mut BTreeMap, keys: &[String], msg: &str) { + for k in keys { + errors.insert(k.clone(), msg.to_string()); + } +} + /// Match a host inventory against Radar by exact coordinate (purl) in batched /// POSTs, falling back to `?search=` for assets with no buildable coordinate. /// Confirmed matches go to `results`; coordinate-unconfirmed to `unconfirmed`. +/// A quota exhausted after the batch keeps what was matched and sets `quota`. pub fn run_scan( client: &ThreatClient, assets: &[Asset], @@ -458,18 +458,41 @@ pub fn run_scan( let mut rejected: BTreeMap = BTreeMap::new(); let mut upgrades: BTreeMap = BTreeMap::new(); let mut truncated: Vec = Vec::new(); + let mut incomplete: Vec = Vec::new(); + let mut quota = None; // Exploited findings (KEV, EUVD, Mirage) survive the severity floor: hiding // them would contradict risk ranking and `--fail-on kev|exploited`. let keep = |e: &ThreatEntry| e.exploited || severity_rank(e.severity.as_deref()) >= severity_floor; if !queries.is_empty() { - let matched = client.match_batch(&queries, strict)?; + let (mut matched, stopped) = client.match_batch(&queries, strict)?; + for (key, _) in &query_keys[matched.len()..] { + errors.insert(key.clone(), "not matched (quota exhausted)".to_string()); + } + quota = stopped; + // The candidate budget is per request, so a smaller follow-up batch gets a fresh one. + let capped: Vec = (0..matched.len()).filter(|&i| matched[i].candidate_capped()).collect(); + if !capped.is_empty() && quota.is_none() { + let retry: Vec = capped.iter().map(|&i| queries[i].clone()).collect(); + match client.match_batch(&retry, strict) { + Ok((again, stopped)) => { + for (i, r) in capped.into_iter().zip(again) { + matched[i] = r; + } + quota = stopped; + } + Err(ThreatError::RateLimitExceeded(q)) => quota = Some(q), + Err(e) => tracing::warn!(error = %e, "candidate-cap retry failed"), + } + } for ((key, distro), result) in query_keys.iter().zip(matched) { - if let Some(e) = result.error { - rejected.insert(key.clone(), e); + if let Some(e) = &result.error { + rejected.insert(key.clone(), e.clone()); } - if result.truncated { + if result.candidate_capped() { + incomplete.push(key.clone()); + } else if result.truncated { truncated.push(key.clone()); } if let Some(v) = result.upgrade_to { @@ -492,30 +515,41 @@ pub fn run_scan( } // One ?search= per unique name; apply to every asset key sharing it. - for (name, keys) in fallback { + let mut fallback = fallback.into_iter(); + for (name, keys) in fallback.by_ref().take(MAX_FALLBACK_SEARCHES) { + if quota.is_some() { + note(&mut errors, &keys, "not searched (quota exhausted)"); + continue; + } match client.search_threats(&name) { Ok(threats) => { let entries: Vec = threats.iter().map(search_to_entry).filter(|e| keep(e)).collect(); - for key in keys { - if !entries.is_empty() { + if !entries.is_empty() { + for key in keys { unconfirmed.entry(key).or_default().extend(entries.iter().cloned()); } } } - Err(ThreatError::RateLimitExceeded(m)) => return Err(ThreatError::RateLimitExceeded(m)), - Err(e) => { - errors.insert(name, e.to_string()); + Err(ThreatError::RateLimitExceeded(q)) => { + note(&mut errors, &keys, "not searched (quota exhausted)"); + quota = Some(q); } + Err(e) => note(&mut errors, &keys, &e.to_string()), } } + // Search hits are unconfirmed and never trip --fail-on, so skipping them must not either. + for (_, keys) in fallback { + note(&mut rejected, &keys, &format!("not searched (fallback budget of {MAX_FALLBACK_SEARCHES} searches per run)")); + } for v in results.values_mut().chain(unconfirmed.values_mut()) { v.sort_by_key(|e| std::cmp::Reverse(e.risk_key())); dedup_by_cve(v); } + prune_unconfirmed(&results, &mut unconfirmed); - Ok(BatchOutcome { results, unconfirmed, errors, rejected, upgrades, truncated }) + Ok(BatchOutcome { results, unconfirmed, errors, rejected, upgrades, truncated, incomplete, quota }) } #[cfg(test)] @@ -670,4 +704,83 @@ mod tests { dedup_by_cve(&mut v); assert_eq!(v.len(), 2, "id-less entries are never collapsed"); } + + fn win_app(name: &str) -> Asset { + Asset { ecosystem: Ecosystem::WinApp, name: name.into(), pkg_name: Some(name.into()), version: "1.0".into(), + sources: vec![Source::PackageDb], locations: vec![], runtime: None, cpe: None } + } + + #[test] + fn quota_in_fallback_keeps_batch_results() { + use crate::api::{http, serve}; + let batch = http(200, r#"{"data":{"results":[{"matches":[{"cveId":"CVE-1","severity":"high","confirmed":true}]}]}}"#); + let quota = http(429, r#"{"message":"Daily quota reached.","upgrade":{"reason":"api-day","urls":{"checkout":"https://c/o"}}}"#); + let (client, server) = serve(vec![batch, quota]); + let assets = [asset_eco(Ecosystem::Deb, "nginx", "1.0"), win_app("Alpha"), win_app("Beta")]; + let out = run_scan(&client, &assets, &linux(LinuxDistro::Debian), false, 0).unwrap(); + assert_eq!(server.join().unwrap().len(), 2, "no search after the quota ran out"); + assert_eq!(out.results["nginx@1.0"][0].cve_id.as_deref(), Some("CVE-1")); + assert_eq!(out.quota.unwrap().checkout.as_deref(), Some("https://c/o")); + assert_eq!(out.errors.keys().collect::>(), ["Alpha@1.0", "Beta@1.0"]); + assert!(out.errors.values().all(|e| e.contains("quota"))); + } + + #[test] + fn fallback_searches_are_bounded_per_run() { + use crate::api::{http, serve}; + let empty = http(200, r#"{"data":{"threats":[]}}"#); + let (client, server) = serve(vec![empty; MAX_FALLBACK_SEARCHES]); + let assets: Vec = (0..MAX_FALLBACK_SEARCHES + 2).map(|i| win_app(&format!("app{i:02}"))).collect(); + let out = run_scan(&client, &assets, &OsType::Windows(Default::default()), false, 0).unwrap(); + assert_eq!(server.join().unwrap().len(), MAX_FALLBACK_SEARCHES); + assert!(out.errors.is_empty(), "budget skips never fail --fail-on"); + assert_eq!(out.rejected.len(), 2); + assert!(out.rejected.values().all(|e| e.contains("fallback budget")), "{:?}", out.rejected); + } + + #[test] + fn quota_mid_batch_keeps_matched_chunks() { + use crate::api::{http, serve, FREE_BATCH}; + let results = vec![r#"{"matches":[]}"#; FREE_BATCH].join(","); + let first = http(200, &format!(r#"{{"data":{{"results":[{results}]}}}}"#)); + let quota = http(429, r#"{"message":"Daily quota reached.","upgrade":{"reason":"api-day"}}"#); + let (client, server) = serve(vec![first, quota]); + let assets: Vec = (0..FREE_BATCH + 3).map(|i| asset_eco(Ecosystem::Deb, &format!("p{i:03}"), "1.0")).collect(); + let out = run_scan(&client, &assets, &linux(LinuxDistro::Debian), false, 0).unwrap(); + assert_eq!(server.join().unwrap().len(), 2); + assert!(out.quota.is_some()); + assert_eq!(out.errors.len(), 3, "only the unsent chunk is unmatched"); + assert!(out.errors.values().all(|e| e.contains("not matched (quota exhausted)"))); + } + + #[test] + fn candidate_capped_results_are_retried_once() { + use crate::api::{http, serve}; + let first = http(200, r#"{"data":{"results":[ + {"truncated":true,"candidatesTruncated":true,"totalMatches":1,"matches":[{"cveId":"CVE-1","confirmed":true}]}, + {"truncated":true,"totalMatches":40,"matches":[{"cveId":"CVE-2","confirmed":true}]}, + {"truncated":true,"totalMatches":1,"matches":[{"cveId":"CVE-3","confirmed":true}]}]}}"#); + let retry = http(200, r#"{"data":{"results":[ + {"truncated":false,"candidatesTruncated":false,"totalMatches":2,"matches":[{"cveId":"CVE-1","confirmed":true},{"cveId":"CVE-4","confirmed":true}]}, + {"truncated":true,"candidatesTruncated":true,"totalMatches":1,"matches":[{"cveId":"CVE-3","confirmed":true}]}]}}"#); + let (client, server) = serve(vec![first, retry]); + let assets = ["a", "b", "c"].map(|n| asset_eco(Ecosystem::Deb, n, "1.0")); + let out = run_scan(&client, &assets, &linux(LinuxDistro::Debian), false, 0).unwrap(); + assert_eq!(server.join().unwrap().len(), 2); + assert_eq!(out.results["a@1.0"].len(), 2, "retry replaced the capped result"); + assert_eq!(out.truncated, ["b@1.0"]); + assert_eq!(out.incomplete, ["c@1.0"]); + } + + #[test] + fn confirmed_finding_drops_its_unconfirmed_copy() { + use crate::api::{http, serve}; + let batch = http(200, r#"{"data":{"results":[{"matches":[ + {"cveId":"CVE-1","confirmed":true},{"cveId":"CVE-1","confirmed":false},{"cveId":"CVE-2","confirmed":false}]}]}}"#); + let (client, server) = serve(vec![batch]); + let out = run_scan(&client, &[asset_eco(Ecosystem::Deb, "a", "1.0")], &linux(LinuxDistro::Debian), false, 0).unwrap(); + server.join().unwrap(); + let ids: Vec<_> = out.unconfirmed["a@1.0"].iter().map(|e| e.cve_id.as_deref()).collect(); + assert_eq!(ids, [Some("CVE-2")]); + } }