From 215e419e8d9aa67cf73886f49e62f587c598c008 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Wed, 18 Nov 2026 11:55:07 -0500 Subject: [PATCH] Catch vulnerabilities in the language runtimes a team runs A JDK is not a Maven package and a JDK unpacked into an image is not an OS package, so CVE-2026-114938 in the JDK's Base64 decoder matched nothing. Runtimes are now found in code (Dockerfile JDK images, version files, Gradle and Maven, CI setup steps, Lambda runtimes) and on AWS (every package SSM inventory lists, not only the kernel), matched against the OpenJDK Vulnerability Group's advisories with what the Amazon Linux java advisories add, and each finding says whether the CPU it runs on meets the advisory's hardware condition. --- docs/runtime-vulnerabilities.md | 78 ++ docs/self-host/requirements.md | 3 +- services/common/src/infra_vuln/feeds.rs | 26 + services/common/src/infra_vuln/inventory.rs | 138 ++++ services/common/src/infra_vuln/matching.rs | 425 ++++++++++ services/common/src/infra_vuln/raw.rs | 54 +- services/common/src/infra_vuln/store.rs | 9 + services/common/src/lib.rs | 2 + .../common/src/runtime_vuln/advisories.rs | 612 +++++++++++++++ services/common/src/runtime_vuln/cpu.rs | 287 +++++++ services/common/src/runtime_vuln/decls.rs | 672 ++++++++++++++++ services/common/src/runtime_vuln/findings.rs | 727 ++++++++++++++++++ services/common/src/runtime_vuln/mod.rs | 170 ++++ services/common/src/runtime_vuln/notes.json | 14 + services/common/src/runtime_vuln/replay.rs | 412 ++++++++++ .../testdata/alas2-2026-4123.html | 155 ++++ .../runtime_vuln/testdata/alas2-java-rss.xml | 131 ++++ .../testdata/alas2023-2026-3479.html | 148 ++++ .../testdata/alas2023-java-rss.xml | 131 ++++ .../testdata/openjdk-2026-11-17.html | 32 + .../runtime_vuln/testdata/openjdk-index.html | 24 + services/common/src/security_fixes.rs | 6 +- services/gateway/src/routes/security.rs | 1 + services/worker/src/passes/base_images.rs | 15 + .../incidents/an_six_database_findings.rs | 1 + .../incidents/bn_infra_list_follows_aws.rs | 1 + services/worker/src/passes/infra_feeds.rs | 107 +++ services/worker/src/passes/infra_findings.rs | 2 + services/worker/src/passes/infra_inventory.rs | 170 ++-- services/worker/src/passes/security_fixes.rs | 183 ++++- 30 files changed, 4677 insertions(+), 59 deletions(-) create mode 100644 docs/runtime-vulnerabilities.md create mode 100644 services/common/src/runtime_vuln/advisories.rs create mode 100644 services/common/src/runtime_vuln/cpu.rs create mode 100644 services/common/src/runtime_vuln/decls.rs create mode 100644 services/common/src/runtime_vuln/findings.rs create mode 100644 services/common/src/runtime_vuln/mod.rs create mode 100644 services/common/src/runtime_vuln/notes.json create mode 100644 services/common/src/runtime_vuln/replay.rs create mode 100644 services/common/src/runtime_vuln/testdata/alas2-2026-4123.html create mode 100644 services/common/src/runtime_vuln/testdata/alas2-java-rss.xml create mode 100644 services/common/src/runtime_vuln/testdata/alas2023-2026-3479.html create mode 100644 services/common/src/runtime_vuln/testdata/alas2023-java-rss.xml create mode 100644 services/common/src/runtime_vuln/testdata/openjdk-2026-11-17.html create mode 100644 services/common/src/runtime_vuln/testdata/openjdk-index.html diff --git a/docs/runtime-vulnerabilities.md b/docs/runtime-vulnerabilities.md new file mode 100644 index 000000000..970d42a91 --- /dev/null +++ b/docs/runtime-vulnerabilities.md @@ -0,0 +1,78 @@ +# Runtime vulnerabilities + +A flaw in a language runtime (a JDK, Node.js, Python, Go) is neither a library nor an operating system package. A JDK is not a Maven artifact, and a JDK unpacked into an image is not a Debian or Alpine package. CoderHelm finds the runtimes a team runs from its code and its AWS accounts, and matches them by version line against the runtime projects' own advisories. No model is called: every match is a comparison. + +The code is in `services/common/src/runtime_vuln/` (the rules) and in the security and infrastructure passes of the worker (the reads). + +## What runs, from the code + +Read with each repository's dependency list (`refresh_inventory`), and listed in it under the `runtime` ecosystem: + +| Where | Example | Precision | +|---|---|---| +| Dockerfile `FROM` | `eclipse-temurin:21.0.4_7-jre`, `amazoncorretto:21`, `gradle:8.10-jdk21`, `gcr.io/distroless/java21-debian12`, `node:20.11.0`, `python:3.12`, `golang:1.22.3` | the tag's | +| Version files | `.java-version`, `.sdkmanrc` (`java=21.0.4-tem`), `.tool-versions`, `.nvmrc`, `.node-version`, `.python-version`, `go.mod` `toolchain` | the value's | +| Build toolchains | Gradle `JavaLanguageVersion.of(21)`, `jvmToolchain(21)` | a line | +| Build targets | Maven `maven.compiler.release`, `java.version`, `release`; Gradle `sourceCompatibility` | a line | +| CI setup steps | `java-version`, `node-version`, `python-version`, `go-version` in `.github/workflows` | the value's | +| Lambda runtimes | Terraform `runtime = "java21"`, SAM and CloudFormation `Runtime: java21`, Serverless `runtime: java21`, CDK `Runtime.JAVA_21` | a line AWS manages | + +A value with a patch number (`21.0.4`, `21.0.4_7`) is an exact build. A line (`21`, `21-jre`, a toolchain) takes whatever build is newest when the image is built or the job runs. A tag a registry republishes for every build of an update (`amazoncorretto:21.0.13` while the advisory's last affected build is `21.0.13.0.3`) is treated as a line. Values from variables are not read. `FROM --platform=linux/arm64` is kept as the image's architecture. + +## The advisories + +Read once a day with the infrastructure feeds (`infra_feeds`), each kept as `RUNTIME_ADV#` under `SECURITY#GLOBAL`: + +1. The OpenJDK Vulnerability Group's index and each advisory page (the newest three again every day, older ones once). A page gives the lines each CVE affects (its risk matrix) and the last affected build of each line ("The affected versions are 27.0.1.0.3, 25.0.5.0.3, 21.0.13.0.3, 17.0.21.0.3, 11.0.33, 8u512, and earlier"). +2. The Amazon Linux advisories for the `java-*-amazon-corretto` packages (ALAS, already read for the infrastructure findings), for what the OpenJDK page does not say: where a line starts being affected ("17.0.6 and later"), the hardware ("on x86-64 systems", "ARM64 systems are not affected"), JVM flags, and Corretto's fixed builds (and from them the upstream fix: Corretto `21.0.13.1.2` is upstream `21.0.13.1`). +3. `runtime_vuln/notes.json`: what no feed carries in a form that can be read (a CPU feature, a JVM flag), per CVE, dated and with its source. A feed's own value wins. + +A page that can't be fetched or no longer parses keeps the last good copy, and the feed's status row (`INFRA_FEED#openjdk`, on the Sources panel) carries the error. + +OSV was checked first: it has no JDK ecosystem. It lists a JDK CVE only under distributions' `openjdk-*` source packages (Debian, Ubuntu, Alpine), which the base image findings already cover for images whose registry publishes a package list. + +## Findings in repositories + +One finding per declaration and CVE, recorded like a dependency finding (package = the image's name or the runtime's, version = the tag or value as written, manifest = the file), so tiers, cards, fix runs and pull requests work the same way. + +- An exact build that is affected gets a pull request when a fixed build is known in the same form: for an image, the lowest published tag of the same variant past the last affected build (from the registry's tag list: `21.0.4_7-jre` moves to `21.0.13.1_2-jre`, never to a `-jdk` or another vendor); for a version file or CI pin, the upstream fix, or the vendor's build when the source names the vendor's. +- A line, a floating tag or a republished tag is a finding without a pull request: rebuild and redeploy (or pin a fixed build). +- An exact build with no fixed build published yet for its vendor is a finding without a pull request, until one is. +- Every finding names the advisory's hardware condition and its JVM flag for the time until the fix runs. +- An image built only for an architecture the advisory says is not affected stays a finding, at the lowest tier, with the reason. +- A finding closes when a fresh read of the repository no longer declares an affected build there (a merged pull request alone does not close it). + +## Findings on AWS + +- SSM inventory: every installed package of up to 100 SSM-managed instances per account and region (the first of each Auto Scaling group and node group first), not only the kernel. Each is matched against every Amazon Linux advisory for a package other than the kernel (the kernel decides the AMI finding), by the package's own release (`amzn2023` or `amzn2`). One finding per affected source package and group, a runbook (`dnf upgrade --advisory ...`, then restart the JVMs), with the JVM flag when the advisory names one. +- Lambda functions on a managed Java runtime whose line is affected are AWS-managed rows: AWS ships the fixed build in the managed runtime; the row says how each runtime update mode takes it. +- The hardware: EC2 instance types (and node group instance types) map to their architecture and CPU generation (`runtime_vuln::cpu`). When every CVE behind a finding names a hardware condition: + - it holds (for AVX-512 VBMI: Intel Ice Lake, Sapphire Rapids, Granite Rapids; AMD Zen 4, Zen 5): P0 when internet-facing, else at least P1; + - it does not (Graviton, or an x86 family without the feature): P3, with the reason and what moving to an affected family would mean. A later read on an affected family raises the tier, which posts a card for P0 and P1; + - not known (a family not in the table): the tier stays as matched, and the finding says the CPU is not known. + +No new AWS permission is needed: `ec2:DescribeInstances` already returns the instance type and architecture, `eks:DescribeNodegroup` the node group's instance types, and `ssm:ListInventoryEntries` every package. + +## Worked example: CVE-2026-114938 + +A heap overflow in the `java.util.Base64` decoder's AVX-512 VBMI intrinsic (OpenJDK advisory 2026-11-17). The OpenJDK page lists lines 17, 21, 25 and 27 (not 8 or 11), last affected 17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3. ALAS2023-2026-3478 to 3481 and ALAS2-2026-4123 add "17.0.6 and later on x86-64 ... ARM64 systems are not affected" and Corretto 17.0.21.1.2 and 21.0.13.1.2; the notes add AVX-512 VBMI and `-XX:-UseBASE64Intrinsics`. + +| What the team runs | What CoderHelm says | +|---|---| +| `FROM eclipse-temurin:21.0.4_7-jre` | P1, pull request to the lowest fixed `_N-jre` tag once the registry has one | +| `FROM eclipse-temurin:21-jre` | P1, rebuild and redeploy to take 21.0.13.1 | +| `.java-version` `17.0.15` | P1, pull request to `17.0.21.1` | +| Gradle toolchain 21, `maven.compiler.release` 21, `setup-java` `21` | P1 each, rebuild (the line takes the fix) | +| `FROM --platform=linux/arm64 eclipse-temurin:21-jre` | P3, ARM64 is not affected | +| Lambda `runtime = "java21"` | AWS-managed row | +| `java-21-amazon-corretto-headless` 21.0.13.0.11 on `m7i` | P1 (P0 when internet-facing), `dnf upgrade --advisory ALAS2023-2026-3479` | +| the same on `m6g` or `m5` | P3, with why and what moving to `m7i` would mean | +| Java 8, Java 11, 17.0.5, 21.0.13.1 | nothing | + +The replay tests are `runtime_vuln::findings::tests` and `runtime_vuln::replay`, on the pages as they were read on 2026-11-18 (`runtime_vuln/testdata`). + +## Not covered yet + +- Node.js, Python and Go advisories: their declarations are read and listed, but only the OpenJDK feed is matched. Go's (`stdlib` in OSV's Go ecosystem) and Node.js's (the security working group's `vuln/core` index) are the next sources. +- A JDK inside a container is the repository finding of the Dockerfile that builds it; the hardware it runs on is not tied to that finding yet (ECS services and EKS pods are not mapped back to their image's Dockerfile). What CPU runs a Fargate task or an x86 Lambda function AWS does not say, so those stay "not known". +- A vendor whose fixed build no source names (an `.sdkmanrc` on Temurin, say) gets a finding without a pull request until the source names it. diff --git a/docs/self-host/requirements.md b/docs/self-host/requirements.md index 1a2e7ad4c..f2ae4f287 100644 --- a/docs/self-host/requirements.md +++ b/docs/self-host/requirements.md @@ -42,11 +42,12 @@ Besides GitHub and your model provider, the worker calls these hosts over HTTPS, | `api.osv.dev` | Advisories for each dependency (`/v1/querybatch`, then `/v1/vulns/`) | Package names and versions from the repository's dependency list. No code | | `www.cisa.gov` | CISA's list of exploited vulnerabilities, once a day | Nothing about your install | | `api.first.org` | EPSS scores for the CVEs your findings name, once a day | CVE ids | -| `auth.docker.io`, `registry-1.docker.io`, `production.cloudflare.docker.com` (and the registry a `FROM` line names, such as `public.ecr.aws` or `ghcr.io`) | A Dockerfile base image's manifest and its published package list (SBOM attestation), anonymous pulls only, once a day per repository | The image names and tags in your Dockerfiles. No code, no credentials | +| `auth.docker.io`, `registry-1.docker.io`, `production.cloudflare.docker.com` (and the registry a `FROM` line names, such as `public.ecr.aws` or `ghcr.io`) | A Dockerfile base image's manifest and its published package list (SBOM attestation), and for a pinned JDK image its tag list (to find the fixed tag), anonymous pulls only, once a day per repository | The image names and tags in your Dockerfiles. No code, no credentials | | `alas.aws.amazon.com` | Amazon Linux 2 and 2023 security advisories (RSS, and the page of each kernel or important advisory), once a day | Nothing about your install | | `advisories.bottlerocket.aws` | Bottlerocket's security advisories (`updateinfo.xml.gz`), once a day | Nothing about your install | | `aws.amazon.com` | AWS security bulletins (RSS, and each bulletin's page for its per-service status), once a day | Nothing about your install | | `docs.aws.amazon.com` | The Lambda runtime deprecation table, once a day | Nothing about your install | +| `openjdk.org` | The OpenJDK Vulnerability Group's advisories (the index, and each advisory page's risk matrix), once a day | Nothing about your install | The worker also reads AWS's public "latest image" parameters for ECS, EKS and Bottlerocket (`ssm:GetParameters` on `/aws/service/*` in us-east-1) with its own role. These public reads run only while a team has security fixes on. diff --git a/services/common/src/infra_vuln/feeds.rs b/services/common/src/infra_vuln/feeds.rs index fb771933f..3a065d3ca 100644 --- a/services/common/src/infra_vuln/feeds.rs +++ b/services/common/src/infra_vuln/feeds.rs @@ -34,6 +34,7 @@ pub const LAMBDA_RUNTIMES: &str = /// The hosts the feeds are read from (the self-host docs list them). pub const HOSTS: &[&str] = &[ "alas.aws.amazon.com", + crate::runtime_vuln::advisories::HOST, "advisories.bottlerocket.aws", "aws.amazon.com", "docs.aws.amazon.com", @@ -47,6 +48,10 @@ pub const FEEDS: &[(&str, &str)] = &[ ("bulletins", "AWS security bulletins"), ("lambda_runtimes", "Lambda runtime deprecations"), ("latest_images", "AWS latest AMI parameters"), + ( + crate::runtime_vuln::advisories::FEED, + "OpenJDK vulnerability advisories", + ), ]; /// A feed whose read went wrong: why, in a line for the log and the page. @@ -226,6 +231,10 @@ pub struct Advisory { /// carries everything). #[serde(default)] pub detailed: bool, + /// The page's issue overview, shortened: what is affected, on which + /// hardware (`runtime_vuln::advisories` reads it for runtime CVEs). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub overview: String, } impl Advisory { @@ -284,6 +293,7 @@ pub struct AlasPage { pub cves: Vec, pub releasever: String, pub fixed: Vec, + pub overview: String, } /// A package's full name (`kernel-6.1.189-236.400.amzn2023.x86_64`) as @@ -348,7 +358,20 @@ pub fn parse_alas_page(html: &str) -> Result { .nth(1) .map(|r| r.split("").next().unwrap_or("")) .unwrap_or(""); + let overview = html + .split("id='issue_overview'") + .nth(1) + .map(|o| o.split("").next().unwrap_or("")) + .map(|o| { + text_of(o) + .trim_start_matches("Issue Overview:") + .trim() + .to_string() + }) + .map(|o| crate::truncate_str(&o, 1500).to_string()) + .unwrap_or_default(); Ok(AlasPage { + overview, id, severity: severity.split_whitespace().next().unwrap_or("").to_string(), released, @@ -367,6 +390,9 @@ impl Advisory { if !p.fixed.is_empty() { self.fixed = p.fixed.clone(); } + if !p.overview.is_empty() { + self.overview = p.overview.clone(); + } for c in &p.cves { if !self.cves.contains(c) { self.cves.push(c.clone()); diff --git a/services/common/src/infra_vuln/inventory.rs b/services/common/src/infra_vuln/inventory.rs index a678c250a..d557258ad 100644 --- a/services/common/src/infra_vuln/inventory.rs +++ b/services/common/src/infra_vuln/inventory.rs @@ -373,6 +373,40 @@ pub struct Versions { pub runtime: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub package_type: String, + /// The instance types that run it (an instance's, a group's, a node + /// group's), and the architecture AWS or the code says. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub instance_types: Vec, + /// `x86_64` or `arm64`, empty when not known. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub arch: String, + /// Installed packages from SSM inventory, `name version-release`, the + /// oldest copy across the group (what a fix must replace). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub packages: Vec, +} + +/// Packages kept per resource. +pub const MAX_PACKAGES: usize = 3_000; + +/// Adds `more` to `into`, keeping per package name the oldest version. +pub fn merge_packages(into: &mut Vec, more: &[String]) { + for p in more { + let (name, ver) = p.split_once(' ').unwrap_or((p.as_str(), "")); + match into + .iter() + .position(|x| x.split_once(' ').map(|(n, _)| n) == Some(name)) + { + Some(i) => { + let old = into[i].split_once(' ').map(|(_, v)| v).unwrap_or(""); + if super::matching::rpm_lt(ver, old) { + into[i] = p.clone(); + } + } + None if into.len() < MAX_PACKAGES => into.push(p.clone()), + None => {} + } + } } /// Whether the internet can reach the resource, and why it was decided. @@ -715,6 +749,7 @@ pub fn lambdas_from_terraform( let runtime = re(r#"(?m)^\s*runtime\s*=\s*"([a-z0-9.]+)""#); let package = re(r#"(?m)^\s*package_type\s*=\s*"([A-Za-z]+)""#); let fname = re(r#"(?m)^\s*function_name\s*=\s*"([^"$]+)""#); + let archs = re(r#"(?m)^\s*architectures\s*=\s*\[\s*"([a-z0-9_]+)""#); let mut out = Vec::new(); let starts: Vec<(usize, String)> = block .captures_iter(content) @@ -749,6 +784,10 @@ pub fn lambdas_from_terraform( versions: Versions { runtime: rt, package_type: pt, + arch: archs + .captures(body) + .map(|c| c[1].to_string()) + .unwrap_or_default(), ..Default::default() }, exposure: Exposure { @@ -786,6 +825,95 @@ pub fn lambdas_from_terraform( out } +/// Lambda functions SAM, CloudFormation, Serverless or CDK code defines, +/// from their runtime declarations (`runtime_vuln::decls`): named by the +/// key that opens their block, placed at the runtime's line. +pub fn lambdas_from_templates( + repo: &str, + path: &str, + content: &str, + account: &str, + region: &str, + now: &str, +) -> Vec { + if path.ends_with(".tf") { + return Vec::new(); + } + let lines: Vec<&str> = content.lines().collect(); + let key = re(r#"^(\s*)"?([A-Za-z][A-Za-z0-9_-]*)"?\s*:\s*\{?\s*$"#); + let mut out = Vec::new(); + for d in crate::runtime_vuln::decls::lambda_runtimes(path, content) { + let at = d.line as usize; + let indent = lines + .get(at.saturating_sub(1)) + .map(|l| l.len() - l.trim_start().len()) + .unwrap_or(0); + // The nearest key above at a smaller indent that is not a property block. + let name = (0..at.saturating_sub(1)) + .rev() + .filter_map(|i| { + key.captures(lines[i]) + .map(|c| (c[1].len(), c[2].to_string())) + }) + .find(|(ind, n)| { + *ind < indent.saturating_sub(2) + && !matches!( + n.as_str(), + "Properties" + | "Globals" + | "Function" + | "provider" + | "functions" + | "Resources" + ) + }) + .map(|(_, n)| n) + .unwrap_or_else(|| format!("{}:{}", path, d.line)); + out.push(Resource { + id: format!("iac:{repo}:{path}:{name}"), + kind: Kind::LambdaFunction, + name: name.clone(), + account: account.into(), + region: region.into(), + group: name.clone(), + versions: Versions { + runtime: d.package.clone(), + package_type: "Zip".into(), + ..Default::default() + }, + exposure: Exposure { + public: false, + why: "Lambda functions have no inbound ports".into(), + }, + defined_in: Some(Location { + repo: repo.into(), + file: path.into(), + address: name, + line: d.line, + how: "search".into(), + tool: String::new(), + confidence: Confidence::Medium, + evidence: vec!["read from the runtime declaration in this file".into()], + edit: Some(Edit { + file: path.into(), + line: d.line, + attribute: "runtime".into(), + value: d.written.clone(), + via: "template".into(), + shared: String::new(), + }), + environment: super::locate::environment_of(&[path]), + ..Default::default() + }), + source: "iac".into(), + seen_at: now.into(), + count: 1, + ..Default::default() + }); + } + out +} + /// Instances that one fix changes together collapse into their group's /// record: one row per launch template or Auto Scaling group, counting /// the instances and keeping the oldest AMI seen (what a fix must replace). @@ -800,6 +928,13 @@ pub fn group_instances(instances: Vec) -> Vec { match by.get_mut(&key) { Some(g) => { g.count += i.count.max(1); + for t in &i.versions.instance_types { + if !g.versions.instance_types.contains(t) { + g.versions.instance_types.push(t.clone()); + } + } + let mut pkgs = std::mem::take(&mut g.versions.packages); + merge_packages(&mut pkgs, &i.versions.packages); g.exposure.public |= i.exposure.public; if i.exposure.public && !g.exposure.why.starts_with("public") { g.exposure.why = i.exposure.why.clone(); @@ -809,9 +944,12 @@ pub fn group_instances(instances: Vec) -> Vec { (None, Some(_)) => true, _ => false, }; + let types = std::mem::take(&mut g.versions.instance_types); if older { g.versions = i.versions.clone(); } + g.versions.packages = pkgs; + g.versions.instance_types = types; for h in i.inspector { if !g .inspector diff --git a/services/common/src/infra_vuln/matching.rs b/services/common/src/infra_vuln/matching.rs index f5f9aee56..558ec00ef 100644 --- a/services/common/src/infra_vuln/matching.rs +++ b/services/common/src/infra_vuln/matching.rs @@ -27,6 +27,8 @@ use super::actions::{self, Meaning, Tie}; use super::feeds::{Advisory, Bulletin, Distro, LatestImage, Runtime, Who}; use super::inventory::{Exposure, Kind, Location, Os, Pending, Resource}; use super::runbook::{self, PrNotes, Runbook}; +use crate::runtime_vuln::advisories::{RuntimeAdvisory, Standing}; +use crate::runtime_vuln::cpu::{self, Holds}; use crate::security_fixes::Tier; /// What kind of fix a finding has. @@ -159,6 +161,22 @@ pub struct InfraFinding { /// `production`, `staging`, ...; empty when not known. #[serde(default, skip_serializing_if = "String::is_empty")] pub environment: String, + /// Whether the hardware the advisories need is what runs it, when + /// every advisory behind the finding names a hardware condition. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hardware: Option, +} + +/// The hardware condition on a finding, as the instance types say. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct HardwareFacts { + pub holds: Holds, + /// Why, in a line per instance type. + pub why: String, + /// What moving it means (to an affected family, when it does not hold + /// now). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub if_moved: String, } /// Amazon Inspector's facts on a finding. @@ -188,6 +206,9 @@ pub struct Feeds<'a> { pub kev: &'a BTreeMap, /// AWS's latest AL2023 AMI per architecture in the resource's region. pub latest_al2023: &'a BTreeMap, + /// Runtime advisories (`runtime_vuln`), for Lambda runtimes and the + /// hardware an advisory needs. + pub runtime: &'a [RuntimeAdvisory], /// YYYY-MM-DD. pub today: &'a str, } @@ -230,6 +251,55 @@ pub fn tier(severity: &str, kev: bool, public: bool) -> Tier { } } +/// Compares RPM `version-release` strings (`21.0.13.0.11-1.amzn2023.1` +/// before `21.0.13.1.2-1.amzn2023.1`): segment by segment, numbers as +/// numbers and words as words, as `rpmvercmp` does; an epoch (`1:`) is +/// dropped. +pub fn rpm_lt(a: &str, b: &str) -> bool { + fn segs(s: &str) -> Vec<(bool, String)> { + let s = match s.split_once(':') { + Some((e, rest)) if e.chars().all(|c| c.is_ascii_digit()) => rest, + _ => s, + }; + let mut out = Vec::new(); + let mut cur = String::new(); + let mut num = false; + for c in s.chars() { + if c.is_ascii_alphanumeric() { + let n = c.is_ascii_digit(); + if !cur.is_empty() && n != num { + out.push((num, std::mem::take(&mut cur))); + } + num = n; + cur.push(c); + } else if !cur.is_empty() { + out.push((num, std::mem::take(&mut cur))); + } + } + if !cur.is_empty() { + out.push((num, cur)); + } + out + } + let (x, y) = (segs(a), segs(b)); + for (p, q) in x.iter().zip(y.iter()) { + let o = match (p.0, q.0) { + (true, true) => { + let (m, n) = (p.1.trim_start_matches('0'), q.1.trim_start_matches('0')); + m.len().cmp(&n.len()).then_with(|| m.cmp(n)) + } + (false, false) => p.1.cmp(&q.1), + // A number is newer than a word. + (true, false) => std::cmp::Ordering::Greater, + (false, true) => std::cmp::Ordering::Less, + }; + if o != std::cmp::Ordering::Equal { + return o == std::cmp::Ordering::Less; + } + } + x.len() < y.len() +} + /// Compares dotted versions (`1.68.1` and `1.67.0`, `2023.12.20261102`). pub fn version_lt(a: &str, b: &str) -> bool { let parts = |s: &str| -> Vec { @@ -366,6 +436,7 @@ fn finding(r: &Resource, key: &str, title: String, hits: Hits, fix: Fix) -> Infr exposure: r.exposure.clone(), fix, inspector: None, + hardware: None, environment: r .defined_in .as_ref() @@ -693,6 +764,7 @@ fn match_lambda(r: &Resource, feeds: &Feeds, out: &mut Vec) { // findings cover it. return; } + lambda_runtime_advisories(r, feeds, out); if let Some(runtime) = feeds.runtimes.iter().find(|x| &x.id == rt) { if runtime.deprecated_at(feeds.today) { let next = feeds @@ -763,6 +835,101 @@ fn match_lambda(r: &Resource, feeds: &Feeds, out: &mut Vec) { } } +/// A Lambda function on a managed runtime whose line a runtime advisory +/// affects (`java21`): AWS ships the fixed build in the managed runtime, so +/// the row is AWS-managed, with how the function's update mode takes it. +fn lambda_runtime_advisories(r: &Resource, feeds: &Feeds, out: &mut Vec) { + let rt = r.versions.runtime.to_ascii_lowercase(); + let Some(line) = rt + .strip_prefix("java") + .map(|l| l.trim_end_matches(".al2").to_string()) + else { + return; + }; + let arch = if r.versions.arch.is_empty() { + "x86_64" + } else { + r.versions.arch.as_str() + }; + // One row per function: every advisory that affects its line. + let mut hits = Hits::new(); + let mut fixed: Vec = Vec::new(); + let mut hardware: Vec = Vec::new(); + for adv in feeds + .runtime + .iter() + .filter(|a| a.runtime == crate::runtime_vuln::Runtime::Java) + { + let (st, l) = crate::runtime_vuln::advisories::standing(adv, &line, false); + if st == Standing::NotAffected { + continue; + } + if let Some(l) = l { + let f = if l.vendor_fixed.is_empty() { + l.fixed.clone() + } else { + l.vendor_fixed.join(", ") + }; + if !f.is_empty() && !fixed.contains(&f) { + fixed.push(f); + } + } + if !adv.hardware.is_empty() { + let (h, why) = cpu::holds( + &adv.hardware, + &cpu::cpu_of("", arch), + &format!("this function ({arch})"), + ); + hardware.push(match h { + Holds::No => format!("{}: {why}.", adv.id), + _ => format!( + "{}: {why}; Lambda does not say which x86 CPU runs a function.", + adv.id + ), + }); + } + hits.add_cves(std::slice::from_ref(&adv.id), feeds.kev); + hits.severity(adv.severity()); + hits.sources.push(Source { + id: adv.id.clone(), + kind: "runtime".into(), + url: adv.url.clone(), + severity: adv.severity().into(), + }); + } + if hits.sources.is_empty() { + return; + } + let n = hits.cves.len(); + out.push(finding( + r, + &format!("aws:runtime:{rt}"), + format!( + "Lambda {} ({rt}): AWS-managed runtime ({n} runtime advisor{})", + r.name, + if n == 1 { "y" } else { "ies" } + ), + hits, + Fix { + kind: Some(FixKind::Aws), + summary: "AWS-managed, nothing to do".into(), + reason: format!( + "AWS patches the {rt} managed runtime{}. A function on the Auto runtime update mode takes it on its own; one set to Function update takes it on its next deploy; one set to Manual stays on its pinned runtime version until that is changed.{}", + if fixed.is_empty() { + String::new() + } else { + format!(" with the fixed build ({})", fixed.join(", ")) + }, + hardware + .iter() + .map(|h| format!(" {h}")) + .collect::() + ), + ..Default::default() + }, + )); +} + /// What a stored pending row means: its own reading, or, for a row saved /// before meanings were kept, what its kind says. fn meaning(r: &Resource, p: &Pending) -> Meaning { @@ -1431,7 +1598,259 @@ pub fn findings(resources: &[Resource], feeds: &Feeds) -> Vec { out } +/// One source package's hits: the advisories, `(binary, installed, fixed)` +/// per package, and the advisory ids. +type PackageHits = (Hits, Vec<(String, String, String)>, Vec); + +/// The installed packages SSM inventory lists, against every Amazon Linux +/// advisory for a package other than the kernel (an AMI's kernel is +/// [`match_ami`]'s): one finding per affected source package, a runbook +/// (packages are updated on the instances, or baked into the next AMI). +fn match_packages(r: &Resource, feeds: &Feeds, out: &mut Vec) { + if r.versions.packages.is_empty() { + return; + } + let installed: BTreeMap<&str, &str> = r + .versions + .packages + .iter() + .filter_map(|p| p.split_once(' ')) + .collect(); + let distro_of = |v: &str| { + if v.contains("amzn2023") { + Some(Distro::Al2023) + } else if v.contains("amzn2") { + Some(Distro::Al2) + } else { + None + } + }; + // Source package to (hits, (binary, installed, fixed), advisory ids). + let mut by: BTreeMap = BTreeMap::new(); + for a in feeds + .advisories + .iter() + .filter(|a| a.distro != Distro::Bottlerocket && !a.is_kernel() && !a.fixed.is_empty()) + { + for p in &a.fixed { + let Some(v) = installed.get(p.name.as_str()) else { + continue; + }; + if distro_of(v) != Some(a.distro) { + continue; + } + let fixed = format!("{}-{}", p.version, p.release); + if !rpm_lt(v, &fixed) { + continue; + } + let e = by + .entry(a.package.clone()) + .or_insert_with(|| (Hits::new(), Vec::new(), Vec::new())); + e.0.advisory(a, feeds.kev); + match e.1.iter_mut().find(|(n, _, _)| n == &p.name) { + Some(x) => { + if rpm_lt(&x.2, &fixed) { + x.2 = fixed; + } + } + None => e.1.push((p.name.clone(), v.to_string(), fixed)), + } + if !e.2.contains(&a.id) { + e.2.push(a.id.clone()); + } + } + } + for (source, (hits, pkgs, ids)) in by { + let al2023 = pkgs.iter().any(|(_, v, _)| v.contains("amzn2023")); + let names: Vec = pkgs.iter().map(|(n, _, _)| n.clone()).collect(); + let from = pkgs + .iter() + .map(|(n, v, _)| format!("{n} {v}")) + .collect::>() + .join(", "); + let to = pkgs + .iter() + .map(|(_, _, f)| f.clone()) + .max_by(|a, b| { + if rpm_lt(a, b) { + std::cmp::Ordering::Less + } else { + std::cmp::Ordering::Greater + } + }) + .unwrap_or_default(); + let mut cli = vec![if al2023 { + format!( + "sudo dnf upgrade -y {}", + ids.iter() + .map(|i| format!("--advisory {i}")) + .collect::>() + .join(" ") + ) + } else { + format!("sudo yum update -y {}", names.join(" ")) + }]; + let jvm = source.starts_with("java-"); + if jvm { + cli.push("Restart every service that runs on this JVM (it keeps the old build in memory until it restarts)".into()); + } + let flags: Vec = feeds + .runtime + .iter() + .filter(|ra| hits.cves.iter().any(|c| c.eq_ignore_ascii_case(&ra.id))) + .flat_map(|ra| ra.mitigations.clone()) + .collect::>() + .into_iter() + .collect(); + let reason = if flags.is_empty() { + String::new() + } else { + format!( + "Until the update runs: start the JVM with {} (for example in JAVA_TOOL_OPTIONS), and remove it once the fixed build runs.", + flags.join(" ") + ) + }; + let what = match r.kind { + Kind::AutoScalingGroup => "the group's instances", + Kind::EksNodegroup => "the node group's nodes", + _ => "the instance", + }; + let fix = Fix { + kind: Some(FixKind::Runbook), + summary: format!("Update {source} to {to} on {what}"), + location: r.defined_in.clone(), + from, + to: to.clone(), + cli, + console: "Systems Manager > Run Command > AWS-RunPatchBaseline (or Patch Manager), or an AMI with the update".into(), + reason, + decision: format!( + "A runbook: an installed package is updated on {what} (or baked into the next AMI it starts from); nothing in infrastructure code pins a package version." + ), + ..Default::default() + }; + out.push(finding( + r, + &format!("pkg:{source}:{to}"), + format!( + "{} {}: {source} {} (fixed in {to})", + r.kind.label(), + r.name, + pkgs.first().map(|(_, v, _)| v.as_str()).unwrap_or("") + ), + hits, + fix, + )); + } +} + +/// When every CVE behind a finding has a runtime advisory that names the +/// hardware it needs: whether the resource's instance types have it. It +/// holds: the top of the finding's exposure (P0 when internet-facing, else +/// at least P1). It does not: P3, with the reason and what moving to an +/// affected family would mean. Not known: the tier stays as matched. +fn apply_hardware(f: &mut InfraFinding, r: &Resource, feeds: &Feeds) { + if f.cves.is_empty() || f.fix.kind == Some(FixKind::Aws) { + return; + } + let advs: Vec<&RuntimeAdvisory> = f + .cves + .iter() + .filter_map(|c| { + feeds + .runtime + .iter() + .find(|a| a.id.eq_ignore_ascii_case(c) && !a.hardware.is_empty()) + }) + .collect(); + if advs.len() != f.cves.len() { + return; + } + let types: Vec = if r.versions.instance_types.is_empty() { + vec![String::new()] + } else { + r.versions.instance_types.clone() + }; + let mut results: Vec<(Holds, String)> = Vec::new(); + for t in &types { + let c = cpu::cpu_of(t, &r.versions.arch); + let label = if t.is_empty() { + "the instance type (not read)".to_string() + } else { + t.clone() + }; + // Holds when any advisory's condition holds. + let mut best = (Holds::No, String::new()); + for a in &advs { + let h = cpu::holds(&a.hardware, &c, &label); + if h.0 == Holds::Yes + || (h.0 == Holds::Unknown && best.0 == Holds::No) + || best.1.is_empty() + { + best = h; + } + } + results.push(best); + } + let holds = if results.iter().any(|(h, _)| *h == Holds::Yes) { + Holds::Yes + } else if results.iter().all(|(h, _)| *h == Holds::No) { + Holds::No + } else { + Holds::Unknown + }; + let why = results + .iter() + .map(|(_, w)| w.clone()) + .collect::>() + .join("; "); + let feature = advs + .iter() + .map(|a| a.hardware.cpu_feature.as_str()) + .find(|f| !f.is_empty()) + .unwrap_or(""); + let if_moved = match holds { + Holds::No if !feature.is_empty() => format!( + "Moving it to {} makes this exploitable: its tier rises when a read sees that.", + cpu::families_with(feature) + ), + Holds::No => { + "Moving it to x86-64 makes this exploitable: its tier rises when a read sees that." + .into() + } + _ => String::new(), + }; + f.tier = match holds { + Holds::Yes => Some(if f.exposure.public { + Tier::P0 + } else { + f.tier.map_or(Tier::P1, |t| t.min(Tier::P1)) + }), + Holds::No => Some(Tier::P3), + Holds::Unknown => f.tier, + }; + f.hardware = Some(HardwareFacts { + holds, + why, + if_moved, + }); +} + fn match_one(r: &Resource, feeds: &Feeds, out: &mut Vec) { + let start = out.len(); + if matches!( + r.kind, + Kind::AutoScalingGroup | Kind::Ec2Instance | Kind::EksNodegroup + ) { + match_packages(r, feeds, out); + } + match_runs(r, feeds, out); + for f in &mut out[start..] { + apply_hardware(f, r, feeds); + } +} + +fn match_runs(r: &Resource, feeds: &Feeds, out: &mut Vec) { { if !r.inspector.is_empty() && matches!( @@ -1545,6 +1964,7 @@ mod tests { latest: &[], kev: &kev, latest_al2023: &raw.latest_al2023, + runtime: &[], today: "2026-11-10", }; findings(&resources, &f) @@ -1704,6 +2124,7 @@ mod tests { latest: &[], kev: &BTreeMap::new(), latest_al2023: &BTreeMap::new(), + runtime: &[], today: "2026-11-12", }, ); @@ -1739,6 +2160,7 @@ mod tests { latest: &[], kev: &kev, latest_al2023: &latest, + runtime: &[], today: "2026-11-10", }, ); @@ -1803,6 +2225,7 @@ mod tests { latest: &[], kev: &kev, latest_al2023: &latest, + runtime: &[], today: "2026-11-10", }, ); @@ -1864,6 +2287,7 @@ mod tests { latest: &[], kev: &kev, latest_al2023: &latest, + runtime: &[], today: "2026-11-10", }, ); @@ -1894,6 +2318,7 @@ mod tests { latest: &[], kev, latest_al2023: latest, + runtime: &[], today: "2026-11-13", } } diff --git a/services/common/src/infra_vuln/raw.rs b/services/common/src/infra_vuln/raw.rs index d1d3064cd..d01b526f4 100644 --- a/services/common/src/infra_vuln/raw.rs +++ b/services/common/src/infra_vuln/raw.rs @@ -20,6 +20,18 @@ pub struct RawInstance { /// Has a public IPv4 address (the address itself isn't kept). pub public_ip: bool, pub tags: Vec<(String, String)>, + /// `m7i.large`, and AWS's `x86_64` or `arm64`. + pub instance_type: String, + pub architecture: String, +} + +/// The packages SSM inventory lists on one instance: `(name, +/// version-release)`, bounded by the read. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct RawPackages { + pub instance: String, + pub packages: Vec<(String, String)>, } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -80,6 +92,8 @@ pub struct RawNodegroup { /// A custom launch template (its AMI is the team's, not EKS's). pub launch_template_id: String, pub tags: Vec<(String, String)>, + /// The node group's instance types. + pub instance_types: Vec, } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -252,6 +266,8 @@ pub struct RawAccount { pub domains: Vec, /// `(instance id, running kernel)` from SSM inventory. pub kernels: Vec<(String, String)>, + /// Every package SSM inventory lists, per instance (bounded). + pub packages: Vec, pub scans: Vec, /// Amazon Inspector's active findings (when the team runs it). pub inspector: Vec, @@ -326,14 +342,34 @@ impl RawAccount { .iter() .map(|(i, k)| (i.as_str(), k.as_str())) .collect(); + let packages: BTreeMap<&str, Vec> = self + .packages + .iter() + .map(|p| { + ( + p.instance.as_str(), + p.packages.iter().map(|(n, v)| format!("{n} {v}")).collect(), + ) + }) + .collect(); let public_tgs = self.public_tgs(); let mut out: Vec = Vec::new(); // EC2: instances, collapsed into their Auto Scaling group. Node // group members are the node group's record. let mut instances = Vec::new(); + // Node group members' packages and types, for their node group. + let mut node_packages: BTreeMap> = BTreeMap::new(); for i in &self.instances { - if tag(&i.tags, "eks:nodegroup-name").is_some() { + if let Some(ng) = tag(&i.tags, "eks:nodegroup-name") { + let e = node_packages.entry(ng).or_default(); + inv::merge_packages( + e, + packages + .get(i.id.as_str()) + .map(Vec::as_slice) + .unwrap_or(&[]), + ); continue; } let asg = tag(&i.tags, "aws:autoscaling:groupName"); @@ -352,6 +388,13 @@ impl RawAccount { .get(i.id.as_str()) .map(|k| k.to_string()) .unwrap_or_default(), + packages: packages.get(i.id.as_str()).cloned().unwrap_or_default(), + instance_types: if i.instance_type.is_empty() { + Vec::new() + } else { + vec![i.instance_type.clone()] + }, + arch: i.architecture.clone(), ..Default::default() }; r.inspector = self @@ -460,6 +503,15 @@ impl RawAccount { date: if date.len() == 8 { date } else { String::new() }, kernel_line: String::new(), }), + instance_types: n.instance_types.clone(), + arch: if n.ami_type.contains("ARM_64") || n.ami_type.contains("arm64") { + "arm64".into() + } else if n.ami_type.contains("x86_64") { + "x86_64".into() + } else { + String::new() + }, + packages: node_packages.get(&n.name).cloned().unwrap_or_default(), ..Default::default() }; if !n.launch_template_id.is_empty() { diff --git a/services/common/src/infra_vuln/store.rs b/services/common/src/infra_vuln/store.rs index bfafdb0e7..d018db184 100644 --- a/services/common/src/infra_vuln/store.rs +++ b/services/common/src/infra_vuln/store.rs @@ -78,6 +78,15 @@ pub async fn bulletins(dynamo: &aws_sdk_dynamodb::Client, table: &str) -> Vec Vec { + all(dynamo, table, crate::runtime_vuln::ADVISORY_PREFIX).await +} + pub async fn runtimes(dynamo: &aws_sdk_dynamodb::Client, table: &str) -> Vec { get(dynamo, table, super::RUNTIMES_SK) .await diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index bdfcb1d20..944f9adde 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -114,6 +114,8 @@ pub mod log_incident; pub mod reachability; /// One repo's reviewer settings: the page's view and the saved item. pub mod review_config; +/// Language runtimes (a JDK, Node.js, Python, Go) against their own advisories. +pub mod runtime_vuln; /// Security fixes: advisories, triage, fix runs and cards (gateway and worker). pub mod security_fixes; pub mod security_release; diff --git a/services/common/src/runtime_vuln/advisories.rs b/services/common/src/runtime_vuln/advisories.rs new file mode 100644 index 000000000..376179884 --- /dev/null +++ b/services/common/src/runtime_vuln/advisories.rs @@ -0,0 +1,612 @@ +//! Runtime advisories: the OpenJDK Vulnerability Group's pages, with what +//! the Amazon Linux advisory for the same CVE and the dated notes add. +//! +//! The OpenJDK page is the source of record for which lines a CVE affects +//! and the last affected build of each ("The affected versions are +//! 27.0.1.0.3, 25.0.5.0.3, 21.0.13.0.3, 17.0.21.0.3, 11.0.33, 8u512, and +//! earlier", then one risk-matrix row per CVE with a bullet under each +//! affected line). It does not say where a line starts being affected, what +//! hardware the flaw needs, or a JVM flag that avoids it: the Amazon Linux +//! advisory's overview often does ("affecting OpenJDK 17.0.6 and later on +//! x86-64 systems ... ARM64 systems are not affected"), and its package list +//! gives a vendor's fixed build. [`NOTES`] holds what no feed carries in a +//! form that can be read, each entry dated and with its source. +//! +//! Every parser answers `Err` when the page no longer looks the way it did: +//! the caller keeps the last good copy. + +use regex::Regex; +use serde::{Deserialize, Serialize}; + +use super::{java_cmp, java_line, java_numbers, Runtime}; +use crate::infra_vuln::feeds::{text_of, Advisory, ParseError}; + +pub const OPENJDK_INDEX: &str = "https://openjdk.org/groups/vulnerability/advisories/"; +/// The feed's status row key, and its host (the self-host docs list it). +pub const FEED: &str = "openjdk"; +pub const HOST: &str = "openjdk.org"; + +pub fn openjdk_page(date: &str) -> String { + format!("{OPENJDK_INDEX}{date}") +} + +fn re(p: &str) -> Regex { + Regex::new(p).expect("a valid pattern") +} + +fn err(m: impl Into) -> Result { + Err(ParseError(m.into())) +} + +/// One affected line of a runtime. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct LineRange { + /// `21`. + pub line: String, + /// The first affected build, empty when the whole line is. + pub introduced: String, + /// The last affected build (`21.0.13.0.3`). + pub last_affected: String, + /// The first fixed upstream build, when a source names it (`21.0.13.1`). + pub fixed: String, + /// Vendors' fixed builds (`corretto 21.0.13.1.2`). + pub vendor_fixed: Vec, +} + +/// What hardware an advisory's flaw needs. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Hardware { + /// Architectures it is exploitable on (`x86_64`); empty when any. + pub arch: Vec, + /// Architectures a source says are not affected (`arm64`). + pub not_arch: Vec, + /// A CPU feature it needs (`avx512_vbmi`), empty when not named. + pub cpu_feature: String, + /// The source's words. + pub words: String, +} + +impl Hardware { + pub fn is_empty(&self) -> bool { + self.arch.is_empty() && self.not_arch.is_empty() && self.cpu_feature.is_empty() + } +} + +/// One runtime CVE. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct RuntimeAdvisory { + /// `CVE-2026-114938`. + pub id: String, + pub runtime: Runtime, + /// `hotspot/compiler`. + pub component: String, + pub cvss: Option, + /// The page's vector shorthand (`NHNNUHHH`). + pub vector: String, + /// YYYY-MM-DD. + pub published: String, + pub url: String, + pub lines: Vec, + pub hardware: Hardware, + /// JVM options that turn the flawed code off until the fix runs. + pub mitigations: Vec, + /// What it is, in a line. + pub summary: String, + /// Every page that said something about it. + pub sources: Vec, +} + +impl RuntimeAdvisory { + pub fn line(&self, line: &str) -> Option<&LineRange> { + self.lines.iter().find(|l| l.line == line) + } + + /// A severity word from the score. + pub fn severity(&self) -> &'static str { + match self.cvss.unwrap_or(5.0) { + s if s >= 9.0 => "critical", + s if s >= 7.0 => "important", + s if s >= 4.0 => "medium", + _ => "low", + } + } +} + +/// The dates of every advisory the index lists, newest first. +pub fn parse_openjdk_index(html: &str) -> Result, ParseError> { + let mut out: Vec = Vec::new(); + for c in re(r#"href="(?:/groups/vulnerability/advisories/)?(\d{4}-\d{2}-\d{2})/?""#) + .captures_iter(html) + { + if !out.contains(&c[1].to_string()) { + out.push(c[1].to_string()); + } + } + if out.is_empty() { + return err( + "OpenJDK advisories: no dated advisory on the index (its format may have changed)", + ); + } + out.sort(); + out.reverse(); + Ok(out) +} + +/// The last affected build of each line from the page's opening sentence +/// (`27.0.1.0.3, ..., 11.0.33, 8u512, and earlier`). +fn last_affected(text: &str) -> Vec<(String, String)> { + let Some(c) = + re(r"(?i)affected versions are (.+?)(?:,?\s+and earlier|\.\s|\.$)").captures(text) + else { + return Vec::new(); + }; + c[1].split(',') + .map(|v| v.trim().trim_start_matches("and ").trim()) + .filter(|v| v.starts_with(|c: char| c.is_ascii_digit())) + .map(|v| (java_line(v), v.to_string())) + .collect() +} + +/// One OpenJDK advisory page: one advisory per CVE in its OpenJDK risk +/// matrix (the OpenJFX matrix is not the runtime's). +pub fn parse_openjdk_page(html: &str, url: &str) -> Result, ParseError> { + let date = re(r"OpenJDK Vulnerability Advisory:\s*(\d{4})/(\d{2})/(\d{2})") + .captures(html) + .map(|c| format!("{}-{}-{}", &c[1], &c[2], &c[3])); + let Some(date) = date else { + return err(format!( + "OpenJDK advisory {url}: no advisory date (its format may have changed)" + )); + }; + let opening = re(r"(?s)

(.*?)

") + .captures(html) + .map(|c| text_of(&c[1])) + .unwrap_or_default(); + let last = last_affected(&opening); + if last.is_empty() { + return err(format!( + "OpenJDK advisory {url}: no affected versions sentence (its format may have changed)" + )); + } + // The OpenJDK matrix: from its heading to the next heading. + let matrix = html + .split_once(r#"id="risk-matrix""#) + .map(|(_, rest)| rest.split("(.*?)"); + let cell_re = re(r"(?s)]*>(.*?)"); + let mut columns: Vec = Vec::new(); + let mut out = Vec::new(); + for r in row_re.captures_iter(matrix) { + let raw: Vec<&str> = cell_re + .captures_iter(&r[1]) + .map(|c| c.get(1).map(|m| m.as_str()).unwrap_or("")) + .collect(); + let cells: Vec = raw.iter().map(|c| text_of(c)).collect(); + if cells.first().is_some_and(|c| c == "CVE ID") { + columns = cells.iter().skip(3).cloned().collect(); + continue; + } + if !cells.first().is_some_and(|c| c.starts_with("CVE-")) || columns.is_empty() { + continue; + } + let (score, vector) = { + let parts: Vec<&str> = raw.get(2).unwrap_or(&"").split("'))) + .unwrap_or_default(); + (score.parse::().ok(), vector) + }; + let mut lines = Vec::new(); + for (i, col) in columns.iter().enumerate() { + let mark = raw.get(3 + i).copied().unwrap_or(""); + if !(mark.contains("•") || mark.contains('\u{2022}')) { + continue; + } + let last_build = last + .iter() + .find(|(l, _)| l == col) + .map(|(_, v)| v.clone()) + .unwrap_or_default(); + lines.push(LineRange { + line: col.clone(), + last_affected: last_build, + ..Default::default() + }); + } + out.push(RuntimeAdvisory { + id: cells[0].clone(), + runtime: Runtime::Java, + component: cells.get(1).cloned().unwrap_or_default().replace("/ ", "/"), + cvss: score, + vector, + published: date.clone(), + url: url.to_string(), + lines, + sources: vec![url.to_string()], + ..Default::default() + }); + } + if out.is_empty() && !matrix.contains("None") { + return err(format!( + "OpenJDK advisory {url}: no risk matrix rows (its format may have changed)" + )); + } + Ok(out) +} + +/// What an Amazon Linux advisory's words and packages add to the runtime +/// advisory for the same CVE: where a line starts being affected, the +/// hardware it needs, JVM flags, and the vendor's fixed builds. +pub fn apply_alas(adv: &mut RuntimeAdvisory, a: &Advisory) { + if !a.cves.iter().any(|c| c.eq_ignore_ascii_case(&adv.id)) { + return; + } + let text = &a.overview; + // "affecting OpenJDK 17.0.6 and later": the first affected build of its line. + for c in re(r"(?i)(?:OpenJDK|JDK|Java)\s+(\d+(?:\.\d+)+)\s+and later").captures_iter(text) { + let v = c[1].to_string(); + if let Some(l) = adv.lines.iter_mut().find(|l| l.line == java_line(&v)) { + if l.introduced.is_empty() { + l.introduced = v; + } + } + } + read_hardware(&mut adv.hardware, text); + for f in flags_in(text) { + if !adv.mitigations.contains(&f) { + adv.mitigations.push(f); + } + } + // `java-21-amazon-corretto` 21.0.13.1.2: Corretto's build is the + // upstream update with one more number (21.0.13.1 + build 2). + for p in &a.fixed { + let Some(c) = re(r"^java-(\d+)-amazon-corretto(?:-headless)?$").captures(&p.name) else { + continue; + }; + let line = c[1].to_string(); + let Some(l) = adv.lines.iter_mut().find(|l| l.line == line) else { + continue; + }; + let vendor = format!("corretto {}", p.version); + if !l.vendor_fixed.contains(&vendor) { + l.vendor_fixed.push(vendor); + } + let n = java_numbers(&p.version); + if n.len() == 5 { + let upstream = n[..4] + .iter() + .map(|x| x.to_string()) + .collect::>() + .join("."); + if l.fixed.is_empty() && java_cmp(&upstream, &l.last_affected).is_gt() { + l.fixed = upstream; + } + } + } + if adv.summary.is_empty() { + if let Some(s) = text + .split_inclusive(". ") + .find(|s| s.to_ascii_lowercase().contains("vulnerab")) + { + adv.summary = crate::truncate_str(s.trim(), 300).to_string(); + } + } + if !a.link.is_empty() && !adv.sources.contains(&a.link) { + adv.sources.push(a.link.clone()); + } +} + +/// Hardware words in an advisory's text. +pub fn read_hardware(h: &mut Hardware, text: &str) { + let l = text.to_ascii_lowercase(); + let mut said = false; + if re(r"(?i)\bon (?:x86-64|x86_64|amd64)\b").is_match(text) + || l.contains("x86-64 only") + || l.contains("x86_64 only") + { + if !h.arch.contains(&"x86_64".to_string()) { + h.arch.push("x86_64".into()); + } + said = true; + } + if re(r"(?i)\b(?:arm64|aarch64)\b[^.]{0,30}\bnot affected").is_match(text) { + if !h.not_arch.contains(&"arm64".to_string()) { + h.not_arch.push("arm64".into()); + } + said = true; + } + if re(r"(?i)avx-?512[ _-]?vbmi").is_match(text) { + h.cpu_feature = "avx512_vbmi".into(); + said = true; + } else if h.cpu_feature.is_empty() && re(r"(?i)avx-?512").is_match(text) { + h.cpu_feature = "avx512".into(); + said = true; + } + if said && h.words.is_empty() { + if let Some(s) = text.split(". ").find(|s| { + let s = s.to_ascii_lowercase(); + s.contains("x86") || s.contains("cpu") || s.contains("avx") + }) { + h.words = crate::truncate_str(s.trim(), 300).to_string(); + } + } +} + +/// JVM options an advisory names (`-XX:-UseBASE64Intrinsics`). +pub fn flags_in(text: &str) -> Vec { + let mut out: Vec = Vec::new(); + for m in re(r"-XX:[-+]?[A-Za-z][A-Za-z0-9_]*(?:=[A-Za-z0-9_]+)?").find_iter(text) { + if !out.contains(&m.as_str().to_string()) { + out.push(m.as_str().to_string()); + } + } + out +} + +/// What no feed carries in a form that can be read, per CVE: dated, with +/// where it was read. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Note { + pub id: String, + /// When this was read (YYYY-MM-DD). + pub as_of: String, + pub source: String, + pub cpu_feature: String, + pub arch: Vec, + pub not_arch: Vec, + /// `(line, first affected build)`. + pub introduced: Vec<(String, String)>, + /// `(line, first fixed upstream build)`. + pub fixed: Vec<(String, String)>, + pub mitigations: Vec, + pub summary: String, +} + +/// The notes, as shipped. +pub const NOTES_JSON: &str = include_str!("notes.json"); + +pub fn notes() -> Vec { + serde_json::from_str(NOTES_JSON).expect("runtime_vuln/notes.json is valid") +} + +/// Applies the notes for this advisory: a feed's own value wins where it +/// has one. +pub fn apply_notes(adv: &mut RuntimeAdvisory, notes: &[Note]) { + for n in notes.iter().filter(|n| n.id.eq_ignore_ascii_case(&adv.id)) { + if (adv.hardware.cpu_feature.is_empty() || adv.hardware.cpu_feature == "avx512") + && !n.cpu_feature.is_empty() + { + adv.hardware.cpu_feature = n.cpu_feature.clone(); + } + for a in &n.arch { + if !adv.hardware.arch.contains(a) { + adv.hardware.arch.push(a.clone()); + } + } + for a in &n.not_arch { + if !adv.hardware.not_arch.contains(a) { + adv.hardware.not_arch.push(a.clone()); + } + } + for (line, v) in &n.introduced { + if let Some(l) = adv.lines.iter_mut().find(|l| &l.line == line) { + if l.introduced.is_empty() { + l.introduced = v.clone(); + } + } + } + for (line, v) in &n.fixed { + if let Some(l) = adv.lines.iter_mut().find(|l| &l.line == line) { + if l.fixed.is_empty() { + l.fixed = v.clone(); + } + } + } + for m in &n.mitigations { + if !adv.mitigations.contains(m) { + adv.mitigations.push(m.clone()); + } + } + if adv.summary.is_empty() { + adv.summary = n.summary.clone(); + } + let src = format!("{} (read {})", n.source, n.as_of); + if !adv.sources.contains(&src) { + adv.sources.push(src); + } + } +} + +/// Every runtime advisory with what the Amazon Linux advisories and the +/// notes add. +pub fn enrich(advs: &mut [RuntimeAdvisory], alas: &[Advisory], notes: &[Note]) { + for adv in advs.iter_mut() { + for a in alas + .iter() + .filter(|a| a.package.starts_with("java-") && a.detailed) + { + apply_alas(adv, a); + } + apply_notes(adv, notes); + } +} + +/// How a version stands against an advisory. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Standing { + /// This build is affected. + Affected, + /// A line or a tag the registry moves: what runs is the newest build + /// when it was built or deployed, and a new build takes the fix. + Floating, + NotAffected, +} + +/// Where an exact build or a line stands. `exact` is false for a line +/// (`21`) or a moving tag; a moving tag at the last affected update +/// (`21.0.13`, republished with each build of that update) is floating. +pub fn standing<'a>( + adv: &'a RuntimeAdvisory, + version: &str, + exact: bool, +) -> (Standing, Option<&'a LineRange>) { + let Some(l) = adv.line(&java_line(version)) else { + return (Standing::NotAffected, None); + }; + if !exact { + return (Standing::Floating, Some(l)); + } + if !l.introduced.is_empty() && java_cmp(version, &l.introduced).is_lt() { + return (Standing::NotAffected, Some(l)); + } + if l.last_affected.is_empty() || !java_cmp(version, &l.last_affected).is_gt() { + return (Standing::Affected, Some(l)); + } + (Standing::NotAffected, Some(l)) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::infra_vuln::feeds::{self, Distro}; + + pub const PAGE: &str = include_str!("testdata/openjdk-2026-11-17.html"); + const INDEX: &str = include_str!("testdata/openjdk-index.html"); + const ALAS_PAGE: &str = include_str!("testdata/alas2023-2026-3479.html"); + const ALAS2_PAGE: &str = include_str!("testdata/alas2-2026-4123.html"); + const RSS: &str = include_str!("testdata/alas2023-java-rss.xml"); + + /// The live advisory of 2026-11-17, read with the Amazon Linux pages + /// and the notes, as the daily read stores it. + pub fn java4shell() -> RuntimeAdvisory { + let advs = parse_openjdk_page(PAGE, &openjdk_page("2026-11-17")).unwrap(); + let mut alas = Vec::new(); + for (html, distro) in [(ALAS_PAGE, Distro::Al2023), (ALAS2_PAGE, Distro::Al2)] { + let p = feeds::parse_alas_page(html).unwrap(); + let mut a = Advisory { + id: p.id.clone(), + distro, + package: if distro == Distro::Al2023 { + "java-21-amazon-corretto".into() + } else { + "java-17-amazon-corretto".into() + }, + link: format!("https://alas.aws.amazon.com/{}.html", p.id), + ..Default::default() + }; + a.apply_page(&p); + alas.push(a); + } + let mut advs = advs; + enrich(&mut advs, &alas, ¬es()); + advs.into_iter() + .find(|a| a.id == "CVE-2026-114938") + .unwrap() + } + + #[test] + fn the_index_lists_the_november_advisory_first() { + let d = parse_openjdk_index(INDEX).unwrap(); + assert_eq!(d[0], "2026-11-17"); + assert!(d.contains(&"2026-10-21".to_string())); + assert!(parse_openjdk_index("Service Unavailable").is_err()); + } + + #[test] + fn the_live_page_names_the_lines_and_last_affected_builds() { + let advs = parse_openjdk_page(PAGE, &openjdk_page("2026-11-17")).unwrap(); + assert_eq!(advs.len(), 10, "OpenJDK rows only, not OpenJFX"); + let a = advs.iter().find(|a| a.id == "CVE-2026-114938").unwrap(); + assert_eq!(a.published, "2026-11-17"); + assert_eq!(a.component, "hotspot/compiler"); + assert_eq!(a.cvss, Some(8.1)); + assert_eq!(a.vector, "NHNNUHHH"); + let lines: Vec<(&str, &str)> = a + .lines + .iter() + .map(|l| (l.line.as_str(), l.last_affected.as_str())) + .collect(); + assert_eq!( + lines, + vec![ + ("17", "17.0.21.0.3"), + ("21", "21.0.13.0.3"), + ("25", "25.0.5.0.3"), + ("27", "27.0.1.0.3") + ], + "8 and 11 are not affected" + ); + // Another row affects 8 and 11 too. + let all = advs.iter().find(|a| a.id == "CVE-2026-114939").unwrap(); + assert_eq!(all.line("8").unwrap().last_affected, "8u512"); + assert_eq!(all.line("11").unwrap().last_affected, "11.0.33"); + assert!(!advs.iter().any(|a| a.id == "CVE-2026-86144"), "OpenJFX"); + } + + #[test] + fn a_page_that_changed_shape_is_an_error() { + assert!(parse_openjdk_page("nope", "u").is_err()); + let no_sentence = PAGE.replace("The affected versions are", "Versions:"); + assert!(parse_openjdk_page(&no_sentence, "u").is_err()); + } + + #[test] + fn amazon_linux_adds_the_start_the_hardware_and_the_fixed_builds() { + let a = java4shell(); + assert_eq!(a.line("17").unwrap().introduced, "17.0.6"); + assert!(a.line("21").unwrap().introduced.is_empty()); + assert_eq!(a.hardware.arch, vec!["x86_64"]); + assert_eq!(a.hardware.not_arch, vec!["arm64"]); + assert_eq!(a.hardware.cpu_feature, "avx512_vbmi", "from the notes"); + assert!(a.hardware.words.contains("x86-64"), "{}", a.hardware.words); + let l21 = a.line("21").unwrap(); + assert_eq!(l21.fixed, "21.0.13.1"); + assert_eq!(l21.vendor_fixed, vec!["corretto 21.0.13.1.2"]); + assert_eq!(a.line("17").unwrap().fixed, "17.0.21.1"); + assert_eq!(a.mitigations, vec!["-XX:-UseBASE64Intrinsics"]); + assert!(a.summary.contains("Base64"), "{}", a.summary); + assert!(a.sources.iter().any(|s| s.contains("ALAS2023-2026-3479"))); + // The feed's own RSS lists the java advisories with the CVE. + let rss = feeds::parse_alas_rss(RSS, Distro::Al2023).unwrap(); + assert!(rss.iter().any(|x| x.package == "java-21-amazon-corretto" + && x.cves.contains(&"CVE-2026-114938".to_string()))); + } + + #[test] + fn builds_stand_where_the_ranges_put_them() { + let a = java4shell(); + let s = |v: &str, exact: bool| standing(&a, v, exact).0; + assert_eq!(s("21.0.12", true), Standing::Affected); + assert_eq!(s("21.0.13.0.3", true), Standing::Affected); + assert_eq!(s("21.0.13.1", true), Standing::NotAffected); + assert_eq!(s("17.0.15", true), Standing::Affected); + assert_eq!(s("17.0.5", true), Standing::NotAffected, "before 17.0.6"); + assert_eq!(s("11.0.25", true), Standing::NotAffected); + assert_eq!(s("8u402", true), Standing::NotAffected); + assert_eq!(s("21", false), Standing::Floating); + assert_eq!(s("11", false), Standing::NotAffected); + } + + #[test] + fn flags_and_hardware_are_read_from_words() { + let mut h = Hardware::default(); + read_hardware( + &mut h, + "Only x86-64 CPUs with AVX-512 VBMI are affected. aarch64 systems are not affected.", + ); + assert_eq!(h.cpu_feature, "avx512_vbmi"); + assert_eq!(h.not_arch, vec!["arm64"]); + assert_eq!( + flags_in("Start the JVM with -XX:-UseBASE64Intrinsics or -XX:UseAVX=2 until patched."), + vec!["-XX:-UseBASE64Intrinsics", "-XX:UseAVX=2"] + ); + } +} diff --git a/services/common/src/runtime_vuln/cpu.rs b/services/common/src/runtime_vuln/cpu.rs new file mode 100644 index 000000000..4924c3947 --- /dev/null +++ b/services/common/src/runtime_vuln/cpu.rs @@ -0,0 +1,287 @@ +//! What an EC2 instance type runs on: its architecture and CPU generation, +//! and whether that CPU has the features an advisory's flaw needs. +//! +//! The family is the part of the type before the dot (`m7i-flex` in +//! `m7i-flex.large`). Graviton families carry a `g` after the generation +//! (`m6g`, `c7gn`, `t4g`, `r8gd`). The x86 families are listed by their +//! processors as AWS documents them; a family not listed is "not known", +//! never guessed. + +use serde::{Deserialize, Serialize}; + +use super::advisories::Hardware; + +/// What runs an instance. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Cpu { + /// `x86_64`, `arm64`, or empty when not known. + pub arch: String, + /// `Intel Ice Lake`, `AMD Zen 4`, `AWS Graviton`; empty when not known. + pub generation: String, + /// AVX-512 VBMI: `None` when the family is not known. + pub avx512_vbmi: Option, + /// Any AVX-512. + pub avx512: Option, +} + +/// x86 families with AVX-512 VBMI: Intel Ice Lake and newer, AMD Zen 4 +/// and newer. +const VBMI: &[(&str, &[&str])] = &[ + ( + "Intel Ice Lake", + &[ + "m6i", "m6id", "m6in", "m6idn", "c6i", "c6id", "c6in", "r6i", "r6id", "r6in", "r6idn", + "i4i", "x2idn", "x2iedn", "trn1", "trn1n", + ], + ), + ( + "Intel Sapphire Rapids", + &[ + "m7i", "m7i-flex", "c7i", "c7i-flex", "r7i", "r7iz", "i7ie", "i7i", "u7i", "u7in", + "u7inh", + ], + ), + ( + "Intel Granite Rapids", + &[ + "m8i", "m8i-flex", "c8i", "c8i-flex", "r8i", "r8i-flex", "x8i", "i8i", + ], + ), + ("AMD Zen 4", &["m7a", "c7a", "r7a", "hpc7a"]), + ("AMD Zen 5", &["m8a", "c8a", "r8a", "hpc8a"]), +]; + +/// x86 families without AVX-512 VBMI. +const NO_VBMI: &[(&str, bool, &[&str])] = &[ + // (generation, has some AVX-512, families) + ( + "Intel Skylake or Cascade Lake", + true, + &[ + "t3", "m5", "m5d", "m5n", "m5dn", "m5zn", "c5", "c5d", "c5n", "r5", "r5d", "r5n", + "r5dn", "r5b", "z1d", "x2iezn", "i3en", "d3", "d3en", "g4dn", "inf1", "p3dn", + ], + ), + ( + "Intel Broadwell or older", + false, + &[ + "t2", "m4", "c4", "r4", "x1", "x1e", "i3", "d2", "h1", "p2", "p3", "g3", "m3", "c3", + "r3", "t1", "m1", "m2", "c1", + ], + ), + ( + "AMD Zen 1 to Zen 3", + false, + &[ + "t3a", "m5a", "c5a", "c5ad", "r5a", "r5ad", "m6a", "c6a", "r6a", "hpc6a", "g4ad", + ], + ), +]; + +/// The family of an instance type (`m7i-flex` in `m7i-flex.large`). +pub fn family(instance_type: &str) -> String { + instance_type + .split('.') + .next() + .unwrap_or("") + .trim() + .to_ascii_lowercase() +} + +fn graviton(f: &str) -> bool { + if f == "a1" { + return true; + } + // A letter or letters, a generation digit, then `g`. + let letters = f.chars().take_while(|c| c.is_ascii_lowercase()).count(); + let rest = &f[letters..]; + let digits = rest.chars().take_while(|c| c.is_ascii_digit()).count(); + letters > 0 && digits > 0 && rest[digits..].starts_with('g') +} + +/// What an instance type runs on. `arch` is what AWS reported for the +/// instance, when known (`DescribeInstances`' architecture). +pub fn cpu_of(instance_type: &str, arch: &str) -> Cpu { + let f = family(instance_type); + if let Some((generation, _)) = VBMI.iter().find(|(_, fs)| fs.contains(&f.as_str())) { + return Cpu { + arch: "x86_64".into(), + generation: generation.to_string(), + avx512_vbmi: Some(true), + avx512: Some(true), + }; + } + if !f.is_empty() && graviton(&f) { + return Cpu { + arch: "arm64".into(), + generation: "AWS Graviton".into(), + avx512_vbmi: Some(false), + avx512: Some(false), + }; + } + if let Some((generation, any, _)) = NO_VBMI.iter().find(|(_, _, fs)| fs.contains(&f.as_str())) { + return Cpu { + arch: "x86_64".into(), + generation: generation.to_string(), + avx512_vbmi: Some(false), + avx512: Some(*any), + }; + } + let arch = match arch { + "arm64" | "aarch64" => "arm64", + "x86_64" | "amd64" => "x86_64", + _ => "", + }; + Cpu { + arch: arch.into(), + avx512_vbmi: (arch == "arm64").then_some(false), + avx512: (arch == "arm64").then_some(false), + ..Default::default() + } +} + +/// Whether an advisory's hardware condition holds. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "snake_case")] +pub enum Holds { + Yes, + No, + #[default] + Unknown, +} + +/// Whether `h` holds on `cpu`, and why, in a line. +pub fn holds(h: &Hardware, cpu: &Cpu, what: &str) -> (Holds, String) { + if h.is_empty() { + return (Holds::Yes, String::new()); + } + let named = if cpu.generation.is_empty() { + what.to_string() + } else { + format!("{what} ({}, {})", cpu.generation, cpu.arch) + }; + if !cpu.arch.is_empty() && h.not_arch.contains(&cpu.arch) { + return ( + Holds::No, + format!( + "{named} is {}; the advisory says {} is not affected", + cpu.arch, cpu.arch + ), + ); + } + if !cpu.arch.is_empty() && !h.arch.is_empty() && !h.arch.contains(&cpu.arch) { + return ( + Holds::No, + format!( + "{named} is {}; the flaw needs {}", + cpu.arch, + h.arch.join(" or ") + ), + ); + } + let feature = match h.cpu_feature.as_str() { + "avx512_vbmi" => cpu.avx512_vbmi, + "avx512" => cpu.avx512, + _ => None, + }; + let feature_name = match h.cpu_feature.as_str() { + "avx512_vbmi" => "AVX-512 VBMI", + "avx512" => "AVX-512", + _ => "", + }; + match (feature_name.is_empty(), feature) { + (true, _) if !cpu.arch.is_empty() => ( + Holds::Yes, + format!("{named} is {}, the architecture the flaw needs", cpu.arch), + ), + (false, Some(true)) => ( + Holds::Yes, + format!("{named} has {feature_name}, which the flaw needs"), + ), + (false, Some(false)) => ( + Holds::No, + format!("{named} has no {feature_name}, which the flaw needs"), + ), + _ => ( + Holds::Unknown, + if feature_name.is_empty() { + format!("CoderHelm does not know what CPU {what} runs on") + } else { + format!("CoderHelm does not know whether {what} has {feature_name}, which the flaw needs") + }, + ), + } +} + +/// The instance families where a `feature` condition holds, for the line +/// that says what moving there means. +pub fn families_with(feature: &str) -> String { + match feature { + "avx512_vbmi" => { + "Intel Ice Lake and newer (m6i, c6i, r6i, m7i, c7i, r7i, m8i ...) and AMD Zen 4 and newer (m7a, c7a, r7a, m8a ...)".into() + } + _ => String::new(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn vbmi() -> Hardware { + Hardware { + arch: vec!["x86_64".into()], + not_arch: vec!["arm64".into()], + cpu_feature: "avx512_vbmi".into(), + words: String::new(), + } + } + + #[test] + fn instance_types_name_their_cpu() { + let c = cpu_of("m7i-flex.large", ""); + assert_eq!((c.arch.as_str(), c.avx512_vbmi), ("x86_64", Some(true))); + assert_eq!(cpu_of("c7a.2xlarge", "").generation, "AMD Zen 4"); + assert_eq!(cpu_of("m6g.large", "").arch, "arm64"); + assert_eq!(cpu_of("c7gn.xlarge", "").arch, "arm64"); + assert_eq!(cpu_of("t4g.micro", "").arch, "arm64"); + assert_eq!(cpu_of("m5.large", "").avx512_vbmi, Some(false)); + assert_eq!(cpu_of("m6a.large", "").avx512, Some(false)); + let unknown = cpu_of("zz9.large", "x86_64"); + assert_eq!( + (unknown.arch.as_str(), unknown.avx512_vbmi), + ("x86_64", None) + ); + assert_eq!(cpu_of("zz9.large", "arm64").avx512_vbmi, Some(false)); + } + + #[test] + fn the_hardware_condition_holds_only_on_vbmi_x86() { + let h = vbmi(); + assert_eq!( + holds(&h, &cpu_of("m7i.large", ""), "m7i.large").0, + Holds::Yes + ); + assert_eq!( + holds(&h, &cpu_of("m6i.large", ""), "m6i.large").0, + Holds::Yes + ); + let (no, why) = holds(&h, &cpu_of("m6g.large", ""), "m6g.large"); + assert_eq!(no, Holds::No); + assert!(why.contains("arm64"), "{why}"); + let (no, why) = holds(&h, &cpu_of("m5.large", ""), "m5.large"); + assert_eq!(no, Holds::No); + assert!(why.contains("no AVX-512 VBMI"), "{why}"); + assert_eq!( + holds(&h, &cpu_of("zz9.large", "x86_64"), "zz9.large").0, + Holds::Unknown + ); + // No condition: it holds everywhere. + assert_eq!( + holds(&Hardware::default(), &Cpu::default(), "x").0, + Holds::Yes + ); + } +} diff --git a/services/common/src/runtime_vuln/decls.rs b/services/common/src/runtime_vuln/decls.rs new file mode 100644 index 000000000..481e2ea1b --- /dev/null +++ b/services/common/src/runtime_vuln/decls.rs @@ -0,0 +1,672 @@ +//! Where a repository's code says which runtime runs, and how precisely. +//! +//! | Where | Example | Precision | +//! |---|---|---| +//! | Dockerfile `FROM` | `eclipse-temurin:21.0.4_7-jre`, `amazoncorretto:21` | the tag's | +//! | Version file | `.java-version`, `.sdkmanrc`, `.tool-versions`, `.nvmrc`, `.python-version`, `go.mod` `toolchain` | the value's | +//! | Build toolchain | Gradle `JavaLanguageVersion.of(21)`, `jvmToolchain(21)` | a line | +//! | Build target | Maven `maven.compiler.release`, `java.version`; Gradle `sourceCompatibility` | a line | +//! | CI setup | `actions/setup-java` `java-version: '21'` (and node, python, go) | the value's | +//! | Lambda runtime | Terraform `runtime = "java21"`, SAM/CloudFormation `Runtime: java21`, Serverless `runtime: java21`, CDK `Runtime.JAVA_21` | a line AWS manages | +//! +//! A value with a patch number and a build (`21.0.4_7`, `21.0.4+7`) or +//! more is exact. A line (`21`, `21-jre`, a toolchain) takes whatever build +//! is newest when the image is built or the job runs: a rebuild takes a +//! fix. Values from variables (`${JAVA_VERSION}`, `${{ matrix.java }}`) +//! are not read. + +use regex::Regex; +use serde::{Deserialize, Serialize}; + +use super::{java_numbers, Runtime}; + +/// What kind of place declares it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "snake_case")] +pub enum DeclKind { + #[default] + Image, + VersionFile, + Toolchain, + BuildTarget, + Ci, + Lambda, +} + +impl DeclKind { + pub fn label(self) -> &'static str { + match self { + DeclKind::Image => "base image", + DeclKind::VersionFile => "version file", + DeclKind::Toolchain => "build toolchain", + DeclKind::BuildTarget => "build target", + DeclKind::Ci => "CI setup step", + DeclKind::Lambda => "Lambda runtime", + } + } +} + +/// One declaration of a runtime in code. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Decl { + pub runtime: Runtime, + pub kind: DeclKind, + pub file: String, + /// 1-based. + pub line: u32, + /// The image's name as written, or the runtime's name. + pub package: String, + /// What a fix edits, as written: the tag, or the value. + pub written: String, + /// The runtime version it reads as (`21.0.4_7`, `21`). + pub version: String, + /// An exact build (else a line, or a tag the registry moves). + pub exact: bool, + /// `temurin`, `corretto`, `zulu`, ...; empty when not said. + pub vendor: String, + /// `linux/arm64` from `FROM --platform=`, empty when not said. + pub platform: String, +} + +impl Decl { + /// The dependency row it is kept as (`security_fixes::Dep`), so the + /// repository's inventory lists it. + pub fn to_dep(&self) -> crate::security_fixes::Dep { + crate::security_fixes::Dep { + ecosystem: super::ECOSYSTEM.into(), + name: self.package.clone(), + version: self.written.clone(), + manifest: self.file.clone(), + scope: crate::security_fixes::Scope::Runtime, + path: vec![format!( + "{DEP_TAG}{}", + serde_json::to_string(self).unwrap_or_default() + )], + } + } + + pub fn from_dep(d: &crate::security_fixes::Dep) -> Option { + if d.ecosystem != super::ECOSYSTEM { + return None; + } + d.path + .first() + .and_then(|p| p.strip_prefix(DEP_TAG)) + .and_then(|j| serde_json::from_str(j).ok()) + } + + /// Where it is, in words (`Dockerfile line 3, base image eclipse-temurin:21-jre`). + pub fn describe(&self) -> String { + let what = match self.kind { + DeclKind::Image => format!("{}:{}", self.package, self.written), + _ => self.written.clone(), + }; + format!( + "`{}` line {}, {} `{what}`", + self.file, + self.line, + self.kind.label() + ) + } +} + +const DEP_TAG: &str = "runtime-decl:"; + +fn re(p: &str) -> Regex { + Regex::new(p).expect("a valid pattern") +} + +fn line_at(text: &str, byte: usize) -> u32 { + text[..byte.min(text.len())].matches('\n').count() as u32 + 1 +} + +/// Exact when it has a patch number and a build, or more numbers +/// (`21.0.4_7`, `21.0.4+7`, `21.0.13.1`); `21.0.4` is exact too (a tag +/// that names a patch update), except where the findings say a registry +/// moves it. +fn java_exact(v: &str) -> bool { + java_numbers(v).len() >= 3 +} + +fn plain_exact(v: &str) -> bool { + v.trim_start_matches(|c: char| !c.is_ascii_digit()) + .split(|c: char| !(c.is_ascii_digit() || c == '.')) + .next() + .unwrap_or("") + .split('.') + .filter(|p| !p.is_empty()) + .count() + >= 3 +} + +/// The runtime an image runs, its version as the tag or name says, and the +/// vendor: `(runtime, version, vendor)`. +pub fn image_runtime(name: &str, tag: &str) -> Option<(Runtime, String, String)> { + let n = name.to_ascii_lowercase(); + let short = n.rsplit('/').next().unwrap_or(&n).to_string(); + let t = tag.to_ascii_lowercase(); + let lead = |s: &str| -> String { + re(r"^(?:open-|certified-|jdk-?|jre-?)?(\d+(?:\.\d+)*(?:[_+]\d+)?)") + .captures(s) + .map(|c| c[1].to_string()) + .unwrap_or_default() + }; + let java_vendor = match short.as_str() { + "eclipse-temurin" => Some("temurin"), + "openjdk" => Some("openjdk"), + "amazoncorretto" => Some("corretto"), + "ibm-semeru-runtimes" => Some("semeru"), + "sapmachine" => Some("sapmachine"), + s if s.starts_with("zulu-openjdk") => Some("zulu"), + s if s.starts_with("liberica-") => Some("liberica"), + "jdk" | "jre" if n.contains("microsoft") => Some("microsoft"), + _ => None, + }; + if let Some(vendor) = java_vendor { + let v = lead(&t); + return (!v.is_empty()).then(|| (Runtime::Java, v, vendor.to_string())); + } + // A line in the name: `ubi9/openjdk-21`, `distroless/java21-debian12`. + if let Some(c) = re(r"(?:^|/)(?:openjdk-|java)(\d{1,2})(?:-|$)").captures(&n) { + return Some((Runtime::Java, c[1].to_string(), String::new())); + } + // Build and server images that carry a JDK line in the tag: + // `gradle:8.10-jdk21`, `maven:3.9-eclipse-temurin-21`, `tomcat:10.1-jdk21-temurin`. + if matches!( + short.as_str(), + "gradle" | "maven" | "tomcat" | "jetty" | "sbt" | "clojure" | "groovy" + ) { + if let Some(c) = re( + r"(?:jdk|jre|temurin-|corretto-|openjdk-|zulu-|sapmachine-|graalvm-community-)(\d{1,2})(?:\b|$|-)", + ) + .captures(&t) + { + return Some((Runtime::Java, c[1].to_string(), String::new())); + } + return None; + } + let other = match short.as_str() { + "node" => Some(Runtime::Node), + "python" => Some(Runtime::Python), + "golang" => Some(Runtime::Go), + _ => None, + }?; + let v = lead(&t); + (!v.is_empty()).then(|| (other, v, String::new())) +} + +/// The runtimes a Dockerfile's `FROM` lines name. +pub fn from_dockerfile(path: &str, text: &str) -> Vec { + let from = re(r"(?im)^\s*FROM\s+((?:--\S+\s+)*)(\S+)"); + let mut out = Vec::new(); + for c in from.captures_iter(text) { + let image = &c[2]; + if image.contains('$') { + continue; + } + let platform = re(r"--platform=(\S+)") + .captures(&c[1]) + .map(|p| p[1].to_string()) + .unwrap_or_default(); + let (name, tag) = match image.split_once('@') { + Some((n, _)) => match n.rsplit_once(':') { + Some((nn, t)) if !t.contains('/') => (nn.to_string(), t.to_string()), + _ => (n.to_string(), "latest".to_string()), + }, + None => match image.rsplit_once(':') { + Some((n, t)) if !t.contains('/') => (n.to_string(), t.to_string()), + _ => (image.to_string(), "latest".to_string()), + }, + }; + let Some((runtime, version, vendor)) = image_runtime(&name, &tag) else { + continue; + }; + let line = line_at(text, c.get(2).map(|m| m.start()).unwrap_or(0)); + let exact = match runtime { + Runtime::Java => java_exact(&version) && !tag_names_line_only(&tag, &version), + _ => plain_exact(&version), + }; + out.push(Decl { + runtime, + kind: DeclKind::Image, + file: path.into(), + line, + package: name, + written: tag.clone(), + version, + exact, + vendor, + platform, + }); + } + out +} + +/// A tag whose version came from a JDK line in a build image's tag +/// (`gradle:8.10-jdk21`): never exact. +fn tag_names_line_only(tag: &str, version: &str) -> bool { + !tag.to_ascii_lowercase() + .starts_with(|c: char| c.is_ascii_digit()) + && !tag.to_ascii_lowercase().starts_with("open-") + && !tag.to_ascii_lowercase().starts_with("certified-") + && version.len() <= 2 +} + +fn runtime_of_tool(tool: &str) -> Option { + match tool.to_ascii_lowercase().as_str() { + "java" => Some(Runtime::Java), + "nodejs" | "node" => Some(Runtime::Node), + "python" => Some(Runtime::Python), + "golang" | "go" => Some(Runtime::Go), + _ => None, + } +} + +fn vendor_of(v: &str) -> String { + let l = v.to_ascii_lowercase(); + for (w, name) in [ + ("temurin", "temurin"), + ("-tem", "temurin"), + ("corretto", "corretto"), + ("-amzn", "corretto"), + ("zulu", "zulu"), + ("-zulu", "zulu"), + ("liberica", "liberica"), + ("-librca", "liberica"), + ("semeru", "semeru"), + ("-sem", "semeru"), + ("sapmachine", "sapmachine"), + ("-sapmchn", "sapmachine"), + ("graalvm", "graalvm"), + ("-graal", "graalvm"), + ("oracle", "oracle"), + ("-oracle", "oracle"), + ("-ms", "microsoft"), + ("microsoft", "microsoft"), + ] { + if l.contains(w) { + return name.to_string(); + } + } + String::new() +} + +fn value_decl(runtime: Runtime, kind: DeclKind, path: &str, line: u32, value: &str) -> Decl { + let exact = match runtime { + Runtime::Java => java_exact(value), + _ => plain_exact(value), + }; + Decl { + runtime, + kind, + file: path.into(), + line, + package: runtime.name().into(), + written: value.to_string(), + version: value.to_string(), + exact, + vendor: if runtime == Runtime::Java { + vendor_of(value) + } else { + String::new() + }, + platform: String::new(), + } +} + +fn base(path: &str) -> String { + path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase() +} + +/// Whether a file may declare a runtime (Dockerfiles are read for their +/// base images already). +pub fn is_runtime_file(path: &str) -> bool { + let b = base(path); + let p = path.to_ascii_lowercase(); + matches!( + b.as_str(), + ".java-version" + | ".sdkmanrc" + | ".tool-versions" + | ".nvmrc" + | ".node-version" + | ".python-version" + | "go.mod" + | "pom.xml" + | "build.gradle" + | "build.gradle.kts" + | "template.yaml" + | "template.yml" + | "serverless.yml" + | "serverless.yaml" + ) || (p.starts_with(".github/workflows/") && (b.ends_with(".yml") || b.ends_with(".yaml"))) + || b.ends_with(".tf") + || b.ends_with(".template.json") + || b.ends_with(".template.yaml") +} + +/// The runtimes one file declares (not a Dockerfile's: [`from_dockerfile`]). +pub fn from_file(path: &str, text: &str) -> Vec { + let b = base(path); + let mut out = Vec::new(); + let first_value = || -> Option<(u32, String)> { + text.lines() + .enumerate() + .map(|(i, l)| (i as u32 + 1, l.trim())) + .find(|(_, l)| !l.is_empty() && !l.starts_with('#')) + .map(|(i, l)| (i, l.split_whitespace().next().unwrap_or("").to_string())) + }; + match b.as_str() { + ".java-version" | ".nvmrc" | ".node-version" | ".python-version" => { + let rt = match b.as_str() { + ".java-version" => Runtime::Java, + ".python-version" => Runtime::Python, + _ => Runtime::Node, + }; + if let Some((line, v)) = first_value() { + if v.chars().any(|c| c.is_ascii_digit()) { + out.push(value_decl(rt, DeclKind::VersionFile, path, line, &v)); + } + } + } + ".sdkmanrc" => { + for (i, l) in text.lines().enumerate() { + if let Some(v) = l.trim().strip_prefix("java=") { + out.push(value_decl( + Runtime::Java, + DeclKind::VersionFile, + path, + i as u32 + 1, + v.trim(), + )); + } + } + } + ".tool-versions" => { + for (i, l) in text.lines().enumerate() { + let w: Vec<&str> = l.split_whitespace().collect(); + if let (Some(tool), Some(v)) = (w.first(), w.get(1)) { + if let Some(rt) = runtime_of_tool(tool) { + out.push(value_decl(rt, DeclKind::VersionFile, path, i as u32 + 1, v)); + } + } + } + } + "go.mod" => { + for (i, l) in text.lines().enumerate() { + if let Some(v) = l.trim().strip_prefix("toolchain go") { + out.push(value_decl( + Runtime::Go, + DeclKind::Toolchain, + path, + i as u32 + 1, + v.trim(), + )); + } + } + } + "pom.xml" => { + let r = re( + r"<(maven\.compiler\.release|java\.version|maven\.compiler\.target|release)>\s*(\d{1,2}|1\.8)\s* { + let tool = re(r"(?:JavaLanguageVersion\.of|jvmToolchain)\s*\(\s*(\d{1,2})\s*\)"); + for c in tool.captures_iter(text) { + let line = line_at(text, c.get(1).unwrap().start()); + out.push(value_decl( + Runtime::Java, + DeclKind::Toolchain, + path, + line, + &c[1], + )); + } + if out.is_empty() { + let target = re( + r#"(?:source|target)Compatibility\s*=?\s*(?:JavaVersion\.VERSION_(\d{1,2})|['"]?(\d{1,2})['"]?)"#, + ); + if let Some(c) = target.captures(text) { + let v = c.get(1).or(c.get(2)).unwrap(); + let line = line_at(text, v.start()); + out.push(value_decl( + Runtime::Java, + DeclKind::BuildTarget, + path, + line, + v.as_str(), + )); + } + } + } + _ => {} + } + let p = path.to_ascii_lowercase(); + if p.starts_with(".github/workflows/") { + let r = re( + r#"(?m)^\s*(java|node|python|go)-version:\s*(\[[^\]\n]*\]|['"]?[0-9][0-9A-Za-z.+_-]*['"]?)"#, + ); + for c in r.captures_iter(text) { + let rt = runtime_of_tool(&c[1]).unwrap_or(Runtime::Java); + let raw = c.get(2).unwrap(); + for v in raw + .as_str() + .trim_matches(|c| c == '[' || c == ']') + .split(',') + .map(|v| v.trim().trim_matches(|c| c == '\'' || c == '"')) + .filter(|v| v.starts_with(|c: char| c.is_ascii_digit())) + { + let line = line_at(text, raw.start()); + out.push(value_decl(rt, DeclKind::Ci, path, line, v)); + } + } + } + out.extend(lambda_runtimes(path, text)); + out +} + +/// Lambda runtimes in infrastructure code, as lines AWS manages. +pub fn lambda_runtimes(path: &str, text: &str) -> Vec { + let b = base(path); + let iac = b.ends_with(".tf") + || b.ends_with(".yml") + || b.ends_with(".yaml") + || b.ends_with(".json") + || b.ends_with(".ts") + || b.ends_with(".py"); + if !iac { + return Vec::new(); + } + let r = re( + r#"(?m)(?:\bruntime\s*=\s*"|\bRuntime"?\s*:\s*"?|\bruntime:\s*"?|Runtime\.)(java\d+(?:\.al2)?|JAVA_\d+|nodejs\d+\.x|NODEJS_\d+_X|python3\.\d+|PYTHON_3_\d+)"#, + ); + let mut out = Vec::new(); + for c in r.captures_iter(text) { + let m = c.get(1).unwrap(); + let id = lambda_id(m.as_str()); + let (rt, line) = match id.as_str() { + s if s.starts_with("java") => ( + Runtime::Java, + s.trim_start_matches("java") + .trim_end_matches(".al2") + .to_string(), + ), + s if s.starts_with("nodejs") => ( + Runtime::Node, + s.trim_start_matches("nodejs") + .trim_end_matches(".x") + .to_string(), + ), + s => (Runtime::Python, s.trim_start_matches("python").to_string()), + }; + out.push(Decl { + runtime: rt, + kind: DeclKind::Lambda, + file: path.into(), + line: line_at(text, m.start()), + package: id.clone(), + written: m.as_str().to_string(), + version: line, + exact: false, + vendor: if rt == Runtime::Java { + "corretto".into() + } else { + String::new() + }, + platform: String::new(), + }); + } + out +} + +/// A CDK runtime constant as Lambda's id (`JAVA_21` is `java21`). +fn lambda_id(s: &str) -> String { + let l = s.to_ascii_lowercase(); + if let Some(n) = l.strip_prefix("java_") { + return format!("java{n}"); + } + if let Some(n) = l.strip_prefix("nodejs_") { + return format!("nodejs{}.x", n.trim_end_matches("_x")); + } + if let Some(n) = l.strip_prefix("python_3_") { + return format!("python3.{n}"); + } + l +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn jdk_images_say_their_build_or_line() { + let df = "FROM eclipse-temurin:21.0.4_7-jre AS run\nFROM --platform=linux/arm64 amazoncorretto:21-al2023-headless\nFROM gradle:8.10-jdk21 AS build\nFROM maven:3.9-eclipse-temurin-17\nFROM gcr.io/distroless/java21-debian12\nFROM node:20.11.0-alpine\nFROM debian:12-slim\nFROM ${BASE}\n"; + let d = from_dockerfile("Dockerfile", df); + let got: Vec<(&str, &str, bool, u32)> = d + .iter() + .map(|x| (x.package.as_str(), x.version.as_str(), x.exact, x.line)) + .collect(); + assert_eq!( + got, + vec![ + ("eclipse-temurin", "21.0.4_7", true, 1), + ("amazoncorretto", "21", false, 2), + ("gradle", "21", false, 3), + ("maven", "17", false, 4), + ("gcr.io/distroless/java21-debian12", "21", false, 5), + ("node", "20.11.0", true, 6), + ] + ); + assert_eq!(d[1].platform, "linux/arm64"); + assert_eq!(d[0].vendor, "temurin"); + assert_eq!(d[0].written, "21.0.4_7-jre"); + assert_eq!(d[0].runtime, Runtime::Java); + assert_eq!(d[5].runtime, Runtime::Node); + } + + #[test] + fn version_files_toolchains_and_ci_steps() { + let j = from_file(".java-version", "17.0.15\n"); + assert_eq!((j[0].version.as_str(), j[0].exact), ("17.0.15", true)); + let s = from_file(".sdkmanrc", "# sdk\njava=21.0.4-tem\n"); + assert_eq!((s[0].line, s[0].vendor.as_str()), (2, "temurin")); + let t = from_file( + ".tool-versions", + "java temurin-21.0.4+7.0.LTS\nnodejs 20.11.0\n", + ); + assert_eq!(t.len(), 2); + assert_eq!(t[1].runtime, Runtime::Node); + let g = from_file( + "build.gradle.kts", + "java {\n toolchain {\n languageVersion = JavaLanguageVersion.of(21)\n }\n}\n", + ); + assert_eq!( + (g[0].kind, g[0].version.as_str(), g[0].exact, g[0].line), + (DeclKind::Toolchain, "21", false, 3) + ); + let pom = from_file( + "pom.xml", + "\n 21\n", + ); + assert_eq!((pom[0].kind, pom[0].line), (DeclKind::BuildTarget, 2)); + let ci = from_file( + ".github/workflows/ci.yml", + "steps:\n - uses: actions/setup-java@v4\n with:\n distribution: temurin\n java-version: '21'\n - uses: actions/setup-node@v4\n with:\n node-version: [18, 20]\n", + ); + let got: Vec<(Runtime, &str, u32)> = ci + .iter() + .map(|x| (x.runtime, x.version.as_str(), x.line)) + .collect(); + assert_eq!( + got, + vec![ + (Runtime::Java, "21", 5), + (Runtime::Node, "18", 8), + (Runtime::Node, "20", 8) + ] + ); + assert!(from_file( + ".github/workflows/ci.yml", + "java-version: ${{ matrix.java }}\n" + ) + .is_empty()); + } + + #[test] + fn lambda_runtimes_in_every_tool() { + let tf = from_file( + "infra/lambda.tf", + "resource \"aws_lambda_function\" \"x\" {\n runtime = \"java21\"\n}\n", + ); + assert_eq!( + ( + tf[0].kind, + tf[0].package.as_str(), + tf[0].version.as_str(), + tf[0].line + ), + (DeclKind::Lambda, "java21", "21", 2) + ); + let sam = from_file("template.yaml", "Resources:\n Fn:\n Type: AWS::Serverless::Function\n Properties:\n Runtime: java17\n"); + assert_eq!(sam[0].package, "java17"); + let cdk = lambda_runtimes("infra/stack.ts", "runtime: lambda.Runtime.JAVA_21,"); + assert_eq!(cdk[0].package, "java21"); + let node = from_file("serverless.yml", "provider:\n runtime: nodejs20.x\n"); + assert_eq!( + (node[0].runtime, node[0].version.as_str()), + (Runtime::Node, "20") + ); + } + + #[test] + fn a_declaration_round_trips_through_the_dependency_list() { + let d = &from_dockerfile("svc/Dockerfile", "FROM eclipse-temurin:21-jre\n")[0]; + let dep = d.to_dep(); + assert_eq!(dep.ecosystem, "runtime"); + assert_eq!( + (dep.name.as_str(), dep.version.as_str()), + ("eclipse-temurin", "21-jre") + ); + assert_eq!(Decl::from_dep(&dep).as_ref(), Some(d)); + assert!(is_runtime_file(".github/workflows/build.yaml")); + assert!(is_runtime_file("api/.java-version")); + assert!(!is_runtime_file("src/main/App.java")); + } +} diff --git a/services/common/src/runtime_vuln/findings.rs b/services/common/src/runtime_vuln/findings.rs new file mode 100644 index 000000000..04c5e2c60 --- /dev/null +++ b/services/common/src/runtime_vuln/findings.rs @@ -0,0 +1,727 @@ +//! A repository's runtime declarations against the runtime advisories, as +//! dependency findings (`security_fixes`) of the [`super::ECOSYSTEM`] +//! ecosystem, so they take the same tiers, cards, fix runs and pull +//! requests. +//! +//! - One finding per declaration and CVE: package = the image's name (or +//! the runtime's), version = the tag or value as written, manifest = the +//! file. +//! - An exact build that is affected gets a pull request when a fixed build +//! is known in the same form: for an image, a published tag of the same +//! variant past the last affected build ([`fixed_tag`], from the +//! registry's tag list); for a version file or a CI pin, the upstream fix +//! (or the vendor's fixed build, when the advisory names the vendor's). +//! - A line, a floating tag (`21-jre`), or a tag the registry republishes +//! for each build of an update (`amazoncorretto:21.0.13`) takes the fix +//! on its next build: no pull request; the finding says to rebuild and +//! redeploy, or to pin a fixed build. +//! - Every finding names the advisory's hardware condition and its JVM flag +//! for the time until the fix runs. An image built only for an +//! architecture the advisory says is not affected stays a finding, with +//! that reason and the lowest tier ([`Verdict::NotReachable`]). +//! - Lambda runtimes are the infrastructure findings' (AWS patches them). + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; + +use super::advisories::{standing, LineRange, RuntimeAdvisory, Standing}; +use super::decls::{Decl, DeclKind}; +use super::{java_cmp, java_numbers, Runtime}; +use crate::security_fixes::{ + self as sec, AdvisoryRecord, Evidence, Finding, FindingState, FixUnit, Observation, Relation, + Scope, Status, Verdict, +}; + +/// Why a runtime finding has no code verdict. +pub const NOT_CODE: &str = "a runtime's own flaw: what runs it decides, not a call in the code"; + +/// What one read of a repository's runtime declarations found, for +/// closing findings the code no longer has. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Read { + /// Files read in full this time. + pub files: BTreeSet, + /// `(manifest, package, written)` to the advisory ids it is affected by. + pub seen: BTreeMap<(String, String, String), BTreeSet>, +} + +/// A tag the registry republishes for each build of an update: three +/// numbers, no build, at the update the advisory's last affected build is +/// on (`21.0.13` while the last affected build is `21.0.13.0.3`). +fn moving_tag(d: &Decl, l: &LineRange) -> bool { + if d.kind != DeclKind::Image || d.version.contains(['_', '+']) { + return false; + } + let v = java_numbers(&d.version); + let last = java_numbers(&l.last_affected); + v.len() == 3 && last.len() > 3 && last[..3] == v[..] +} + +/// The newest-variant-preserving fixed tag: the lowest published tag with +/// the same shape (`21.0.4_7-jre` keeps `_N-jre`) on the same line, past +/// the last affected build. +pub fn fixed_tag(current: &str, tags: &[String], l: &LineRange) -> Option { + let shape = |t: &str| -> Option<(Vec, String)> { + let lead: String = t + .chars() + .take_while(|c| c.is_ascii_digit() || matches!(c, '.' | '_' | '+')) + .collect(); + if lead.is_empty() { + return None; + } + let suffix = t[lead.len()..].to_string(); + let build = lead.contains(['_', '+']); + let mut n = java_numbers(&lead); + if build { + // Keep the build as a last number so `_9` sorts after `_7`. + let b: u64 = lead + .rsplit(['_', '+']) + .next() + .and_then(|x| x.parse().ok()) + .unwrap_or(0); + n.push(b); + } + Some((n, format!("{}|{suffix}", if build { "b" } else { "" }))) + }; + let (_, want) = shape(current)?; + let line = &l.line; + let mut best: Option<(Vec, String)> = None; + for t in tags { + let Some((n, s)) = shape(t) else { continue }; + if s != want || n.first().map(|x| x.to_string()).as_deref() != Some(line.as_str()) { + continue; + } + let lead: String = t + .chars() + .take_while(|c| c.is_ascii_digit() || c == &'.') + .collect(); + if !java_cmp(&lead, &l.last_affected).is_gt() { + continue; + } + if !l.introduced.is_empty() && java_cmp(&lead, &l.introduced).is_lt() { + continue; + } + if best.as_ref().is_none_or(|(b, _)| n < *b) { + best = Some((n, t.clone())); + } + } + best.map(|(_, t)| t) +} + +/// The fixed value for a version file or CI pin, written the way the file +/// writes it, when one is known for its vendor. +fn fixed_value(d: &Decl, l: &LineRange) -> Option { + let numbers_at = d.written.find(|c: char| c.is_ascii_digit())?; + let rest = &d.written[numbers_at..]; + let numeric_len = rest + .find(|c: char| !(c.is_ascii_digit() || c == '.')) + .unwrap_or(rest.len()); + let prefix = &d.written[..numbers_at]; + let to = match d.vendor.as_str() { + "" | "openjdk" => { + // A plain version (`17.0.15`): the upstream fix, nothing after it. + if !prefix.is_empty() || numeric_len != rest.len() { + return None; + } + l.fixed.clone() + } + "corretto" => l + .vendor_fixed + .iter() + .find_map(|v| v.strip_prefix("corretto ")) + .map(|v| format!("{prefix}{v}"))?, + // A vendor whose fixed build no source names yet. + _ => return None, + }; + (!to.is_empty()).then_some(to) +} + +fn hardware_lines(adv: &RuntimeAdvisory) -> Vec { + let mut out = Vec::new(); + let h = &adv.hardware; + if !h.is_empty() { + let mut s = String::from("Hardware: exploitable only on "); + s.push_str(if h.arch.is_empty() { + "CPUs" + } else { + "x86-64 CPUs" + }); + if h.cpu_feature == "avx512_vbmi" { + s.push_str(&format!( + " with AVX-512 VBMI ({})", + super::cpu::families_with("avx512_vbmi") + )); + } + if !h.not_arch.is_empty() { + s.push_str(&format!("; {} is not affected", h.not_arch.join(", "))); + } + out.push(s); + } + if !adv.mitigations.is_empty() { + out.push(format!( + "Until the fix runs: start the JVM with {} (for example in JAVA_TOOL_OPTIONS), then remove it once the fixed build runs", + adv.mitigations.join(" ") + )); + } + out +} + +/// The observations a repository's declarations make, and what the read +/// saw. `fixed_tags` maps `(image, tag)` to the fixed tag the registry has. +pub fn observations( + repo: &str, + decls: &[Decl], + files_read: &BTreeSet, + advs: &[RuntimeAdvisory], + fixed_tags: &BTreeMap<(String, String), String>, +) -> (Vec, Read) { + let mut out = Vec::new(); + let mut read = Read { + files: files_read.clone(), + ..Default::default() + }; + for d in decls.iter().filter(|d| d.kind != DeclKind::Lambda) { + for adv in advs.iter().filter(|a| a.runtime == d.runtime) { + let Some(l) = adv.line(&super::java_line(&d.version)) else { + continue; + }; + let exact = d.exact && !moving_tag(d, l); + let (st, _) = standing(adv, &d.version, exact); + if st == Standing::NotAffected { + continue; + } + read.seen + .entry((d.file.clone(), d.package.clone(), d.written.clone())) + .or_default() + .insert(adv.id.clone()); + let mut path = vec![format!( + "{} {}: {} {} on the {} line, affected through {}{}", + d.describe(), + if exact { "pins" } else { "follows" }, + d.runtime.label(), + d.version, + l.line, + l.last_affected, + if l.introduced.is_empty() { + String::new() + } else { + format!(" from {}", l.introduced) + } + )]; + let fixed_words = if l.fixed.is_empty() { + format!("the first build after {}", l.last_affected) + } else { + l.fixed.clone() + }; + let to: Option = match (st, d.kind) { + (Standing::Floating, _) => { + path.push(format!( + "Fix: rebuild and redeploy so it runs {fixed_words} or later (this {} takes the newest build when it is built), or pin a fixed build", + if moving_tag(d, l) { "tag is republished for each build of the update and" } else { "line" } + )); + None + } + (_, DeclKind::Image) => { + let t = fixed_tags + .get(&(d.package.clone(), d.written.clone())) + .cloned(); + match &t { + Some(t) => path.push(format!("Fix: move the image to `{}:{t}`, then rebuild and redeploy", d.package)), + None => path.push(format!( + "Fix: no `{}` tag of this variant past {} is published yet; until one is, rebuild on the line's floating tag or use the JVM flag below", + d.package, l.last_affected + )), + } + t + } + _ => { + let t = fixed_value(d, l); + match &t { + Some(t) => path.push(format!("Fix: set it to `{t}`")), + None => path.push(format!( + "Fix: move to {}'s build of {fixed_words} once it is published; until then use the JVM flag below", + if d.vendor.is_empty() { "the distribution" } else { d.vendor.as_str() } + )), + } + t + } + }; + path.extend(hardware_lines(adv)); + if !l.vendor_fixed.is_empty() { + path.push(format!("Fixed builds: {}", l.vendor_fixed.join(", "))); + } + out.push(Observation { + repo: repo.to_string(), + manifest: d.file.clone(), + ecosystem: super::ECOSYSTEM.into(), + package: d.package.clone(), + version: d.written.clone(), + advisory: AdvisoryRecord { + ids: vec![adv.id.clone()], + title: format!( + "{} in the {} {} runtime ({})", + adv.id, + d.runtime.label(), + l.line, + adv.component + ), + summary: adv.summary.clone(), + cvss: adv.cvss, + severity: Some(adv.severity().into()), + published_at: Some(adv.published.clone()), + urls: adv + .sources + .iter() + .filter(|s| s.starts_with("https://")) + .cloned() + .collect(), + source: "openjdk".into(), + fixed: to.into_iter().collect(), + ..Default::default() + }, + scope: Scope::Runtime, + relation: Relation::Direct, + path, + ..Default::default() + }); + } + } + (out, read) +} + +/// The verdict a runtime finding carries: an image built only for an +/// architecture the advisory says is not affected is not reachable (the +/// lowest tier, with the reason); everything else is not known from code. +fn verdict_of(f: &Finding, decls: &[Decl], advs: &[RuntimeAdvisory]) -> (Verdict, String) { + let platform_arch = decls + .iter() + .find(|d| d.file == f.manifest && d.package == f.package && d.written == f.version) + .map(|d| d.platform.rsplit('/').next().unwrap_or("").to_string()) + .unwrap_or_default(); + let arch = match platform_arch.as_str() { + "arm64" | "aarch64" => "arm64", + "amd64" | "x86_64" => "x86_64", + _ => "", + }; + let not = advs + .iter() + .filter(|a| f.advisory.ids.iter().any(|i| i.eq_ignore_ascii_case(&a.id))) + .all(|a| !arch.is_empty() && a.hardware.not_arch.iter().any(|x| x == arch)); + if not { + return ( + Verdict::NotReachable, + format!("The image is built for linux/{arch}, which the advisory says is not affected: kept at the lowest tier in case the platform changes"), + ); + } + (Verdict::Unknown, NOT_CODE.to_string()) +} + +/// What [`apply_reads`] changed on a finding. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Change { + Fixed, + Updated, +} + +/// Brings a repository's runtime findings up to date with the read: a +/// finding whose file was read and no longer declares an affected runtime +/// is fixed; the rest carry their verdict (never triaged in code) and tier. +pub fn apply_reads( + findings: &mut [(Finding, FindingState)], + repo: &str, + read: &Read, + decls: &[Decl], + advs: &[RuntimeAdvisory], + cfg: &sec::SecurityConfig, +) -> Vec<(usize, Change)> { + let mut out = Vec::new(); + for (i, (f, st)) in findings.iter_mut().enumerate() { + if f.ecosystem != super::ECOSYSTEM + || !f.repo.eq_ignore_ascii_case(repo) + || !f.status.is_open() + { + continue; + } + let before = (f.fixed_version.clone(), f.verdict, f.tier); + if read.files.contains(&f.manifest) { + let still = read + .seen + .get(&(f.manifest.clone(), f.package.clone(), f.version.clone())) + .is_some_and(|ids| f.advisory.ids.iter().any(|id| ids.contains(id))); + if !still { + f.status = Status::Fixed; + f.updated_at = chrono::Utc::now().to_rfc3339(); + out.push((i, Change::Fixed)); + continue; + } + } + let (v, why) = verdict_of(f, decls, advs); + if f.verdict != v || f.evidence.as_ref().map(|e| e.summary.as_str()) != Some(why.as_str()) { + f.verdict = v; + f.evidence = Some(Evidence { + summary: why, + lines: Vec::new(), + checked: + "The runtime declarations in the repository, against the runtime advisories" + .into(), + confidence: "medium".into(), + }); + } + sec::retier(f, st, cfg); + if (f.fixed_version.clone(), f.verdict, f.tier) != before { + f.updated_at = chrono::Utc::now().to_rfc3339(); + out.push((i, Change::Updated)); + } + } + out +} + +/// The plan a runtime fix run follows: the exact line to change. +pub fn ticket_body(unit: &FixUnit, members: &[&Finding]) -> String { + let mut s = format!( + "{}\n\n\n", + sec::MARKER, + unit.branch + ); + s.push_str("Fix these advisories in a language runtime the repository pins (a JDK build). Change only the lines named here.\n\n## Change\n"); + for b in &unit.bumps { + let runtime_name = [Runtime::Java, Runtime::Node, Runtime::Python, Runtime::Go] + .iter() + .any(|r| r.name() == b.package); + let file = if b.manifest.is_empty() { + "the file" + } else { + b.manifest.as_str() + }; + if runtime_name { + s.push_str(&format!( + "- In `{file}`, replace the value `{}` with `{}`. Keep the file's format; change nothing else in it.\n", + b.from, b.to + )); + } else { + s.push_str(&format!( + "- In `{file}`, replace `FROM {}:{}` with `FROM {}:{}`. Keep the line's flags and its `AS` stage name. Every other `FROM {}:{}` in the repository changes the same way.\n", + b.package, b.from, b.package, b.to, b.package, b.from + )); + } + } + s.push_str("\nThe new build is on the same feature line as the old one; don't move to another line or another vendor. Once merged, every image and service built from these files has to be rebuilt and redeployed for the fix to run.\n\n## Advisories\n"); + for f in members { + s.push_str(&format!( + "- {} ({})\n", + f.advisory.primary, + f.advisory.ids.join(", ") + )); + for p in &f.path { + s.push_str(&format!(" - {p}\n")); + } + } + s +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runtime_vuln::advisories::tests::java4shell; + use crate::runtime_vuln::decls::{from_dockerfile, from_file}; + + fn scan(files: &[(&str, &str)]) -> (Vec, BTreeSet) { + let mut decls = Vec::new(); + let mut read = BTreeSet::new(); + for (p, t) in files { + read.insert(p.to_string()); + if p.ends_with("Dockerfile") { + decls.extend(from_dockerfile(p, t)); + } else { + decls.extend(from_file(p, t)); + } + } + (decls, read) + } + + fn temurin_tags() -> Vec { + [ + "21.0.4_7-jre", + "21.0.12_7-jre", + "21.0.13_11-jre", + "21.0.13.1_2-jre", + "21.0.13.1_2-jdk", + "21.0.13.1_3-jre", + "21-jre", + "25.0.5.1_1-jre", + ] + .iter() + .map(|s| s.to_string()) + .collect() + } + + fn findings_of( + repo: &str, + files: &[(&str, &str)], + tags: &BTreeMap<(String, String), String>, + ) -> (Vec<(Finding, FindingState)>, Vec, Read) { + let advs = vec![java4shell()]; + let (decls, read_files) = scan(files); + let (obs, read) = observations(repo, &decls, &read_files, &advs, tags); + let now = chrono::Utc::now(); + let mut out: Vec<(Finding, FindingState)> = Vec::new(); + for o in &obs { + let idx = out.iter().position(|(f, _)| { + sec::merges_into_at( + f, + &o.advisory.ids, + &o.repo, + &o.manifest, + &o.package, + &o.version, + ) + }); + let (f, st, _) = sec::apply(idx.map(|i| out[i].clone()), o, now); + match idx { + Some(i) => out[i] = (f, st), + None => out.push((f, st)), + } + } + let cfg = sec::SecurityConfig { + enabled: true, + ..Default::default() + }; + apply_reads(&mut out, repo, &read, &decls, &advs, &cfg); + (out, decls, read) + } + + fn cfg() -> sec::SecurityConfig { + sec::SecurityConfig { + enabled: true, + ..Default::default() + } + } + + /// (a) A pinned JDK image and a floating one. + #[test] + fn a_pinned_jdk_image_gets_a_pull_request_to_the_fixed_tag() { + let l = java4shell().line("21").unwrap().clone(); + let fixed = fixed_tag("21.0.4_7-jre", &temurin_tags(), &l).unwrap(); + assert_eq!(fixed, "21.0.13.1_2-jre", "same variant, lowest fixed"); + let tags = BTreeMap::from([( + ("eclipse-temurin".to_string(), "21.0.4_7-jre".to_string()), + fixed.clone(), + )]); + let (f, _, _) = findings_of( + "acme/api", + &[( + "Dockerfile", + "FROM eclipse-temurin:21.0.4_7-jre\nCOPY app.jar /app.jar\n", + )], + &tags, + ); + assert_eq!(f.len(), 1); + let (x, _) = &f[0]; + assert_eq!(x.advisory.primary, "CVE-2026-114938"); + assert_eq!(x.ecosystem, "runtime"); + assert_eq!( + (x.package.as_str(), x.version.as_str()), + ("eclipse-temurin", "21.0.4_7-jre") + ); + assert_eq!(x.fixed_version.as_deref(), Some("21.0.13.1_2-jre")); + assert_eq!(x.verdict, Verdict::Unknown); + assert_eq!( + x.tier, + Some(sec::Tier::P1), + "8.1, a runtime, hardware not known from code" + ); + assert!( + x.path.iter().any(|p| p.contains("AVX-512 VBMI")), + "{:?}", + x.path + ); + assert!(x + .path + .iter() + .any(|p| p.contains("-XX:-UseBASE64Intrinsics"))); + // One unit, one bump, and the ticket names the FROM line. + let units = sec::plan_units(&f, &cfg(), chrono::Utc::now()); + assert_eq!(units.len(), 1, "{units:?}"); + assert_eq!(units[0].bumps[0].to, "21.0.13.1_2-jre"); + let members: Vec<&Finding> = f.iter().map(|(x, _)| x).collect(); + let body = sec::ticket_body(&units[0], &members, &cfg()); + assert!( + body.contains("replace `FROM eclipse-temurin:21.0.4_7-jre` with `FROM eclipse-temurin:21.0.13.1_2-jre`"), + "{body}" + ); + assert!(!body.contains("lockfile")); + } + + #[test] + fn a_floating_jdk_tag_is_a_rebuild_not_a_pull_request() { + let (f, _, _) = findings_of( + "acme/api", + &[("Dockerfile", "FROM eclipse-temurin:21-jre\n")], + &BTreeMap::new(), + ); + assert_eq!(f.len(), 1); + let (x, _) = &f[0]; + assert!(x.fixed_version.is_none()); + assert!( + x.path.iter().any(|p| p.contains("rebuild and redeploy")), + "{:?}", + x.path + ); + assert!(x.path.iter().any(|p| p.contains("21.0.13.1"))); + assert!(sec::plan_units(&f, &cfg(), chrono::Utc::now()).is_empty()); + // A pinned build no registry has a fix for yet: a finding, no PR. + let (g, _, _) = findings_of( + "acme/api", + &[("Dockerfile", "FROM eclipse-temurin:21.0.12_7-jre\n")], + &BTreeMap::new(), + ); + assert_eq!(g.len(), 1); + assert!(g[0].0.fixed_version.is_none()); + // A tag republished for each build of the update. + let (h, _, _) = findings_of( + "acme/api", + &[("Dockerfile", "FROM amazoncorretto:21.0.13-al2023\n")], + &BTreeMap::new(), + ); + assert!( + h[0].0.path.iter().any(|p| p.contains("republished")), + "{:?}", + h[0].0.path + ); + } + + /// (b) A version file. + #[test] + fn a_java_version_file_on_17_is_bumped_to_the_fix() { + let (f, _, _) = findings_of( + "acme/svc", + &[(".java-version", "17.0.15\n")], + &BTreeMap::new(), + ); + assert_eq!(f.len(), 1); + let (x, _) = &f[0]; + assert_eq!(x.fixed_version.as_deref(), Some("17.0.21.1")); + let units = sec::plan_units(&f, &cfg(), chrono::Utc::now()); + let members: Vec<&Finding> = f.iter().map(|(x, _)| x).collect(); + let body = sec::ticket_body(&units[0], &members, &cfg()); + assert!( + body.contains("In `.java-version`, replace the value `17.0.15` with `17.0.21.1`"), + "{body}" + ); + // A vendor whose fixed build no source names: a finding, no PR. + let (g, _, _) = findings_of( + "acme/svc", + &[(".sdkmanrc", "java=21.0.4-tem\n")], + &BTreeMap::new(), + ); + assert_eq!(g.len(), 1); + assert!(g[0].0.fixed_version.is_none()); + assert!( + g[0].0.path.iter().any(|p| p.contains("temurin's build")), + "{:?}", + g[0].0.path + ); + } + + /// (c) A Gradle toolchain, Maven's release, and CI's setup-java. + #[test] + fn toolchains_and_ci_lines_are_findings_to_rebuild() { + let (f, _, _) = findings_of( + "acme/svc", + &[ + ("build.gradle.kts", "java { toolchain { languageVersion = JavaLanguageVersion.of(21) } }\n"), + ("pom.xml", "21\n"), + (".github/workflows/ci.yml", " - uses: actions/setup-java@v4\n with:\n java-version: '21'\n"), + ], + &BTreeMap::new(), + ); + let manifests: BTreeSet<&str> = f.iter().map(|(x, _)| x.manifest.as_str()).collect(); + assert_eq!( + manifests, + BTreeSet::from(["build.gradle.kts", "pom.xml", ".github/workflows/ci.yml"]) + ); + assert!(f + .iter() + .all(|(x, _)| x.fixed_version.is_none() && x.status == Status::Open)); + assert!(f + .iter() + .all(|(x, _)| x.advisory.ids.contains(&"CVE-2026-114938".to_string()))); + } + + #[test] + fn java_8_11_and_fixed_builds_are_not_findings() { + let (f, _, _) = findings_of( + "acme/old", + &[ + ("Dockerfile", "FROM eclipse-temurin:11.0.25_9-jre\nFROM eclipse-temurin:8u432-b06-jre\nFROM eclipse-temurin:21.0.13.1_2-jre\nFROM openjdk:17.0.5-jdk\n"), + (".java-version", "11.0.25\n"), + ("pom.xml", "1.8\n"), + (".tool-versions", "java 21.0.13.1\n"), + ], + &BTreeMap::new(), + ); + assert!( + f.is_empty(), + "{:?}", + f.iter() + .map(|(x, _)| (&x.manifest, &x.version)) + .collect::>() + ); + } + + #[test] + fn an_arm64_only_image_is_kept_at_the_lowest_tier_with_the_reason() { + let (f, _, _) = findings_of( + "acme/api", + &[( + "Dockerfile", + "FROM --platform=linux/arm64 eclipse-temurin:21-jre\n", + )], + &BTreeMap::new(), + ); + assert_eq!(f.len(), 1, "never dropped"); + let (x, _) = &f[0]; + assert_eq!(x.verdict, Verdict::NotReachable); + assert_eq!(x.tier, Some(sec::Tier::P3)); + assert!(x.evidence.as_ref().unwrap().summary.contains("arm64")); + } + + #[test] + fn a_file_that_no_longer_declares_an_affected_build_closes_its_finding() { + let (mut f, _, _) = findings_of( + "acme/svc", + &[(".java-version", "17.0.15\n")], + &BTreeMap::new(), + ); + let advs = vec![java4shell()]; + let (decls, files) = scan(&[(".java-version", "17.0.21.1\n")]); + let (obs, read) = observations("acme/svc", &decls, &files, &advs, &BTreeMap::new()); + assert!(obs.is_empty()); + let ch = apply_reads(&mut f, "acme/svc", &read, &decls, &advs, &cfg()); + assert_eq!(ch, vec![(0, Change::Fixed)]); + assert_eq!(f[0].0.status, Status::Fixed); + // A read that did not read the file closes nothing. + let (mut g, _, _) = findings_of( + "acme/svc", + &[(".java-version", "17.0.15\n")], + &BTreeMap::new(), + ); + apply_reads(&mut g, "acme/svc", &Read::default(), &[], &advs, &cfg()); + assert!(g[0].0.status.is_open()); + } + + #[test] + fn lambda_declarations_are_left_to_the_infrastructure_findings() { + let (f, decls, _) = findings_of( + "acme/infra", + &[( + "lambda.tf", + "resource \"aws_lambda_function\" \"f\" {\n runtime = \"java21\"\n}\n", + )], + &BTreeMap::new(), + ); + assert_eq!(decls.len(), 1); + assert!(f.is_empty()); + } +} diff --git a/services/common/src/runtime_vuln/mod.rs b/services/common/src/runtime_vuln/mod.rs new file mode 100644 index 000000000..eba84cfe4 --- /dev/null +++ b/services/common/src/runtime_vuln/mod.rs @@ -0,0 +1,170 @@ +//! Language runtimes a team runs (a JDK, Node.js, Python, Go), matched by +//! version line against the runtime projects' own advisories. Libraries +//! are the dependency findings' (`security_fixes`), operating system +//! packages the base images' and the infrastructure findings'; a runtime is +//! neither: a JDK is not a Maven package, and a JDK unpacked into an image +//! is not an OS package. +//! +//! - [`decls`]: where code says which runtime runs: Dockerfile `FROM` +//! images whose tag carries the version (`eclipse-temurin:21.0.4_7-jre`, +//! `amazoncorretto:21`), version files (`.java-version`, `.sdkmanrc`, +//! `.tool-versions`, `.nvmrc`, `.python-version`), build toolchains +//! (Gradle `JavaLanguageVersion.of(21)`, Maven `maven.compiler.release`), +//! CI setup steps (`actions/setup-java` and the others) and Lambda runtime +//! declarations in infrastructure code (`java21`). Each says how precise +//! it is: an exact build, or a line that takes whatever build is newest +//! when it is built or deployed. +//! +//! - [`advisories`]: the OpenJDK Vulnerability Group's advisories (the +//! index and each dated page, with its risk matrix and the last affected +//! build of every line), read once a day with the infrastructure feeds and +//! kept as `RUNTIME_ADV#`. What the page does not say (the first +//! affected build, the CPU it needs, a JVM flag that turns the code path +//! off, a vendor's fixed build) comes from the Amazon Linux advisory for +//! the same CVE, read the same day, and from [`advisories::NOTES`], dated +//! and sourced. A page that no longer parses keeps the last good copy. +//! +//! - [`findings`]: a repository's declarations against the advisories, as +//! dependency findings of the `runtime` ecosystem: a pull request that +//! moves a pinned build to a fixed one when one is published, else a +//! runbook that says to rebuild (a floating tag or line takes the fix on +//! rebuild) and names the advisory's JVM flag. +//! +//! - [`cpu`]: what an EC2 instance type runs on (architecture, CPU +//! generation, AVX-512 VBMI), so a finding states whether an advisory's +//! hardware condition holds. The infrastructure findings use it for the +//! packages SSM inventory lists on instances (`infra_vuln::matching`). +//! +//! Nothing here calls a model: every match is a comparison. + +pub mod advisories; +pub mod cpu; +pub mod decls; +pub mod findings; +#[cfg(test)] +mod replay; + +use serde::{Deserialize, Serialize}; + +/// The ecosystem runtime findings are recorded under. +pub const ECOSYSTEM: &str = "runtime"; +/// One row per runtime advisory, under the infrastructure feeds' partition. +pub const ADVISORY_PREFIX: &str = "RUNTIME_ADV#"; + +pub fn advisory_sk(id: &str) -> String { + format!("{ADVISORY_PREFIX}{}", id.to_ascii_uppercase()) +} + +/// A language runtime. +#[derive( + Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default, +)] +#[serde(rename_all = "snake_case")] +pub enum Runtime { + #[default] + Java, + Node, + Python, + Go, +} + +impl Runtime { + /// The name a finding's package carries when no image names it. + pub fn name(self) -> &'static str { + match self { + Runtime::Java => "java", + Runtime::Node => "node", + Runtime::Python => "python", + Runtime::Go => "go", + } + } + + pub fn label(self) -> &'static str { + match self { + Runtime::Java => "Java (JDK)", + Runtime::Node => "Node.js", + Runtime::Python => "Python", + Runtime::Go => "Go", + } + } +} + +/// A Java version as numbers: `1.8.0_402` and `8u402` are `8.0.402`; +/// a build after `+` or `_` is dropped (`21.0.4+7`, `21.0.4_7`, +/// `17.0.21.1_p2-r0`); a vendor's prefix or suffix is dropped +/// (`temurin-21.0.4`, `21.0.4-tem`, `21.0.4.LTS`). +pub fn java_numbers(v: &str) -> Vec { + let mut s = v.trim().to_ascii_lowercase(); + // A vendor prefix: everything before the first digit. + if let Some(i) = s.find(|c: char| c.is_ascii_digit()) { + s = s[i..].to_string(); + } else { + return Vec::new(); + } + // `8u402` and `1.8.0_402`. + if let Some((major, update)) = s.split_once('u') { + if major.chars().all(|c| c.is_ascii_digit()) { + let upd: String = update.chars().take_while(|c| c.is_ascii_digit()).collect(); + return vec![major.parse().unwrap_or(0), 0, upd.parse().unwrap_or(0)]; + } + } + if let Some(rest) = s.strip_prefix("1.8.0_") { + let upd: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + return vec![8, 0, upd.parse().unwrap_or(0)]; + } + let core: String = s + .chars() + .take_while(|c| c.is_ascii_digit() || *c == '.') + .collect(); + core.trim_end_matches('.') + .split('.') + .filter(|p| !p.is_empty()) + .map(|p| p.parse().unwrap_or(0)) + .collect() +} + +/// Compares two Java versions by their numbers, missing parts as zero. +pub fn java_cmp(a: &str, b: &str) -> std::cmp::Ordering { + let (x, y) = (java_numbers(a), java_numbers(b)); + let n = x.len().max(y.len()); + for i in 0..n { + let o = x.get(i).unwrap_or(&0).cmp(y.get(i).unwrap_or(&0)); + if o != std::cmp::Ordering::Equal { + return o; + } + } + std::cmp::Ordering::Equal +} + +/// The feature line of a Java version (`21` for `21.0.4`, `8` for `8u402`). +pub fn java_line(v: &str) -> String { + java_numbers(v) + .first() + .map(|n| n.to_string()) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cmp::Ordering; + + #[test] + fn java_versions_read_every_way_they_are_written() { + assert_eq!(java_numbers("21.0.4_7-jre"), vec![21, 0, 4]); + assert_eq!(java_numbers("21.0.4+7"), vec![21, 0, 4]); + assert_eq!(java_numbers("temurin-17.0.15+6"), vec![17, 0, 15]); + assert_eq!(java_numbers("21.0.4-tem"), vec![21, 0, 4]); + assert_eq!(java_numbers("8u402"), vec![8, 0, 402]); + assert_eq!(java_numbers("1.8.0_402"), vec![8, 0, 402]); + assert_eq!(java_numbers("17.0.21.1_p2-r0"), vec![17, 0, 21, 1]); + assert_eq!(java_line("21-jre"), "21"); + assert_eq!(java_cmp("21.0.13", "21.0.13.0.3"), Ordering::Less); + assert_eq!(java_cmp("21.0.13.1", "21.0.13.0.3"), Ordering::Greater); + assert_eq!(java_cmp("21.0.4_7", "21.0.4+9"), Ordering::Equal); + assert_eq!( + advisory_sk("cve-2026-114938"), + "RUNTIME_ADV#CVE-2026-114938" + ); + } +} diff --git a/services/common/src/runtime_vuln/notes.json b/services/common/src/runtime_vuln/notes.json new file mode 100644 index 000000000..cf6a4e130 --- /dev/null +++ b/services/common/src/runtime_vuln/notes.json @@ -0,0 +1,14 @@ +[ + { + "id": "CVE-2026-114938", + "as_of": "2026-11-18", + "source": "OpenJDK Vulnerability Group advisory 2026-11-17 (https://openjdk.org/groups/vulnerability/advisories/2026-11-17) with the vendor advisories for the November 2026 updates", + "cpu_feature": "avx512_vbmi", + "arch": ["x86_64"], + "not_arch": ["arm64"], + "introduced": [["17", "17.0.6"]], + "fixed": [["17", "17.0.21.1"], ["21", "21.0.13.1"], ["25", "25.0.5.1"], ["27", "27.0.1.1"]], + "mitigations": ["-XX:-UseBASE64Intrinsics"], + "summary": "A heap overflow in the java.util.Base64 decoder's AVX-512 VBMI intrinsic: malformed Base64 reaching the decoder writes past its output buffer. Exploitable only on x86-64 CPUs with AVX-512 VBMI (Intel Ice Lake, Sapphire Rapids and newer; AMD Zen 4 and newer)." + } +] diff --git a/services/common/src/runtime_vuln/replay.rs b/services/common/src/runtime_vuln/replay.rs new file mode 100644 index 000000000..331bb8de6 --- /dev/null +++ b/services/common/src/runtime_vuln/replay.rs @@ -0,0 +1,412 @@ +//! CVE-2026-114938 end to end, on the AWS side: SSM inventory's packages +//! on instances of several CPU generations and a Lambda function on +//! `java21`, matched against the live Amazon Linux feeds and the OpenJDK +//! advisory of 2026-11-17 (saved as they were read on 2026-11-18). + +use std::collections::BTreeMap; + +use crate::infra_vuln::feeds::{self, Advisory, Distro}; +use crate::infra_vuln::inventory::{self, Kind}; +use crate::infra_vuln::matching::{findings, Feeds, FixKind, InfraFinding}; +use crate::infra_vuln::raw::{RawAccount, RawAsg, RawInstance, RawPackages}; +use crate::runtime_vuln::advisories::tests::java4shell; +use crate::runtime_vuln::cpu::Holds; +use crate::security_fixes::Tier; + +const RSS23: &str = include_str!("testdata/alas2023-java-rss.xml"); +const RSS2: &str = include_str!("testdata/alas2-java-rss.xml"); +const PAGE23: &str = include_str!("testdata/alas2023-2026-3479.html"); +const PAGE2: &str = include_str!("testdata/alas2-2026-4123.html"); + +/// The two feeds as the daily read stores them: every RSS row, and the +/// pages read for the java advisories. +fn alas() -> Vec { + let mut out = feeds::parse_alas_rss(RSS23, Distro::Al2023).unwrap(); + out.extend(feeds::parse_alas_rss(RSS2, Distro::Al2).unwrap()); + for page in [PAGE23, PAGE2] { + let p = feeds::parse_alas_page(page).unwrap(); + for a in out.iter_mut().filter(|a| a.id == p.id) { + a.apply_page(&p); + } + } + out +} + +fn instance(id: &str, ty: &str, arch: &str, asg: Option<&str>) -> RawInstance { + let mut tags = vec![("Name".to_string(), id.to_string())]; + if let Some(g) = asg { + tags.push(("aws:autoscaling:groupName".into(), g.into())); + } + RawInstance { + id: id.into(), + image_id: "ami-0abc".into(), + instance_type: ty.into(), + architecture: arch.into(), + tags, + ..Default::default() + } +} + +fn pkgs(id: &str, list: &[(&str, &str)]) -> RawPackages { + RawPackages { + instance: id.into(), + packages: list + .iter() + .map(|(n, v)| (n.to_string(), v.to_string())) + .collect(), + } +} + +/// (e) instances whose SSM inventory has an affected java package, on +/// Sapphire Rapids (VBMI), Graviton (arm64) and Skylake (no VBMI), one +/// already on the fixed build, and (d) a Lambda function on java21. +pub fn replay() -> Vec { + replay_with(&alas(), &[java4shell()]) +} + +/// The same account against any feeds (the live ones in [`live`]). +pub fn replay_with( + adv: &[Advisory], + runtime: &[crate::runtime_vuln::advisories::RuntimeAdvisory], +) -> Vec { + let raw = RawAccount { + account: "111122223333".into(), + region: "us-east-1".into(), + read_at: "2026-11-18T12:00:00Z".into(), + instances: vec![ + instance("i-0a00000000000001", "m7i.large", "x86_64", Some("api")), + instance("i-0a00000000000002", "m7i.large", "x86_64", Some("api")), + instance("i-0b00000000000001", "m6g.large", "arm64", None), + instance("i-0c00000000000001", "m5.xlarge", "x86_64", None), + instance("i-0d00000000000001", "c7i.large", "x86_64", None), + ], + asgs: vec![RawAsg { + name: "api".into(), + arn: "arn:aws:autoscaling:us-east-1:111122223333:autoScalingGroup:x:autoScalingGroupName/api".into(), + desired: 2, + ..Default::default() + }], + packages: vec![ + pkgs( + "i-0a00000000000001", + &[ + ("java-21-amazon-corretto-headless", "21.0.13.0.11-1.amzn2023.1"), + ("bash", "5.2.15-1.amzn2023.0.2"), + ], + ), + pkgs( + "i-0a00000000000002", + &[("java-21-amazon-corretto-headless", "21.0.12.7.1-1.amzn2023.1")], + ), + pkgs( + "i-0b00000000000001", + &[("java-17-amazon-corretto-headless", "1:17.0.15.6.1-1.amzn2.1")], + ), + pkgs( + "i-0c00000000000001", + &[("java-21-amazon-corretto-headless", "21.0.13.0.11-1.amzn2023.1")], + ), + pkgs( + "i-0d00000000000001", + &[("java-21-amazon-corretto-headless", "21.0.13.1.2-1.amzn2023.1")], + ), + ], + ..Default::default() + }; + let mut resources = raw.resources(); + resources.extend(inventory::lambdas_from_terraform( + "acme/infra", + "lambda.tf", + "resource \"aws_lambda_function\" \"auth\" {\n function_name = \"auth\"\n runtime = \"java21\"\n}\nresource \"aws_lambda_function\" \"edge\" {\n function_name = \"edge\"\n runtime = \"java17\"\n architectures = [\"arm64\"]\n}\nresource \"aws_lambda_function\" \"old\" {\n function_name = \"old\"\n runtime = \"java11\"\n}\n", + "111122223333", + "us-east-1", + "2026-11-18T12:00:00Z", + )); + resources.extend(inventory::lambdas_from_templates( + "acme/infra", + "template.yaml", + "Resources:\n OrdersFn:\n Type: AWS::Serverless::Function\n Properties:\n Runtime: java21\n", + "111122223333", + "us-east-1", + "2026-11-18T12:00:00Z", + )); + let kev = BTreeMap::new(); + let latest = BTreeMap::new(); + findings( + &resources, + &Feeds { + advisories: adv, + bulletins: &[], + runtimes: &[], + latest: &[], + kev: &kev, + latest_al2023: &latest, + runtime, + today: "2026-11-18", + }, + ) +} + +fn by_name<'a>(f: &'a [InfraFinding], name: &str) -> Vec<&'a InfraFinding> { + f.iter().filter(|x| x.name == name).collect() +} + +#[test] +fn an_affected_java_package_on_a_vbmi_instance_is_the_top_tier() { + let f = replay(); + let api = by_name(&f, "api"); + assert_eq!(api.len(), 1, "one finding for the group's package"); + let a = api[0]; + assert_eq!(a.kind, Some(Kind::AutoScalingGroup)); + assert_eq!(a.cves, vec!["CVE-2026-114938"]); + assert!(a.sources.iter().any(|s| s.id == "ALAS2023-2026-3479")); + assert_eq!(a.fix.kind, Some(FixKind::Runbook)); + assert!( + a.fix.from.contains("21.0.12.7.1"), + "the oldest copy in the group: {}", + a.fix.from + ); + assert_eq!(a.fix.to, "21.0.13.1.2-1.amzn2023.1"); + assert!( + a.fix.cli[0].contains("--advisory ALAS2023-2026-3479"), + "{:?}", + a.fix.cli + ); + assert!( + a.fix.reason.contains("-XX:-UseBASE64Intrinsics"), + "{}", + a.fix.reason + ); + let h = a.hardware.as_ref().expect("hardware facts"); + assert_eq!(h.holds, Holds::Yes); + assert!(h.why.contains("Sapphire Rapids"), "{}", h.why); + assert_eq!(a.tier, Some(Tier::P1), "VBMI, not internet-facing"); +} + +#[test] +fn arm64_and_pre_vbmi_instances_are_findings_at_the_lowest_tier_with_the_reason() { + let f = replay(); + let arm = by_name(&f, "i-0b00000000000001"); + assert_eq!(arm.len(), 1, "never dropped"); + let h = arm[0].hardware.as_ref().unwrap(); + assert_eq!(h.holds, Holds::No); + assert!(h.why.contains("arm64"), "{}", h.why); + assert!(h.if_moved.contains("m7i"), "{}", h.if_moved); + assert_eq!(arm[0].tier, Some(Tier::P3)); + assert!( + arm[0].sources.iter().any(|s| s.id == "ALAS2-2026-4123"), + "AL2 too" + ); + let sky = by_name(&f, "i-0c00000000000001"); + assert_eq!(sky.len(), 1); + let h = sky[0].hardware.as_ref().unwrap(); + assert_eq!(h.holds, Holds::No); + assert!(h.why.contains("no AVX-512 VBMI"), "{}", h.why); + assert_eq!(sky[0].tier, Some(Tier::P3)); +} + +#[test] +fn a_fixed_build_and_unrelated_packages_are_not_findings() { + let f = replay(); + assert!( + by_name(&f, "i-0d00000000000001").is_empty(), + "21.0.13.1.2 is fixed" + ); + assert!(!f.iter().any(|x| x.title.contains("bash"))); +} + +#[test] +fn lambda_java_runtimes_are_aws_managed_rows_and_java_11_is_not_affected() { + let f = replay(); + let auth = by_name(&f, "auth"); + assert_eq!(auth.len(), 1); + assert_eq!(auth[0].fix.kind, Some(FixKind::Aws)); + assert!(auth[0].cves.contains(&"CVE-2026-114938".to_string())); + assert!( + auth[0].fix.reason.contains("java21"), + "{}", + auth[0].fix.reason + ); + assert!( + auth[0].fix.reason.contains("corretto 21.0.13.1.2"), + "{}", + auth[0].fix.reason + ); + assert!(!auth[0].is_open()); + let edge = by_name(&f, "edge"); + assert!( + edge[0].fix.reason.contains("not affected"), + "{}", + edge[0].fix.reason + ); + assert!(by_name(&f, "old").is_empty(), "java11 is not affected"); + let sam = by_name(&f, "OrdersFn"); + assert_eq!(sam.len(), 1, "SAM templates too"); + assert_eq!(sam[0].fix.kind, Some(FixKind::Aws)); +} + +#[test] +fn package_versions_compare_like_rpm() { + use crate::infra_vuln::matching::rpm_lt; + assert!(rpm_lt( + "21.0.13.0.11-1.amzn2023.1", + "21.0.13.1.2-1.amzn2023.1" + )); + assert!(rpm_lt("1:17.0.15.6.1-1.amzn2.1", "17.0.21.1.2-1.amzn2.1")); + assert!(!rpm_lt( + "21.0.13.1.2-1.amzn2023.1", + "21.0.13.1.2-1.amzn2023.1" + )); + assert!(rpm_lt("2.36-9", "2.36-10")); +} + +/// The live sources, read now: the OpenJDK index and its newest page, the +/// ALAS feeds and the page of every java advisory naming the CVE; then +/// every fixture of this module and of `findings::tests` against them. +/// Run by hand: `cargo test -p common runtime_vuln::replay::live -- --ignored --nocapture`. +#[tokio::test] +#[ignore] +async fn live() { + use crate::runtime_vuln::advisories as ra; + use crate::runtime_vuln::decls::{from_dockerfile, from_file}; + let http = reqwest::Client::new(); + let get = |u: String| { + let http = http.clone(); + async move { + http.get(&u) + .header("user-agent", "CoderHelm security feeds") + .send() + .await + .unwrap() + .text() + .await + .unwrap() + } + }; + let dates = ra::parse_openjdk_index(&get(ra::OPENJDK_INDEX.to_string()).await).unwrap(); + println!("OpenJDK index: newest advisory {}", dates[0]); + let url = ra::openjdk_page(&dates[0]); + let mut runtime = ra::parse_openjdk_page(&get(url.clone()).await, &url).unwrap(); + let mut alas: Vec = Vec::new(); + for (rss, distro) in [ + (feeds::ALAS2023_RSS, Distro::Al2023), + (feeds::ALAS2_RSS, Distro::Al2), + ] { + let mut rows = feeds::parse_alas_rss(&get(rss.to_string()).await, distro).unwrap(); + for a in rows.iter_mut().filter(|a| { + a.package.starts_with("java-") && a.cves.iter().any(|c| c == "CVE-2026-114938") + }) { + let p = feeds::parse_alas_page(&get(a.link.clone()).await).unwrap(); + a.apply_page(&p); + println!( + "ALAS {} {}: fixed {:?}", + a.id, + a.package, + a.fixed + .iter() + .map(|f| format!("{}-{}", f.version, f.release)) + .collect::>() + .first() + ); + } + alas.extend(rows); + } + ra::enrich(&mut runtime, &alas, &ra::notes()); + let j = runtime + .iter() + .find(|a| a.id == "CVE-2026-114938") + .expect("the live page lists it"); + println!( + "\n{} {} cvss {:?} published {}", + j.id, j.component, j.cvss, j.published + ); + for l in &j.lines { + println!( + " line {}: from {:?} through {} fixed {:?} vendor {:?}", + l.line, l.introduced, l.last_affected, l.fixed, l.vendor_fixed + ); + } + println!( + " hardware {:?}\n mitigations {:?}\n sources {:?}", + j.hardware, j.mitigations, j.sources + ); + // The repository fixtures. + let repos: &[(&str, &str, &str)] = &[ + ( + "a pinned image", + "Dockerfile", + "FROM eclipse-temurin:21.0.12_7-jre\n", + ), + ( + "a floating image", + "Dockerfile", + "FROM eclipse-temurin:21-jre\n", + ), + ("version file", ".java-version", "17.0.15\n"), + ( + "gradle toolchain", + "build.gradle.kts", + "languageVersion = JavaLanguageVersion.of(21)\n", + ), + ( + "maven release", + "pom.xml", + "21\n", + ), + ( + "setup-java", + ".github/workflows/ci.yml", + " java-version: '21'\n", + ), + ( + "arm64 image", + "Dockerfile", + "FROM --platform=linux/arm64 eclipse-temurin:21-jre\n", + ), + ( + "java 11", + "Dockerfile", + "FROM eclipse-temurin:11.0.25_9-jre\n", + ), + ("java 8", "pom.xml", "1.8\n"), + ("fixed build", ".java-version", "21.0.13.1\n"), + ]; + println!("\nRepositories:"); + for (what, path, text) in repos { + let decls = if path.ends_with("Dockerfile") { + from_dockerfile(path, text) + } else { + from_file(path, text) + }; + let files = std::collections::BTreeSet::from([path.to_string()]); + let (obs, _) = + super::findings::observations("acme/svc", &decls, &files, &runtime, &BTreeMap::new()); + let hit: Vec<&crate::security_fixes::Observation> = obs + .iter() + .filter(|o| o.advisory.ids[0] == "CVE-2026-114938") + .collect(); + match hit.first() { + None => println!("- {what}: no finding"), + Some(o) => println!( + "- {what}: {} ({} {}), fix {:?}\n {}", + o.advisory.ids[0], + o.package, + o.version, + o.advisory.fixed.first(), + o.path.join("\n ") + ), + } + } + println!("\nAWS:"); + for f in replay_with(&alas, &runtime) { + println!( + "- {} {} [{:?} {:?}] {} | hardware {:?}", + f.kind.map(|k| k.label()).unwrap_or(""), + f.name, + f.tier, + f.fix.kind, + f.title, + f.hardware.as_ref().map(|h| (h.holds, h.why.clone())) + ); + } +} diff --git a/services/common/src/runtime_vuln/testdata/alas2-2026-4123.html b/services/common/src/runtime_vuln/testdata/alas2-2026-4123.html new file mode 100644 index 000000000..6486e6199 --- /dev/null +++ b/services/common/src/runtime_vuln/testdata/alas2-2026-4123.html @@ -0,0 +1,155 @@ + + + + + + ALAS2-2026-4123 + + + + + + + + + + + + + + + +
+ +
+
+
+

ALAS2-2026-4123

+
+ +
+
+ + Amazon Linux 2 (EOS) Security Advisory: ALAS2-2026-4123 +
+ Advisory Released Date: 2026-11-17
+ Advisory Updated Date: 2026-11-17
+ +
+ Severity: + + + + + + Important
+
+ + + +
+
+ Issue Overview:
+ +

A memory-corruption vulnerability exists in the OpenJDK Base64 decoder affecting OpenJDK 17.0.6 and later on x86-64 systems with specific CPU capabilities. ARM64 systems are not affected. Depending on the deployment context, exploitation could result in a JVM crash for unauthenticated users or, in certain application environments, code execution by an authenticated low-privileged user. Oracle has issued a patch covering versions 17, 21, 25, and 27. (CVE-2026-114938)

+ +
+ +
+
+ Affected Packages: +
+

java-17-amazon-corretto

+
+
+ Note: +

+ This advisory is applicable to Amazon Linux 2 (AL2) Core repository. Visit this FAQ section + for the difference between AL2 Core and AL2 Extras advisories. +

+
+ +
+
+Issue Correction: +
+Run yum update java-17-amazon-corretto or yum update --advisory ALAS2-2026-4123 to update your system.
+
+
+
+ New Packages:
aarch64:
    java-17-amazon-corretto-17.0.21.1.2-1.amzn2.1.aarch64
    java-17-amazon-corretto-debugsymbols-17.0.21.1.2-1.amzn2.1.aarch64
    java-17-amazon-corretto-devel-17.0.21.1.2-1.amzn2.1.aarch64
    java-17-amazon-corretto-headless-17.0.21.1.2-1.amzn2.1.aarch64
    java-17-amazon-corretto-javadoc-17.0.21.1.2-1.amzn2.1.aarch64
    java-17-amazon-corretto-jmods-17.0.21.1.2-1.amzn2.1.aarch64

src:
    java-17-amazon-corretto-17.0.21.1.2-1.amzn2.1.src

x86_64:
    java-17-amazon-corretto-17.0.21.1.2-1.amzn2.1.x86_64
    java-17-amazon-corretto-debugsymbols-17.0.21.1.2-1.amzn2.1.x86_64
    java-17-amazon-corretto-devel-17.0.21.1.2-1.amzn2.1.x86_64
    java-17-amazon-corretto-headless-17.0.21.1.2-1.amzn2.1.x86_64
    java-17-amazon-corretto-javadoc-17.0.21.1.2-1.amzn2.1.x86_64
    java-17-amazon-corretto-jmods-17.0.21.1.2-1.amzn2.1.x86_64

+ +
+
+
+ + + + \ No newline at end of file diff --git a/services/common/src/runtime_vuln/testdata/alas2-java-rss.xml b/services/common/src/runtime_vuln/testdata/alas2-java-rss.xml new file mode 100644 index 000000000..7bdf1d2e8 --- /dev/null +++ b/services/common/src/runtime_vuln/testdata/alas2-java-rss.xml @@ -0,0 +1,131 @@ + + + + Amazon Linux AMI Security Bulletins + Amazon Linux AMI Security Bulletins + https://alas.aws.amazon.com + en-us + 35 + + + ALAS2-2026-4123 (important): java-17-amazon-corretto + + CVE-2026-114938 + + Tue, 17 Nov 2026 23:08:00 GMT + Tue, 17 Nov 2026 23:08:00 GMT + https://alas.aws.amazon.com/AL2/ALAS2-2026-4123.html + https://alas.aws.amazon.com/AL2/ALAS2-2026-4123.html + + + ALAS2-2026-4066 (important): java-17-amazon-corretto + + CVE-2026-114820 + + Fri, 30 Oct 2026 23:19:00 GMT + Mon, 02 Nov 2026 09:00:00 GMT + https://alas.aws.amazon.com/AL2/ALAS2-2026-4066.html + https://alas.aws.amazon.com/AL2/ALAS2-2026-4066.html + + + ALAS2-2026-4067 (important): java-11-amazon-corretto + + CVE-2026-114820 + + Fri, 30 Oct 2026 23:19:00 GMT + Mon, 02 Nov 2026 09:00:00 GMT + https://alas.aws.amazon.com/AL2/ALAS2-2026-4067.html + https://alas.aws.amazon.com/AL2/ALAS2-2026-4067.html + + + ALAS2CORRETTO8-2026-027 (important): java-1.8.0-amazon-corretto + + CVE-2026-114820 + + Fri, 30 Oct 2026 23:19:00 GMT + Mon, 02 Nov 2026 09:00:00 GMT + https://alas.aws.amazon.com/AL2/ALAS2CORRETTO8-2026-027.html + https://alas.aws.amazon.com/AL2/ALAS2CORRETTO8-2026-027.html + + + ALAS2-2026-4039 (important): java-11-amazon-corretto + + CVE-2026-101516, CVE-2026-113470, CVE-2026-83374, CVE-2026-83376, CVE-2026-83378, CVE-2026-83380, CVE-2026-83381, CVE-2026-83387, CVE-2026-83400, CVE-2026-87255, CVE-2026-87290, CVE-2026-87291, CVE-2026-87292, CVE-2026-87293, CVE-2026-87294, CVE-2026-87367, CVE-2026-91332, CVE-2026-91334, CVE-2026-91335, CVE-2026-91373, CVE-2026-91374, CVE-2026-91375, CVE-2026-91379, CVE-2026-91380, CVE-2026-91381, CVE-2026-91382, CVE-2026-91394, CVE-2026-91395, CVE-2026-91396, CVE-2026-91397, CVE-2026-91398, CVE-2026-91400, CVE-2026-91403, CVE-2026-91409, CVE-2026-91410, CVE-2026-91411, CVE-2026-91415, CVE-2026-91418, CVE-2026-91451, CVE-2026-91452, CVE-2026-91453, CVE-2026-91461, CVE-2026-91462, CVE-2026-91463, CVE-2026-91464, CVE-2026-91487 + + Sat, 24 Oct 2026 22:23:00 GMT + Wed, 04 Nov 2026 02:08:00 GMT + https://alas.aws.amazon.com/AL2/ALAS2-2026-4039.html + https://alas.aws.amazon.com/AL2/ALAS2-2026-4039.html + + + ALAS2-2026-4040 (important): java-17-amazon-corretto + + CVE-2026-101516, CVE-2026-113470, CVE-2026-83374, CVE-2026-83376, CVE-2026-83378, CVE-2026-83380, CVE-2026-83381, CVE-2026-83387, CVE-2026-83400, CVE-2026-87255, CVE-2026-87290, CVE-2026-87291, CVE-2026-87292, CVE-2026-87293, CVE-2026-87294, CVE-2026-87367, CVE-2026-91332, CVE-2026-91334, CVE-2026-91335, CVE-2026-91373, CVE-2026-91374, CVE-2026-91375, CVE-2026-91379, CVE-2026-91380, CVE-2026-91381, CVE-2026-91382, CVE-2026-91394, CVE-2026-91395, CVE-2026-91396, CVE-2026-91397, CVE-2026-91398, CVE-2026-91400, CVE-2026-91403, CVE-2026-91409, CVE-2026-91410, CVE-2026-91411, CVE-2026-91415, CVE-2026-91418, CVE-2026-91451, CVE-2026-91452, CVE-2026-91453, CVE-2026-91461, CVE-2026-91462, CVE-2026-91463, CVE-2026-91464, CVE-2026-91487 + + Sat, 24 Oct 2026 22:23:00 GMT + Wed, 04 Nov 2026 02:08:00 GMT + https://alas.aws.amazon.com/AL2/ALAS2-2026-4040.html + https://alas.aws.amazon.com/AL2/ALAS2-2026-4040.html + + + ALAS2CORRETTO8-2026-026 (important): java-1.8.0-amazon-corretto + + CVE-2026-101516, CVE-2026-113470, CVE-2026-83374, CVE-2026-83376, CVE-2026-83378, CVE-2026-83380, CVE-2026-83381, CVE-2026-83387, CVE-2026-83400, CVE-2026-87255, CVE-2026-87290, CVE-2026-87291, CVE-2026-87292, CVE-2026-87293, CVE-2026-87294, CVE-2026-87367, CVE-2026-91332, CVE-2026-91334, CVE-2026-91335, CVE-2026-91373, CVE-2026-91374, CVE-2026-91375, CVE-2026-91379, CVE-2026-91380, CVE-2026-91381, CVE-2026-91382, CVE-2026-91394, CVE-2026-91395, CVE-2026-91396, CVE-2026-91397, CVE-2026-91400, CVE-2026-91403, CVE-2026-91409, CVE-2026-91410, CVE-2026-91411, CVE-2026-91415, CVE-2026-91417, CVE-2026-91418, CVE-2026-91451, CVE-2026-91452, CVE-2026-91453, CVE-2026-91461, CVE-2026-91462, CVE-2026-91463, CVE-2026-91464, CVE-2026-91487 + + Sat, 24 Oct 2026 22:23:00 GMT + Wed, 04 Nov 2026 02:07:00 GMT + https://alas.aws.amazon.com/AL2/ALAS2CORRETTO8-2026-026.html + https://alas.aws.amazon.com/AL2/ALAS2CORRETTO8-2026-026.html + + + ALAS2-2026-3878 (medium): java-17-amazon-corretto + + CVE-2026-60589, CVE-2026-61308, CVE-2026-70907 + + Mon, 31 Aug 2026 21:39:00 GMT + Mon, 31 Aug 2026 21:39:00 GMT + https://alas.aws.amazon.com/AL2/ALAS2-2026-3878.html + https://alas.aws.amazon.com/AL2/ALAS2-2026-3878.html + + + ALAS2-2026-3879 (medium): java-11-amazon-corretto + + CVE-2026-60589, CVE-2026-61308, CVE-2026-70907 + + Mon, 31 Aug 2026 21:39:00 GMT + Mon, 31 Aug 2026 21:39:00 GMT + https://alas.aws.amazon.com/AL2/ALAS2-2026-3879.html + https://alas.aws.amazon.com/AL2/ALAS2-2026-3879.html + + + ALAS2-2026-3888 (medium): java-1.8.0-openjdk + + CVE-2026-60589, CVE-2026-61308, CVE-2026-70907 + + Mon, 31 Aug 2026 21:39:00 GMT + Mon, 31 Aug 2026 21:39:00 GMT + https://alas.aws.amazon.com/AL2/ALAS2-2026-3888.html + https://alas.aws.amazon.com/AL2/ALAS2-2026-3888.html + + + ALAS2CORRETTO8-2026-025 (medium): java-1.8.0-amazon-corretto + + CVE-2026-60589, CVE-2026-61308, CVE-2026-70907 + + Mon, 31 Aug 2026 21:39:00 GMT + Mon, 31 Aug 2026 21:39:00 GMT + https://alas.aws.amazon.com/AL2/ALAS2CORRETTO8-2026-025.html + https://alas.aws.amazon.com/AL2/ALAS2CORRETTO8-2026-025.html + + + ALAS2-2026-3841 (important): java-11-amazon-corretto + + CVE-2026-46917, CVE-2026-46968, CVE-2026-47010, CVE-2026-47021, CVE-2026-47027, CVE-2026-47057, CVE-2026-47058, CVE-2026-47059, CVE-2026-47063, CVE-2026-60147 + + Tue, 04 Aug 2026 21:36:00 GMT + Tue, 04 Aug 2026 21:36:00 GMT + https://alas.aws.amazon.com/AL2/ALAS2-2026-3841.html + https://alas.aws.amazon.com/AL2/ALAS2-2026-3841.html + + + diff --git a/services/common/src/runtime_vuln/testdata/alas2023-2026-3479.html b/services/common/src/runtime_vuln/testdata/alas2023-2026-3479.html new file mode 100644 index 000000000..9dc56ae8e --- /dev/null +++ b/services/common/src/runtime_vuln/testdata/alas2023-2026-3479.html @@ -0,0 +1,148 @@ + + + + + + ALAS2023-2026-3479 + + + + + + + + + + + + + + + +
+ +
+
+
+

ALAS2023-2026-3479

+
+ +
+
+ + Amazon Linux 2023 Security Advisory: ALAS2023-2026-3479 +
+ Advisory Released Date: 2026-11-17
+ Advisory Updated Date: 2026-11-17
+ +
+ Severity: + + + + + + Important
+
+ + + +
+
+ Issue Overview:
+ +

Amazon Corretto has been updated to , which includes fixes for security issues in the JDK. See the Corretto release notes for details

A memory-corruption vulnerability exists in the OpenJDK Base64 decoder affecting OpenJDK 17.0.6 and later on x86-64 systems with specific CPU capabilities. ARM64 systems are not affected. Depending on the deployment context, exploitation could result in a JVM crash for unauthenticated users or, in certain application environments, code execution by an authenticated low-privileged user. Oracle has issued a patch covering versions 17, 21, 25, and 27. (CVE-2026-114938)

+ +
+ +
+
+ Affected Packages: +
+

java-21-amazon-corretto

+
+ +
+
+Issue Correction: +
+Run dnf update java-21-amazon-corretto --releasever 2023.12.20261117 or dnf update --advisory ALAS2023-2026-3479 --releasever 2023.12.20261117 to update your system.
More information on how to update your system can be found on this page: Amazon Linux 2023 documentation
+
+
+ New Packages:
aarch64:
    java-21-amazon-corretto-jmods-21.0.13.1.2-1.amzn2023.1.aarch64
    java-21-amazon-corretto-21.0.13.1.2-1.amzn2023.1.aarch64
    java-21-amazon-corretto-debugsymbols-21.0.13.1.2-1.amzn2023.1.aarch64
    java-21-amazon-corretto-devel-21.0.13.1.2-1.amzn2023.1.aarch64
    java-21-amazon-corretto-headless-21.0.13.1.2-1.amzn2023.1.aarch64
    java-21-amazon-corretto-javadoc-21.0.13.1.2-1.amzn2023.1.aarch64

src:
    java-21-amazon-corretto-21.0.13.1.2-1.amzn2023.1.src

x86_64:
    java-21-amazon-corretto-headless-21.0.13.1.2-1.amzn2023.1.x86_64
    java-21-amazon-corretto-21.0.13.1.2-1.amzn2023.1.x86_64
    java-21-amazon-corretto-devel-21.0.13.1.2-1.amzn2023.1.x86_64
    java-21-amazon-corretto-jmods-21.0.13.1.2-1.amzn2023.1.x86_64
    java-21-amazon-corretto-debugsymbols-21.0.13.1.2-1.amzn2023.1.x86_64
    java-21-amazon-corretto-javadoc-21.0.13.1.2-1.amzn2023.1.x86_64

+ +
+
+
+ + + + \ No newline at end of file diff --git a/services/common/src/runtime_vuln/testdata/alas2023-java-rss.xml b/services/common/src/runtime_vuln/testdata/alas2023-java-rss.xml new file mode 100644 index 000000000..74fdda9f6 --- /dev/null +++ b/services/common/src/runtime_vuln/testdata/alas2023-java-rss.xml @@ -0,0 +1,131 @@ + + + + Amazon Linux 2023 Security Bulletins + Amazon Linux 2023 Security Bulletins + https://alas.aws.amazon.com + en-us + 35 + + + ALAS2023-2026-3478 (important): java-17-amazon-corretto + + CVE-2026-114938 + + Tue, 17 Nov 2026 22:34:00 GMT + Tue, 17 Nov 2026 23:01:00 GMT + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3478.html + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3478.html + + + ALAS2023-2026-3479 (important): java-21-amazon-corretto + + CVE-2026-114938 + + Tue, 17 Nov 2026 22:34:00 GMT + Tue, 17 Nov 2026 23:01:00 GMT + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3479.html + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3479.html + + + ALAS2023-2026-3480 (important): java-25-amazon-corretto + + CVE-2026-114938 + + Tue, 17 Nov 2026 22:34:00 GMT + Tue, 17 Nov 2026 23:01:00 GMT + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3480.html + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3480.html + + + ALAS2023-2026-3481 (important): java-27-amazon-corretto + + CVE-2026-114938 + + Tue, 17 Nov 2026 22:34:00 GMT + Tue, 17 Nov 2026 23:01:00 GMT + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3481.html + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3481.html + + + ALAS2023-2026-3418 (medium): javapackages-bootstrap + + CVE-2026-102554 + + Mon, 09 Nov 2026 23:26:00 GMT + Mon, 09 Nov 2026 23:26:00 GMT + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3418.html + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3418.html + + + ALAS2023-2026-3372 (important): java-11-amazon-corretto + + CVE-2026-114820 + + Fri, 30 Oct 2026 21:00:00 GMT + Mon, 02 Nov 2026 09:00:00 GMT + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3372.html + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3372.html + + + ALAS2023-2026-3369 (important): java-25-amazon-corretto + + CVE-2026-114820 + + Fri, 30 Oct 2026 21:00:00 GMT + Mon, 02 Nov 2026 09:00:00 GMT + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3369.html + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3369.html + + + ALAS2023-2026-3368 (important): java-27-amazon-corretto + + CVE-2026-114820 + + Fri, 30 Oct 2026 21:00:00 GMT + Mon, 02 Nov 2026 09:00:00 GMT + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3368.html + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3368.html + + + ALAS2023-2026-3370 (important): java-21-amazon-corretto + + CVE-2026-114820 + + Fri, 30 Oct 2026 21:00:00 GMT + Mon, 02 Nov 2026 09:00:00 GMT + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3370.html + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3370.html + + + ALAS2023-2026-3371 (important): java-17-amazon-corretto + + CVE-2026-114820 + + Fri, 30 Oct 2026 21:00:00 GMT + Mon, 02 Nov 2026 09:00:00 GMT + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3371.html + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3371.html + + + ALAS2023-2026-3373 (important): java-1.8.0-amazon-corretto + + CVE-2026-114820 + + Fri, 30 Oct 2026 21:00:00 GMT + Mon, 02 Nov 2026 09:00:00 GMT + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3373.html + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3373.html + + + ALAS2023-2026-3317 (important): java-11-amazon-corretto + + CVE-2026-101516, CVE-2026-113470, CVE-2026-83374, CVE-2026-83376, CVE-2026-83378, CVE-2026-83380, CVE-2026-83381, CVE-2026-83387, CVE-2026-83400, CVE-2026-87255, CVE-2026-87290, CVE-2026-87291, CVE-2026-87292, CVE-2026-87293, CVE-2026-87294, CVE-2026-87367, CVE-2026-91332, CVE-2026-91334, CVE-2026-91335, CVE-2026-91373, CVE-2026-91374, CVE-2026-91375, CVE-2026-91379, CVE-2026-91380, CVE-2026-91381, CVE-2026-91382, CVE-2026-91394, CVE-2026-91395, CVE-2026-91396, CVE-2026-91397, CVE-2026-91398, CVE-2026-91400, CVE-2026-91403, CVE-2026-91409, CVE-2026-91410, CVE-2026-91411, CVE-2026-91415, CVE-2026-91418, CVE-2026-91451, CVE-2026-91452, CVE-2026-91453, CVE-2026-91461, CVE-2026-91462, CVE-2026-91463, CVE-2026-91464, CVE-2026-91487 + + Sat, 24 Oct 2026 20:57:00 GMT + Wed, 04 Nov 2026 10:10:00 GMT + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3317.html + https://alas.aws.amazon.com/AL2023/ALAS2023-2026-3317.html + + + diff --git a/services/common/src/runtime_vuln/testdata/openjdk-2026-11-17.html b/services/common/src/runtime_vuln/testdata/openjdk-2026-11-17.html new file mode 100644 index 000000000..ea6df2416 --- /dev/null +++ b/services/common/src/runtime_vuln/testdata/openjdk-2026-11-17.html @@ -0,0 +1,32 @@ +OpenJDK Vulnerability Advisory: 2026/11/17

OpenJDK Vulnerability Advisory: 2026/11/17

The following vulnerabilities in OpenJDK source code were fixed +in this release. The affected versions are 27.0.1.0.3, 25.0.5.0.3, +21.0.13.0.3, 17.0.21.0.3, 11.0.33, 8u512, and earlier. Please note +that defense-in-depth issues are not assigned CVEs. We recommend +that you upgrade as soon as possible.

The current and previous advisories are +available for reference.

OpenJDK Risk matrix

Affects ...
CVE IDComponentCVSSv3.1
Vector
81117212527
CVE-2026-114938hotspot/
compiler
8.1
NHNNUHHH
••••
CVE-2026-114939security-libs/
org.ietf.jgss
7.4
NHNNUHHN
••••••
CVE-2026-114940security-libs/
javax.net.ssl
7.4
NHNNUHHN
••••••
CVE-2026-114941hotspot/
compiler
7.0
NHNNULLH
•••
CVE-2026-114942core-libs7.0
NHNNULLH
••••
CVE-2026-114943hotspot/
runtime
6.5
NHNNUNLH
••••••
CVE-2026-114944core-svc/
java.lang.management
5.9
NHNNUNHN
••••••
CVE-2026-114945core-libs/
java.lang
5.3
NLNNUNLN
••••
CVE-2026-114946hotspot/
compiler
4.8
NHNNULLN
••••••
CVE-2026-114947security-libs/
javax.net.ssl
3.7
NHNNUNLN
••

OpenJFX Risk matrix

Affects ...
CVE IDComponentCVSSv3.1
Vector
212527
CVE-2026-86144javafx/
web
7.5
NHNRUHHH
•••

Acknowledgements

We acknowledge the following parties for their reports and +contributions: Albert Yang, Alexander Dezhinov, Maximilian Radoy, +Nicholas Carlini, Nikita Kozlov, Quang Luong, Stanislav Dukhin, +XUBB, and Zeng Adolph.

We also thank the Leads of the JDK 8 +Updates, JDK 11 +Updates, JDK 17 +Updates, JDK 21 +Updates, JDK 25 +Updates, and OpenJFX Projects for +providing the risk-matrix information for their releases.

How to report a vulnerability

Please see the reporting +instructions for information about how to report a +vulnerability.

Last update: 2026/11/17 17:44 UTC
diff --git a/services/common/src/runtime_vuln/testdata/openjdk-index.html b/services/common/src/runtime_vuln/testdata/openjdk-index.html new file mode 100644 index 000000000..4f8124cb3 --- /dev/null +++ b/services/common/src/runtime_vuln/testdata/openjdk-index.html @@ -0,0 +1,24 @@ +OpenJDK Vulnerability Advisories

OpenJDK Vulnerability Advisories

We publish fixes to vulnerabilities in OpenJDK source code four +times per year, in January, April, July, and October, on the third +Tuesday of the month. We post advisories describing the severity, +area, and affected versions of each fix to the vuln-announce +mailing list, signed with the advisory key +for integrity.

We encourage you to update to the latest version of your +preferred JDK distribution as soon as possible.

Advisories

How to report a vulnerability

Please see the reporting +instructions for information about how to report a +vulnerability.

Last update: 2026/11/17 20:24 UTC
diff --git a/services/common/src/security_fixes.rs b/services/common/src/security_fixes.rs index 16564f3c1..1886bf65b 100644 --- a/services/common/src/security_fixes.rs +++ b/services/common/src/security_fixes.rs @@ -2336,6 +2336,7 @@ pub fn ecosystem_label(ecosystem: &str) -> Option<&'static str> { "rubygems" | "gem" | "bundler" => "ruby", "cargo" | "crates.io" | "rust" => "rust", "docker" => "docker", + "runtime" => "runtime", "actions" | "github actions" | "github" => "github_actions", "nuget" => ".NET", "composer" | "packagist" => "php", @@ -2955,6 +2956,9 @@ pub fn ticket_body_with( if unit.ecosystem == crate::base_images::ECOSYSTEM { return crate::base_images::ticket_body(unit, members); } + if unit.ecosystem == crate::runtime_vuln::ECOSYSTEM { + return crate::runtime_vuln::findings::ticket_body(unit, members); + } let mut s = String::new(); s.push_str(&format!( "{MARKER}\n\n\n", @@ -4955,7 +4959,7 @@ pub fn match_github_advisory(repo: &str, adv: &Value, deps: &[Dep]) -> Vec Vec { deps.iter() - .filter(|d| d.ecosystem != "docker") + .filter(|d| d.ecosystem != "docker" && d.ecosystem != crate::runtime_vuln::ECOSYSTEM) .map(|d| json!({"package": {"name": d.name, "ecosystem": d.ecosystem}, "version": d.version})) .collect() } diff --git a/services/gateway/src/routes/security.rs b/services/gateway/src/routes/security.rs index a5a071c90..d490f05d8 100644 --- a/services/gateway/src/routes/security.rs +++ b/services/gateway/src/routes/security.rs @@ -2061,6 +2061,7 @@ pub fn retry_of( // (`infra_security::retry_of`); base images have their own runs. if unit.ecosystem == common::infra_vuln::records::UNIT_ECOSYSTEM || unit.ecosystem == common::base_images::ECOSYSTEM + || unit.ecosystem == common::runtime_vuln::ECOSYSTEM { return None; } diff --git a/services/worker/src/passes/base_images.rs b/services/worker/src/passes/base_images.rs index d6a703a47..9ea614dab 100644 --- a/services/worker/src/passes/base_images.rs +++ b/services/worker/src/passes/base_images.rs @@ -125,6 +125,21 @@ impl<'a> Registry<'a> { Err(format!("{} refused an anonymous pull", r.registry)) } + /// The repository's tags (`tags/list`), as far as one page goes. + pub async fn tags(&mut self, r: &ImageRef) -> Result, String> { + let (body, _) = self + .get(r, "tags/list?n=10000", "application/json", 8 * 1024 * 1024) + .await?; + let v: Value = + serde_json::from_slice(&body).map_err(|_| "the tag list isn't JSON".to_string())?; + Ok(v["tags"] + .as_array() + .into_iter() + .flatten() + .filter_map(|t| t.as_str().map(String::from)) + .collect()) + } + /// Reads a reference: its digest and, when published, the linux/amd64 /// package list. pub async fn read(&mut self, r: &ImageRef) -> Result { diff --git a/services/worker/src/passes/incidents/an_six_database_findings.rs b/services/worker/src/passes/incidents/an_six_database_findings.rs index e59740f88..49c2e8f78 100644 --- a/services/worker/src/passes/incidents/an_six_database_findings.rs +++ b/services/worker/src/passes/incidents/an_six_database_findings.rs @@ -303,6 +303,7 @@ fn scene() -> Scene { latest: &[], kev: &kev, latest_al2023: &latest, + runtime: &[], today: "2026-11-13", }, ); diff --git a/services/worker/src/passes/incidents/bn_infra_list_follows_aws.rs b/services/worker/src/passes/incidents/bn_infra_list_follows_aws.rs index 015be41da..30fbb7ae1 100644 --- a/services/worker/src/passes/incidents/bn_infra_list_follows_aws.rs +++ b/services/worker/src/passes/incidents/bn_infra_list_follows_aws.rs @@ -303,6 +303,7 @@ fn find(resources: &[Resource], today: &str) -> Vec { latest: &[], kev: &kev, latest_al2023: &latest, + runtime: &[], today, }, ) diff --git a/services/worker/src/passes/infra_feeds.rs b/services/worker/src/passes/infra_feeds.rs index 98fcc4eac..30ca88562 100644 --- a/services/worker/src/passes/infra_feeds.rs +++ b/services/worker/src/passes/infra_feeds.rs @@ -17,6 +17,10 @@ //! - The Lambda runtime table, and AWS's latest-image parameters (read with //! the worker's own role in us-east-1: public parameters, no team's //! account). +//! - The OpenJDK Vulnerability Group's advisories: the index, then each +//! page not read yet (the newest few again every day), stored per CVE as +//! `RUNTIME_ADV#` with what the Amazon Linux advisories for the java +//! packages, read just before, add (`common::runtime_vuln::advisories`). use std::collections::{BTreeSet, HashMap}; use std::io::Read; @@ -40,6 +44,10 @@ const PAGES_PER_DAY: usize = 60; const BULLETINS_PER_DAY: usize = 60; /// Advisories older than this aren't kept on a first read. const BACKFILL_DAYS: i64 = 400; +/// OpenJDK advisory pages read per day, and how many of the newest are read +/// again every day (a page is updated after it is published). +const OPENJDK_PAGES_PER_DAY: usize = 12; +const OPENJDK_REREAD: usize = 3; /// Largest response read (the AL2 feed is about 2 MB). const MAX_BYTES: usize = 12 * 1024 * 1024; @@ -50,6 +58,7 @@ pub struct FeedReport { pub advisories: usize, pub pages: usize, pub bulletins: usize, + pub runtime: usize, pub failed: Vec, } @@ -167,6 +176,7 @@ pub fn merge_advisories( if k.detailed { a.releasever = k.releasever.clone(); a.fixed = k.fixed.clone(); + a.overview = k.overview.clone(); a.detailed = true; for c in &k.cves { if !a.cves.contains(c) { @@ -372,6 +382,76 @@ async fn latest(state: &WorkerState, report: &mut FeedReport) { record(state, "latest_images", outcome, report).await; } +/// The OpenJDK pages to read now: the newest [`OPENJDK_REREAD`] again, +/// then those not read yet, newer than `oldest`, newest first. +pub fn openjdk_pages_to_read( + dates: &[String], + read: &BTreeSet, + oldest: &str, +) -> Vec { + dates + .iter() + .enumerate() + .filter(|(i, d)| d.as_str() >= oldest && (*i < OPENJDK_REREAD || !read.contains(*d))) + .map(|(_, d)| d.clone()) + .take(OPENJDK_PAGES_PER_DAY) + .collect() +} + +async fn openjdk(state: &WorkerState, report: &mut FeedReport) { + use common::runtime_vuln::{self as rv, advisories as ra}; + let outcome = async { + let html = fetch_text(state, ra::OPENJDK_INDEX).await?; + let dates = ra::parse_openjdk_index(&html).map_err(|e| e.to_string())?; + let known = store::runtime_advisories(&state.dynamo, &state.config.settings_table_name).await; + let pages_read: BTreeSet = known + .iter() + .filter_map(|a| a.url.rsplit('/').find(|p| !p.is_empty()).map(String::from)) + .collect(); + let oldest = (Utc::now() - Duration::days(BACKFILL_DAYS)).format("%Y-%m-%d").to_string(); + let mut all: Vec = known.clone(); + let mut failures = 0usize; + let mut parsed = 0usize; + for d in openjdk_pages_to_read(&dates, &pages_read, &oldest) { + let url = ra::openjdk_page(&d); + match fetch_text(state, &url).await.and_then(|h| ra::parse_openjdk_page(&h, &url).map_err(|e| e.to_string())) { + Ok(advs) => { + parsed += 1; + for a in advs { + // A page read again replaces what it said; what the + // enrichment added is added again below. + match all.iter_mut().find(|x| x.id == a.id) { + Some(x) => *x = a, + None => all.push(a), + } + } + } + // The stored copy of this page's advisories stays as it was. + Err(e) => { + warn!(page = %url, error = %e, "infra feeds: OpenJDK advisory page not read; keeping the last good copy"); + failures += 1; + } + } + } + if parsed == 0 && failures > 0 { + return Err(format!("none of {failures} OpenJDK advisory pages could be read (the page format may have changed)")); + } + let alas = advisories(state).await; + ra::enrich(&mut all, &alas, &ra::notes()); + for a in &all { + if known.iter().any(|k| k == a) { + continue; + } + if put_json(state, &rv::advisory_sk(&a.id), a, &[]).await { + report.runtime += 1; + } + } + Ok::(all.len()) + } + .await; + record(state, ra::FEED, outcome, report).await; +} + /// The daily read, on the review-reminder tick. Only the first tick of a /// UTC day reads; a read that failed outright is tried again next tick. pub async fn sweep(state: &WorkerState) -> FeedReport { @@ -403,6 +483,8 @@ pub async fn sweep(state: &WorkerState) -> FeedReport { bottlerocket(state, &mut report).await; lambda_runtimes(state, &mut report).await; latest(state, &mut report).await; + // After ALAS: the java advisories' pages add to the runtime advisories. + openjdk(state, &mut report).await; if report.failed.len() == feeds::FEEDS.len() { // Nothing answered (no network?): try again on the next tick. common::claim::release( @@ -417,6 +499,7 @@ pub async fn sweep(state: &WorkerState) -> FeedReport { advisories = report.advisories, pages = report.pages, bulletins = report.bulletins, + runtime = report.runtime, failed = ?report.failed, "Infrastructure feeds read" ); @@ -486,6 +569,30 @@ mod tests { assert!(pages_to_read(&[low], &BTreeSet::new(), 5).is_empty()); } + #[test] + fn openjdk_pages_reread_the_newest_and_read_the_rest_once() { + let dates: Vec = [ + "2026-11-17", + "2026-10-24", + "2026-10-21", + "2026-10-20", + "2026-07-21", + "2024-01-16", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let read = BTreeSet::from([ + "2026-11-17".to_string(), + "2026-10-24".to_string(), + "2026-10-20".to_string(), + ]); + assert_eq!( + openjdk_pages_to_read(&dates, &read, "2025-10-14"), + vec!["2026-11-17", "2026-10-24", "2026-10-21", "2026-07-21"] + ); + } + #[test] fn the_bottlerocket_feed_unzips() { use std::io::Write; diff --git a/services/worker/src/passes/infra_findings.rs b/services/worker/src/passes/infra_findings.rs index 0c762f6a7..6fcfa3dd2 100644 --- a/services/worker/src/passes/infra_findings.rs +++ b/services/worker/src/passes/infra_findings.rs @@ -187,6 +187,7 @@ pub async fn match_team(state: &WorkerState, team_id: &str) -> Vec { let advisories = store::advisories(&state.dynamo, table).await; let bulletins = store::bulletins(&state.dynamo, table).await; let runtimes = store::runtimes(&state.dynamo, table).await; + let runtime_advisories = store::runtime_advisories(&state.dynamo, table).await; let images = store::latest_images(&state.dynamo, table).await; let kev = kev(state).await; let today = Utc::now().format("%Y-%m-%d").to_string(); @@ -204,6 +205,7 @@ pub async fn match_team(state: &WorkerState, team_id: &str) -> Vec { latest: &images, kev: &kev, latest_al2023: latest.get(account).unwrap_or(&empty), + runtime: &runtime_advisories, today: &today, }; fresh.extend(matching::findings(res, &feeds)); diff --git a/services/worker/src/passes/infra_inventory.rs b/services/worker/src/passes/infra_inventory.rs index b99d85027..8b5bf4bf0 100644 --- a/services/worker/src/passes/infra_inventory.rs +++ b/services/worker/src/passes/infra_inventory.rs @@ -137,6 +137,14 @@ async fn read_ec2(s: &Session, raw: &mut RawAccount) { image_id: i.image_id().unwrap_or("").into(), launch_time: i.launch_time().map(|t| t.to_string()).unwrap_or_default(), public_ip: i.public_ip_address().is_some_and(|a| !a.is_empty()), + instance_type: i + .instance_type() + .map(|t| t.as_str().to_string()) + .unwrap_or_default(), + architecture: i + .architecture() + .map(|a| a.as_str().to_string()) + .unwrap_or_default(), tags: tags_of( i.tags() .iter() @@ -379,6 +387,7 @@ async fn read_eks(s: &Session, raw: &mut RawAccount) { .tags() .map(|t| tags_of(t.iter().map(|(k, v)| (k.as_str(), v.as_str())))) .unwrap_or_default(), + instance_types: n.instance_types().to_vec(), }); } } @@ -869,7 +878,34 @@ async fn read_opensearch(s: &Session, raw: &mut RawAccount) { } } -/// Kernels of SSM-managed instances, and AWS's latest AL2023 AMIs here. +/// Instances whose installed packages are read per account and region. +const MAX_PACKAGE_INSTANCES: usize = 100; +/// Pages of 50 inventory entries read per instance (a host has about 500 +/// to 1,500 packages). +const MAX_PACKAGE_PAGES: usize = 40; + +/// SSM inventory's `AWS:Application` entry as `(name, version-release)`. +fn package_of(e: &std::collections::HashMap) -> Option<(String, String)> { + let name = e.get("Name")?.trim(); + let version = e.get("Version").map(String::as_str).unwrap_or("").trim(); + if name.is_empty() || version.is_empty() { + return None; + } + let release = e.get("Release").map(String::as_str).unwrap_or("").trim(); + let epoch = e.get("Epoch").map(String::as_str).unwrap_or("").trim(); + let mut v = if release.is_empty() { + version.to_string() + } else { + format!("{version}-{release}") + }; + if !epoch.is_empty() && epoch != "0" && !v.contains(':') { + v = format!("{epoch}:{v}"); + } + Some((name.to_string(), v)) +} + +/// Every package of SSM-managed instances (bounded), the kernels among +/// them, and AWS's latest AL2023 AMIs here. async fn read_ssm(s: &Session, raw: &mut RawAccount) { let ssm = client!(aws_sdk_ssm, s); let names: Vec = common::infra_vuln::feeds::AL2023_PARAMETERS @@ -890,59 +926,89 @@ async fn read_ssm(s: &Session, raw: &mut RawAccount) { } Err(e) => note!(raw, "GetParameters", e), } - let ids: Vec = raw - .instances - .iter() - .map(|i| i.id.clone()) - .take(25) - .collect(); - for id in ids { - let f = aws_sdk_ssm::types::InventoryFilter::builder() - .key("AWS:Application.Name") - .values("kernel") - .r#type(aws_sdk_ssm::types::InventoryQueryOperatorType::Equal) - .build(); - let Ok(f) = f else { - continue; - }; - match ssm - .list_inventory_entries() - .instance_id(&id) - .type_name("AWS:Application") - .filters(f) - .max_results(10) - .send() - .await - { - Ok(o) => { - // The newest kernel package is the one that boots after a reboot; - // the running one may be older until then. - let mut best = String::new(); - for e in o.entries() { - let v = format!( - "{}-{}", - e.get("Version").map(String::as_str).unwrap_or(""), - e.get("Release").map(String::as_str).unwrap_or("") - ); - if v > best { - best = v; + // Instances in different Auto Scaling groups and node groups first, so + // the cap reaches every group before a second copy of one. + let group = |i: &RawInstance| { + i.tags + .iter() + .find(|(k, _)| k == "aws:autoscaling:groupName" || k == "eks:nodegroup-name") + .map(|(_, v)| v.clone()) + .unwrap_or_else(|| i.id.clone()) + }; + let mut seen = BTreeSet::new(); + let mut ids: Vec = Vec::new(); + for pass in 0..2 { + for i in &raw.instances { + let first = seen.insert(group(i)); + if (pass == 0 && first) || (pass == 1 && !ids.contains(&i.id)) { + ids.push(i.id.clone()); + } + } + } + // Past the cap, an instance's packages are not read; its kind's read + // stays complete (what was not read is not gone, it is not matched). + if ids.len() > MAX_PACKAGE_INSTANCES { + warn!( + account = %raw.account, + instances = ids.len(), + "infra inventory: packages read for the first {MAX_PACKAGE_INSTANCES} instances only" + ); + } + 'instances: for id in ids.into_iter().take(MAX_PACKAGE_INSTANCES) { + let mut token: Option = None; + let mut list: Vec<(String, String)> = Vec::new(); + for _ in 0..MAX_PACKAGE_PAGES { + match ssm + .list_inventory_entries() + .instance_id(&id) + .type_name("AWS:Application") + .max_results(50) + .set_next_token(token.take()) + .send() + .await + { + Ok(o) => { + list.extend(o.entries().iter().filter_map(package_of)); + token = o.next_token().map(String::from); + if token.is_none() { + break; } } - if !best.is_empty() && best != "-" { - raw.kernels.push((id, best)); - } - } - // Instances not managed by SSM say so; that's not a missing permission. - Err(e) => { - if e.as_service_error().is_some_and(|x| { - use aws_sdk_dynamodb::error::ProvideErrorMetadata; - x.code() == Some("AccessDeniedException") - }) { - note!(raw, "ListInventoryEntries", e); + // Instances not managed by SSM say so; that's not a missing permission. + Err(e) => { + if e.as_service_error().is_some_and(|x| { + use aws_sdk_dynamodb::error::ProvideErrorMetadata; + x.code() == Some("AccessDeniedException") + }) { + note!(raw, "ListInventoryEntries", e); + break 'instances; + } break; } } } + // The newest kernel package is the one that boots after a reboot; + // the running one may be older until then. + let kernel = list + .iter() + .filter(|(n, _)| n == "kernel") + .map(|(_, v)| v.clone()) + .max_by(|a, b| { + if common::infra_vuln::matching::rpm_lt(a, b) { + std::cmp::Ordering::Less + } else { + std::cmp::Ordering::Greater + } + }); + if let Some(k) = kernel { + raw.kernels.push((id.clone(), k)); + } + if !list.is_empty() { + raw.packages.push(common::infra_vuln::raw::RawPackages { + instance: id, + packages: list, + }); + } } } @@ -1515,6 +1581,14 @@ async fn place( BTreeSet::new() }; for f in &files { + if !f.path.ends_with(".tf") { + let dir = f.path.rsplit_once('/').map(|(d, _)| d).unwrap_or(""); + if !uncalled.contains(&format!("{}:{dir}", f.repo)) { + resources.extend(inv::lambdas_from_templates( + &f.repo, &f.path, &f.content, account, region, &now, + )); + } + } if f.path.ends_with(".tf") { let dir = f.path.rsplit_once('/').map(|(d, _)| d).unwrap_or(""); let found = diff --git a/services/worker/src/passes/security_fixes.rs b/services/worker/src/passes/security_fixes.rs index cbb79c2b5..dbb2a0f87 100644 --- a/services/worker/src/passes/security_fixes.rs +++ b/services/worker/src/passes/security_fixes.rs @@ -33,7 +33,7 @@ //! pull request opening, CI passing and the merge, and at half the //! deadline and the deadline. Every card is claimed once. -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::time::Instant; use aws_sdk_dynamodb::types::AttributeValue; @@ -523,6 +523,13 @@ async fn refresh_inventory( } for p in paths.iter().filter(|p| sec::is_dockerfile(p)).take(10) { if let Ok(text) = gh.read_file(owner, name, p, &branch).await { + // The runtime its images run (a JDK, Node.js, Python, Go). + for d in common::runtime_vuln::decls::from_dockerfile(p, &text) { + let dep = d.to_dep(); + if !deps.contains(&dep) { + deps.push(dep); + } + } for (image, tag) in sec::dockerfile_images(&text) { let d = Dep { ecosystem: "docker".into(), @@ -538,10 +545,46 @@ async fn refresh_inventory( } } } + // Runtime declarations outside Dockerfiles: version files, build + // toolchains, CI setup steps. Lambda runtimes are the infrastructure + // findings' (`infra_inventory` reads them with the rest of the code). + let mut runtime_files: Vec<&String> = paths + .iter() + .filter(|p| common::runtime_vuln::decls::is_runtime_file(p) && !iac_template(p)) + .collect(); + runtime_files.sort(); + for p in runtime_files.into_iter().take(MAX_RUNTIME_FILES) { + if let Ok(text) = gh.read_file(owner, name, p, &branch).await { + for d in common::runtime_vuln::decls::from_file(p, &text) { + if d.kind == common::runtime_vuln::decls::DeclKind::Lambda { + continue; + } + let dep = d.to_dep(); + if !deps.contains(&dep) { + deps.push(dep); + } + } + } + } save_deps(state, team_id, repo, &deps, &status, unpinned, &branch).await; Ok(deps) } +/// Runtime declaration files read per repository sync (Dockerfiles are +/// read for their base images, up to ten). +const MAX_RUNTIME_FILES: usize = 40; + +/// Infrastructure templates: their Lambda runtimes are read with the +/// account's resources, not as the repository's runtime. +fn iac_template(p: &str) -> bool { + let b = p.rsplit('/').next().unwrap_or(p).to_ascii_lowercase(); + b.ends_with(".tf") + || b.ends_with(".template.json") + || b.ends_with(".template.yaml") + || b.starts_with("template.y") + || b.starts_with("serverless.y") +} + fn apply_scopes( deps: &mut [Dep], ecosystem: &str, @@ -931,7 +974,12 @@ async fn osv_observations( cache: &mut HashMap, ) -> Result, String> { use futures::StreamExt; - let lookup: Vec<&Dep> = deps.iter().filter(|d| d.ecosystem != "docker").collect(); + // Base images and runtimes are matched on their own (`base_images`, + // `runtime_vuln`); `osv_queries` leaves them out too, so the indexes line up. + let lookup: Vec<&Dep> = deps + .iter() + .filter(|d| d.ecosystem != "docker" && d.ecosystem != common::runtime_vuln::ECOSYSTEM) + .collect(); let mut hits: Vec<(usize, String)> = vec![]; for (chunk_i, chunk) in lookup.chunks(500).enumerate() { let owned: Vec = chunk.iter().map(|d| (*d).clone()).collect(); @@ -1778,6 +1826,7 @@ async fn triage_tick(cx: &Ctx<'_>, findings: &mut [(Finding, FindingState)]) -> // Base images are not searched in code (common::base_images). if f.status.is_open() && f.ecosystem != common::base_images::ECOSYSTEM + && f.ecosystem != common::runtime_vuln::ECOSYSTEM && cx.cfg.repos.includes(&f.repo) && triage_due(f, st, now) { @@ -1952,9 +2001,24 @@ struct Ctx<'a> { started: Instant, /// OSV records read this tick (repositories share packages). osv: tokio::sync::Mutex>, + /// The runtime advisories, read once a tick when a repository needs them. + runtime: tokio::sync::OnceCell>, } impl Ctx<'_> { + async fn runtime(&self) -> Vec { + self.runtime + .get_or_init(|| async { + common::infra_vuln::store::runtime_advisories( + &self.state.dynamo, + &self.state.config.settings_table_name, + ) + .await + }) + .await + .clone() + } + /// The tick's time is used, or the sweep may not spend GitHub's budget /// now (the runs' share, its own hour's cap, a spent limit): every loop /// here asks before its next item, so a sweep stops instead of failing @@ -1971,14 +2035,17 @@ async fn sync_repo( findings: &mut Vec<(Finding, FindingState)>, with_alerts: bool, ) -> usize { - let deps = match refresh_inventory(cx.state, cx.team_id, &cx.gh, repo).await { - Ok(d) => d, + let (deps, fresh) = match refresh_inventory(cx.state, cx.team_id, &cx.gh, repo).await { + Ok(d) => (d, true), Err(e) => { warn!(team_id = cx.team_id, repo, error = %e, "security: inventory failed"); - load_deps(cx.state, cx.team_id, repo) - .await - .map(|(d, _)| d) - .unwrap_or_default() + ( + load_deps(cx.state, cx.team_id, repo) + .await + .map(|(d, _)| d) + .unwrap_or_default(), + false, + ) } }; let mut obs: Vec = vec![]; @@ -2014,6 +2081,9 @@ async fn sync_repo( super::base_images::sync(cx.state, repo, &deps, &mut cache).await }; obs.extend(base_obs); + // Runtimes the code declares, against the runtime advisories. + let (runtime_obs, runtime_read) = runtime_observations(cx, repo, &deps, findings, fresh).await; + obs.extend(runtime_obs); let now = Utc::now().to_rfc3339(); match osv { Ok(o) => { @@ -2064,11 +2134,13 @@ async fn sync_repo( } let applied = upsert(cx.state, cx.team_id, cx.cfg, findings, obs).await; base_images_settle(cx, repo, findings, &base_reads).await; + runtime_settle(cx, repo, findings, &deps, &runtime_read).await; // The dependency list now shows some fixed: a merged bump, a removal. for (f, st) in findings.iter_mut() { if f.repo.eq_ignore_ascii_case(repo) && f.status.is_open() && f.ecosystem != "docker" + && f.ecosystem != common::runtime_vuln::ECOSYSTEM && sec::fixed_by_inventory(f, &deps) { f.status = Status::Fixed; @@ -2095,6 +2167,98 @@ async fn sync_repo( applied.created } +/// A repository's runtime declarations against the runtime advisories: +/// the observations, and what the read saw (to close what the code no +/// longer declares). A pinned image's fixed tag comes from its registry's +/// tag list. An inventory that could not be read fresh closes nothing. +async fn runtime_observations( + cx: &Ctx<'_>, + repo: &str, + deps: &[Dep], + findings: &[(Finding, FindingState)], + fresh: bool, +) -> (Vec, common::runtime_vuln::findings::Read) { + use common::runtime_vuln::{advisories as ra, decls::Decl, findings as rf}; + let decls: Vec = deps.iter().filter_map(Decl::from_dep).collect(); + let advs = cx.runtime().await; + // Every file was read this time: a finding whose file no longer + // declares an affected runtime is fixed. + let files: BTreeSet = if fresh { + findings + .iter() + .filter(|(f, _)| { + f.ecosystem == common::runtime_vuln::ECOSYSTEM && f.repo.eq_ignore_ascii_case(repo) + }) + .map(|(f, _)| f.manifest.clone()) + .chain(decls.iter().map(|d| d.file.clone())) + .collect() + } else { + BTreeSet::new() + }; + let mut tags: BTreeMap<(String, String), String> = BTreeMap::new(); + let mut reg = super::base_images::Registry::new(&cx.state.http); + let mut listed: HashMap> = HashMap::new(); + for d in decls + .iter() + .filter(|d| d.kind == common::runtime_vuln::decls::DeclKind::Image && d.exact) + { + for adv in advs.iter().filter(|a| a.runtime == d.runtime) { + let (st, line) = ra::standing(adv, &d.version, true); + let (ra::Standing::Affected, Some(line)) = (st, line) else { + continue; + }; + if !listed.contains_key(&d.package) { + let list = match common::base_images::ImageRef::parse(&format!("{}:{}", d.package, d.written)) { + Some(r) => reg.tags(&r).await.unwrap_or_else(|e| { + warn!(team_id = cx.team_id, repo, image = %d.package, error = %e, "security: the image's tags couldn't be listed"); + Vec::new() + }), + None => Vec::new(), + }; + listed.insert(d.package.clone(), list); + } + if let Some(t) = rf::fixed_tag(&d.written, &listed[&d.package], line) { + let key = (d.package.clone(), d.written.clone()); + let higher = tags + .get(&key) + .is_none_or(|old| common::runtime_vuln::java_cmp(&t, old).is_gt()); + if higher { + tags.insert(key, t); + } + } + } + } + rf::observations(repo, &decls, &files, &advs, &tags) +} + +/// Runtime findings after a read: fixed when the code no longer declares +/// an affected runtime; else their verdict (never triaged in code) and tier. +async fn runtime_settle( + cx: &Ctx<'_>, + repo: &str, + findings: &mut [(Finding, FindingState)], + deps: &[Dep], + read: &common::runtime_vuln::findings::Read, +) { + use common::runtime_vuln::{decls::Decl, findings as rf}; + let decls: Vec = deps.iter().filter_map(Decl::from_dep).collect(); + let advs = cx.runtime().await; + for (i, change) in rf::apply_reads(findings, repo, read, &decls, &advs, cx.cfg) { + let (f, st) = &findings[i]; + save_finding(cx.state, cx.team_id, f, st).await; + if change == rf::Change::Fixed { + add_event( + cx.state, + cx.team_id, + &f.id, + "Fixed: the code no longer declares an affected runtime build", + None, + ) + .await; + } + } +} + /// Base image findings after a read: fixed when the image no longer has /// the version, else their pinned-digest fix; never triaged in code. async fn base_images_settle( @@ -3636,6 +3800,7 @@ async fn team_tick( gh: github(state, installation_id)?, started, osv: Default::default(), + runtime: Default::default(), }; let mut report = TeamReport::default(); let mut findings = load_findings(state, team_id).await; @@ -4125,6 +4290,7 @@ async fn event_for_team( gh: github(state, installation_id)?, started: Instant::now(), osv: Default::default(), + runtime: Default::default(), }; let mut findings = load_findings(state, team_id).await; let mut report = TeamReport::default(); @@ -4835,6 +5001,7 @@ pub(crate) async fn dep_inputs( let unit = load_unit(state, team_id, ticket).await?; if unit.ecosystem == common::infra_vuln::records::UNIT_ECOSYSTEM || unit.ecosystem == common::base_images::ECOSYSTEM + || unit.ecosystem == common::runtime_vuln::ECOSYSTEM { return None; }