From 5532b566aeedb99c1ccd76f82f0b072b3001619b Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Tue, 17 Nov 2026 22:32:40 +0000 Subject: [PATCH 001/119] java4shell: knowledge table for CVE-2026-114938 with sources Fix commit and JDK bug per OpenJDK line, the commit that introduced the AVX-512 VBMI decode path and the first release on each line that has it, and the fixed or not-yet-fixed release per vendor and distribution as of 2026-11-17. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/FACTS.md | 69 +++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 detectors/java4shell/FACTS.md diff --git a/detectors/java4shell/FACTS.md b/detectors/java4shell/FACTS.md new file mode 100644 index 0000000..e48cd63 --- /dev/null +++ b/detectors/java4shell/FACTS.md @@ -0,0 +1,69 @@ +# Java4Shell (CVE-2026-114938): what is known, and from where + +Checked 2026-11-17. Every row names its source. "Not fixed yet" means the +source was read on that date and had no fixed release; it is not a guess +about the future. Rows marked **inferred** are reasoning from the sources, +not something a source states. + +## The flaw + +| Fact | Source | +| --- | --- | +| The fix is JDK-8393212 "Base64 optimization improvements", 4 added lines in `generate_base64_decodeBlock()` in `src/hotspot/cpu/x86/stubGenerator_x86_64.cpp`: before the final 1 to 63 byte fragment of the AVX-512 VBMI path, `cmpl(length, 4); jcc(less, L_bruteForce)` ("A padded Base64 tail shorter than one complete block is handled by Java"). Authored 2026-10-13 by Tobias Hartmann, reviewed by rhalade, mschoene (the OpenJDK vulnerability group's reviewers), chagedorn, rcastanedalo | openjdk/jdk commit [`5177a70b385c16f26ede191fdac7aaba0bed0f8b`](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b), pushed 2026-11-16 | +| What the unfixed code does with a 1 to 3 byte tail that ends in `=`: `output_size` is 0, `L_padding` decrements it to -1, `bzhiq(output_mask, -1, output_size)` with an index of 255 keeps all 64 mask bits, and the masked `evmovdqub` stores 64 bytes at `dest + dp`: a write of up to 64 bytes past the output the caller sized. **Inferred** from reading the stub; no source states the impact in words | same file, lines around `L_finalBit` and `L_padding` | +| CVE-2026-114938 is listed with CVSS 8.1, component hotspot/compiler, in Amazon Corretto's changelogs of 2026-11-17 | [corretto-17 CHANGELOG 17.0.21.1.2](https://github.com/corretto/corretto-17/blob/17.0.21.1.2/CHANGELOG.md), [corretto-21 21.0.13.1.2](https://github.com/corretto/corretto-21/blob/21.0.13.1.2/CHANGELOG.md), [corretto-25 25.0.5.1.2](https://github.com/corretto/corretto-25/blob/25.0.5.1.2/CHANGELOG.md), [corretto-27 27.0.1.1.4](https://github.com/corretto/corretto-27/blob/27.0.1.1.4/CHANGELOG.md) | +| CVE-2026-114938 is JDK-8393212. **Inferred**: the Corretto changelogs list CVEs by component, not by JDK bug. Each fixed release carries two hotspot/compiler fixes (8393212 and 8390694 "Enhance vector masks"; 21u, 25u and 27u also 8390852 "Improve integer compression") and lists two or three hotspot/compiler CVEs. The brief's description (AVX-512 VBMI Base64 decode, mitigated by `-XX:-UseBASE64Intrinsics`) matches only 8393212. The OpenJDK advisory page that would state the mapping could not be reached from the research host | as above; openjdk.org unreachable | +| The vulnerable path runs only when the CPU reports AVX-512 VBMI, AVX-512BW and BMI2 and HotSpot keeps them enabled: `if (VM_Version::supports_avx512_vbmi() && VM_Version::supports_avx512bw() && VM_Version::supports_bmi2())`. AVX-512 features need AVX-512F, so the four CPU flags are `avx512f avx512bw avx512vbmi bmi2` | stubGenerator_x86_64.cpp at the fix commit | +| MIME decoding (`isMIME`) skips the AVX-512 path; standard and URL-safe decoding use it | same function, `cmpl(isMIME, 0)` | +| `-XX:UseAVX=0/1/2` clears every AVX-512 feature, VBMI included, so the path is not generated | `src/hotspot/cpu/x86/vm_version_x86.cpp`, `if (UseAVX < 3)` block (jdk17u-dev and jdk HEAD) | +| `-XX:-UseBASE64Intrinsics` stops the stub being generated at all: `if (UseBASE64Intrinsics) { ... StubRoutines::_base64_decodeBlock = generate_base64_decodeBlock(); }` | stubGenerator_x86_64.cpp | +| Only x86-64 HotSpot has this stub. AArch64, PPC and RISC-V have their own decode intrinsics (8256245, 8248188, 8314124) with different code. 32-bit x86 (`stubGenerator_x86_32.cpp`) has no decode intrinsic | jdk17u-dev and jdk21u-dev trees; `git log --grep` in openjdk/jdk | +| OpenJ9 (IBM Semeru) does not contain HotSpot: its `lib/server/libjvm.so` is a 97 KB redirector and the VM is `libj9vm29.so`. Whether OpenJ9 has a comparable bug of its own is **not known** | `ibm-semeru-runtimes:open-21-jre` image, release file `JVM_VARIANT="Openj9"` | + +## Where the vulnerable path came from + +| Line | First release with the AVX-512 VBMI decode path | Source | +| --- | --- | --- | +| mainline | JDK 18 (8268276 "Base64 Decoding optimization for x86 using AVX-512", Scott Gibbons, 2021-06-25, after JDK 17 forked) | openjdk/jdk [`c37988d0793`](https://github.com/openjdk/jdk/commit/c37988d0793b24d98d285530dfda69999a227937); `jdk-18+36` contains it, `jdk-17+35` does not | +| 17 | 17.0.6 (backport 2022-11-09, first tag `jdk-17.0.6+3`, first GA `jdk-17.0.6-ga`). 17.0.0 to 17.0.5 have no x86 decode intrinsic | openjdk/jdk17u-dev `07050b000c` ("Backport-of: c37988d0793b") | +| 11 | never: jdk11u-dev has no Base64 decode intrinsic (only 8205528, AVX-512 encode) | openjdk/jdk11u-dev `git log --grep base64` | +| 8 | never: jdk8u-dev has no Base64 intrinsics | openjdk/jdk8u-dev `git log --grep base64` | +| vendor builds of 8, 11 or 17.0.0-17.0.5 | **not known** whether any vendor backported 8268276 into them. The detector checks the libjvm for the VBMI decode stubs' names and reports unknown when an "unaffected" version carries them | n/a | + +## Fixed releases + +| Line | Fixed in | Source | +| --- | --- | --- | +| OpenJDK 17 | **17.0.21.1** (`jdk-17.0.21.1+2`, `jdk-17.0.21.1-ga`, 2026-11-15) | openjdk/jdk17u branch `jdk17.0.21.1`, commit `8ea73158af` | +| OpenJDK 21 | **21.0.13.1** (`jdk-21.0.13.1+2`, `-ga`, 2026-11-15) | openjdk/jdk21u branch `jdk21.0.13.1`, commit `8e115fb5c7` | +| OpenJDK 25 | **25.0.5.1** (`jdk-25.0.5.1+2`, `-ga`, 2026-11-15) | openjdk/jdk25u branch `jdk25.0.5.1`, commit `25bb7d35dc` | +| OpenJDK 27 | **27.0.1.1** (`jdk-27.0.1.1+4`, `-ga`) | openjdk/jdk27u branch `jdk27.0.1.1`, commit `564fc7de7e`; master also has it. The `jdk27.0.2` branch does **not** have it yet | +| OpenJDK 26 | **no fix**: last release 26.0.2.1 (2026-07), `jdk26u` master unchanged since 2026-08-18 and without the fix | openjdk/jdk26u | +| 18, 19, 20, 22, 23, 24 | **no fix** (end of life) | n/a | +| JDK 28 (early access) | fix pushed to mainline 2026-11-16; `jdk-28+24` does **not** have it; no later build tagged yet | openjdk/jdk tags | +| 17.0.22, 21.0.14, 25.0.6 (January 2027 updates) | **not known**: the -dev repositories (HEAD of 2026-11-17, tags up to `+2`) do not have the fix yet. Embargoed fixes usually reach -dev at the next release; that is an expectation, not a fact, so these versions are reported as unknown | openjdk/jdk17u-dev, jdk21u-dev, jdk25u-dev HEAD | +| 17.0.21.0.2 / .0.3, 21.0.13.0.2 / .0.3, 25.0.5.0.2 / .0.3, 27.0.1.0.2 / .0.3 | **not fixed**: these October 2026 out-of-band releases carry CA changes only (8395142, 8395690) | -dev repo tags `jdk-*.0.3+*` | + +## Vendors and distributions (2026-11-17) + +| Vendor | Status | Source | +| --- | --- | --- | +| Amazon Corretto | fixed: 17.0.21.1.2, 21.0.13.1.2, 25.0.5.1.2, 27.0.1.1.4 (all 2026-11-17, each "Import jdk-…1+2/+4", CVE-2026-114938 listed). Corretto 8 and 11: no release after October (not affected) | GitHub releases API, CHANGELOG.md of each tag | +| SapMachine | releases 17.0.21.1, 21.0.13.1, 25.0.5.1, 27.0.1.1 published 2026-11-17 (the release page names no CVE) | GitHub releases API, SAP/SapMachine | +| Eclipse Temurin | **not fixed yet**: no `jdk-17.0.21.1+2`, `jdk-21.0.13.1+2`, `jdk-25.0.5.1+2` or `jdk-27.0.1.1+4` release in adoptium/temurinNN-binaries; Docker Hub `eclipse-temurin` newest tags are 17.0.21_9, 21.0.13_9, 25.0.5_8, 27.0.1.0 | GitHub API, registry-1.docker.io tag list | +| Azul Zulu, BellSoft Liberica, Microsoft, Oracle | **not checked**: their sites could not be reached from the research host. Docker Hub `azul/zulu-openjdk` and `bellsoft/liberica-openjdk-debian` newest tags are 27.0.1.0.3 / 21.0.13.0.3 (not fixed) | registry-1.docker.io tag list | +| IBM Semeru | OpenJ9, not HotSpot (see above) | image inspection | +| Debian | **not fixed yet**: newest sources openjdk-17 17.0.21.0.3+1-1, openjdk-21 21.0.13.0.3+1-1, openjdk-25 25.0.5.0.3+1-3; security.debian.org 17.0.21+9-1~deb12u1, 21.0.13+9-1~deb13u2, 25.0.5+8-1~deb13u1. The security tracker has no page for CVE-2026-114938 | deb.debian.org and security.debian.org pools, security-tracker.debian.org | +| Ubuntu | **not fixed yet**: newest sources openjdk-17 17.0.21.0.3+1-1~XX.04.1, openjdk-25 25.0.5.0.3+1-3~XX.04.1 (openjdk-21 listing timed out) | archive.ubuntu.com pool | +| Alpine | **not fixed yet**: community openjdk17 17.0.21.0.3_p1-r0, openjdk21 21.0.13.0.3_p1-r0, openjdk25 25.0.5.0.3_p1-r0/-r1 (3.23, 3.24, edge); 3.21 and 3.22 carry older 17/21 | dl-cdn.alpinelinux.org APKINDEX | +| Red Hat (RHEL, UBI) | **not checked**: access.redhat.com and registry.access.redhat.com unreachable | n/a | + +## How the detector uses this + +- The version that decides is the one inside the libjvm (` () for - JRE ()`), read from the binary, with the + `release` file as a second witness; the CPU architecture comes from the ELF, PE or Mach-O header. +- A packaged JDK (apk, dpkg, rpm) is judged by the same upstream version: no distribution has published a fixed package or a backport + statement yet. When one does, its fixed package version goes into the knowledge table. +- No marker in the binary separates fixed from unfixed code: the stub is generated at run time by C++ code, and the fix only adds a compare + and a branch to that generator. The stubs' names (`lookup_lo_base64`, `pack_vec_base64`, `join_0_1_base64`) do show that the AVX-512 + decode path is present, which is how a vendor backport into an older line is caught. From d96bc7f2f277857b5b5af19575098de9395c9604 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Tue, 17 Nov 2026 22:50:05 +0000 Subject: [PATCH 002/119] java4shell: detector for Java runtimes, images and source trees (WIP, tests next) Finds Java runtimes by their VM library and judges each by its CPU architecture, the version compiled into it and the AVX-512 VBMI decode stubs it carries, with the release file as a second witness. JVM options that keep the decoder from being generated are reported as mitigated. Source trees: Java images, version files, setup-java, toolchains, buildpacks and distribution packages; fix moves image tags and setup-java versions after verifying them. Co-Authored-By: Claude Opus 5.5 --- detectors/all/all.go | 1 + detectors/java4shell/context.go | 72 ++ .../java4shell/internal/assess/assess.go | 442 +++++++++ .../java4shell/internal/assess/packages.go | 135 +++ .../java4shell/internal/assess/product.go | 83 ++ detectors/java4shell/internal/jvm/jvm.go | 323 +++++++ detectors/java4shell/internal/jvm/options.go | 205 +++++ detectors/java4shell/internal/jvm/settings.go | 192 ++++ .../internal/knowledge/knowledge.go | 289 ++++++ .../internal/knowledge/knowledge_test.go | 123 +++ detectors/java4shell/internal/repo/images.go | 205 +++++ detectors/java4shell/internal/repo/plan.go | 280 ++++++ detectors/java4shell/internal/repo/refscan.go | 189 ++++ detectors/java4shell/internal/repo/repo.go | 845 ++++++++++++++++++ detectors/java4shell/java4shell.go | 370 ++++++++ detectors/java4shell/repo.go | 344 +++++++ go.mod | 2 +- 17 files changed, 4099 insertions(+), 1 deletion(-) create mode 100644 detectors/java4shell/context.go create mode 100644 detectors/java4shell/internal/assess/assess.go create mode 100644 detectors/java4shell/internal/assess/packages.go create mode 100644 detectors/java4shell/internal/assess/product.go create mode 100644 detectors/java4shell/internal/jvm/jvm.go create mode 100644 detectors/java4shell/internal/jvm/options.go create mode 100644 detectors/java4shell/internal/jvm/settings.go create mode 100644 detectors/java4shell/internal/knowledge/knowledge.go create mode 100644 detectors/java4shell/internal/knowledge/knowledge_test.go create mode 100644 detectors/java4shell/internal/repo/images.go create mode 100644 detectors/java4shell/internal/repo/plan.go create mode 100644 detectors/java4shell/internal/repo/refscan.go create mode 100644 detectors/java4shell/internal/repo/repo.go create mode 100644 detectors/java4shell/java4shell.go create mode 100644 detectors/java4shell/repo.go diff --git a/detectors/all/all.go b/detectors/all/all.go index c1c78a4..7549169 100644 --- a/detectors/all/all.go +++ b/detectors/all/all.go @@ -4,6 +4,7 @@ package all import ( _ "github.com/DefectDojo/earlylight/detectors/brotli" _ "github.com/DefectDojo/earlylight/detectors/emudhra" + _ "github.com/DefectDojo/earlylight/detectors/java4shell" _ "github.com/DefectDojo/earlylight/detectors/php2shell" _ "github.com/DefectDojo/earlylight/detectors/sshole" ) diff --git a/detectors/java4shell/context.go b/detectors/java4shell/context.go new file mode 100644 index 0000000..9b046c4 --- /dev/null +++ b/detectors/java4shell/context.go @@ -0,0 +1,72 @@ +package java4shell + +import ( + "regexp" + "runtime" + "strings" + + "golang.org/x/sys/cpu" +) + +// CPU is the CPU this scan ran on, as context. The vulnerable decoder runs +// only on a CPU with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2, but a +// runtime that does not run it here can run it on another host (containers +// and virtual machines move), so a CPU without them clears nothing. +type CPU struct { + Arch string `json:"arch"` + AVX512F bool `json:"avx512f"` + AVX512BW bool `json:"avx512bw"` + AVX512VBMI bool `json:"avx512vbmi"` + BMI2 bool `json:"bmi2"` + Affected bool `json:"runs_vulnerable_decoder"` + Note string `json:"note"` +} + +// thisCPU reads the scanning machine's CPU features (CPUID, with the +// operating system's AVX-512 state support checked). +func thisCPU() (CPU, bool) { + if runtime.GOARCH != "amd64" { + return CPU{Arch: runtime.GOARCH, Note: "this scan ran on a CPU that is not x86-64; that says nothing about where the scanned runtimes run"}, true + } + c := CPU{Arch: "x86-64", AVX512F: cpu.X86.HasAVX512F, AVX512BW: cpu.X86.HasAVX512BW, AVX512VBMI: cpu.X86.HasAVX512VBMI, BMI2: cpu.X86.HasBMI2} + c.Affected = c.AVX512F && c.AVX512BW && c.AVX512VBMI && c.BMI2 + if c.Affected { + c.Note = "this CPU has AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2: a vulnerable runtime started here generates the vulnerable decoder unless its options turn it off" + } else { + c.Note = "this CPU lacks at least one of AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2, so a vulnerable runtime started here does not generate the vulnerable decoder; this is context only, not a clearance: the same runtime or image runs it on a host that has them" + } + return c, true +} + +// crash is a HotSpot crash log (hs_err_pid*.log), as context: the Java +// version and CPU of a past crash, and whether the crashing frame was the +// Base64 decoder. +type crash struct { + Path string `json:"path"` + Version string `json:"java_version,omitempty"` + CPUVBMI bool `json:"cpu_avx512vbmi"` + Frame string `json:"problematic_frame,omitempty"` + Base64 bool `json:"base64_decoder_frame"` +} + +var ( + jreLine = regexp.MustCompile(`(?m)^# JRE version: [^\n(]*\(([0-9][^)\s]{0,60})\)`) + frameLine = regexp.MustCompile(`(?m)^# Problematic frame:\s*\n#\s*([^\n]{1,300})`) + cpuLine = regexp.MustCompile(`(?m)^CPU:[^\n]*`) +) + +func readCrash(p string, b []byte) crash { + c := crash{Path: p} + if m := jreLine.FindSubmatch(b); m != nil { + c.Version = string(m[1]) + } + if m := frameLine.FindSubmatch(b); m != nil { + c.Frame = strings.TrimSpace(string(m[1])) + lf := strings.ToLower(c.Frame) + c.Base64 = strings.Contains(lf, "base64") || strings.Contains(lf, "decodeblock") + } + if m := cpuLine.Find(b); m != nil { + c.CPUVBMI = strings.Contains(string(m), "avx512_vbmi") || strings.Contains(string(m), "avx512vbmi") + } + return c +} diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go new file mode 100644 index 0000000..a08f9df --- /dev/null +++ b/detectors/java4shell/internal/assess/assess.go @@ -0,0 +1,442 @@ +// Package assess decides what each Java runtime in a filesystem or image is +// with respect to Java4Shell (CVE-2026-114938): vulnerable, fixed, not +// affected, mitigated or unknown, with the reason. It knows nothing about +// the engine. +package assess + +import ( + "fmt" + "path" + "sort" + "strings" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" +) + +// Status is a verdict. +type Status string + +const ( + Vulnerable Status = "vulnerable" + Fixed Status = "fixed" + NotAffected Status = "not-affected" + // Mitigated: vulnerable code, kept from running by JVM options the + // target sets. It still needs the update. + Mitigated Status = "mitigated" + Unknown Status = "unknown" +) + +// Finding kinds. +const ( + KindRuntime = "runtime" + KindBundled = "bundled-runtime" +) + +// Finding is the verdict on one Java runtime. +type Finding struct { + Kind string `json:"kind"` + Path string `json:"path"` // the runtime directory + Status Status `json:"status"` + Reason string `json:"reason"` + Message string `json:"message"` + Fix string `json:"fix"` + // Version is the version that decided, and where it was read. + Version string `json:"version,omitempty"` + VersionFrom string `json:"version_from,omitempty"` // vm-library, release-file + // ReleaseVersion is the release file's version when it differs from + // the VM library's. + ReleaseVersion string `json:"release_version,omitempty"` + Arch jvm.Arch `json:"arch,omitempty"` + VM string `json:"vm,omitempty"` + Vendor string `json:"vendor,omitempty"` + Library *jvm.Library `json:"library,omitempty"` + JLinked bool `json:"jlinked,omitempty"` + Product string `json:"product,omitempty"` + ProductDir string `json:"product_dir,omitempty"` + Package *Package `json:"package,omitempty"` + Mitigation string `json:"mitigation,omitempty"` + MitigatedFor []string `json:"mitigated_for,omitempty"` // partial mitigations (one service) + Release knowledge.Status `json:"release_status,omitempty"` +} + +// Input is everything one target gives. +type Input struct { + Libraries []*jvm.Library + // Releases maps a runtime directory to its parsed release file; + // BadReleases to why one was not used. + Releases map[string]jvm.Release + BadReleases map[string]string + Settings []jvm.Setting + // Env and Command are the image's configuration (nil for a + // filesystem). Scripts lists, for each startup script kept, the script + // variables it passes on to java. + Env []string + Command []string + Scripts map[string]map[string]bool + // Owners maps installed files to the OS package that installed them. + Owners map[string]Package + // Resolve follows symbolic links within the target. + Resolve func(string) string +} + +// Run judges every runtime in the target. +func Run(in Input) []Finding { + byRoot := map[string][]*jvm.Library{} + var loose []*jvm.Library + for _, l := range in.Libraries { + root, ok := jvm.Root(l.Path) + if !ok { + loose = append(loose, l) + continue + } + byRoot[root] = append(byRoot[root], l) + } + roots := make([]string, 0, len(byRoot)) + for r := range byRoot { + roots = append(roots, r) + } + sort.Strings(roots) + env := jvm.EnvMap(in.Env) + var out []Finding + for _, r := range roots { + out = append(out, withFix(judge(in, env, r, byRoot[r]))) + } + for _, l := range loose { + out = append(out, withFix(judge(in, env, path.Dir(l.Path), []*jvm.Library{l}))) + } + return out +} + +func withFix(f Finding) Finding { + v, ok := knowledge.Parse(f.Version) + f.Fix = fixText(f, v, ok) + return f +} + +// primary picks the library that decides: a HotSpot server VM first. +func primary(libs []*jvm.Library) *jvm.Library { + best := libs[0] + score := func(l *jvm.Library) int { + s := 0 + if l.HotSpot() { + s += 4 + } + if l.Variant == "server" { + s += 2 + } + if l.VMVersion != "" { + s++ + } + return s + } + for _, l := range libs[1:] { + if score(l) > score(best) { + best = l + } + } + return best +} + +func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Finding { + lib := primary(libs) + rel, hasRel := in.Releases[root] + if !hasRel && path.Base(root) == "jre" { + // Java 8 JDKs keep the release file one level up. + rel, hasRel = in.Releases[path.Dir(root)] + } + f := Finding{Kind: KindRuntime, Path: root, Library: lib, Arch: firstArch(lib)} + if hasRel { + f.Vendor = rel["IMPLEMENTOR"] + f.JLinked = rel.JLinked() + } + if name, dir, ok := Product(root); ok { + f.Kind, f.Product, f.ProductDir = KindBundled, name, dir + } + if p, ok := owner(in, root, lib); ok { + f.Package = &p + } + openj9 := hasRel && rel.OpenJ9() + for _, l := range libs { + if l.OpenJ9 { + openj9 = true + } + } + + // The version: the VM library's own, the release file's otherwise. + verText, from := "", "" + if lib.HotSpot() { + verText, from = lib.JREVersion, "vm-library" + } + if verText == "" && hasRel { + verText, from = rel.Version(), "release-file" + } + v, vok := knowledge.Parse(verText) + if vok { + f.Version, f.VersionFrom = verText, from + } + if hasRel && from == "vm-library" { + if rv, ok := knowledge.Parse(rel.Version()); ok && knowledge.Compare(rv.Nums, v.Nums) != 0 { + f.ReleaseVersion = rel.Version() + } + } + f.VM = lib.VMName + if openj9 { + f.VM = "OpenJ9" + } + what := describe(f, v, vok) + + switch { + case openj9: + return f.set(NotAffected, "an OpenJ9 VM: the vulnerable decoder is HotSpot code that OpenJ9 does not contain", + what+" runs the OpenJ9 VM, not HotSpot") + case len(lib.Archs) == 0 || len(lib.Archs) == 1 && lib.Archs[0] == jvm.Other: + return f.set(Unknown, "the VM library's CPU architecture could not be read", what+": CPU architecture unknown") + case !lib.Has(jvm.X8664): + return f.set(NotAffected, fmt.Sprintf("an %s runtime: only x86-64 HotSpot has the AVX-512 VBMI decoder", lib.Archs[0]), + fmt.Sprintf("%s is built for %s, which Java4Shell does not affect", what, lib.Archs[0])) + case !vok: + why := "neither the VM library nor a release file states the Java version" + if b, ok := in.BadReleases[root]; ok { + why += " (" + b + ")" + } + return f.set(Unknown, why, what+": Java version unknown") + } + ks, kwhy := knowledge.Judge(v) + f.Release = ks + read := lib.HotSpot() // the stub names are only meaningful in a HotSpot library that was read + switch ks { + case knowledge.NotAffected: + if read && lib.VBMIStubs { + return f.set(Unknown, fmt.Sprintf("Java %s should predate the AVX-512 VBMI Base64 decoder, but this VM library carries its stubs: a vendor backport, and whether it has the fix is not known", v), + what+" carries the AVX-512 VBMI Base64 decoder of later releases") + } + if !read { + return f.set(NotAffected, kwhy+" (judged by the release file: no HotSpot version line was found in the VM library)", what+" is not affected by Java4Shell") + } + return f.set(NotAffected, kwhy+"; its VM library has no AVX-512 VBMI decode stubs", what+" is not affected by Java4Shell") + case knowledge.Fixed: + return f.set(Fixed, kwhy, what+" has the Java4Shell fix") + case knowledge.Unknown: + return f.set(Unknown, kwhy, what+": not known whether it has the Java4Shell fix") + } + // The release data says vulnerable. + if read && !lib.VBMIStubs { + return f.set(Unknown, fmt.Sprintf("%s, but this VM library does not carry the AVX-512 VBMI Base64 decode stubs, which every affected OpenJDK build has: it may be built without them; check it", kwhy), + what+": release says vulnerable, VM library lacks the vulnerable decoder") + } + if !read { + kwhy += " (judged by the release file: no HotSpot version line was found in the VM library)" + } + if ok, how := mitigation(in, env, root, v.Feature(), &f); ok { + f.Mitigation = how + return f.set(Mitigated, kwhy+"; "+how, what+" is vulnerable to Java4Shell, mitigated by its JVM options until it is updated") + } + return f.set(Vulnerable, kwhy, what+" is vulnerable to Java4Shell") +} + +func (f Finding) set(s Status, reason, msg string) Finding { + f.Status, f.Reason, f.Message = s, reason, msg + return f +} + +func firstArch(l *jvm.Library) jvm.Arch { + if l.Has(jvm.X8664) { + return jvm.X8664 + } + if len(l.Archs) > 0 { + return l.Archs[0] + } + return "" +} + +// describe names a runtime in a message: "Java 21.0.13+9 (Eclipse +// Adoptium) bundled in Atlassian Jira". +func describe(f Finding, v knowledge.Version, ok bool) string { + s := "Java runtime" + if ok { + s = "Java " + v.Raw + } + if f.Vendor != "" { + s += " (" + f.Vendor + ")" + } + if f.JLinked { + s += ", a jlink image," + } + if f.Product != "" { + s += " bundled in " + f.Product + } + return s +} + +// owner finds the package that installed the runtime. +func owner(in Input, root string, lib *jvm.Library) (Package, bool) { + for _, p := range []string{lib.Path, root + "/release"} { + cands := []string{p} + if in.Resolve != nil { + if r := in.Resolve(p); r != "" && r != p { + cands = append(cands, r) + } + } + for _, c := range cands { + if o, ok := in.Owners[c]; ok { + return o, true + } + } + } + // Debian's runtime directory is reached through symlinks into + // /usr/lib/jvm/java-17-openjdk-amd64; the list names the real path. + for k, o := range in.Owners { + if strings.HasPrefix(k, root+"/") { + return o, true + } + } + return rpmFromPath(root) +} + +// mitigation decides whether JVM options the target sets keep the +// vulnerable decoder from being generated for this runtime. Mitigations +// that cover only some launches are recorded on f, not counted. +func mitigation(in Input, env map[string]string, root string, feature int, f *Finding) (bool, string) { + // Settings files of the product the runtime is bundled in. + var o jvm.Options + if in.Env != nil { + if v, ok := env["JAVA_TOOL_OPTIONS"]; ok { + o.Apply(v, "the image's JAVA_TOOL_OPTIONS") + } + if v, ok := env["JDK_JAVA_OPTIONS"]; ok && feature >= 9 { + o.Apply(v, "the image's JDK_JAVA_OPTIONS") + } + // Script variables count when the container's command passes them on. + vars := scriptVarsOf(in) + for _, n := range jvm.ScriptVars { + if v, ok := env[n]; ok && vars[n] { + o.Apply(v, "the image's "+n+" (passed on by the container's start script)") + } + } + if opts, ok := jvm.JavaOptions(in.Command); ok && commandRuns(in, env, root) { + for _, w := range opts { + o.ApplyWord(w, "the container's command") + } + } + } + for _, s := range in.Settings { + if s.Kind == "systemd" || s.Scope == "" || !within(root, s.Scope) { + continue + } + s.ApplyTo(&o, feature) + } + if in.Env != nil { + if v, ok := env["_JAVA_OPTIONS"]; ok { + o.Apply(v, "the image's _JAVA_OPTIONS") + } + } + if ok, how := o.Mitigates(); ok { + return true, how + } + // systemd units: they cover the service, and the runtime only when it + // is bundled in the product the service starts. + for _, s := range in.Settings { + if s.Kind != "systemd" { + continue + } + so := s.Options(feature) + ok, how := so.Mitigates() + if !ok || s.Exec == "" { + continue + } + exec := s.Exec + if in.Resolve != nil { + if r := in.Resolve(exec); r != "" { + exec = r + } + } + if f.ProductDir != "" && within(exec, f.ProductDir) { + return true, how + " for the " + s.Unit + " service, which starts " + f.Product + } + if within(exec, root) { + f.MitigatedFor = append(f.MitigatedFor, s.Unit) + } + } + return false, "" +} + +// commandRuns reports whether the container's command starts this +// runtime's java: by path, or by name through PATH. +func commandRuns(in Input, env map[string]string, root string) bool { + for _, w := range in.Command { + if path.Base(w) != "java" { + continue + } + p := w + if !strings.Contains(w, "/") { + for _, d := range strings.Split(env["PATH"], ":") { + if d != "" && (d == root+"/bin" || in.Resolve != nil && in.Resolve(d+"/java") == in.Resolve(root+"/bin/java")) { + return true + } + } + return false + } + if in.Resolve != nil { + p = in.Resolve(p) + } + return within(p, root) + } + return false +} + +// scriptVarsOf lists the script variables the container's command passes +// on: catalina.sh passes CATALINA_OPTS and JAVA_OPTS, and a startup script +// passes the ones it names. +func scriptVarsOf(in Input) map[string]bool { + out := map[string]bool{} + for _, w := range in.Command { + if path.Base(w) == "catalina.sh" { + out["CATALINA_OPTS"], out["JAVA_OPTS"] = true, true + } + p := w + if in.Resolve != nil { + p = in.Resolve(w) + } + for k := range in.Scripts[p] { + out[k] = true + } + for k := range in.Scripts[w] { + out[k] = true + } + } + return out +} + +func within(p, dir string) bool { + return p == dir || strings.HasPrefix(p, strings.TrimSuffix(dir, "/")+"/") +} + +// fixText is what to do. +func fixText(f Finding, v knowledge.Version, ok bool) string { + switch f.Status { + case Fixed, NotAffected: + return "" + } + interim := " Until then, start it with -XX:-UseBASE64Intrinsics (for example JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics); that keeps the vulnerable decoder from being generated, at some cost to Base64 decoding speed." + if f.Status == Mitigated { + interim = " The JVM options keep the vulnerable decoder from running until then; keep them until it is updated." + } + target := "a release with the fix (17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later on the same update)" + if ok { + if fx := knowledge.FixedVersion(v.Feature()); fx != "" { + target = fx + " or later of the same update" + } else if v.Feature() >= 17 { + target = "a supported release with the fix, such as " + knowledge.Upgrade(v.Feature()) + " (Java " + fmt.Sprint(v.Feature()) + " received none)" + } + } + switch { + case f.Product != "": + return fmt.Sprintf("Upgrade %s to a release that bundles Java %s; its own runtime is not updated by the operating system's Java packages.%s", f.Product, target, interim) + case f.Package != nil: + return fmt.Sprintf("Update the %s package to Java %s: %s (%s).%s", f.Package.Name, target, upgradeLine(*f.Package), distroStatus(*f.Package), interim) + case f.JLinked: + return fmt.Sprintf("Rebuild this jlink image from a JDK at %s.%s", target, interim) + } + return fmt.Sprintf("Update this runtime to Java %s (Amazon Corretto and SapMachine published theirs on 2026-11-17; check your vendor).%s", target, interim) +} diff --git a/detectors/java4shell/internal/assess/packages.go b/detectors/java4shell/internal/assess/packages.go new file mode 100644 index 0000000..e34daa2 --- /dev/null +++ b/detectors/java4shell/internal/assess/packages.go @@ -0,0 +1,135 @@ +package assess + +import ( + "path" + "regexp" + "strings" +) + +// Package is the OS package that installed a runtime. +type Package struct { + Manager string `json:"manager"` // apk, dpkg, rpm + Name string `json:"name"` + Version string `json:"version,omitempty"` + // From says how it was found: the package database, or the install path + // (rpm, whose database this detector does not read). + From string `json:"from"` +} + +// javaPackage reports a package name that can hold a Java runtime. +func javaPackage(name string) bool { + n := strings.ToLower(name) + for _, s := range []string{"openjdk", "jdk", "jre", "java", "corretto", "temurin", "zulu", "liberica", "sapmachine", "semeru", "graalvm", "jbr"} { + if strings.Contains(n, s) { + return true + } + } + return false +} + +// APKOwners maps the files of Java packages in an apk database to their +// package. +func APKOwners(db []byte) map[string]Package { + out := map[string]Package{} + var name, ver, dir string + keep := false + for _, line := range strings.Split(string(db), "\n") { + if len(line) < 2 || line[1] != ':' { + if line == "" { + name, ver, dir, keep = "", "", "", false + } + continue + } + v := line[2:] + switch line[0] { + case 'P': + name, keep = v, javaPackage(v) + case 'V': + ver = v + case 'F': + dir = v + case 'R': + if keep && strings.HasPrefix(v, "libjvm.so") || keep && v == "release" { + out["/"+path.Join(dir, v)] = Package{Manager: "apk", Name: name, Version: ver, From: "/lib/apk/db/installed"} + } + } + } + return out +} + +// DpkgOwners maps the files listed in dpkg .list files of Java packages to +// their package, with versions from the status file. +func DpkgOwners(status []byte, lists map[string][]byte) map[string]Package { + versions := map[string]string{} + var name string + for _, line := range strings.Split(string(status), "\n") { + switch { + case strings.HasPrefix(line, "Package: "): + name = strings.TrimSpace(strings.TrimPrefix(line, "Package: ")) + case strings.HasPrefix(line, "Version: ") && name != "": + versions[name] = strings.TrimSpace(strings.TrimPrefix(line, "Version: ")) + case line == "": + name = "" + } + } + out := map[string]Package{} + for pkg, b := range lists { + n, _, _ := strings.Cut(pkg, ":") + for _, f := range strings.Split(string(b), "\n") { + f = strings.TrimSpace(f) + if strings.HasSuffix(f, "/libjvm.so") || strings.HasSuffix(f, "/release") { + out[f] = Package{Manager: "dpkg", Name: n, Version: versions[n], From: "/var/lib/dpkg/status"} + } + } + } + return out +} + +// IsDpkgList reports a dpkg file list worth reading. +func IsDpkgList(p string) bool { + return strings.HasPrefix(p, "/var/lib/dpkg/info/") && strings.HasSuffix(p, ".list") && + javaPackage(strings.TrimSuffix(path.Base(p), ".list")) +} + +// rpmPath is how Red Hat, Fedora, SUSE and Amazon Linux name a packaged +// runtime: /usr/lib/jvm/java-17-openjdk-17.0.13.0.11-3.el9.x86_64. +var rpmPath = regexp.MustCompile(`^/usr/lib(?:64)?/jvm/(java-(\d+)-openjdk)-(\d[\w.]*-[\w.]+?)\.(x86_64|aarch64|ppc64le|s390x)$`) + +// rpmFromPath names the rpm package a runtime directory belongs to. +func rpmFromPath(root string) (Package, bool) { + m := rpmPath.FindStringSubmatch(root) + if m == nil { + if strings.HasPrefix(root, "/usr/lib/jvm/java-") && strings.Contains(root, "amazon-corretto") { + return Package{Manager: "rpm", Name: path.Base(root), From: "install path"}, true + } + return Package{}, false + } + return Package{Manager: "rpm", Name: m[1] + "-headless", Version: m[3], From: "install path"}, true +} + +// upgradeLine is the command that upgrades a package. +func upgradeLine(p Package) string { + switch p.Manager { + case "apk": + return "apk upgrade " + p.Name + case "dpkg": + return "apt-get install --only-upgrade " + p.Name + case "rpm": + return "dnf upgrade " + p.Name + " (or yum upgrade)" + } + return "" +} + +// distroStatus says whether the distribution had a fixed package when the +// data was checked. +func distroStatus(p Package) string { + switch p.Manager { + case "apk": + return "Alpine had published no fixed package as of 2026-11-17" + case "dpkg": + return "Debian and Ubuntu had published no fixed package as of 2026-11-17" + case "rpm": + return "the distribution's fix status was not checked" + } + return "" +} diff --git a/detectors/java4shell/internal/assess/product.go b/detectors/java4shell/internal/assess/product.go new file mode 100644 index 0000000..f63b7ec --- /dev/null +++ b/detectors/java4shell/internal/assess/product.go @@ -0,0 +1,83 @@ +package assess + +import ( + "path" + "strings" +) + +// standardPlaces are where Java runtimes are installed on their own (by a +// package, an image, an installer, a version manager or a CI runner). A +// runtime there is not part of another product. +var standardPlaces = []string{ + "/usr/lib/jvm/", "/usr/lib64/jvm/", "/usr/java/", "/opt/java/", "/usr/local/java/", "/usr/jdk/", + "/usr/local/openjdk", "/opt/openjdk", "/opt/jdk", "/opt/hostedtoolcache/", "/Library/Java/JavaVirtualMachines/", + "/System/Library/Java/", "/.sdkman/candidates/java/", "/.jdks/", "/.gradle/jdks/", "/.asdf/installs/java/", + "/.local/share/mise/installs/java/", "/.m2/jdks/", "/usr/lib/jvm-", "/opt/ibm/java", "/opt/graalvm", + "/Program Files/Java/", "/Program Files/Eclipse Adoptium/", "/Program Files/Eclipse Foundation/", "/Program Files/Zulu/", + "/Program Files/Amazon Corretto/", "/Program Files/Microsoft/", "/Program Files/BellSoft/", "/Program Files/Semeru/", + "/Program Files/SapMachine/", "/Program Files (x86)/Java/", +} + +// runtimeDirs are the names products give the runtime they bundle. +var runtimeDirs = map[string]bool{"jre": true, "jdk": true, "jbr": true, "java": true, "runtime": true, "jre64": true, "openjdk": true, + "jre-x64": true, "jdk-x64": true, "Home": true} + +// products names well-known products by a piece of their install path. +var products = []struct{ part, name string }{ + {"/atlassian/jira", "Atlassian Jira"}, {"/atlassian/confluence", "Atlassian Confluence"}, {"/atlassian/bitbucket", "Atlassian Bitbucket"}, + {"/atlassian/bamboo", "Atlassian Bamboo"}, {"/atlassian/crowd", "Atlassian Crowd"}, {"/atlassian/", "Atlassian product"}, + {"/elasticsearch", "Elasticsearch"}, {"/logstash", "Logstash"}, {"/opensearch", "OpenSearch"}, {"/kibana", "Kibana"}, + {"/artifactory", "JFrog Artifactory"}, {"/jfrog/", "JFrog product"}, {"/sonatype/nexus", "Sonatype Nexus"}, {"/nexus", "Sonatype Nexus"}, + {"/teamcity", "JetBrains TeamCity"}, {"/youtrack", "JetBrains YouTrack"}, {"IntelliJ", "IntelliJ IDEA"}, {"/idea", "IntelliJ IDEA"}, + {"PyCharm", "PyCharm"}, {"/pycharm", "PyCharm"}, {"/android-studio", "Android Studio"}, {"Android Studio", "Android Studio"}, + {"/JetBrains/", "JetBrains IDE"}, {"/jetbrains", "JetBrains IDE"}, {"/sonarqube", "SonarQube"}, {"/keycloak", "Keycloak"}, + {"/jenkins", "Jenkins"}, {"/solr", "Apache Solr"}, {"/kafka", "Apache Kafka"}, {"/confluent", "Confluent Platform"}, + {"/BurpSuite", "Burp Suite"}, {"Burp Suite", "Burp Suite"}, {"/dbeaver", "DBeaver"}, {"DBeaver", "DBeaver"}, {"/eclipse", "Eclipse IDE"}, + {"/netbeans", "Apache NetBeans"}, {"/minecraft", "Minecraft"}, {"/tableau", "Tableau"}, {"/MATLAB", "MATLAB"}, + {"/cassandra", "Apache Cassandra"}, {"/neo4j", "Neo4j"}, {"/gitbucket", "GitBucket"}, {"/rundeck", "Rundeck"}, +} + +// standard reports a runtime installed on its own. +func standard(root string) bool { + for _, p := range standardPlaces { + if strings.Contains(root, p) { + return true + } + } + return false +} + +// Product returns the product a runtime is bundled with: its name and +// install directory. ok is false for a runtime installed on its own. +func Product(root string) (name, dir string, ok bool) { + if standard(root) { + return "", "", false + } + dir = root + // A macOS runtime: .app/Contents/jbr/Contents/Home. + if strings.HasSuffix(dir, "/Contents/Home") { + dir = strings.TrimSuffix(dir, "/Contents/Home") + } + if !runtimeDirs[path.Base(dir)] { + // Products also nest it one level deeper (lib/runtime/jre, + // app/third-party/java/). + parent := path.Base(path.Dir(dir)) + if !runtimeDirs[parent] && parent != "third-party" { + return "", "", false + } + dir = path.Dir(dir) + } + dir = path.Dir(dir) + for _, x := range []string{"/third-party", "/app", "/lib", "/Contents"} { + dir = strings.TrimSuffix(dir, x) + } + if dir == "/" || dir == "." || dir == "" { + return "", "", false + } + for _, p := range products { + if strings.Contains(dir, p.part) { + return p.name, dir, true + } + } + return path.Base(dir), dir, true +} diff --git a/detectors/java4shell/internal/jvm/jvm.go b/detectors/java4shell/internal/jvm/jvm.go new file mode 100644 index 0000000..b063c8b --- /dev/null +++ b/detectors/java4shell/internal/jvm/jvm.go @@ -0,0 +1,323 @@ +// Package jvm reads what a Java runtime's files prove: the VM library's CPU +// architecture (from its ELF, PE or Mach-O header), the VM name and version +// compiled into it, whether it carries the AVX-512 VBMI Base64 decode stubs, +// and the runtime's release file. It knows nothing about the engine. +package jvm + +import ( + "bytes" + "encoding/binary" + "path" + "regexp" + "strings" +) + +// Arch is a CPU architecture. +type Arch string + +const ( + X8664 Arch = "x86-64" + AArch64 Arch = "aarch64" + X86 Arch = "x86" + ARM Arch = "arm" + PPC64 Arch = "ppc64" + S390X Arch = "s390x" + RISCV64 Arch = "riscv64" + Other Arch = "other" +) + +// Library is one JVM library file: libjvm.so, jvm.dll, libjvm.dylib, or an +// OpenJ9 VM library. +type Library struct { + Path string `json:"path"` + Format string `json:"format"` // elf, pe, macho + // Archs are the architectures the file holds code for (a universal + // Mach-O file holds several). + Archs []Arch `json:"archs"` + // VMName, VMVersion and JREVersion come from the version line compiled + // into HotSpot ("OpenJDK 64-Bit Server VM (21.0.13+9-LTS) for + // linux-amd64 JRE (21.0.13+9-LTS)"). Empty when it is not there. + VMName string `json:"vm_name,omitempty"` + VMVersion string `json:"vm_version,omitempty"` + JREVersion string `json:"jre_version,omitempty"` + Platform string `json:"platform,omitempty"` // "linux-amd64" + // VBMIStubs is true when the library names the AVX-512 VBMI Base64 + // decode stubs (lookup_lo_base64, pack_vec_base64), which come with the + // vulnerable decoder (8268276). + VBMIStubs bool `json:"vbmi_stubs"` + // OpenJ9 is true for an OpenJ9 VM library or redirector. + OpenJ9 bool `json:"openj9,omitempty"` + // Variant is the VM directory: server, client, minimal, zero, j9vm... + Variant string `json:"variant,omitempty"` +} + +// HotSpot reports whether the library is a HotSpot VM. +func (l *Library) HotSpot() bool { return !l.OpenJ9 && l.VMName != "" } + +// Has reports whether the library holds code for a. +func (l *Library) Has(a Arch) bool { + for _, x := range l.Archs { + if x == a { + return true + } + } + return false +} + +var libNames = map[string]bool{"libjvm.so": true, "jvm.dll": true, "libjvm.dylib": true} + +// IsOpenJ9Name reports an OpenJ9 VM library name (libj9vm29.so, j9vm29.dll). +func IsOpenJ9Name(base string) bool { + b := strings.ToLower(base) + return (strings.HasPrefix(b, "libj9vm") || strings.HasPrefix(b, "j9vm")) && + (strings.HasSuffix(b, ".so") || strings.HasSuffix(b, ".dll") || strings.HasSuffix(b, ".dylib")) +} + +// IsLibraryName reports whether a file name is a JVM library. +func IsLibraryName(base string) bool { + return libNames[base] || libNames[strings.ToLower(base)] || IsOpenJ9Name(base) +} + +// vmLine is the version line HotSpot compiles in. JDK 8 has the same shape +// ("... JRE (1.8.0_452-b09)"). +var vmLine = regexp.MustCompile(`([A-Za-z][ -~]{2,80}?VM) \(([0-9][!-'*-~]{0,60})\) for ([a-z0-9_]{1,20})-([a-z0-9_]{1,20}) JRE \(([0-9][!-'*-~]{0,80})\)`) + +// maxScan bounds how much of a file the version line is looked for in: it +// sits in read-only data, and a libjvm is under 64 MiB. +const maxScan = 256 << 20 + +// Inspect reads a JVM library. ok is false when the file is not one (wrong +// name or not an executable format). +func Inspect(p string, data []byte) (*Library, bool) { + base := path.Base(p) + if !IsLibraryName(base) { + return nil, false + } + format, archs := header(data) + if format == "" { + return nil, false + } + l := &Library{Path: p, Format: format, Archs: archs, Variant: path.Base(path.Dir(p))} + b := data + if len(b) > maxScan { + b = b[:maxScan] + } + if m := vmLine.FindSubmatch(b); m != nil { + l.VMName, l.VMVersion, l.JREVersion = string(m[1]), string(m[2]), string(m[5]) + l.Platform = string(m[3]) + "-" + string(m[4]) + } + l.VBMIStubs = bytes.Contains(b, []byte("lookup_lo_base64\x00")) && bytes.Contains(b, []byte("pack_vec_base64\x00")) + if IsOpenJ9Name(base) || l.VMName == "" && (bytes.Contains(b, []byte("OPENJ9_JAVA_OPTIONS")) || bytes.Contains(b, []byte("j9vm"))) { + l.OpenJ9 = true + } + return l, true +} + +// header reads an executable header: the format and the architectures. +func header(b []byte) (string, []Arch) { + switch { + case len(b) >= 20 && bytes.HasPrefix(b, []byte("\x7fELF")): + var m uint16 + if b[5] == 2 { + m = binary.BigEndian.Uint16(b[18:20]) + } else { + m = binary.LittleEndian.Uint16(b[18:20]) + } + return "elf", []Arch{elfArch(m)} + case len(b) >= 64 && b[0] == 'M' && b[1] == 'Z': + off := int(binary.LittleEndian.Uint32(b[60:64])) + if off < 0 || off+6 > len(b) || !bytes.Equal(b[off:off+4], []byte("PE\x00\x00")) { + return "", nil + } + return "pe", []Arch{peArch(binary.LittleEndian.Uint16(b[off+4 : off+6]))} + case len(b) >= 8: + le := binary.LittleEndian.Uint32(b[0:4]) + if le == 0xfeedfacf || le == 0xfeedface { + return "macho", []Arch{machoArch(binary.LittleEndian.Uint32(b[4:8]))} + } + be := binary.BigEndian.Uint32(b[0:4]) + if be == 0xcafebabe || be == 0xcafebabf { + n := int(binary.BigEndian.Uint32(b[4:8])) + // A Java class file has the same magic; its "count" is a version + // number of 45 or more. A universal binary holds a few slices. + if n < 1 || n > 8 { + return "", nil + } + size := 20 + if be == 0xcafebabf { + size = 32 + } + var out []Arch + for i := 0; i < n; i++ { + o := 8 + i*size + if o+4 > len(b) { + return "", nil + } + out = append(out, machoArch(binary.BigEndian.Uint32(b[o:o+4]))) + } + return "macho", out + } + } + return "", nil +} + +func elfArch(m uint16) Arch { + switch m { + case 0x3e: + return X8664 + case 0xb7: + return AArch64 + case 3: + return X86 + case 0x28: + return ARM + case 0x15: + return PPC64 + case 0x16: + return S390X + case 0xf3: + return RISCV64 + } + return Other +} + +func peArch(m uint16) Arch { + switch m { + case 0x8664: + return X8664 + case 0xaa64: + return AArch64 + case 0x14c: + return X86 + } + return Other +} + +func machoArch(c uint32) Arch { + switch c { + case 0x01000007: + return X8664 + case 0x0100000c: + return AArch64 + case 7: + return X86 + } + return Other +} + +// variantDirs are the directories a VM library sits in. +var variantDirs = map[string]bool{"server": true, "client": true, "minimal": true, "zero": true, "j9vm": true, "default": true, + "compressedrefs": true, "classic": true, "hotspot": true, "jvmci": true} + +// archDirs are the CPU directories of JDK 8 layouts (jre/lib/amd64/server). +var archDirs = map[string]bool{"amd64": true, "x86_64": true, "i386": true, "i586": true, "aarch64": true, "arm64": true, "ppc64le": true, "ppc64": true, + "s390x": true, "riscv64": true, "arm": true, "sparcv9": true} + +// Root returns the runtime directory a VM library belongs to: +// /lib/server/libjvm.so, /bin/server/jvm.dll, +// /lib/amd64/server/libjvm.so (Java 8). ok is false for any other +// place. +func Root(lib string) (string, bool) { + dir := path.Dir(lib) + if !variantDirs[path.Base(dir)] { + // OpenJ9 and some builds keep a VM library directly in lib/ or bin/. + if b := path.Base(dir); b == "lib" || b == "bin" { + return path.Dir(dir), true + } + return "", false + } + dir = path.Dir(dir) + if archDirs[path.Base(dir)] { + dir = path.Dir(dir) + } + if b := path.Base(dir); b != "lib" && b != "bin" { + return "", false + } + return path.Dir(dir), true +} + +// Release is a runtime's release file. +type Release map[string]string + +// maxRelease bounds a release file: real ones are a few KiB. +const maxRelease = 64 << 10 + +// ParseRelease reads KEY="value" lines. ok is false for a file too large +// or with nothing a release file has. +func ParseRelease(b []byte) (Release, bool) { + if len(b) > maxRelease { + return nil, false + } + r := Release{} + for _, line := range strings.Split(string(b), "\n") { + line = strings.TrimSpace(strings.TrimSuffix(line, "\r")) + k, v, ok := strings.Cut(line, "=") + if !ok || k == "" || len(k) > 64 || strings.ContainsAny(k, " \t\"") { + continue + } + v = strings.TrimSpace(v) + if len(v) >= 2 && v[0] == '"' && v[len(v)-1] == '"' { + v = v[1 : len(v)-1] + } + if len(v) > 4096 { + v = v[:4096] + } + if _, dup := r[k]; !dup { + r[k] = v + } + } + if r["JAVA_VERSION"] == "" { + return nil, false + } + return r, true +} + +// Version is the most precise version the release file states. +func (r Release) Version() string { + if v := r["JAVA_RUNTIME_VERSION"]; v != "" { + return v + } + return r["JAVA_VERSION"] +} + +// Arch is the release file's OS_ARCH as an Arch, "" when it does not say. +func (r Release) Arch() Arch { + switch strings.ToLower(r["OS_ARCH"]) { + case "": + return "" + case "x86_64", "amd64", "x64": + return X8664 + case "aarch64", "arm64": + return AArch64 + case "x86", "i386", "i586", "i686": + return X86 + case "arm": + return ARM + case "ppc64le", "ppc64": + return PPC64 + case "s390x": + return S390X + case "riscv64": + return RISCV64 + } + return Other +} + +// OpenJ9 reports a release file that names the OpenJ9 VM. +func (r Release) OpenJ9() bool { return strings.EqualFold(r["JVM_VARIANT"], "openj9") } + +// JLinked reports a runtime made with jlink: a release file with MODULES and +// without java.se, the module every full JDK and JRE has. A jlink image +// keeps only JAVA_VERSION and MODULES of the JDK's release file. +func (r Release) JLinked() bool { + m := r["MODULES"] + if m == "" { + return false + } + for _, x := range strings.Fields(m) { + if x == "java.se" { + return false + } + } + return true +} diff --git a/detectors/java4shell/internal/jvm/options.go b/detectors/java4shell/internal/jvm/options.go new file mode 100644 index 0000000..6ebfbd0 --- /dev/null +++ b/detectors/java4shell/internal/jvm/options.go @@ -0,0 +1,205 @@ +package jvm + +import ( + "fmt" + "strconv" + "strings" +) + +// Options is what JVM options say about the vulnerable decoder: the last +// value given to -XX:±UseBASE64Intrinsics and -XX:UseAVX. HotSpot applies +// options in order, so the last one wins. +type Options struct { + Base64 *bool // nil: not set + UseAVX *int + // Where names the setting that decided each value ("JAVA_TOOL_OPTIONS"). + Base64From, AVXFrom string +} + +// maxOptionText bounds an option string: environment values and option +// files are short. +const maxOptionText = 256 << 10 + +// Apply reads one option string from source (an environment variable, a +// file) on top of what is already set. +func (o *Options) Apply(text, source string) { + if len(text) > maxOptionText { + text = text[:maxOptionText] + } + for _, w := range Words(text) { + o.ApplyWord(w, source) + } +} + +// ApplyWord reads one option. +func (o *Options) ApplyWord(w, source string) { + switch { + case w == "-XX:-UseBASE64Intrinsics": + f := false + o.Base64, o.Base64From = &f, source + case w == "-XX:+UseBASE64Intrinsics": + t := true + o.Base64, o.Base64From = &t, source + case strings.HasPrefix(w, "-XX:UseBASE64Intrinsics="): + switch strings.TrimPrefix(w, "-XX:UseBASE64Intrinsics=") { + case "false": + f := false + o.Base64, o.Base64From = &f, source + case "true": + t := true + o.Base64, o.Base64From = &t, source + } + case strings.HasPrefix(w, "-XX:UseAVX="): + if n, err := strconv.Atoi(strings.TrimPrefix(w, "-XX:UseAVX=")); err == nil && n >= 0 && n < 100 { + o.UseAVX, o.AVXFrom = &n, source + } + } +} + +// Mitigates reports whether the options keep HotSpot from generating the +// vulnerable decoder, and how. +func (o Options) Mitigates() (bool, string) { + if o.Base64 != nil && !*o.Base64 { + return true, fmt.Sprintf("-XX:-UseBASE64Intrinsics (from %s) turns the Base64 intrinsics off", o.Base64From) + } + if o.UseAVX != nil && *o.UseAVX <= 2 { + return true, fmt.Sprintf("-XX:UseAVX=%d (from %s) turns AVX-512 off, so the AVX-512 VBMI decoder is not generated", *o.UseAVX, o.AVXFrom) + } + return false, "" +} + +// Set reports whether either option was given at all. +func (o Options) Set() bool { return o.Base64 != nil || o.UseAVX != nil } + +// Words splits an option string the way a shell or the JVM's option +// variables do: on white space, with single and double quotes grouping. +func Words(s string) []string { + var out []string + var b strings.Builder + in := false + var q byte + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case q != 0: + if c == q { + q = 0 + } else { + b.WriteByte(c) + } + case c == '"' || c == '\'': + q, in = c, true + case c == '\\' && i+1 < len(s): + i++ + b.WriteByte(s[i]) + in = true + case c == ' ' || c == '\t' || c == '\n' || c == '\r': + if in { + out = append(out, b.String()) + b.Reset() + in = false + } + default: + b.WriteByte(c) + in = true + } + } + if in { + out = append(out, b.String()) + } + return out +} + +// EnvVars are the variables the JVM itself reads, in the order HotSpot +// applies them: JAVA_TOOL_OPTIONS first, then JDK_JAVA_OPTIONS (the java +// launcher, Java 9 and later, puts it before the command line), then the +// command line, then _JAVA_OPTIONS, which overrides everything. +var EnvVars = []string{"JAVA_TOOL_OPTIONS", "JDK_JAVA_OPTIONS", "_JAVA_OPTIONS"} + +// ScriptVars are variables only launch scripts read (catalina.sh, +// Atlassian's setenv.sh, many start scripts). +var ScriptVars = []string{"JAVA_OPTS", "CATALINA_OPTS", "JVM_SUPPORT_RECOMMENDED_ARGS", "JVM_OPTS", "ES_JAVA_OPTS", "SOLR_OPTS", "KAFKA_OPTS", "KAFKA_HEAP_OPTS"} + +// FromEnv computes the options a JVM started in env with command line cmd +// gets. feature is the Java release (JDK_JAVA_OPTIONS needs 9 or later); +// scriptVars lists the script variables the launch passes on. +func FromEnv(env map[string]string, cmd []string, feature int, scriptVars map[string]bool) Options { + var o Options + if v, ok := env["JAVA_TOOL_OPTIONS"]; ok { + o.Apply(v, "JAVA_TOOL_OPTIONS") + } + if v, ok := env["JDK_JAVA_OPTIONS"]; ok && feature >= 9 { + o.Apply(v, "JDK_JAVA_OPTIONS") + } + for _, name := range ScriptVars { + if v, ok := env[name]; ok && scriptVars[name] { + o.Apply(v, name) + } + } + for _, w := range cmd { + o.ApplyWord(w, "the command line") + } + if v, ok := env["_JAVA_OPTIONS"]; ok { + o.Apply(v, "_JAVA_OPTIONS") + } + return o +} + +// EnvMap turns "KEY=value" entries into a map, the last one winning. +func EnvMap(env []string) map[string]string { + m := map[string]string{} + for _, e := range env { + if k, v, ok := strings.Cut(e, "="); ok { + m[k] = v + } + } + return m +} + +// valueOptions are java launcher options followed by a separate value. +var valueOptions = map[string]bool{"-cp": true, "-classpath": true, "--class-path": true, "-p": true, "--module-path": true, + "--upgrade-module-path": true, "--add-modules": true, "--enable-native-access": true, "--limit-modules": true, + "--add-reads": true, "--add-exports": true, "--add-opens": true, "--patch-module": true, "--source": true} + +// JavaOptions returns the JVM options a container command gives the java +// launcher: the words after a java executable up to the main class or +// -jar. A "sh -c" script is split into words first. ok is false when the +// command does not start java directly. +func JavaOptions(cmd []string) ([]string, bool) { + if len(cmd) > 1024 { + cmd = cmd[:1024] + } + words := cmd + for i := 0; i+2 < len(cmd); i++ { + if b := baseName(cmd[i]); (b == "sh" || b == "bash" || b == "ash" || b == "dash") && cmd[i+1] == "-c" { + words = Words(cmd[i+2]) + break + } + } + for i, w := range words { + if baseName(w) != "java" { + continue + } + var out []string + for j := i + 1; j < len(words); j++ { + x := words[j] + if x == "-jar" || x == "-m" || x == "--module" || !strings.HasPrefix(x, "-") { + break + } + if valueOptions[x] { + j++ + continue + } + out = append(out, x) + } + return out, true + } + return nil, false +} + +func baseName(p string) string { + if i := strings.LastIndexAny(p, "/\\"); i >= 0 { + p = p[i+1:] + } + return strings.TrimSuffix(strings.ToLower(p), ".exe") +} diff --git a/detectors/java4shell/internal/jvm/settings.go b/detectors/java4shell/internal/jvm/settings.go new file mode 100644 index 0000000..ad93594 --- /dev/null +++ b/detectors/java4shell/internal/jvm/settings.go @@ -0,0 +1,192 @@ +package jvm + +import ( + "path" + "regexp" + "strconv" + "strings" +) + +// Setting is a file that gives JVM options to the JVMs one product or +// service starts: a Tomcat or Atlassian setenv.sh, an Elasticsearch-style +// jvm.options, a JetBrains or install4j .vmoptions file, a systemd unit. +type Setting struct { + File string `json:"file"` + Kind string `json:"kind"` // setenv, jvm.options, vmoptions, systemd + // Scope is the product directory whose JVMs the file configures; "" for + // a systemd unit, which configures the service it starts. + Scope string `json:"scope,omitempty"` + // Unit is the systemd unit name. + Unit string `json:"unit,omitempty"` + // Exec is the program a systemd unit starts. + Exec string `json:"exec,omitempty"` + // Env are the JVM option variables a systemd unit sets. + Env map[string]string `json:"env,omitempty"` + lines []optLine +} + +// optLine is one option, with the Java releases it applies to +// (Elasticsearch's "17-:-XX:..." lines); hi 0 means no upper bound. +type optLine struct { + lo, hi int + word string +} + +// Options returns what the file sets for a runtime of the given Java +// release. +func (s Setting) Options(feature int) Options { + var o Options + s.ApplyTo(&o, feature) + return o +} + +// ApplyTo applies the file's options, in order, on top of o. +func (s Setting) ApplyTo(o *Options, feature int) { + for _, l := range s.lines { + if feature > 0 && (l.lo > 0 && feature < l.lo || l.hi > 0 && feature > l.hi) { + continue + } + o.ApplyWord(l.word, s.File) + } +} + +// Mentions reports whether the file sets either option at all. +func (s Setting) Mentions() bool { return len(s.lines) > 0 } + +// SettingKind classifies a path, "" when it is not a settings file. +func SettingKind(p string) string { + base := path.Base(p) + dir := path.Dir(p) + switch { + case base == "setenv.sh" || base == "setenv.bat": + return "setenv" + case base == "jvm.options" || strings.HasPrefix(base, "jvm") && strings.HasSuffix(base, ".options") || + strings.HasSuffix(base, ".options") && path.Base(dir) == "jvm.options.d": + return "jvm.options" + case strings.HasSuffix(base, ".vmoptions"): + return "vmoptions" + case (strings.HasSuffix(base, ".service") || strings.HasSuffix(base, ".conf") && strings.HasSuffix(dir, ".service.d")) && systemdDir(p): + return "systemd" + } + return "" +} + +func systemdDir(p string) bool { + for _, d := range []string{"/etc/systemd/system/", "/usr/lib/systemd/system/", "/lib/systemd/system/", "/run/systemd/system/", "/usr/local/lib/systemd/system/"} { + if strings.HasPrefix(p, d) { + return true + } + } + return false +} + +// maxSetting bounds a settings file. +const maxSetting = 1 << 20 + +var ( + xxRE = regexp.MustCompile(`-XX:(?:[+-]UseBASE64Intrinsics|UseBASE64Intrinsics=(?:true|false)|UseAVX=\d{1,2})\b`) + selectorRE = regexp.MustCompile(`^(\d{1,3})(-(\d{1,3})?)?:`) +) + +// ReadSetting reads a settings file. ok is false when p is not one, or it +// is too large. +func ReadSetting(p string, b []byte) (Setting, bool) { + kind := SettingKind(p) + if kind == "" || len(b) > maxSetting { + return Setting{}, false + } + s := Setting{File: p, Kind: kind} + dir := path.Dir(p) + switch kind { + case "setenv", "vmoptions": + if path.Base(dir) == "bin" { + dir = path.Dir(dir) + } + s.Scope = dir + case "jvm.options": + if path.Base(dir) == "jvm.options.d" { + dir = path.Dir(dir) + } + if b := path.Base(dir); b == "config" || b == "conf" || b == "etc" { + dir = path.Dir(dir) + } + s.Scope = dir + case "systemd": + u := path.Base(p) + if strings.HasSuffix(dir, ".service.d") { + u = path.Base(dir) + u = strings.TrimSuffix(u, ".d") + } + s.Unit = u + s.Env = map[string]string{} + } + for _, raw := range strings.Split(string(b), "\n") { + line := strings.TrimSpace(strings.TrimSuffix(raw, "\r")) + if line == "" || line[0] == '#' || line[0] == ';' || strings.HasPrefix(strings.ToLower(line), "rem ") { + continue + } + switch kind { + case "jvm.options", "vmoptions": + lo, hi := 0, 0 + if m := selectorRE.FindStringSubmatch(line); m != nil { + lo, _ = strconv.Atoi(m[1]) + switch { + case m[2] == "": + hi = lo + case m[3] != "": + hi, _ = strconv.Atoi(m[3]) + } + line = line[len(m[0]):] + } + if xxRE.MatchString(line) && strings.HasPrefix(line, "-XX:") { + s.lines = append(s.lines, optLine{lo, hi, strings.TrimSpace(line)}) + } + case "setenv": + for _, w := range xxRE.FindAllString(line, -1) { + s.lines = append(s.lines, optLine{0, 0, w}) + } + case "systemd": + s.systemdLine(line) + } + } + return s, true +} + +func (s *Setting) systemdLine(line string) { + k, v, ok := strings.Cut(line, "=") + if !ok { + return + } + switch strings.TrimSpace(k) { + case "Environment": + for _, a := range Words(v) { + name, val, ok := strings.Cut(a, "=") + if !ok { + continue + } + for _, n := range append(append([]string{}, EnvVars...), ScriptVars...) { + if name == n { + s.Env[name] = val + for _, w := range xxRE.FindAllString(val, -1) { + s.lines = append(s.lines, optLine{0, 0, w}) + } + } + } + } + case "ExecStart": + v = strings.TrimSpace(v) + v = strings.TrimLeft(v, "-@:+!") + ws := Words(v) + if len(ws) == 0 { + return + } + s.Exec = ws[0] + if opts, ok := JavaOptions(ws); ok { + for _, w := range opts { + if xxRE.MatchString(w) { + s.lines = append(s.lines, optLine{0, 0, w}) + } + } + } + } +} diff --git a/detectors/java4shell/internal/knowledge/knowledge.go b/detectors/java4shell/internal/knowledge/knowledge.go new file mode 100644 index 0000000..611ab0b --- /dev/null +++ b/detectors/java4shell/internal/knowledge/knowledge.go @@ -0,0 +1,289 @@ +// Package knowledge holds what is known about Java4Shell (CVE-2026-114938) +// release by release, and judges a Java version against it. FACTS.md, next +// to the detector, gives the source of every number here. +package knowledge + +import ( + "fmt" + "strconv" + "strings" +) + +// CVE is the vulnerability this detector checks. +const CVE = "CVE-2026-114938" + +// Bug is the OpenJDK bug that fixed it. +const Bug = "JDK-8393212" + +// Checked is the date the release data was last checked. +const Checked = "2026-11-17" + +// Status is what the release data says about a version. +type Status string + +const ( + // Vulnerable: a release with the AVX-512 VBMI decode path and without the fix. + Vulnerable Status = "vulnerable" + // Fixed: a release with the fix. + Fixed Status = "fixed" + // NotAffected: a release without the vulnerable code. + NotAffected Status = "not-affected" + // Unknown: the release data does not settle it. + Unknown Status = "unknown" +) + +// Version is a Java version as the runtime reports it: its numbers +// (feature, interim, update, patch and any vendor numbers), the build number +// after "+" and whether it is an early-access build. +type Version struct { + Nums []int + Build int // -1 when absent + EA bool + Raw string +} + +// Feature is the major release (8, 11, 17...). +func (v Version) Feature() int { + if len(v.Nums) == 0 { + return 0 + } + return v.Nums[0] +} + +// String is the dotted version without the build. +func (v Version) String() string { return join(v.Nums) } + +func join(ns []int) string { + parts := make([]string, len(ns)) + for i, n := range ns { + parts[i] = strconv.Itoa(n) + } + return strings.Join(parts, ".") +} + +const maxVersionLen = 120 + +// Parse reads the version strings Java runtimes report: "17.0.21.1+2-LTS", +// "21.0.13.0.3+1", "17.0.21+9-1-deb12u1-Debian", "1.8.0_452-b09", +// "28-ea+24", "25.0.5". A string that does not start with a version is +// refused. +func Parse(s string) (Version, bool) { + v := Version{Build: -1, Raw: s} + s = strings.TrimSpace(s) + if s == "" || len(s) > maxVersionLen { + return v, false + } + // Java 8 and older: 1.8.0_452-b09. + if rest, ok := strings.CutPrefix(s, "1."); ok { + feat, rest2 := leadingInt(rest) + if feat < 2 || feat > 8 || !strings.HasPrefix(rest2, ".0") { + return v, false + } + v.Nums = []int{feat, 0} + rest2 = strings.TrimPrefix(rest2, ".0") + if r, ok := strings.CutPrefix(rest2, "_"); ok { + u, r2 := leadingInt(r) + if u < 0 { + return v, false + } + v.Nums = append(v.Nums, u) + rest2 = r2 + } + if i := strings.Index(rest2, "-b"); i >= 0 { + if b, _ := leadingInt(rest2[i+2:]); b >= 0 { + v.Build = b + } + } + v.EA = strings.Contains(rest2, "-ea") + return v, true + } + rest := s + for { + n, r := leadingInt(rest) + if n < 0 { + break + } + v.Nums = append(v.Nums, n) + rest = r + if len(v.Nums) > 8 { + return v, false + } + if !strings.HasPrefix(rest, ".") { + break + } + rest = rest[1:] + } + if len(v.Nums) == 0 || v.Nums[0] < 9 || v.Nums[0] > 99 { + return v, false + } + // A pre-release identifier ("-ea", "-internal") comes before the build. + if r, ok := strings.CutPrefix(rest, "-"); ok { + pre := r + rest = "" + if i := strings.IndexByte(r, '+'); i >= 0 { + pre, rest = r[:i], r[i:] + } + v.EA = strings.HasPrefix(pre, "ea") + } + if r, ok := strings.CutPrefix(rest, "+"); ok { + if b, _ := leadingInt(r); b >= 0 { + v.Build = b + } + } + return v, true +} + +func leadingInt(s string) (int, string) { + i := 0 + for i < len(s) && i < 9 && s[i] >= '0' && s[i] <= '9' { + i++ + } + if i == 0 { + return -1, s + } + n, err := strconv.Atoi(s[:i]) + if err != nil { + return -1, s + } + return n, s[i:] +} + +// Compare compares two dotted versions, missing numbers counting as zero. +func Compare(a, b []int) int { + for i := 0; i < len(a) || i < len(b); i++ { + x, y := 0, 0 + if i < len(a) { + x = a[i] + } + if i < len(b) { + y = b[i] + } + switch { + case x < y: + return -1 + case x > y: + return 1 + } + } + return 0 +} + +// Line is one Java feature release line. +type Line struct { + Feature int + // Introduced is the first version with the AVX-512 VBMI decode path + // (nil: the whole line has it). + Introduced []int + // IntroducedBuild is the first build of Introduced that has it (17.0.6+3). + IntroducedBuild int + // Fixed is the first release with the fix (nil: none). + Fixed []int + // Note is why the line has no fix, or other context. + Note string +} + +// Lines is the release data, newest last. FACTS.md gives the sources. +var Lines = []Line{ + {Feature: 17, Introduced: []int{17, 0, 6}, IntroducedBuild: 3, Fixed: []int{17, 0, 21, 1}}, + {Feature: 18, Note: "JDK 18 is end of life and received no fix"}, + {Feature: 19, Note: "JDK 19 is end of life and received no fix"}, + {Feature: 20, Note: "JDK 20 is end of life and received no fix"}, + {Feature: 21, Fixed: []int{21, 0, 13, 1}}, + {Feature: 22, Note: "JDK 22 is end of life and received no fix"}, + {Feature: 23, Note: "JDK 23 is end of life and received no fix"}, + {Feature: 24, Note: "JDK 24 is end of life and received no fix"}, + {Feature: 25, Fixed: []int{25, 0, 5, 1}}, + {Feature: 26, Note: "JDK 26 is end of life (last release 26.0.2.1) and received no fix"}, + {Feature: 27, Fixed: []int{27, 0, 1, 1}}, +} + +// EAFeature is the line in early access, and the last EA build known to +// lack the fix (the fix reached mainline after jdk-28+24). +const ( + EAFeature = 28 + EALastUnfixed = 24 + newestFeature = 28 + firstVBMIDecode = 17 +) + +// LineOf returns the release line of a feature release. +func LineOf(feature int) (Line, bool) { + for _, l := range Lines { + if l.Feature == feature { + return l, true + } + } + return Line{}, false +} + +// FixedVersion is the first fixed release of a line, "" when it has none. +func FixedVersion(feature int) string { + if l, ok := LineOf(feature); ok && l.Fixed != nil { + return join(l.Fixed) + } + return "" +} + +// Upgrade names the releases to move to from a line without a fix. +func Upgrade(feature int) string { + switch { + case feature <= 21: + return "21.0.13.1 (or 25.0.5.1)" + case feature <= 25: + return "25.0.5.1 (or 27.0.1.1)" + } + return "27.0.1.1 (or 25.0.5.1, a long-term support release)" +} + +// Judge says what the release data shows about a HotSpot runtime of version +// v on x86-64, with the reason in words. +func Judge(v Version) (Status, string) { + f := v.Feature() + ver := v.String() + switch { + case f == 0: + return Unknown, "the version could not be read" + case f < firstVBMIDecode: + return NotAffected, fmt.Sprintf("Java %s: OpenJDK %d has no x86-64 Base64 decode intrinsic, so it does not have the vulnerable AVX-512 code", ver, f) + case f == EAFeature: + if v.Build >= 0 && v.Build <= EALastUnfixed { + return Vulnerable, fmt.Sprintf("JDK %d early-access build %d: the fix reached mainline after jdk-28+%d", f, v.Build, EALastUnfixed) + } + return Unknown, fmt.Sprintf("JDK %d early-access build %s: the fix reached mainline on 2026-11-16, after jdk-28+%d; check that this build includes %s", f, buildText(v), EALastUnfixed, Bug) + case f > newestFeature: + return Unknown, fmt.Sprintf("Java %s is newer than this detector's release data (%s)", ver, Checked) + } + l, ok := LineOf(f) + if !ok { + return Unknown, fmt.Sprintf("Java %s is not in this detector's release data", ver) + } + if l.Introduced != nil { + c := Compare(v.Nums, l.Introduced) + if c < 0 || c == 0 && v.EA && v.Build >= 0 && v.Build < l.IntroducedBuild { + return NotAffected, fmt.Sprintf("Java %s predates %s, the first %d update with the AVX-512 VBMI Base64 decoder (8268276)", ver, join(l.Introduced), f) + } + } + if l.Fixed == nil { + return Vulnerable, fmt.Sprintf("Java %s has the AVX-512 VBMI Base64 decoder without the fix: %s", ver, l.Note) + } + if Compare(v.Nums, l.Fixed) < 0 { + return Vulnerable, fmt.Sprintf("Java %s is older than %s, the first %d release with the fix (%s)", ver, join(l.Fixed), f, Bug) + } + // Releases of the same update as the fix (17.0.21.1, 17.0.21.2) carry + // it. A later update (17.0.22) was not released when the data was + // checked, and its development builds did not have the fix yet. + if len(v.Nums) >= 3 && len(l.Fixed) >= 3 && v.Nums[2] > l.Fixed[2] || len(v.Nums) >= 2 && v.Nums[1] > l.Fixed[1] { + return Unknown, fmt.Sprintf("Java %s is a later update than %s; it was not released when this detector's data was checked (%s), and the %d update repository did not have %s yet: check its release notes", ver, join(l.Fixed), Checked, f, Bug) + } + if v.EA { + return Unknown, fmt.Sprintf("Java %s is an early-access build; check that it includes %s", ver, Bug) + } + return Fixed, fmt.Sprintf("Java %s is at or past %s, the first %d release with the fix (%s)", ver, join(l.Fixed), f, Bug) +} + +func buildText(v Version) string { + if v.Build < 0 { + return "(no build number)" + } + return strconv.Itoa(v.Build) +} diff --git a/detectors/java4shell/internal/knowledge/knowledge_test.go b/detectors/java4shell/internal/knowledge/knowledge_test.go new file mode 100644 index 0000000..7fb32f5 --- /dev/null +++ b/detectors/java4shell/internal/knowledge/knowledge_test.go @@ -0,0 +1,123 @@ +package knowledge + +import ( + "strings" + "testing" +) + +func TestParse(t *testing.T) { + for _, c := range []struct { + in string + nums string + build int + ea bool + }{ + {"17.0.21.1+2-LTS", "17.0.21.1", 2, false}, + {"21.0.13.0.3+1-LTS", "21.0.13.0.3", 1, false}, + {"17.0.21+9-1-deb12u1-Debian", "17.0.21", 9, false}, + {"1.8.0_452-b09", "8.0.452", 9, false}, + {"1.8.0_452", "8.0.452", -1, false}, + {"28-ea+24", "28", 24, true}, + {"17.0.6-ea+2", "17.0.6", 2, true}, + {"25.0.5", "25.0.5", -1, false}, + {"21", "21", -1, false}, + {"11.0.33+7", "11.0.33", 7, false}, + {"21.0.13-internal+0-adhoc.root.src", "21.0.13", 0, false}, + } { + v, ok := Parse(c.in) + if !ok || v.String() != c.nums || v.Build != c.build || v.EA != c.ea { + t.Errorf("Parse(%q) = %v %q build %d ea %v, want %q build %d ea %v", c.in, ok, v.String(), v.Build, v.EA, c.nums, c.build, c.ea) + } + } + for _, bad := range []string{"", "abc", "1.9.0", "8", "0.1", "100.0.1", strings.Repeat("1.", 200), "1.8x", "17.0.0.0.0.0.0.0.0.0"} { + if v, ok := Parse(bad); ok { + t.Errorf("Parse(%q) accepted: %v", bad, v) + } + } +} + +func TestJudge(t *testing.T) { + for _, c := range []struct { + v string + want Status + }{ + {"1.8.0_452-b09", NotAffected}, + {"11.0.33+7", NotAffected}, + {"16.0.2+7", NotAffected}, + {"17.0.5+8", NotAffected}, + {"17.0.6-ea+2", NotAffected}, + {"17.0.6-ea+3", Vulnerable}, + {"17.0.6+10", Vulnerable}, + {"17.0.21+9", Vulnerable}, + {"17.0.21.0.3+1", Vulnerable}, + {"17.0.21.1+2", Fixed}, + {"17.0.21.2+1", Fixed}, + {"17.0.22+2", Unknown}, + {"17.0.22-ea+2", Unknown}, + {"18.0.2.1+1", Vulnerable}, + {"20.0.2+9", Vulnerable}, + {"21+35", Vulnerable}, + {"21.0.13+9", Vulnerable}, + {"21.0.13.0.3+1", Vulnerable}, + {"21.0.13.1+2", Fixed}, + {"21.0.14+1", Unknown}, + {"24.0.2+12", Vulnerable}, + {"25.0.5+8", Vulnerable}, + {"25.0.5.1+2", Fixed}, + {"26.0.2.1+1", Vulnerable}, + {"27+35", Vulnerable}, + {"27.0.1.0.3+1", Vulnerable}, + {"27.0.1.1+4", Fixed}, + {"27.0.2+1", Unknown}, + {"28-ea+24", Vulnerable}, + {"28-ea+25", Unknown}, + {"29-ea+1", Unknown}, + } { + v, ok := Parse(c.v) + if !ok { + t.Fatalf("Parse(%q) failed", c.v) + } + got, why := Judge(v) + if got != c.want || why == "" { + t.Errorf("Judge(%s) = %s (%s), want %s", c.v, got, why, c.want) + } + } +} + +func TestLinesConsistent(t *testing.T) { + prev := 0 + for _, l := range Lines { + if l.Feature <= prev { + t.Fatalf("lines out of order at %d", l.Feature) + } + prev = l.Feature + if l.Fixed == nil && l.Note == "" { + t.Errorf("line %d has no fix and no note", l.Feature) + } + if l.Fixed != nil && l.Fixed[0] != l.Feature { + t.Errorf("line %d fixed version %v is on another line", l.Feature, l.Fixed) + } + if l.Fixed != nil && l.Introduced != nil && Compare(l.Introduced, l.Fixed) >= 0 { + t.Errorf("line %d fixed before it was introduced", l.Feature) + } + } +} + +func FuzzParse(f *testing.F) { + for _, s := range []string{"17.0.21.1+2-LTS", "1.8.0_452-b09", "28-ea+24", "21.0.13-internal+0-adhoc"} { + f.Add(s) + } + f.Fuzz(func(t *testing.T, s string) { + v, ok := Parse(s) + if !ok { + return + } + if len(v.Nums) == 0 || len(v.Nums) > 9 { + t.Fatalf("Parse(%q) gave %d numbers", s, len(v.Nums)) + } + st, why := Judge(v) + if st == "" || why == "" { + t.Fatalf("Judge(%q) gave no verdict or reason", s) + } + }) +} diff --git a/detectors/java4shell/internal/repo/images.go b/detectors/java4shell/internal/repo/images.go new file mode 100644 index 0000000..0490ec7 --- /dev/null +++ b/detectors/java4shell/internal/repo/images.go @@ -0,0 +1,205 @@ +package repo + +import ( + "regexp" + "strconv" + "strings" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" +) + +// Family is a published Java runtime image whose tags name the Java +// release. +type Family struct { + Repo string // repository, without docker.io/ or library/ + Vendor string + // OpenJ9 images run the OpenJ9 VM, which does not have the decoder. + OpenJ9 bool + // Prefix comes before the version in the tag ("open-" for Semeru). + Prefix string + // exact reports whether the text after the version pins one release + // (Temurin's "_9", Liberica's "-10", Zulu's "-21.52"), so the version + // has no further numbers. + exact *regexp.Regexp +} + +var ( + temurinBuild = regexp.MustCompile(`^_\d+`) + libericaBuild = regexp.MustCompile(`^-\d+(?:-|$)`) + zuluBuild = regexp.MustCompile(`^-\d+\.\d+(?:\.\d+)*`) +) + +// Families are the runtime images this detector reads tags of. +var Families = []Family{ + {Repo: "eclipse-temurin", Vendor: "Eclipse Temurin", exact: temurinBuild}, + {Repo: "amazoncorretto", Vendor: "Amazon Corretto"}, + {Repo: "openjdk", Vendor: "OpenJDK (the deprecated official image)"}, + {Repo: "sapmachine", Vendor: "SapMachine"}, + {Repo: "azul/zulu-openjdk", Vendor: "Azul Zulu", exact: zuluBuild}, + {Repo: "azul/zulu-openjdk-alpine", Vendor: "Azul Zulu", exact: zuluBuild}, + {Repo: "azul/zulu-openjdk-debian", Vendor: "Azul Zulu", exact: zuluBuild}, + {Repo: "azul/zulu-openjdk-centos", Vendor: "Azul Zulu", exact: zuluBuild}, + {Repo: "bellsoft/liberica-openjdk-debian", Vendor: "BellSoft Liberica", exact: libericaBuild}, + {Repo: "bellsoft/liberica-openjre-debian", Vendor: "BellSoft Liberica", exact: libericaBuild}, + {Repo: "bellsoft/liberica-openjdk-alpine", Vendor: "BellSoft Liberica", exact: libericaBuild}, + {Repo: "bellsoft/liberica-openjre-alpine", Vendor: "BellSoft Liberica", exact: libericaBuild}, + {Repo: "bellsoft/liberica-openjdk-alpine-musl", Vendor: "BellSoft Liberica", exact: libericaBuild}, + {Repo: "bellsoft/liberica-openjre-alpine-musl", Vendor: "BellSoft Liberica", exact: libericaBuild}, + {Repo: "bellsoft/liberica-runtime-container", Vendor: "BellSoft Liberica"}, + {Repo: "mcr.microsoft.com/openjdk/jdk", Vendor: "Microsoft Build of OpenJDK"}, + {Repo: "container-registry.oracle.com/java/openjdk", Vendor: "Oracle OpenJDK"}, + {Repo: "container-registry.oracle.com/java/jdk", Vendor: "Oracle JDK"}, + {Repo: "ibm-semeru-runtimes", Vendor: "IBM Semeru", OpenJ9: true, Prefix: "open-"}, + {Repo: "ibmjava", Vendor: "IBM Java", OpenJ9: true}, + {Repo: "icr.io/appcafe/ibm-semeru-runtimes", Vendor: "IBM Semeru", OpenJ9: true, Prefix: "open-"}, +} + +// repoName normalises an image name to a repository: docker.io and +// library/ removed, tag and digest removed. +func repoName(image string) (repo, tag string) { + ref := image + if i := strings.IndexByte(ref, '@'); i >= 0 { + ref = ref[:i] + } + slash := strings.LastIndexByte(ref, '/') + if i := strings.LastIndexByte(ref, ':'); i > slash { + ref, tag = ref[:i], ref[i+1:] + } + for _, p := range []string{"docker.io/", "index.docker.io/", "registry-1.docker.io/"} { + ref = strings.TrimPrefix(ref, p) + } + ref = strings.TrimPrefix(ref, "library/") + return ref, tag +} + +// FamilyOf returns the runtime image family of an image reference. +func FamilyOf(image string) (Family, string, bool) { + repo, tag := repoName(image) + for _, f := range Families { + if repo == f.Repo { + return f, tag, true + } + } + return Family{}, tag, false +} + +var leadingVersion = regexp.MustCompile(`^(\d{1,3}(?:\.\d{1,9}){0,5})`) + +// TagVersion is what a tag says about the Java release. +type TagVersion struct { + Nums []int + // Exact is true when the tag pins one release; otherwise it names every + // release that starts with Nums (a moving tag such as "21" or "21-jre"). + Exact bool + // Text is the version as written in the tag, Variant what follows it + // (and its build), for finding the same variant of another release. + Text, Build, Variant string +} + +// ParseTag reads the Java release a family's tag names. ok is false for a +// tag with no leading version ("latest", "jre", "alpine"). +func (f Family) ParseTag(tag string) (TagVersion, bool) { + t, ok := strings.CutPrefix(tag, f.Prefix) + if !ok { + return TagVersion{}, false + } + m := leadingVersion.FindString(t) + if m == "" { + return TagVersion{}, false + } + rest := t[len(m):] + if rest != "" && rest[0] >= '0' && rest[0] <= '9' { + return TagVersion{}, false + } + tv := TagVersion{Text: m, Variant: rest} + for _, p := range strings.Split(m, ".") { + n, err := strconv.Atoi(p) + if err != nil { + return TagVersion{}, false + } + tv.Nums = append(tv.Nums, n) + } + if tv.Nums[0] < 8 || tv.Nums[0] > 99 { + return TagVersion{}, false + } + if f.exact != nil { + if b := f.exact.FindString(rest); b != "" { + b = strings.TrimSuffix(b, "-") + tv.Exact, tv.Build, tv.Variant = true, b, rest[len(b):] + } + } + return tv, true +} + +// JudgeTag says what a tag's version proves. A moving tag that could name +// both unfixed and fixed releases is Unknown: the image has to be read. +func JudgeTag(tv TagVersion) (knowledge.Status, string) { + nums := tv.Nums + feature := nums[0] + what := "the tag names Java " + tv.Text + if !tv.Exact { + what = "the tag names the newest Java " + tv.Text + " release at build time" + } + if tv.Exact || feature < 17 { + st, why := knowledge.Judge(knowledge.Version{Nums: nums, Build: -1}) + return st, what + ": " + why + } + l, ok := knowledge.LineOf(feature) + if !ok { + st, why := knowledge.Judge(knowledge.Version{Nums: nums, Build: -1}) + if st == knowledge.Vulnerable { + return knowledge.Unknown, what + ", which the image has to show" + } + return st, what + ": " + why + } + if l.Introduced != nil { + k := min(len(nums), len(l.Introduced)) + c := knowledge.Compare(nums[:k], l.Introduced[:k]) + if c < 0 { + return knowledge.NotAffected, what + ", before " + join(l.Introduced) + ", the first update with the AVX-512 VBMI decoder" + } + if c == 0 && len(nums) < len(l.Introduced) { + return knowledge.Unknown, what + ": which release that is decides it, so the image has to be read" + } + } + if l.Fixed == nil { + return knowledge.Vulnerable, what + ": " + l.Note + } + k := min(len(nums), len(l.Fixed)) + switch c := knowledge.Compare(nums[:k], l.Fixed[:k]); { + case c < 0: + return knowledge.Vulnerable, what + ", older than " + join(l.Fixed) + ", the first " + strconv.Itoa(feature) + " release with the fix" + case c == 0 && len(nums) < len(l.Fixed): + return knowledge.Unknown, what + ": the newest release it names may or may not have the fix (" + join(l.Fixed) + "), so the image has to be read" + } + st, why := knowledge.Judge(knowledge.Version{Nums: nums, Build: -1}) + return st, what + ": " + why +} + +func join(ns []int) string { + parts := make([]string, len(ns)) + for i, n := range ns { + parts[i] = strconv.Itoa(n) + } + return strings.Join(parts, ".") +} + +// javaish are words in an image name that suggest a Java runtime inside: +// images with them are pulled and read; others are not. +var javaish = []string{"java", "jdk", "jre", "temurin", "corretto", "zulu", "liberica", "sapmachine", "semeru", "openj9", "graalvm", + "maven", "gradle", "tomcat", "jetty", "wildfly", "jboss", "keycloak", "jenkins", "atlassian", "jira", "confluence", "bitbucket", + "bamboo", "elasticsearch", "logstash", "opensearch", "kafka", "zookeeper", "solr", "cassandra", "neo4j", "sonarqube", "sonatype", + "nexus", "artifactory", "spring", "quarkus", "liberty", "payara", "glassfish", "flink", "spark", "hadoop", "hive", "trino", "presto", + "druid", "pinot", "nifi", "activemq", "teamcity", "youtrack", "gerrit", "minecraft", "openliberty", "websphere", "weblogic", "distroless/java"} + +// Javaish reports an image whose name suggests a Java runtime. +func Javaish(image string) bool { + repo, tag := repoName(image) + s := strings.ToLower(repo + ":" + tag) + for _, w := range javaish { + if strings.Contains(s, w) { + return true + } + } + return false +} diff --git a/detectors/java4shell/internal/repo/plan.go b/detectors/java4shell/internal/repo/plan.go new file mode 100644 index 0000000..a334b61 --- /dev/null +++ b/detectors/java4shell/internal/repo/plan.go @@ -0,0 +1,280 @@ +package repo + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "unicode" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" + "github.com/DefectDojo/earlylight/internal/refs" +) + +// Change is one line edit to a repository file. +type Change struct { + File string + Line int + Old string // the whole line, as it was + New string + Summary string +} + +// Declined is a plan that proposes no change, with the reason. +type Declined struct{ Reason string } + +func (d *Declined) Error() string { return d.Reason } + +func declined(format string, args ...any) error { + return &Declined{Reason: refs.CleanText(fmt.Sprintf(format, args...), 1500)} +} + +// Registry is what planning an image move needs from a registry: the tags +// of a repository, and a check that a target image holds only fixed +// runtimes on every platform the current one has (returning its digest). +type Registry struct { + Tags func(ctx context.Context, repo string) ([]string, error) + Verify func(ctx context.Context, current, target string) (string, error) +} + +// Plan finds the edit that fixes a finding, checks it by rescanning the +// edited file in memory, and returns it without writing anything. +func Plan(ctx context.Context, root string, f Finding, reg Registry, opts Options) (*Change, error) { + if !f.Fixable || f.edit == nil { + return nil, declined("%s", f.Fix) + } + switch f.edit.kind { + case "tag": + return planTag(ctx, root, f, reg, opts) + case "setup-java": + return planLine(ctx, root, f, f.edit.file, f.edit.line, f.edit.col, f.edit.old, fmt.Sprint(f.edit.feature), opts, + fmt.Sprintf("Sets setup-java's java-version from %s to %d on line %d of %s: the %s distribution's newest Java %d release has the Java4Shell fix (%s), and setup-java installs it when the job runs.", + f.edit.old, f.edit.feature, f.edit.line, f.edit.file, f.Props["distribution"], f.edit.feature, knowledge.FixedVersion(f.edit.feature))) + } + return nil, declined("no automatic fix for this finding") +} + +// target picks the first published tag of the same family, variant and +// style that has the fix. +func target(tags []string, e *pinEdit) (string, bool) { + type cand struct { + tag string + tv TagVersion + } + var cs []cand + for _, t := range tags { + tv, ok := e.family.ParseTag(t) + if !ok || tv.Variant != e.tv.Variant || tv.Exact != e.tv.Exact || tv.Nums[0] != e.feature || len(tv.Nums) < 3 { + continue + } + if st, _ := JudgeTag(tv); st != knowledge.Fixed { + continue + } + cs = append(cs, cand{t, tv}) + } + if len(cs) == 0 { + return "", false + } + sort.Slice(cs, func(i, j int) bool { + if c := knowledge.Compare(cs[i].tv.Nums, cs[j].tv.Nums); c != 0 { + return c < 0 + } + return cs[i].tv.Build < cs[j].tv.Build + }) + return cs[0].tag, true +} + +func planTag(ctx context.Context, root string, f Finding, reg Registry, opts Options) (*Change, error) { + e, r := f.edit, f.ref + if r == nil { + return nil, declined("the image reference was not located") + } + if reg.Tags == nil || reg.Verify == nil { + return nil, declined("moving %s needs the registry, which this run does not use; change it by hand", e.image) + } + if strings.Contains(e.image, "@") { + return nil, declined("%s is pinned by digest; change the tag and digest by hand", e.image) + } + repo, tag := repoName(e.image) + start := refs.TagStart(e.image) + if start < 0 || e.image[start:] != tag { + return nil, declined("the tag of %s cannot be retagged automatically", e.image) + } + tags, err := reg.Tags(ctx, strings.TrimSuffix(e.image[:start], ":")) + if err != nil { + return nil, declined("the tags of %s could not be listed (%v); try again later, or change it by hand", repo, err) + } + newTag, ok := target(tags, e) + if !ok { + return nil, declined("%s has no published tag of Java %s or later with the variant %q yet (the registry was checked); move to it when %s publishes it", repo, knowledge.FixedVersion(e.feature), strings.TrimPrefix(e.tv.Variant, "-"), e.family.Vendor) + } + newImage := e.image[:start] + newTag + // The part of the reference that holds the whole tag, where it is + // written. + off := 0 + var part *refs.Part + for i := range r.Parts { + p := &r.Parts[i] + if off <= start && off+len(p.Text) >= len(e.image) { + part = p + break + } + off += len(p.Text) + } + if part == nil || part.Column == 0 || part.Line == 0 { + return nil, declined("the tag of %s is not written in one place this fix can edit; change it by hand", e.image) + } + file := part.File + if file == "" { + file = r.File + } + col := part.Column - 1 + (start - off) + if _, err := reg.Verify(ctx, e.image, newImage); err != nil { + var d *Declined + if errors.As(err, &d) { + return nil, err + } + return nil, declined("%s could not be verified (%v); try again later, or change it by hand", newImage, err) + } + where := "" + if part.Var != "" { + where = fmt.Sprintf(" (in the value of %s)", part.Var) + } + return planLine(ctx, root, f, file, part.Line, col, tag, newTag, opts, + fmt.Sprintf("Changes the image %s to %s on line %d of %s%s: the %s release of the same variant with the Java4Shell fix, read and checked on every platform the current tag has. Rebuild and redeploy.", + e.image, newImage, part.Line, file, where, e.family.Vendor)) +} + +// planLine replaces old with repl at col on a line and rescans the file in +// memory: the finding must be gone and nothing new may appear. +func planLine(ctx context.Context, root string, f Finding, file string, line, col int, old, repl string, opts Options, summary string) (*Change, error) { + b, ok := opts.Overlay[file] + if !ok { + var err error + if b, err = readFile(root, file); err != nil { + return nil, declined("%s could not be read: %v", file, err) + } + } + ls := strings.Split(string(b), "\n") + if line < 1 || line > len(ls) { + return nil, declined("line %d of %s is gone; rescan", line, file) + } + cur := strings.TrimSuffix(ls[line-1], "\r") + if col < 0 || col+len(old) > len(cur) || cur[col:col+len(old)] != old { + return nil, declined("line %d of %s no longer reads as the scan found it; rescan", line, file) + } + newLine := cur[:col] + repl + cur[col+len(old):] + cr := "" + if strings.HasSuffix(ls[line-1], "\r") { + cr = "\r" + } + edited := append([]string(nil), ls...) + edited[line-1] = newLine + cr + over := map[string][]byte{} + for k, v := range opts.Overlay { + over[k] = v + } + over[file] = []byte(strings.Join(edited, "\n")) + before, err := Scan(ctx, root, Options{Overlay: opts.Overlay, Platforms: opts.Platforms}) + if err != nil { + return nil, err + } + after, err := Scan(ctx, root, Options{Overlay: over, Platforms: opts.Platforms}) + if err != nil { + return nil, err + } + key := func(x Finding) string { + return x.Rule + "|" + x.File + "|" + x.Props["image"] + "|" + x.Props["current"] + "|" + x.Status + } + had := map[string]int{} + for _, x := range before.Findings { + had[key(x)]++ + } + for _, x := range after.Findings { + if x.File == f.File && x.Line == f.Line && x.Rule == f.Rule && x.Status != StatusMitigated { + return nil, declined("after the edit, line %d of %s still selects a release without the fix; change it by hand", f.Line, f.File) + } + if had[key(x)] == 0 && x.Level != "note" { + return nil, declined("the edit would add a new finding (%s at %s:%d); change it by hand", x.Message, x.File, x.Line) + } + had[key(x)]-- + } + if len(after.Skips) > len(before.Skips) { + return nil, declined("after the edit, %s no longer reads cleanly; change it by hand", file) + } + return &Change{File: file, Line: line, Old: cur, New: newLine, Summary: refs.CleanText(summary, 800)}, nil +} + +// Apply writes a change after checking the line still reads as planned. It +// keeps the file's mode and line ending and writes atomically. +func Apply(root string, ch *Change) error { + p, err := refs.SafePath(root, ch.File) + if err != nil { + return err + } + fi, err := os.Lstat(p) + if err != nil { + return err + } + b, err := readFile(root, ch.File) + if err != nil { + return err + } + ls := strings.Split(string(b), "\n") + if ch.Line < 1 || ch.Line > len(ls) || strings.TrimSuffix(ls[ch.Line-1], "\r") != ch.Old { + return fmt.Errorf("%s changed since the plan: line %d no longer reads as planned", ch.File, ch.Line) + } + cr := "" + if strings.HasSuffix(ls[ch.Line-1], "\r") { + cr = "\r" + } + ls[ch.Line-1] = ch.New + cr + tmp, err := os.CreateTemp(filepath.Dir(p), ".earlylight-*") + if err != nil { + return err + } + name := tmp.Name() + if _, err := tmp.WriteString(strings.Join(ls, "\n")); err != nil { + tmp.Close() + os.Remove(name) + return err + } + if err := tmp.Close(); err != nil { + os.Remove(name) + return err + } + if err := os.Chmod(name, fi.Mode().Perm()); err != nil { + os.Remove(name) + return err + } + return os.Rename(name, p) +} + +// Diff shows a change. +func Diff(ch *Change) string { + return fmt.Sprintf("@@ %s line %d @@\n- %s\n+ %s\n", Printable(ch.File), ch.Line, Printable(ch.Old), Printable(ch.New)) +} + +// Printable shows repository text safely on a terminal. +func Printable(s string) string { + var b strings.Builder + for _, r := range s { + if r != '\t' && (unicode.IsControl(r) || unicode.Is(unicode.Cf, r)) { + fmt.Fprintf(&b, "\\u%04x", r) + continue + } + b.WriteRune(r) + } + return b.String() +} + +// Mitigation is the optional interim edit for a Dockerfile whose image runs +// a vulnerable runtime that cannot be updated here (a product's bundled +// runtime): the line to add after the FROM line. fix prints it and does not +// apply it. +func Mitigation(file string, line int) string { + return fmt.Sprintf("%s: after line %d add\n ENV JAVA_TOOL_OPTIONS=\"-XX:-UseBASE64Intrinsics\"\n (append to any JAVA_TOOL_OPTIONS the image already sets; this keeps the vulnerable decoder from being generated until the product ships a fixed runtime)", file, line) +} diff --git a/detectors/java4shell/internal/repo/refscan.go b/detectors/java4shell/internal/repo/refscan.go new file mode 100644 index 0000000..af8abfb --- /dev/null +++ b/detectors/java4shell/internal/repo/refscan.go @@ -0,0 +1,189 @@ +package repo + +import ( + "fmt" + "strings" + + "gopkg.in/yaml.v3" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" + "github.com/DefectDojo/earlylight/internal/refs" +) + +// images judges the image references the tree builds on and deploys. +func (s *scanner) images(opts Options) { + rs, skips, err := refs.Scan(s.root, refs.Options{Overlay: opts.Overlay}) + if err != nil { + s.skips = append(s.skips, Skip{File: ".", Reason: "image references: " + err.Error()}) + return + } + for _, sk := range skips { + if sk.Text != "" && !Javaish(sk.Text) { + continue // an unresolved reference that does not look like Java + } + s.skips = append(s.skips, Skip{File: sk.File, Line: sk.Line, Reason: sk.Reason}) + } + for i := range rs { + s.judgeRef(rs[i], opts) + } +} + +// amd64 reports whether the tree builds for x86-64 (or does not say). +func amd64(opts Options) bool { + if len(opts.Platforms) == 0 { + return true + } + for _, p := range opts.Platforms { + if strings.Contains(p, "amd64") || strings.Contains(p, "x86_64") || p == "all" { + return true + } + } + return false +} + +func (s *scanner) judgeRef(r refs.Ref, opts Options) { + img := r.Image + if img == "" || img == "scratch" || strings.Contains(img, "$") || !amd64(opts) { + return + } + mit := s.mitigationFor(r) + props := map[string]string{"image": img} + if mit != "" { + props["mitigation"] = mit + } + fam, tag, ok := FamilyOf(img) + if !ok { + if Javaish(img) { + s.add(Finding{Rule: RuleNotChecked, File: r.File, Line: r.Line, Level: "note", Status: StatusUnknown, Pull: img, ref: &r, + Reason: "the image's Java runtime can only be judged by reading the image", + Message: fmt.Sprintf("image %s may hold a Java runtime; it was not read", img), Props: props}) + } + return + } + props["vendor"] = fam.Vendor + if fam.OpenJ9 { + return // OpenJ9: not affected + } + tv, ok := fam.ParseTag(tag) + if !ok { + s.add(Finding{Rule: RuleNotChecked, File: r.File, Line: r.Line, Level: "note", Status: StatusUnknown, Pull: img, ref: &r, + Reason: "the tag does not name a Java release, so only the image can show which one it holds", + Message: fmt.Sprintf("image %s: the tag names no Java release; it was not read", img), Props: props}) + return + } + props["current"] = tv.Text + st, why := JudgeTag(tv) + switch st { + case knowledge.Unknown: + s.add(Finding{Rule: RuleNotChecked, File: r.File, Line: r.Line, Level: "note", Status: StatusUnknown, Pull: img, ref: &r, + Reason: why, Message: fmt.Sprintf("image %s: %s", img, why), Props: props}) + return + case knowledge.Vulnerable: + default: + return + } + feature := tv.Nums[0] + f := Finding{Rule: RuleImagePin, File: r.File, Line: r.Line, Level: "error", Status: StatusVulnerable, Reason: why, ref: &r, Props: props, + Message: fmt.Sprintf("image %s holds %s Java %s, without the Java4Shell fix", img, fam.Vendor, tv.Text)} + if fx := knowledge.FixedVersion(feature); fx != "" { + props["fixed_in"] = fx + f.Fixable = true + f.edit = &pinEdit{kind: "tag", family: fam, tv: tv, image: img, feature: feature} + f.Fix = fmt.Sprintf("Move to the %s image of Java %s or later with the same variant (%q) once %s publishes it, rebuild and redeploy. fix does this after reading the new image.", fam.Vendor, fx, strings.TrimPrefix(tv.Variant, "-"), fam.Vendor) + } else { + f.Fix = fmt.Sprintf("Java %d received no fix: move to a supported release with the fix, such as %s (a major upgrade: test it).", feature, knowledge.Upgrade(feature)) + } + if mit != "" { + f.Status, f.Level = StatusMitigated, "note" + f.Reason = why + "; " + mit + f.Message += ", mitigated by its JVM options until it is updated" + } + s.add(f) +} + +// mitigationFor returns the mitigation the file sets for the container or +// stage of a reference: a Dockerfile stage's ENV, a Compose service's +// environment, a Kubernetes container's env. +func (s *scanner) mitigationFor(r refs.Ref) string { + if r.Kind == refs.KindDockerfile { + return s.mitigated[fmt.Sprintf("%s:%d", r.File, r.Line)] + } + return EnvMitigation(s.root, r, s.opts.Overlay) +} + +// EnvMitigation reads the JVM option variables a Compose service or +// Kubernetes container sets next to an image reference, and returns the +// mitigation they make ("" for none). +func EnvMitigation(root string, r refs.Ref, overlay map[string][]byte) string { + if r.Kind != refs.KindCompose && r.Kind != refs.KindKubernetes { + return "" + } + b, ok := overlay[r.File] + if !ok { + var err error + if b, err = readFile(root, r.File); err != nil { + return "" + } + } + dec := yaml.NewDecoder(strings.NewReader(string(b))) + for i := 0; i < 1000; i++ { + var doc yaml.Node + if err := dec.Decode(&doc); err != nil { + return "" + } + m := findImageMapping(&doc, r.Line, 0) + if m == nil { + continue + } + env := map[string]string{} + if r.Kind == refs.KindCompose { + e := mapGet(m, "environment") + switch { + case e == nil: + case e.Kind == yaml.MappingNode: + for j := 0; j+1 < len(e.Content); j += 2 { + env[e.Content[j].Value] = e.Content[j+1].Value + } + case e.Kind == yaml.SequenceNode: + for _, c := range e.Content { + if k, v, ok := strings.Cut(c.Value, "="); ok { + env[k] = v + } + } + } + } else if e := mapGet(m, "env"); e != nil && e.Kind == yaml.SequenceNode { + for _, c := range e.Content { + if n, v := mapGet(c, "name"), mapGet(c, "value"); n != nil && v != nil { + env[n.Value] = v.Value + } + } + } + o := jvm.FromEnv(env, nil, 17, nil) + if ok, how := o.Mitigates(); ok { + return strings.Replace(how, "(from ", "(from "+r.File+" ", 1) + } + return "" + } + return "" +} + +// findImageMapping finds the mapping whose "image" value sits on line. +func findImageMapping(n *yaml.Node, line, depth int) *yaml.Node { + if n == nil || depth > 64 { + return nil + } + if n.Kind == yaml.MappingNode { + for i := 0; i+1 < len(n.Content); i += 2 { + if n.Content[i].Value == "image" && n.Content[i+1].Line == line { + return n + } + } + } + for _, c := range n.Content { + if m := findImageMapping(c, line, depth+1); m != nil { + return m + } + } + return nil +} diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go new file mode 100644 index 0000000..0e4434d --- /dev/null +++ b/detectors/java4shell/internal/repo/repo.go @@ -0,0 +1,845 @@ +// Package repo finds what in a source tree selects a Java runtime exposed to +// Java4Shell (CVE-2026-114938), and plans the edits that fix it: +// +// - image-pin: a Dockerfile, Compose, Kubernetes, Helm values, CI file or +// Jib configuration names a Java runtime image (eclipse-temurin, +// amazoncorretto, azul/zulu-openjdk...) whose tag is a release without +// the fix. +// - java-pin: a version file (.java-version, .sdkmanrc, .tool-versions, +// mise), a GitHub Actions setup-java step or a buildpack setting pins a +// release without the fix. +// - java-line: a Gradle or Maven toolchain, setup-java or a buildpack +// selects a Java line that received no fix (18 to 20, 22 to 24, 26). +// - os-package: a Dockerfile installs a distribution's OpenJDK package +// (apt, apk, dnf, yum, microdnf) without the fix. +// - not-checked: what could not be read or decided without reading an +// image. +// +// It knows nothing about the engine. +package repo + +import ( + "context" + "errors" + "fmt" + "io/fs" + "os" + "path" + "path/filepath" + "regexp" + "sort" + "strings" + + "gopkg.in/yaml.v3" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" + "github.com/DefectDojo/earlylight/internal/refs" +) + +// Rules. +const ( + RuleImagePin = "image-pin" + RuleJavaPin = "java-pin" + RuleLine = "java-line" + RulePackage = "os-package" + RuleNotChecked = "not-checked" +) + +// Status of a finding. +const ( + StatusVulnerable = "vulnerable" + StatusMitigated = "mitigated" + StatusUnknown = "unknown" +) + +// Finding is one thing in the tree. +type Finding struct { + Rule string `json:"rule"` + File string `json:"file"` + Line int `json:"line"` + Level string `json:"level"` // error, warning, note + Status string `json:"status"` + Reason string `json:"reason,omitempty"` + Message string `json:"message"` + Fix string `json:"fix,omitempty"` + Fixable bool `json:"fixable"` + Props map[string]string `json:"props,omitempty"` + // Pull is set for an image reference that only reading the image can + // decide (a moving tag, a product image). + Pull string `json:"pull,omitempty"` + // Optional is a clearly labelled edit fix offers but does not apply: the + // interim mitigation for an image whose runtime cannot be updated here. + Optional string `json:"optional,omitempty"` + ref *refs.Ref + edit *pinEdit +} + +// pinEdit locates a version or tag to replace on one line. +type pinEdit struct { + file string + line int + col int // 0-based byte column of old on the line + old string + kind string // tag, setup-java + // tag fields + family Family + tv TagVersion + image string + feature int +} + +// Skip is a file that was not read, and why. +type Skip struct { + File string `json:"file"` + Line int `json:"line,omitempty"` + Reason string `json:"reason"` +} + +// Result is a scan of a tree. +type Result struct { + Findings []Finding + Skips []Skip + Files int + Truncated bool +} + +// Options control a scan. +type Options struct { + // Overlay replaces file contents (repository-relative, slash paths), so + // a plan can rescan an edit in memory. + Overlay map[string][]byte + // Platforms are the platforms the tree builds; empty means every one. + Platforms []string +} + +const ( + maxFileSize = 4 << 20 + maxFiles = 200000 +) + +var skipDirs = map[string]bool{".git": true, "node_modules": true, "vendor": true, ".venv": true, "venv": true, "__pycache__": true, + ".tox": true, "bower_components": true, ".gradle": true, "target": true, "build": true, ".idea": true} + +// Scan walks root. +func Scan(ctx context.Context, root string, opts Options) (Result, error) { + var res Result + var list []string + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + rel, _ := filepath.Rel(root, p) + res.Skips = append(res.Skips, Skip{File: filepath.ToSlash(rel), Reason: err.Error()}) + return nil + } + if ctx.Err() != nil { + return ctx.Err() + } + if d.IsDir() { + if p != root && skipDirs[d.Name()] { + return filepath.SkipDir + } + return nil + } + if !d.Type().IsRegular() { + return nil + } + rel, err := filepath.Rel(root, p) + if err != nil { + return nil + } + rel = filepath.ToSlash(rel) + if kindOf(rel) == "" { + return nil + } + if len(list) >= maxFiles { + res.Truncated = true + return filepath.SkipAll + } + list = append(list, rel) + return nil + }) + if err != nil { + return res, err + } + return scanList(ctx, root, list, opts, res) +} + +func scanList(ctx context.Context, root string, list []string, opts Options, res Result) (Result, error) { + for rel := range opts.Overlay { + if kindOf(rel) != "" && !contains(list, rel) { + list = append(list, rel) + } + } + sort.Strings(list) + s := &scanner{root: root, opts: opts, mitigated: map[string]string{}} + for _, rel := range list { + if ctx.Err() != nil { + return res, ctx.Err() + } + b, ok := opts.Overlay[rel] + if !ok { + var err error + if b, err = readFile(root, rel); err != nil { + res.Skips = append(res.Skips, Skip{File: rel, Reason: err.Error()}) + continue + } + } + res.Files++ + text := string(b) + switch kindOf(rel) { + case "dockerfile": + s.dockerfile(rel, text) + case "java-version": + s.javaVersionFile(rel, text) + case "sdkmanrc": + s.sdkmanrc(rel, text) + case "tool-versions": + s.toolVersions(rel, text) + case "mise": + s.mise(rel, text) + case "workflow": + s.workflow(rel, b) + case "gradle": + s.gradle(rel, text) + case "maven": + s.maven(rel, text) + case "project.toml": + s.projectToml(rel, text) + } + } + s.images(opts) + res.Findings = append(res.Findings, s.findings...) + res.Skips = append(res.Skips, s.skips...) + sort.SliceStable(res.Findings, func(i, j int) bool { + a, b := res.Findings[i], res.Findings[j] + if a.File != b.File { + return a.File < b.File + } + return a.Line < b.Line + }) + return res, nil +} + +func contains(xs []string, s string) bool { + for _, x := range xs { + if x == s { + return true + } + } + return false +} + +// kindOf classifies a repository path. +func kindOf(rel string) string { + name := path.Base(rel) + lower := strings.ToLower(name) + switch { + case isDockerfile(lower): + return "dockerfile" + case lower == ".java-version": + return "java-version" + case lower == ".sdkmanrc": + return "sdkmanrc" + case lower == ".tool-versions": + return "tool-versions" + case lower == "mise.toml" || lower == ".mise.toml" || lower == "mise.local.toml" || lower == ".rtx.toml": + return "mise" + case strings.HasPrefix(rel, ".github/workflows/") && (strings.HasSuffix(lower, ".yml") || strings.HasSuffix(lower, ".yaml")): + return "workflow" + case lower == "build.gradle" || lower == "build.gradle.kts" || lower == "settings.gradle" || lower == "settings.gradle.kts" || lower == "gradle.properties": + return "gradle" + case lower == "pom.xml" || lower == "toolchains.xml": + return "maven" + case lower == "project.toml" || lower == "jib.yaml": + return "project.toml" + case strings.HasSuffix(lower, ".yml") || strings.HasSuffix(lower, ".yaml") || lower == ".env": + return "yaml" // read by internal/refs; listed so an overlay rescans it + } + return "" +} + +func isDockerfile(lower string) bool { + for _, n := range []string{"dockerfile", "containerfile"} { + if lower == n || strings.HasSuffix(lower, "."+n) { + return true + } + if strings.HasPrefix(lower, n) && strings.ContainsRune("._-", rune(lower[len(n)])) { + return true + } + } + return false +} + +func readFile(root, rel string) ([]byte, error) { + p, err := refs.SafePath(root, rel) + if err != nil { + return nil, err + } + fi, err := os.Lstat(p) + if err != nil { + return nil, err + } + if !fi.Mode().IsRegular() { + return nil, errors.New("not a regular file") + } + if fi.Size() > maxFileSize { + return nil, fmt.Errorf("larger than %d MiB", maxFileSize>>20) + } + return os.ReadFile(p) +} + +type scanner struct { + root string + opts Options + findings []Finding + skips []Skip + // mitigated maps "file:line" of a Dockerfile FROM to the mitigation its + // stage sets (ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics). + mitigated map[string]string +} + +func (s *scanner) add(f Finding) { + if f.Props == nil { + f.Props = map[string]string{} + } + s.findings = append(s.findings, f) +} + +// lines splits text into lines without terminators. +func lines(text string) []string { + ls := strings.Split(text, "\n") + for i, l := range ls { + ls[i] = strings.TrimSuffix(l, "\r") + } + return ls +} + +// ---- version files + +var versionInText = regexp.MustCompile(`(\d{1,3}(?:\.\d{1,9}){0,5})`) + +// judgeVersion turns a pinned version into a finding, or nothing when it is +// fixed or not affected. A version with fewer numbers than the fix is a +// moving pin (the newest release of that line) and is reported only when +// its line has no fix at all. +func (s *scanner) judgeVersion(rel string, line, col int, verText, source, vendor string) { + tv := TagVersion{Text: verText, Exact: strings.Count(verText, ".") >= 2} + for _, p := range strings.Split(verText, ".") { + n := 0 + fmt.Sscanf(p, "%d", &n) + tv.Nums = append(tv.Nums, n) + } + if len(tv.Nums) == 0 || tv.Nums[0] < 8 || tv.Nums[0] > 99 { + return + } + if strings.Contains(strings.ToLower(vendor), "semeru") || strings.Contains(strings.ToLower(vendor), "openj9") { + return // OpenJ9: not affected + } + st, why := JudgeTag(tv) + props := map[string]string{"source": source, "current": verText} + if vendor != "" { + props["vendor"] = vendor + } + if fx := knowledge.FixedVersion(tv.Nums[0]); fx != "" { + props["fixed_in"] = fx + } + switch st { + case knowledge.Vulnerable: + rule, level := RuleJavaPin, "warning" + l, _ := knowledge.LineOf(tv.Nums[0]) + if l.Fixed == nil && tv.Nums[0] > 17 { + rule, level = RuleLine, "error" + } + s.add(Finding{Rule: rule, File: rel, Line: line, Level: level, Status: StatusVulnerable, Reason: why, + Message: fmt.Sprintf("%s selects Java %s, without the Java4Shell fix", source, verText), + Fix: pinFix(tv.Nums[0], source), Props: props}) + case knowledge.Unknown: + l, ok := knowledge.LineOf(tv.Nums[0]) + if ok && l.Fixed == nil { + s.add(Finding{Rule: RuleLine, File: rel, Line: line, Level: "error", Status: StatusVulnerable, Reason: l.Note, + Message: fmt.Sprintf("%s selects Java %s, a line that received no Java4Shell fix", source, verText), + Fix: pinFix(tv.Nums[0], source), Props: props}) + } + } + _ = col +} + +func pinFix(feature int, source string) string { + if fx := knowledge.FixedVersion(feature); fx != "" { + return fmt.Sprintf("Select Java %s or later of the same update in %s once your vendor publishes it (Amazon Corretto and SapMachine did on 2026-11-17; Temurin, Debian, Ubuntu and Alpine had not), and reinstall.", fx, source) + } + return fmt.Sprintf("Java %d received no fix: move %s to a supported release with the fix, such as %s.", feature, source, knowledge.Upgrade(feature)) +} + +func (s *scanner) javaVersionFile(rel, text string) { + for i, l := range lines(text) { + l = strings.TrimSpace(l) + if l == "" || strings.HasPrefix(l, "#") { + continue + } + if m := versionInText.FindStringIndex(l); m != nil { + s.judgeVersion(rel, i+1, m[0], l[m[0]:m[1]], ".java-version", vendorWord(l)) + } + return // jenv reads the first line + } +} + +var sdkmanLine = regexp.MustCompile(`^\s*java\s*=\s*(\d[\w.]*?)(?:-([a-z]+))?\s*$`) + +var sdkmanVendors = map[string]string{"tem": "Eclipse Temurin", "amzn": "Amazon Corretto", "zulu": "Azul Zulu", "librca": "BellSoft Liberica", + "sapmchn": "SapMachine", "ms": "Microsoft", "oracle": "Oracle", "open": "OpenJDK", "sem": "IBM Semeru (OpenJ9)", "graalce": "GraalVM CE", + "graal": "Oracle GraalVM", "kona": "Tencent Kona", "dragonwell": "Alibaba Dragonwell", "jbr": "JetBrains Runtime", "nik": "Liberica NIK", "mandrel": "Mandrel", "trava": "Trava", "zulufx": "Azul Zulu", "librcafx": "BellSoft Liberica"} + +func (s *scanner) sdkmanrc(rel, text string) { + for i, l := range lines(text) { + m := sdkmanLine.FindStringSubmatch(l) + if m == nil { + continue + } + vendor := sdkmanVendors[m[2]] + if vendor == "" { + vendor = m[2] + } + if m[2] == "graalce" || m[2] == "graal" || m[2] == "nik" || m[2] == "mandrel" { + // GraalVM versions follow the JDK's only for 17 and later builds named so. + if !strings.Contains(m[1], ".") { + continue + } + } + s.judgeVersion(rel, i+1, strings.Index(l, m[1]), m[1], ".sdkmanrc", vendor) + } +} + +// asdfJava reads asdf-java and mise names: temurin-21.0.5+11.0.LTS, +// corretto-21.0.5.11.1, openjdk-21.0.2, sapmachine-21.0.5, zulu-21.38.21 +// (a Zulu version, not a Java version: not judged). +var asdfJava = regexp.MustCompile(`^(?:(adoptopenjdk|temurin|corretto|openjdk|sapmachine|liberica|microsoft|oracle|semeru-openj9|semeru|dragonwell|kona|zulu|graalvm|graalvm-community|oracle-graalvm|mandrel|jetbrains)-)?(?:jre-|jdk-|openj9-)?(\d[\d.]*)`) + +func (s *scanner) asdfValue(rel string, line int, value, source string) { + m := asdfJava.FindStringSubmatch(value) + if m == nil { + return + } + switch m[1] { + case "zulu", "graalvm", "mandrel", "jetbrains": + return // their own version numbers + } + ver := m[2] + if m[1] == "corretto" { + // corretto-21.0.5.11.1: the fourth number is Corretto's build when + // the fifth is 1. Keep the Java part. + parts := strings.Split(ver, ".") + if len(parts) == 5 && parts[3] != "1" && parts[3] != "0" { + ver = strings.Join(parts[:3], ".") + } + } + s.judgeVersion(rel, line, 0, strings.TrimSuffix(ver, "."), source, m[1]) +} + +func (s *scanner) toolVersions(rel, text string) { + for i, l := range lines(text) { + f := strings.Fields(l) + if len(f) >= 2 && f[0] == "java" { + s.asdfValue(rel, i+1, f[1], ".tool-versions") + } + } +} + +var miseJava = regexp.MustCompile(`^\s*java\s*=\s*["']([^"']+)["']`) + +func (s *scanner) mise(rel, text string) { + for i, l := range lines(text) { + if m := miseJava.FindStringSubmatch(l); m != nil { + s.asdfValue(rel, i+1, m[1], path.Base(rel)) + } + } +} + +func vendorWord(s string) string { + l := strings.ToLower(s) + for _, v := range []string{"temurin", "corretto", "zulu", "liberica", "sapmachine", "semeru", "openj9", "graalvm", "oracle", "microsoft"} { + if strings.Contains(l, v) { + return v + } + } + return "" +} + +// ---- GitHub Actions setup-java + +// publishedFix are the distributions (setup-java names) whose newest +// release of each fixed line had the fix when the data was checked, so a +// moving version ("21") installs a fixed release. +var publishedFix = map[string]bool{"corretto": true, "sapmachine": true} + +func (s *scanner) workflow(rel string, b []byte) { + var doc yaml.Node + if err := yaml.Unmarshal(b, &doc); err != nil { + s.skips = append(s.skips, Skip{File: rel, Reason: "not valid YAML: " + refs.CleanText(err.Error(), 200)}) + return + } + text := lines(string(b)) + walkYAML(&doc, 0, func(m *yaml.Node) { + uses := mapGet(m, "uses") + if uses == nil || !strings.HasPrefix(uses.Value, "actions/setup-java@") { + return + } + with := mapGet(m, "with") + if with == nil { + return + } + dist := "" + if d := mapGet(with, "distribution"); d != nil { + dist = d.Value + } + jv := mapGet(with, "java-version") + if jv == nil { + return + } + vals := []*yaml.Node{jv} + if jv.Kind == yaml.ScalarNode && strings.Contains(jv.Value, "\n") { + vals = nil // a block of versions: each line + for i, v := range strings.Split(strings.TrimSpace(jv.Value), "\n") { + vals = append(vals, &yaml.Node{Kind: yaml.ScalarNode, Value: strings.TrimSpace(v), Line: jv.Line + 1 + i}) + } + } + for _, v := range vals { + if v.Kind != yaml.ScalarNode { + continue + } + if strings.Contains(v.Value, "${{") { + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: v.Line, Level: "note", Status: StatusUnknown, + Reason: "the version is a workflow expression decided when the job runs", + Message: fmt.Sprintf("setup-java's java-version %q is decided when the job runs; check that it selects a release with the Java4Shell fix", refs.CleanText(v.Value, 80))}) + continue + } + s.setupJava(rel, v, dist, text) + } + }) +} + +func (s *scanner) setupJava(rel string, v *yaml.Node, dist string, text []string) { + ver := strings.TrimSpace(v.Value) + ver = strings.TrimSuffix(strings.TrimSuffix(ver, "-ea"), ".x") + m := versionInText.FindString(ver) + if m == "" || m != ver && !strings.HasPrefix(ver, m+"+") { + return + } + if dist == "semeru" { + return + } + before := len(s.findings) + s.judgeVersion(rel, v.Line, 0, m, "actions/setup-java", dist) + if len(s.findings) == before { + return + } + f := &s.findings[len(s.findings)-1] + f.Props["distribution"] = dist + feature := 0 + fmt.Sscanf(m, "%d", &feature) + // A pin of a fixed line moves to the moving major version when the + // distribution's newest release is fixed: setup-java then installs it. + if f.Rule == RuleJavaPin && publishedFix[dist] && v.Line >= 1 && v.Line <= len(text) { + line := text[v.Line-1] + col := strings.Index(line, ver) + if col >= 0 && strings.Count(line, ver) == 1 { + f.Fixable = true + f.edit = &pinEdit{file: rel, line: v.Line, col: col, old: ver, kind: "setup-java", feature: feature} + f.Fix = fmt.Sprintf("Set java-version to %d: %s's newest Java %d release has the fix (%s), and setup-java installs it.", feature, dist, feature, knowledge.FixedVersion(feature)) + } + } + if !f.Fixable && f.Rule == RuleJavaPin { + f.Fix = fmt.Sprintf("Set java-version to %s or later once the %s distribution publishes it (it had not when this detector's data was checked, %s), or use distribution corretto or sapmachine, which have.", knowledge.FixedVersion(feature), orAny(dist), knowledge.Checked) + } +} + +func orAny(d string) string { + if d == "" { + return "selected" + } + return d +} + +// ---- Gradle, Maven, buildpacks + +var ( + gradleToolchain = regexp.MustCompile(`JavaLanguageVersion\.of\(\s*["']?(\d{1,2})["']?\s*\)`) + gradleRelease = regexp.MustCompile(`(?:sourceCompatibility|targetCompatibility|options\.release|release\.set)\s*[=(]\s*(?:JavaVersion\.VERSION_|["'])?(\d{1,2})\b`) + bpJVM = regexp.MustCompile(`BP_JVM_VERSION["']?\s*(?:[:=]|to|>)\s*["']?(\d{1,2}(?:\.\d+)*)`) + jibFrom = regexp.MustCompile(`(?:from\s*\{[^}]*?image\s*=\s*|jib\.from\.image\s*=\s*|\s*\s*)["']?([A-Za-z0-9][\w./:@-]*)`) + mavenToolchain = regexp.MustCompile(`\s*\[?(\d{1,2})(?:,\))?\s*`) + enforcerJava = regexp.MustCompile(`(?s)\s*\s*([^<]{1,60})`) +) + +// lineToolchain reports a toolchain or release setting that selects a Java +// line with no fix. Lines with a fix are not reported: the toolchain picks +// whichever release of that line is installed. +func (s *scanner) lineToolchain(rel string, line int, feature int, source string) { + l, ok := knowledge.LineOf(feature) + if !ok || l.Fixed != nil { + return + } + s.add(Finding{Rule: RuleLine, File: rel, Line: line, Level: "error", Status: StatusVulnerable, Reason: l.Note, + Message: fmt.Sprintf("%s selects Java %d, a line that received no Java4Shell fix", source, feature), + Fix: fmt.Sprintf("Java %d received no fix: move to a supported release with the fix, such as %s.", feature, knowledge.Upgrade(feature)), + Props: map[string]string{"source": source, "current": fmt.Sprint(feature)}}) +} + +func (s *scanner) gradle(rel, text string) { + for i, l := range lines(text) { + for _, m := range gradleToolchain.FindAllStringSubmatch(l, -1) { + n := 0 + fmt.Sscanf(m[1], "%d", &n) + s.lineToolchain(rel, i+1, n, "the Gradle toolchain") + } + if m := bpJVM.FindStringSubmatch(l); m != nil { + s.buildpack(rel, i+1, m[1]) + } + s.jib(rel, i+1, l) + } +} + +func (s *scanner) maven(rel, text string) { + ls := lines(text) + inToolchain := false + for i, l := range ls { + if strings.Contains(l, "") || strings.Contains(l, "") || strings.Contains(l, "") { + inToolchain = true + } + if inToolchain { + if m := mavenToolchain.FindStringSubmatch(l); m != nil && path.Base(rel) == "toolchains.xml" || m != nil && strings.Contains(strings.Join(ls[max(0, i-3):i], "\n"), "") { + n := 0 + fmt.Sscanf(m[1], "%d", &n) + s.lineToolchain(rel, i+1, n, "the Maven toolchain") + } + } + if strings.Contains(l, "") || strings.Contains(l, "") { + inToolchain = false + } + if m := bpJVM.FindStringSubmatch(l); m != nil { + s.buildpack(rel, i+1, m[1]) + } + s.jib(rel, i+1, l) + } + for _, m := range enforcerJava.FindAllStringSubmatchIndex(text, -1) { + floor := strings.TrimSpace(text[m[2]:m[3]]) + line := strings.Count(text[:m[2]], "\n") + 1 + lo := strings.TrimLeft(floor, "[(") + lo, _, _ = strings.Cut(lo, ",") + v, ok := knowledge.Parse(lo) + if !ok || v.Feature() < 17 { + continue + } + fx := knowledge.FixedVersion(v.Feature()) + if fx == "" { + continue + } + fv, _ := knowledge.Parse(fx) + if knowledge.Compare(v.Nums, fv.Nums) < 0 && strings.Count(lo, ".") >= 2 { + s.add(Finding{Rule: RuleJavaPin, File: rel, Line: line, Level: "note", Status: StatusUnknown, + Reason: "the Maven Enforcer floor lets a build run on a release without the fix; it does not choose the release", + Message: fmt.Sprintf("the Maven Enforcer requireJavaVersion floor %s is below %s, the first release with the Java4Shell fix", floor, fx), + Fix: fmt.Sprintf("Raise the floor to %s so builds fail on a JDK without the fix.", fx), + Props: map[string]string{"source": "maven-enforcer", "current": floor, "fixed_in": fx}}) + } + } +} + +func (s *scanner) projectToml(rel, text string) { + for i, l := range lines(text) { + if m := bpJVM.FindStringSubmatch(l); m != nil { + s.buildpack(rel, i+1, m[1]) + } + if strings.HasSuffix(rel, "jib.yaml") { + if m := regexp.MustCompile(`^\s*image\s*:\s*["']?([A-Za-z0-9][\w./:@-]*)`).FindStringSubmatchIndex(l); m != nil { + s.jibRef(rel, i+1, m[2], l[m[2]:m[3]]) + } + } + } +} + +// buildpack judges BP_JVM_VERSION: Paketo installs the newest release of +// that line (BellSoft Liberica by default) when the image is built. +func (s *scanner) buildpack(rel string, line int, ver string) { + n := 0 + fmt.Sscanf(ver, "%d", &n) + if l, ok := knowledge.LineOf(n); ok && l.Fixed == nil { + s.lineToolchain(rel, line, n, "BP_JVM_VERSION (Cloud Native Buildpacks)") + return + } + if strings.Count(ver, ".") >= 2 { + s.judgeVersion(rel, line, 0, ver, "BP_JVM_VERSION (Cloud Native Buildpacks)", "") + } +} + +func (s *scanner) jib(rel string, line int, l string) { + m := jibFrom.FindStringSubmatchIndex(l) + if m == nil { + return + } + s.jibRef(rel, line, m[2], l[m[2]:m[3]]) +} + +// jibRef judges a Jib base image like an image reference. +func (s *scanner) jibRef(rel string, line, col int, image string) { + r := refs.Ref{File: rel, Line: line, Column: col + 1, Kind: "jib", Context: "jib.from.image", Text: image, Image: image, + Parts: []refs.Part{{Text: image, File: rel, Line: line, Column: col + 1}}, EditFile: rel, EditLine: line, EditText: image} + s.judgeRef(r, s.opts) +} + +// ---- Dockerfiles: OS packages and the mitigation a stage sets + +var ( + aptJava = regexp.MustCompile(`\b(openjdk-(\d{1,2})-(?:jre|jdk)(?:-headless)?)(?:=([^\s;&|]+))?`) + apkJava = regexp.MustCompile(`\b(openjdk(\d{1,2})(?:-jre|-jdk|-jre-headless|-jmods)?)(?:[=~><]+([^\s;&|]+))?`) + rpmJava = regexp.MustCompile(`\b(java-(\d{1,2})-(?:openjdk|amazon-corretto)(?:-headless|-devel)?)(?:-(\d[\w.:-]*))?`) + envJTO = regexp.MustCompile(`(?i)^\s*ENV\s+`) + fromLine = regexp.MustCompile(`(?i)^\s*FROM\s`) +) + +func (s *scanner) dockerfile(rel, text string) { + ls := lines(text) + from := 0 + for i := 0; i < len(ls); i++ { + l := ls[i] + // Join continuation lines for matching; report the first line. + full := l + j := i + for strings.HasSuffix(strings.TrimRight(ls[j], " \t"), "\\") && j+1 < len(ls) { + j++ + full = strings.TrimSuffix(strings.TrimRight(full, " \t"), "\\") + " " + ls[j] + } + trim := strings.TrimSpace(full) + switch { + case fromLine.MatchString(trim): + from = i + 1 + case envJTO.MatchString(trim): + var o jvm.Options + body := envJTO.ReplaceAllString(trim, "") + for _, kv := range jvm.Words(body) { + k, v, ok := strings.Cut(kv, "=") + if !ok { + continue + } + for _, n := range jvm.EnvVars { + if k == n { + o.Apply(v, "ENV "+k+" in "+rel) + } + } + } + if ok, how := o.Mitigates(); ok && from > 0 { + s.mitigated[fmt.Sprintf("%s:%d", rel, from)] = how + } + case strings.HasPrefix(strings.ToUpper(trim), "RUN "): + s.packages(rel, i+1, trim) + } + i = j + } +} + +// packages finds distribution OpenJDK packages a RUN line installs. +func (s *scanner) packages(rel string, line int, run string) { + lower := run + installs := strings.Contains(lower, "apt-get install") || strings.Contains(lower, "apt install") || strings.Contains(lower, "apk add") || + strings.Contains(lower, "dnf install") || strings.Contains(lower, "yum install") || strings.Contains(lower, "microdnf install") || + strings.Contains(lower, "zypper in") + if !installs { + return + } + type hit struct{ name, ver string } + var hits []struct { + hit + feature int + mgr string + } + for _, m := range aptJava.FindAllStringSubmatch(run, -1) { + n := 0 + fmt.Sscanf(m[2], "%d", &n) + hits = append(hits, struct { + hit + feature int + mgr string + }{hit{m[1], m[3]}, n, "apt"}) + } + for _, m := range apkJava.FindAllStringSubmatch(run, -1) { + n := 0 + fmt.Sscanf(m[2], "%d", &n) + hits = append(hits, struct { + hit + feature int + mgr string + }{hit{m[1], m[3]}, n, "apk"}) + } + for _, m := range rpmJava.FindAllStringSubmatch(run, -1) { + n := 0 + fmt.Sscanf(m[2], "%d", &n) + hits = append(hits, struct { + hit + feature int + mgr string + }{hit{m[1], m[3]}, n, "rpm"}) + } + for _, h := range hits { + if h.feature < 17 { + continue // Java 8 and 11 packages are not affected + } + props := map[string]string{"package": h.name, "manager": h.mgr} + l, _ := knowledge.LineOf(h.feature) + if l.Fixed == nil { + s.add(Finding{Rule: RuleLine, File: rel, Line: line, Level: "error", Status: StatusVulnerable, Reason: l.Note, + Message: fmt.Sprintf("installs %s, a Java %d package: that line received no Java4Shell fix", h.name, h.feature), + Fix: fmt.Sprintf("Install a supported Java package with the fix instead, such as %s.", knowledge.Upgrade(h.feature)), Props: props}) + continue + } + fx := knowledge.FixedVersion(h.feature) + props["fixed_in"] = fx + if h.ver != "" { + props["current"] = h.ver + up := h.ver + if i := strings.IndexByte(up, ':'); i >= 0 { + up = up[i+1:] + } + up = strings.ReplaceAll(up, "_p", "+") + if v, ok := knowledge.Parse(up); ok { + if st, why := knowledge.Judge(v); st == knowledge.Vulnerable { + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "error", Status: StatusVulnerable, Reason: why, + Message: fmt.Sprintf("pins %s to %s, without the Java4Shell fix", h.name, h.ver), + Fix: fmt.Sprintf("Pin %s to a package of Java %s or later once your distribution publishes it (none had as of %s), then rebuild. Until then set ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics in this stage.", h.name, fx, knowledge.Checked), + Props: props}) + } + } + continue + } + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "warning", Status: StatusVulnerable, + Reason: fmt.Sprintf("Debian, Ubuntu and Alpine had published no %s package with the fix as of %s (Red Hat's status was not checked), so a build today installs a release without it", fx, knowledge.Checked), + Message: fmt.Sprintf("installs %s without a version: it gets whatever the distribution has, which had no Java4Shell fix yet", h.name), + Fix: fmt.Sprintf("Rebuild once the distribution publishes Java %s or later and check the installed version; until then set ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics in this stage.", fx), + Props: props}) + } +} + +// ---- YAML helpers + +func walkYAML(n *yaml.Node, depth int, fn func(m *yaml.Node)) { + if n == nil || depth > 64 { + return + } + if n.Kind == yaml.MappingNode { + fn(n) + } + for _, c := range n.Content { + walkYAML(c, depth+1, fn) + } +} + +func mapGet(m *yaml.Node, key string) *yaml.Node { + if m == nil || m.Kind != yaml.MappingNode { + return nil + } + for i := 0; i+1 < len(m.Content); i += 2 { + if m.Content[i].Value == key { + return m.Content[i+1] + } + } + return nil +} diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go new file mode 100644 index 0000000..4a6a370 --- /dev/null +++ b/detectors/java4shell/java4shell.go @@ -0,0 +1,370 @@ +// Package java4shell is the detector for Java4Shell (CVE-2026-114938): an +// out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64 +// (JDK-8393212), fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and +// 27.0.1.1 on 2026-11-15. The decoder came with JDK 18 and 17.0.6; Java 8, +// 11 and 17.0.0 to 17.0.5 do not have it. +// +// It finds Java runtimes in filesystems and container images by their VM +// library (libjvm.so, jvm.dll, libjvm.dylib) and judges each by what the +// library proves: its CPU architecture, the version compiled into it and +// whether it carries the AVX-512 VBMI decode stubs, with the release file as +// a second witness. JVM options that keep the decoder from being generated +// (-XX:-UseBASE64Intrinsics, -XX:UseAVX=2 or lower) are reported as a +// mitigation, never as a fix. In a source tree it finds the Java images, +// versions and packages a project pins, and fix moves them to fixed +// releases. +// +// internal/knowledge, internal/jvm, internal/assess and internal/repo know +// nothing about the engine; this file adapts them. +package java4shell + +import ( + "bytes" + "fmt" + "path" + "regexp" + "sort" + "strings" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/assess" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" + "github.com/DefectDojo/earlylight/internal/archive" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// ID is the detector's ID. +const ID = "java4shell" + +// Kind IDs. +const ( + KindRuntime = assess.KindRuntime + KindBundled = assess.KindBundled +) + +// Detector implements engine.Detector, engine.Reader, engine.RepoScanner and +// engine.Fixer. +type Detector struct{} + +func init() { engine.Register(&Detector{}) } + +const about = " HotSpot's AVX-512 VBMI Base64 decoder (x86-64, JDK 18 and later, 17.0.6 and later) writes up to 64 bytes" + + " past its output when the input ends in a padded fragment shorter than four characters, so a Java program that" + + " decodes untrusted Base64 (tokens, headers, certificates, JSON) can have its heap corrupted once the decoder is" + + " compiled. It runs on CPUs with AVX-512 VBMI (Intel Ice Lake and later, AMD Zen 4 and later). Fixed in OpenJDK" + + " 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 (JDK-8393212); Java 18 to 20, 22 to 24 and 26 received no fix." + + " -XX:-UseBASE64Intrinsics or -XX:UseAVX=2 keep the decoder from being generated until the runtime is updated." + +// Manifest describes the detector. +func (d *Detector) Manifest() engine.Manifest { + cwe := []string{"CWE-787"} + return engine.Manifest{ + ID: ID, + Title: "Java4Shell: HotSpot AVX-512 Base64 decoder out-of-bounds write (" + knowledge.CVE + ")", + CVEs: []string{knowledge.CVE}, + Advisories: []string{ + "https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b", + "https://openjdk.org/groups/vulnerability/advisories/", + "https://github.com/corretto/corretto-21/blob/21.0.13.1.2/CHANGELOG.md", + }, + Disclosed: "2026-11-17", + Targets: []engine.TargetKind{engine.Filesystem, engine.Image, engine.Repository}, + Kinds: append([]engine.Kind{ + {ID: KindRuntime, Title: "Java runtime vulnerable to Java4Shell", Level: "error", SecuritySeverity: "8.1", CWEs: cwe, + Description: "A HotSpot Java runtime for x86-64 with the AVX-512 VBMI Base64 decoder and without the fix: an installed JDK or JRE, a packaged OpenJDK, a jlink image or a runtime in a container image." + about}, + {ID: KindBundled, Title: "Java runtime bundled in a product is vulnerable to Java4Shell", Level: "error", SecuritySeverity: "8.1", CWEs: cwe, + Description: "A Java runtime that a product ships inside its own install directory (Atlassian Jira and Confluence, Elasticsearch, Artifactory, JetBrains IDEs and others) without the fix. Updating the operating system's Java does not fix it: upgrade the product." + about}, + }, repoKinds()...), + Tags: []string{"security", "java", "openjdk", "hotspot", "Java4Shell"}, + Data: "OpenJDK fixed releases (17.0.21.1, 21.0.13.1, 25.0.5.1, 27.0.1.1), the releases that introduced the decoder, and vendor and distribution status, checked " + knowledge.Checked, + } +} + +// Load checks the release data. +func (d *Detector) Load() error { + prev := 0 + for _, l := range knowledge.Lines { + if l.Feature <= prev || l.Fixed == nil && l.Note == "" || l.Fixed != nil && l.Fixed[0] != l.Feature { + return fmt.Errorf("release data for Java %d contradicts itself", l.Feature) + } + prev = l.Feature + } + return nil +} + +// Wants reads VM libraries, release files, the files that set JVM options, +// package databases, crash logs and startup scripts. +func (d *Detector) Wants(p string, head []byte, _ bool) bool { + base := path.Base(p) + switch { + case jvm.IsLibraryName(base): + return archive.IsExecutable(head) + case base == "release", keep(p), jvm.SettingKind(p) != "", hsErr.MatchString(base): + return true + } + return isScript(head) +} + +var hsErr = regexp.MustCompile(`^hs_err_pid\d{1,10}\.log$`) + +func isScript(head []byte) bool { return len(head) > 2 && head[0] == '#' && head[1] == '!' } + +// keep reports the package databases owners are read from. +func keep(p string) bool { + switch p { + case "/lib/apk/db/installed", "/usr/lib/apk/db/installed", "/var/lib/dpkg/status", "/etc/os-release", "/usr/lib/os-release": + return true + } + return assess.IsDpkgList(p) +} + +// Limits on what one target keeps. +const ( + maxKept = 16 << 20 // a package database + maxScript = 256 << 10 + maxHsErr = 4 << 20 + maxHsErrs = 64 + maxLibs = 4096 + maxSetting = 1 << 20 +) + +// NewScan starts a filesystem or image scan. +func (d *Detector) NewScan(kind engine.TargetKind) engine.Scan { + return &scan{kind: kind, releases: map[string]jvm.Release{}, badReleases: map[string]string{}, + kept: map[string][]byte{}, lists: map[string][]byte{}, scripts: map[string]map[string]bool{}} +} + +type scan struct { + kind engine.TargetKind + libs []*jvm.Library + releases map[string]jvm.Release + badReleases map[string]string + settings []jvm.Setting + kept map[string][]byte + lists map[string][]byte + scripts map[string]map[string]bool + crashes []crash + dropped int +} + +func (s *scan) Visit(f engine.File) []engine.Skip { + if f.Member { + return nil // installed runtimes only, not copies inside archives + } + base := path.Base(f.Path) + switch { + case jvm.IsLibraryName(base): + if l, ok := jvm.Inspect(f.Path, f.Data); ok { + if len(s.libs) >= maxLibs { + s.dropped++ + return []engine.Skip{{Path: f.Path, Reason: fmt.Sprintf("more than %d Java VM libraries in one target; not checked", maxLibs)}} + } + s.libs = append(s.libs, l) + } + return nil + case base == "release": + if !archive.IsExecutable(f.Data) { + if r, ok := jvm.ParseRelease(f.Data); ok { + s.releases[path.Dir(f.Path)] = r + } else if len(f.Data) > 64<<10 && bytes.Contains(f.Data[:min(len(f.Data), 4096)], []byte("JAVA_VERSION")) { + s.badReleases[path.Dir(f.Path)] = "its release file is larger than 64 KiB and was not read" + } + } + return nil + case hsErr.MatchString(base): + if len(s.crashes) < maxHsErrs && len(f.Data) <= maxHsErr { + s.crashes = append(s.crashes, readCrash(f.Path, f.Data)) + } + return nil + } + if k := jvm.SettingKind(f.Path); k != "" && len(f.Data) <= maxSetting { + if st, ok := jvm.ReadSetting(f.Path, f.Data); ok { + s.settings = append(s.settings, st) + } + } + if keep(f.Path) && len(f.Data) <= maxKept { + if assess.IsDpkgList(f.Path) { + s.lists[strings.TrimSuffix(path.Base(f.Path), ".list")] = f.Data + } else { + s.kept[f.Path] = f.Data + } + } + if isScript(f.Data) && len(f.Data) <= maxScript { + vars := map[string]bool{} + for _, n := range jvm.ScriptVars { + if bytes.Contains(f.Data, []byte("$"+n)) || bytes.Contains(f.Data, []byte("${"+n)) { + vars[n] = true + } + } + if len(vars) > 0 { + s.scripts[f.Path] = vars + } + } + return nil +} + +func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { + if s.kind == engine.Filesystem { + if c, ok := thisCPU(); ok { + ctx.Annotate("java4shell_scanner_cpu", c) + } + } + if len(s.crashes) > 0 { + ctx.Annotate("java4shell_crash_logs", s.crashes) + } + if len(s.libs) == 0 { + return nil + } + links, _ := ctx.Links() + res := resolver{links: links} + owners := map[string]assess.Package{} + for _, db := range []string{"/lib/apk/db/installed", "/usr/lib/apk/db/installed"} { + if b := s.kept[db]; b != nil { + for k, v := range assess.APKOwners(b) { + owners[k] = v + } + } + } + if st := s.kept["/var/lib/dpkg/status"]; st != nil { + for k, v := range assess.DpkgOwners(st, s.lists) { + owners[k] = v + } + } + in := assess.Input{ + Libraries: s.libs, + Releases: s.releases, + BadReleases: s.badReleases, + Settings: s.settings, + Owners: owners, + Resolve: res.resolve, + Scripts: s.scripts, + } + if s.kind == engine.Image { + in.Env = ctx.Env() + if in.Env == nil { + in.Env = []string{} + } + in.Command = ctx.Command() + } + cpu, haveCPU := thisCPU() + var out []engine.Finding + for _, x := range assess.Run(in) { + f := finding(x) + if haveCPU && s.kind == engine.Filesystem && x.Status == assess.Vulnerable { + f.Facts["scanner_cpu_runs_it"] = yes(cpu.Affected) + } + out = append(out, f) + } + return out +} + +var verdicts = map[assess.Status]engine.Verdict{ + assess.Vulnerable: engine.Vulnerable, + assess.Fixed: engine.Fixed, + assess.NotAffected: engine.Fixed, + assess.Mitigated: engine.Inactive, + assess.Unknown: engine.Unknown, +} + +func finding(x assess.Finding) engine.Finding { + v, ok := verdicts[x.Status] + if !ok { + v = engine.Unknown + } + facts := map[string]string{"status": string(x.Status), "arch": string(x.Arch)} + if x.Version != "" { + facts["version"], facts["version_from"] = x.Version, x.VersionFrom + } + if x.ReleaseVersion != "" { + facts["release_file_version"] = x.ReleaseVersion + } + if x.VM != "" { + facts["vm"] = x.VM + } + if x.Vendor != "" { + facts["vendor"] = x.Vendor + } + if x.Library != nil { + facts["vm_library"] = x.Library.Path + facts["vbmi_decoder"] = yes(x.Library.VBMIStubs) + } + if x.Product != "" { + facts["product"] = x.Product + } + if x.Package != nil { + facts["package"] = strings.TrimSpace(x.Package.Name + " " + x.Package.Version) + } + if x.JLinked { + facts["jlink"] = "yes" + } + if x.Mitigation != "" { + facts["mitigation"] = x.Mitigation + } + if len(x.MitigatedFor) > 0 { + sort.Strings(x.MitigatedFor) + facts["mitigated_only_for"] = strings.Join(x.MitigatedFor, ",") + } + if fx := fixedFor(x.Version); fx != "" { + facts["fixed_in"] = fx + } + method := "vm-library" + if x.VersionFrom == "release-file" { + method = "release-file" + } + return engine.Finding{ + Kind: x.Kind, + Path: x.Path, + Verdict: v, + Reason: x.Reason, + Message: x.Message, + Method: method, + Facts: facts, + CVEs: []engine.CVEResult{{ID: knowledge.CVE, Verdict: v, Reason: x.Reason}}, + Fix: x.Fix, + Details: x, + } +} + +func fixedFor(version string) string { + v, ok := knowledge.Parse(version) + if !ok { + return "" + } + return knowledge.FixedVersion(v.Feature()) +} + +func yes(b bool) string { + if b { + return "yes" + } + return "no" +} + +// resolver follows symbolic links the way the kernel would, component by +// component, within the target. +type resolver struct{ links map[string]string } + +func (r resolver) resolve(p string) string { + cur := path.Clean("/" + p) + for hops := 0; hops < 40; hops++ { + parts := strings.Split(strings.TrimPrefix(cur, "/"), "/") + changed := false + prefix := "/" + for i, part := range parts { + next := path.Join(prefix, part) + if to, ok := r.links[next]; ok { + if !strings.HasPrefix(to, "/") { + to = path.Join(prefix, to) + } + cur = path.Clean(path.Join(append([]string{to}, parts[i+1:]...)...)) + changed = true + break + } + prefix = next + } + if !changed { + return cur + } + } + return cur // a loop: as far as it got +} diff --git a/detectors/java4shell/repo.go b/detectors/java4shell/repo.go new file mode 100644 index 0000000..47935b2 --- /dev/null +++ b/detectors/java4shell/repo.go @@ -0,0 +1,344 @@ +package java4shell + +import ( + "context" + "fmt" + "io" + "strings" + "time" + + "github.com/google/go-containerregistry/pkg/authn" + "github.com/google/go-containerregistry/pkg/name" + "github.com/google/go-containerregistry/pkg/v1/remote" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/repo" + "github.com/DefectDojo/earlylight/internal/engine" + "github.com/DefectDojo/earlylight/internal/image" + "github.com/DefectDojo/earlylight/internal/netguard" + "github.com/DefectDojo/earlylight/internal/refs" + "github.com/DefectDojo/earlylight/internal/source" +) + +// Kind IDs for a source tree. +const ( + KindImagePin = repo.RuleImagePin + KindJavaPin = repo.RuleJavaPin + KindLine = repo.RuleLine + KindPackage = repo.RulePackage + KindImage = "image" + KindNotChecked = repo.RuleNotChecked +) + +func repoKinds() []engine.Kind { + cwe := []string{"CWE-787"} + return []engine.Kind{ + {ID: KindImagePin, Title: "Source tree uses a Java image without the Java4Shell fix", Level: "error", SecuritySeverity: "8.1", CWEs: cwe, + Description: "A Dockerfile, Compose, Kubernetes, Helm values, CI or Jib file names a Java runtime image (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine and others) whose tag is a Java release without the fix."}, + {ID: KindImage, Title: "Image the source tree uses holds a Java runtime vulnerable to Java4Shell", Level: "error", SecuritySeverity: "8.1", CWEs: cwe, + Description: "An image the tree builds on or deploys, read from its registry for linux/amd64 and judged as scan image does: a moving tag, or a product image (Jira, Elasticsearch, Jenkins...) that carries its own runtime."}, + {ID: KindJavaPin, Title: "Source tree pins a Java release without the Java4Shell fix", Level: "warning", SecuritySeverity: "6.5", CWEs: cwe, + Description: "A version file (.java-version, .sdkmanrc, .tool-versions, mise), a GitHub Actions setup-java step, a buildpack setting or a Maven Enforcer floor that selects or allows a Java release without the fix."}, + {ID: KindLine, Title: "Source tree selects a Java line that received no Java4Shell fix", Level: "error", SecuritySeverity: "8.1", CWEs: cwe, + Description: "A toolchain, version file, CI step, buildpack, image or package of Java 18, 19, 20, 22, 23, 24 or 26: those lines are end of life and received no fix."}, + {ID: KindPackage, Title: "Dockerfile installs a distribution OpenJDK package without the Java4Shell fix", Level: "error", SecuritySeverity: "8.1", CWEs: cwe, + Description: "An apt, apk, dnf, yum or microdnf install of an OpenJDK 17 or later package pinned to a release without the fix, or without a version while the distribution had no fixed package."}, + {ID: KindNotChecked, Title: "Java runtime not checked for the Java4Shell fix", Level: "note", + Description: "An image whose tag does not name one Java release (a moving tag, a product image) that was not read, a workflow expression, or a file that could not be read. It is not known to be safe."}, + } +} + +// ScanRepo checks a source tree. +func (d *Detector) ScanRepo(ctx context.Context, dir string, o engine.Options) *engine.Target { + t := &engine.Target{Name: dir, Type: engine.Repository} + res, err := repo.Scan(ctx, dir, repo.Options{Platforms: o.Platforms}) + if err != nil { + t.Error = err.Error() + return t + } + t.Files = res.Files + if res.Truncated { + t.Incomplete = "the source tree has too many files to walk; what lies past the limit is not checked" + } + pulls := map[string]*engine.Target{} + for _, f := range res.Findings { + if f.Pull != "" && !o.Offline { + t.Findings = append(t.Findings, d.pulled(dir, f, o, pulls, t)...) + continue + } + t.Findings = append(t.Findings, repoFinding(f)) + } + for _, s := range res.Skips { + p := s.File + if s.Line > 0 { + p = fmt.Sprintf("%s:%d", s.File, s.Line) + } + t.Skipped = append(t.Skipped, source.Skip{Path: p, Reason: s.Reason}) + } + return t +} + +func repoFinding(f repo.Finding) engine.Finding { + v, reason := engine.Vulnerable, f.Reason + switch f.Status { + case repo.StatusUnknown: + v = engine.Unknown + case repo.StatusMitigated: + v = engine.Inactive + } + if reason == "" && v != engine.Vulnerable { + reason = "not decided" + } + facts := map[string]string{} + for k, val := range f.Props { + facts[k] = val + } + out := engine.Finding{Kind: f.Rule, Path: f.File, Line: f.Line, Verdict: v, Reason: reason, Message: f.Message, Method: "source", + Facts: facts, Fix: f.Fix, CVEs: []engine.CVEResult{{ID: knowledge.CVE, Verdict: v, Reason: reason}}} + if f.Level == "warning" { + out.Severity = "medium" + } + return out +} + +// maxRepoImages bounds the images one source-tree scan pulls. +const maxRepoImages = 20 + +// pulled reads an image the tree references (linux/amd64, the only +// affected platform) through the guarded transport and reports its +// runtimes at the reference. +func (d *Detector) pulled(dir string, f repo.Finding, o engine.Options, cache map[string]*engine.Target, t *engine.Target) []engine.Finding { + img := f.Pull + it, ok := cache[img] + if !ok { + if len(cache) >= maxRepoImages { + t.Skipped = append(t.Skipped, source.Skip{Path: fmt.Sprintf("%s:%d", f.File, f.Line), Reason: fmt.Sprintf("image %s not pulled: this scan already pulled %d images", img, maxRepoImages)}) + return []engine.Finding{repoFinding(f)} + } + it = engine.ScanImage([]engine.Detector{d}, img, engine.Options{Platform: "linux/amd64", MaxFileSize: o.MaxFileSize, Guarded: true, PublicOnly: o.PublicOnly}) + cache[img] = it + } + if it.Error != "" { + g := repoFinding(f) + g.Message = fmt.Sprintf("image %s could not be read for Java4Shell: %s", img, refs.CleanText(it.Error, 300)) + g.Reason = "the image could not be pulled" + g.CVEs[0].Reason = g.Reason + return []engine.Finding{g} + } + var out []engine.Finding + for _, x := range it.Findings { + if x.Verdict.Cleared() { + continue + } + g := x + g.Kind, g.Path, g.Line, g.Method = KindImage, f.File, f.Line, "registry" + g.Facts = map[string]string{} + for k, v := range x.Facts { + g.Facts[k] = v + } + g.Facts["image"], g.Facts["runtime"] = img, x.Path + g.Message = fmt.Sprintf("image %s: %s: %s", img, x.Path, x.Message) + if mit := f.Props["mitigation"]; mit != "" && x.Verdict == engine.Vulnerable { + g.Verdict = engine.Inactive + g.Reason = x.Reason + "; " + mit + g.Message += ", mitigated by its JVM options until it is updated" + g.CVEs = []engine.CVEResult{{ID: knowledge.CVE, Verdict: g.Verdict, Reason: g.Reason}} + } + g.Fix = x.Fix + " Use a release of " + img + " built with the fix (or rebuild it), then redeploy." + out = append(out, g) + } + return out +} + +// Fix moves what can be moved to fixed releases: image tags to the first +// published fixed tag of the same variant (read and checked first) and +// setup-java versions to the moving major version for distributions whose +// newest release is fixed. Each edit is rescanned in memory first. +func (d *Detector) Fix(ctx context.Context, dirs []string, o engine.Options, stdout, stderr io.Writer) int { + reg := repo.Registry{} + if !o.Offline { + reg.Tags = tagLister(o) + reg.Verify = d.verifier(o) + } + code := 0 + for _, dir := range dirs { + ro := repo.Options{Platforms: o.Platforms} + res, err := repo.Scan(ctx, dir, ro) + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", repo.Printable(dir), err) + return 2 + } + if res.Truncated { + fmt.Fprintf(stdout, "incomplete %s: the source tree has too many files to walk; what lies past the limit is not checked\n", repo.Printable(dir)) + code = max(code, 1) + } + for _, sk := range res.Skips { + fmt.Fprintf(stdout, "not checked %s %s\n", repo.Printable(sk.File), repo.Printable(sk.Reason)) + code = max(code, 1) + } + pulls := map[string]*engine.Target{} + for _, f := range res.Findings { + where := fmt.Sprintf("%s:%d", repo.Printable(f.File), f.Line) + if f.Pull != "" { + if o.Offline { + fmt.Fprintf(stdout, "not checked %s %s\n", where, repo.Printable(f.Message)) + code = max(code, 1) + continue + } + dummy := &engine.Target{} + for _, g := range d.pulled(dir, f, o, pulls, dummy) { + if g.Verdict == engine.Inactive { + continue + } + fmt.Fprintf(stdout, "not fixed %s %s\n %s\n", where, repo.Printable(g.Message), repo.Printable(g.Fix)) + if g.Facts["product"] != "" && f.Props["mitigation"] == "" && strings.HasSuffix(strings.ToLower(f.File), "dockerfile") { + fmt.Fprintf(stdout, " optional interim mitigation (not applied):\n %s\n", repo.Printable(repo.Mitigation(f.File, f.Line))) + } + code = max(code, 1) + } + continue + } + if f.Status == repo.StatusMitigated || f.Level == "note" && f.Rule != repo.RuleNotChecked { + continue + } + if f.Rule == repo.RuleNotChecked { + fmt.Fprintf(stdout, "not checked %s %s\n", where, repo.Printable(f.Message)) + code = max(code, 1) + continue + } + if !f.Fixable { + fmt.Fprintf(stdout, "not fixed %s %s\n %s\n", where, repo.Printable(f.Message), repo.Printable(f.Fix)) + code = max(code, 1) + continue + } + ch, err := repo.Plan(ctx, dir, f, reg, ro) + if err != nil { + fmt.Fprintf(stdout, "not fixed %s %s\n %s\n", where, repo.Printable(f.Message), repo.Printable(err.Error())) + code = max(code, 1) + continue + } + verb := "fixed" + if o.DryRun { + verb = "would fix" + } else if err := repo.Apply(dir, ch); err != nil { + fmt.Fprintf(stderr, "%s: %v\n", repo.Printable(ch.File), err) + return 2 + } + fmt.Fprintf(stdout, "%-10s %s %s\n%s", verb, where, repo.Printable(ch.Summary), indent(repo.Diff(ch))) + } + } + return code +} + +func indent(s string) string { + var b strings.Builder + for _, l := range strings.Split(strings.TrimRight(s, "\n"), "\n") { + b.WriteString(" " + l + "\n") + } + return b.String() +} + +// tagLister lists an image repository's tags through the guarded +// transport, a page at a time, at most 20,000, within the timeout. +func tagLister(o engine.Options) func(context.Context, string) ([]string, error) { + return func(ctx context.Context, img string) ([]string, error) { + if err := registryRef(img); err != nil { + return nil, err + } + repoName, err := name.NewRepository(img) + if err != nil { + return nil, err + } + timeout := o.Timeout + if timeout <= 0 { + timeout = 60 * time.Second + } + lctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + p, err := remote.NewPuller(remote.WithContext(lctx), remote.WithTransport(netguard.Transport(o.PublicOnly)), remote.WithAuthFromKeychain(authn.DefaultKeychain)) + if err != nil { + return nil, err + } + l, err := p.Lister(lctx, repoName) + if err != nil { + return nil, err + } + var tags []string + for l.HasNext() && len(tags) < 20000 { + page, err := l.Next(lctx) + if err != nil { + return nil, err + } + tags = append(tags, page.Tags...) + } + return tags, nil + } +} + +// registryRef accepts only a registry reference: never a local archive or +// any other transport a source file could name. +func registryRef(ref string) error { + if strings.Contains(ref, "://") || strings.HasPrefix(ref, "docker-archive:") || strings.HasPrefix(ref, "rootfs:") || strings.HasPrefix(ref, "/") { + return fmt.Errorf("%q is not a registry reference", ref) + } + if _, err := name.ParseReference(ref); err != nil { + return fmt.Errorf("%q is not a valid image reference", ref) + } + return nil +} + +// verifier reads the replacement image on linux/amd64 (and checks it is +// published for every platform the current one has) and requires the +// detector to find at least one runtime with the fix and none without it. +func (d *Detector) verifier(o engine.Options) func(ctx context.Context, current, target string) (string, error) { + return func(ctx context.Context, current, target string) (string, error) { + if err := registryRef(target); err != nil { + return "", err + } + var cur []string + if registryRef(current) == nil { + cur, _ = image.Platforms(current) // the current tag may be gone: judge the target on its own + } + tp, err := image.Platforms(target) + if err != nil { + return "", err + } + have := map[string]bool{} + for _, p := range tp { + have[p] = true + } + for _, p := range cur { + if len(tp) > 0 && !have[p] { + return "", &repo.Declined{Reason: fmt.Sprintf("%s is not published for %s, which %s has; change it by hand", target, p, current)} + } + } + t := engine.ScanImage([]engine.Detector{d}, target, engine.Options{Platform: "linux/amd64", MaxFileSize: o.MaxFileSize, Guarded: true, PublicOnly: o.PublicOnly}) + if t.Error != "" { + return "", fmt.Errorf("reading %s: %s", target, t.Error) + } + if t.Incomplete != "" || t.Gaps() > 0 || len(t.Problems) > 0 { + return "", &repo.Declined{Reason: fmt.Sprintf("%s could not be read in full; change it by hand", target)} + } + fixed := 0 + for _, f := range t.Findings { + switch { + case f.Verdict == engine.Vulnerable || f.Verdict == engine.Unknown || f.Verdict == engine.Inactive: + return "", &repo.Declined{Reason: fmt.Sprintf("%s still holds %s (%s); change it by hand", target, f.Path, f.Verdict)} + case f.Facts["status"] == "fixed": + fixed++ + } + } + if fixed == 0 { + return "", &repo.Declined{Reason: fmt.Sprintf("no Java runtime with the fix was found in %s, so the fix is not proven; change it by hand", target)} + } + ref, err := name.ParseReference(target) + if err != nil { + return "", err + } + desc, err := remote.Head(ref, remote.WithAuthFromKeychain(authn.DefaultKeychain), remote.WithContext(ctx), remote.WithTransport(netguard.Transport(o.PublicOnly))) + if err != nil { + return "", err + } + return desc.Digest.String(), nil + } +} diff --git a/go.mod b/go.mod index 635bc81..9679fe4 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( github.com/knqyf263/go-rpmdb v0.1.1 github.com/ulikunitz/xz v0.5.17 golang.org/x/crypto v0.58.0 + golang.org/x/sys v0.49.0 gopkg.in/yaml.v3 v3.0.1 software.sslmate.com/src/go-pkcs12 v0.7.4 ) @@ -25,7 +26,6 @@ require ( github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/sirupsen/logrus v1.10.2 // indirect golang.org/x/sync v0.24.0 // indirect - golang.org/x/sys v0.49.0 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gotest.tools/v3 v3.5.2 // indirect modernc.org/libc v1.74.1 // indirect From feddaa8e7be87efbfce5a13850f27ed880a9b74b Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Tue, 17 Nov 2026 22:52:32 +0000 Subject: [PATCH 003/119] java4shell: unit tests for the VM library reader, verdicts, mitigations and filesystem scans Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/assess/assess_test.go | 257 ++++++++++++++++++ detectors/java4shell/internal/jvm/jvm_test.go | 237 ++++++++++++++++ .../java4shell/internal/testlib/testlib.go | 78 ++++++ detectors/java4shell/java4shell_test.go | 153 +++++++++++ 4 files changed, 725 insertions(+) create mode 100644 detectors/java4shell/internal/assess/assess_test.go create mode 100644 detectors/java4shell/internal/jvm/jvm_test.go create mode 100644 detectors/java4shell/internal/testlib/testlib.go create mode 100644 detectors/java4shell/java4shell_test.go diff --git a/detectors/java4shell/internal/assess/assess_test.go b/detectors/java4shell/internal/assess/assess_test.go new file mode 100644 index 0000000..9179e2a --- /dev/null +++ b/detectors/java4shell/internal/assess/assess_test.go @@ -0,0 +1,257 @@ +package assess + +import ( + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" +) + +func lib(t *testing.T, p string, l testlib.Lib) *jvm.Library { + t.Helper() + x, ok := jvm.Inspect(p, testlib.Build(l)) + if !ok { + t.Fatalf("%s not inspected", p) + } + return x +} + +func rel(t *testing.T, kv ...string) jvm.Release { + t.Helper() + r, ok := jvm.ParseRelease(testlib.Release(kv...)) + if !ok { + t.Fatal("release not parsed") + } + return r +} + +const temurin = "/opt/java/openjdk" + +func one(t *testing.T, in Input) Finding { + t.Helper() + fs := Run(in) + if len(fs) != 1 { + t.Fatalf("%d findings: %+v", len(fs), fs) + } + return fs[0] +} + +func TestVerdicts(t *testing.T) { + for _, c := range []struct { + name string + lib testlib.Lib + want Status + }{ + {"21 unfixed", testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true}, Vulnerable}, + {"21 fixed", testlib.Lib{Version: "21.0.13.1+2-LTS", VBMI: true}, Fixed}, + {"17.0.5", testlib.Lib{Version: "17.0.5+8"}, NotAffected}, + {"17.0.5 with a vendor backport of the decoder", testlib.Lib{Version: "17.0.5+8", VBMI: true}, Unknown}, + {"11", testlib.Lib{Version: "11.0.33+10"}, NotAffected}, + {"8", testlib.Lib{Version: "1.8.0_512-b09"}, NotAffected}, + {"aarch64", testlib.Lib{Machine: "aarch64", Version: "21.0.13+9-LTS"}, NotAffected}, + {"x86 32-bit", testlib.Lib{Machine: "x86", Version: "21.0.13+9-LTS"}, NotAffected}, + {"universal macOS", testlib.Lib{Format: "fat", Version: "21.0.13+9-LTS", VBMI: true}, Vulnerable}, + {"unfixed but no decoder stubs", testlib.Lib{Version: "21.0.13+9-LTS"}, Unknown}, + {"24 end of life", testlib.Lib{Version: "24.0.2+12", VBMI: true}, Vulnerable}, + {"later update", testlib.Lib{Version: "21.0.14+1", VBMI: true}, Unknown}, + } { + f := one(t, Input{Libraries: []*jvm.Library{lib(t, temurin+"/lib/server/libjvm.so", c.lib)}}) + if f.Status != c.want || f.Reason == "" || f.Message == "" { + t.Errorf("%s: %s (%s)", c.name, f.Status, f.Reason) + } + if (f.Status == Vulnerable || f.Status == Unknown) && f.Fix == "" { + t.Errorf("%s: no fix text", c.name) + } + if f.Status == Fixed || f.Status == NotAffected { + if f.Fix != "" { + t.Errorf("%s: fix text on a cleared finding", c.name) + } + } + } +} + +func TestReleaseFile(t *testing.T) { + // The VM library decides; a release file that says otherwise is noted. + in := Input{ + Libraries: []*jvm.Library{lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true})}, + Releases: map[string]jvm.Release{temurin: rel(t, "JAVA_VERSION", "21.0.13.1", "JAVA_RUNTIME_VERSION", "21.0.13.1+2", "IMPLEMENTOR", "Eclipse Adoptium")}, + } + f := one(t, in) + if f.Status != Vulnerable || f.ReleaseVersion != "21.0.13.1+2" || f.VersionFrom != "vm-library" || f.Vendor != "Eclipse Adoptium" { + t.Errorf("forged release file: %+v", f) + } + // No version line: the release file is used, and says so. + in = Input{ + Libraries: []*jvm.Library{lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{})}, + Releases: map[string]jvm.Release{temurin: rel(t, "JAVA_VERSION", "25.0.5")}, + } + if f := one(t, in); f.Status != Vulnerable || f.VersionFrom != "release-file" || !strings.Contains(f.Reason, "release file") { + t.Errorf("release-file version: %+v", f) + } + // Neither: unknown, with the release file's problem. + in = Input{Libraries: []*jvm.Library{lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{})}, BadReleases: map[string]string{temurin: "too large"}} + if f := one(t, in); f.Status != Unknown || !strings.Contains(f.Reason, "too large") { + t.Errorf("no version: %+v", f) + } + // Java 8 JDK: the release file one level above jre/. + in = Input{ + Libraries: []*jvm.Library{lib(t, "/usr/lib/jvm/j8/jre/lib/amd64/server/libjvm.so", testlib.Lib{})}, + Releases: map[string]jvm.Release{"/usr/lib/jvm/j8": rel(t, "JAVA_VERSION", "1.8.0_452")}, + } + if f := one(t, in); f.Status != NotAffected { + t.Errorf("java 8 jdk: %+v", f) + } + // jlink image. + in = Input{ + Libraries: []*jvm.Library{lib(t, "/app/rt/lib/server/libjvm.so", testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true})}, + Releases: map[string]jvm.Release{"/app/rt": rel(t, "JAVA_VERSION", "21.0.13", "MODULES", "java.base java.logging")}, + } + if f := one(t, in); f.Status != Vulnerable || !f.JLinked || !strings.Contains(f.Fix, "jlink") { + t.Errorf("jlink: %+v", f) + } +} + +func TestOpenJ9(t *testing.T) { + in := Input{ + Libraries: []*jvm.Library{ + lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{Extra: "OPENJ9_JAVA_OPTIONS"}), + lib(t, temurin+"/lib/default/libj9vm29.so", testlib.Lib{}), + }, + Releases: map[string]jvm.Release{temurin: rel(t, "JAVA_VERSION", "21.0.13.0.3", "JVM_VARIANT", "Openj9")}, + } + if f := one(t, in); f.Status != NotAffected || f.VM != "OpenJ9" { + t.Errorf("openj9: %+v", f) + } +} + +func TestProducts(t *testing.T) { + for root, want := range map[string]string{ + "/opt/atlassian/jira/jre": "Atlassian Jira", + "/usr/share/elasticsearch/jdk": "Elasticsearch", + "/opt/jfrog/artifactory/app/third-party/java": "JFrog Artifactory", + "/opt/idea-IU-243/jbr": "IntelliJ IDEA", + "/Applications/IntelliJ IDEA.app/Contents/jbr/Contents/Home": "IntelliJ IDEA", + "/opt/acme/jre": "acme", + } { + if name, _, ok := Product(root); !ok || name != want { + t.Errorf("Product(%s) = %q %v, want %q", root, name, ok, want) + } + } + for _, root := range []string{"/opt/java/openjdk", "/usr/lib/jvm/java-17-openjdk-amd64", "/opt/jdk-21.0.5+11", "/home/u/.sdkman/candidates/java/21.0.5-tem", "/app/jre"} { + if name, _, ok := Product(root); ok { + t.Errorf("Product(%s) = %q, want none", root, name) + } + } + f := one(t, Input{Libraries: []*jvm.Library{lib(t, "/opt/atlassian/jira/jre/lib/server/libjvm.so", testlib.Lib{Version: "17.0.12+7", VBMI: true})}}) + if f.Kind != KindBundled || !strings.Contains(f.Fix, "Upgrade Atlassian Jira") { + t.Errorf("bundled: %+v", f) + } +} + +func TestPackages(t *testing.T) { + apk := []byte("P:openjdk17-jre-headless\nV:17.0.21.0.3_p1-r0\nF:usr/lib/jvm/java-17-openjdk/lib/server\nR:libjvm.so\n\nP:busybox\nV:1\nF:bin\nR:busybox\n") + in := Input{ + Libraries: []*jvm.Library{lib(t, "/usr/lib/jvm/java-17-openjdk/lib/server/libjvm.so", testlib.Lib{Version: "17.0.21.0.3+1-alpine-r0", VBMI: true})}, + Owners: APKOwners(apk), + } + f := one(t, in) + if f.Package == nil || f.Package.Name != "openjdk17-jre-headless" || !strings.Contains(f.Fix, "apk upgrade openjdk17-jre-headless") { + t.Errorf("apk: %+v", f) + } + status := []byte("Package: openjdk-17-jre-headless\nStatus: install ok installed\nVersion: 17.0.21+9-1~deb12u1\n\n") + lists := map[string][]byte{"openjdk-17-jre-headless:amd64": []byte("/usr/lib/jvm/java-17-openjdk-amd64/lib/server/libjvm.so\n")} + in = Input{ + Libraries: []*jvm.Library{lib(t, "/usr/lib/jvm/java-17-openjdk-amd64/lib/server/libjvm.so", testlib.Lib{Version: "17.0.21+9-Debian-1deb12u1", VBMI: true})}, + Owners: DpkgOwners(status, lists), + } + if f := one(t, in); f.Package == nil || f.Package.Version != "17.0.21+9-1~deb12u1" || !strings.Contains(f.Fix, "apt-get install --only-upgrade") { + t.Errorf("dpkg: %+v", f) + } + in = Input{Libraries: []*jvm.Library{lib(t, "/usr/lib/jvm/java-21-openjdk-21.0.13.0.11-1.el9.x86_64/lib/server/libjvm.so", testlib.Lib{Version: "21.0.13+11-LTS", VBMI: true})}} + if f := one(t, in); f.Package == nil || f.Package.Name != "java-21-openjdk-headless" || f.Package.From != "install path" { + t.Errorf("rpm path: %+v", f) + } +} + +func vulnLib(t *testing.T, root string) *jvm.Library { + return lib(t, root+"/lib/server/libjvm.so", testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true}) +} + +func TestMitigations(t *testing.T) { + base := func() Input { return Input{Libraries: []*jvm.Library{vulnLib(t, temurin)}, Env: []string{}} } + + in := base() + in.Env = []string{"JAVA_TOOL_OPTIONS=-Xmx1g -XX:-UseBASE64Intrinsics"} + if f := one(t, in); f.Status != Mitigated || !strings.Contains(f.Reason, "JAVA_TOOL_OPTIONS") || f.Fix == "" { + t.Errorf("image env: %+v", f) + } + in.Env = append(in.Env, "_JAVA_OPTIONS=-XX:+UseBASE64Intrinsics") + if f := one(t, in); f.Status != Vulnerable { + t.Errorf("_JAVA_OPTIONS re-enables: %+v", f) + } + + in = base() + in.Command = []string{"java", "-XX:UseAVX=2", "-jar", "/app.jar"} + in.Env = []string{"PATH=/opt/java/openjdk/bin:/usr/bin"} + if f := one(t, in); f.Status != Mitigated { + t.Errorf("command line: %+v", f) + } + in.Command = []string{"java", "-jar", "/app.jar", "-XX:UseAVX=2"} + if f := one(t, in); f.Status != Vulnerable { + t.Errorf("an application argument counted: %+v", f) + } + + // CATALINA_OPTS counts when the container runs catalina.sh. + in = base() + in.Env = []string{"CATALINA_OPTS=-XX:-UseBASE64Intrinsics"} + if f := one(t, in); f.Status != Vulnerable { + t.Errorf("CATALINA_OPTS without catalina.sh: %+v", f) + } + in.Command = []string{"catalina.sh", "run"} + if f := one(t, in); f.Status != Mitigated { + t.Errorf("CATALINA_OPTS with catalina.sh: %+v", f) + } + + // A product's setenv.sh covers the runtime it bundles, not others. + jira := "/opt/atlassian/jira/jre" + set, _ := jvm.ReadSetting("/opt/atlassian/jira/bin/setenv.sh", []byte(`JVM_SUPPORT_RECOMMENDED_ARGS="-XX:-UseBASE64Intrinsics"`)) + in = Input{Libraries: []*jvm.Library{vulnLib(t, jira), vulnLib(t, temurin)}, Settings: []jvm.Setting{set}} + fs := Run(in) + for _, f := range fs { + want := Vulnerable + if f.Path == jira { + want = Mitigated + } + if f.Status != want { + t.Errorf("setenv.sh scope: %s %s", f.Path, f.Status) + } + } + + // A systemd unit covers a bundled runtime of the product it starts; + // for a shared runtime it is recorded, not counted. + unit, _ := jvm.ReadSetting("/etc/systemd/system/jira.service", []byte("Environment=JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics\nExecStart=/opt/atlassian/jira/bin/start-jira.sh -fg\n")) + in = Input{Libraries: []*jvm.Library{vulnLib(t, jira)}, Settings: []jvm.Setting{unit}} + if f := one(t, in); f.Status != Mitigated || !strings.Contains(f.Reason, "jira.service") { + t.Errorf("systemd bundled: %+v", f) + } + shared := "/usr/lib/jvm/java-21-openjdk-amd64" + unit, _ = jvm.ReadSetting("/etc/systemd/system/app.service", []byte("ExecStart="+shared+"/bin/java -XX:-UseBASE64Intrinsics -jar /srv/app.jar\n")) + in = Input{Libraries: []*jvm.Library{vulnLib(t, shared)}, Settings: []jvm.Setting{unit}} + if f := one(t, in); f.Status != Vulnerable || len(f.MitigatedFor) != 1 { + t.Errorf("systemd shared: %+v", f) + } + + // A mitigation never makes a fixed or unaffected runtime anything else. + in = Input{Libraries: []*jvm.Library{lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{Version: "21.0.13.1+2", VBMI: true})}, Env: []string{"JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics"}} + if f := one(t, in); f.Status != Fixed { + t.Errorf("fixed + mitigation: %+v", f) + } +} + +func TestSymlinkLoopResolve(t *testing.T) { + // A resolver that never settles must not hang owner lookup. + loop := func(p string) string { return p + "/x" } + in := Input{Libraries: []*jvm.Library{vulnLib(t, temurin)}, Resolve: loop, Env: []string{}, Command: []string{"java", "-XX:UseAVX=2"}} + _ = one(t, in) +} diff --git a/detectors/java4shell/internal/jvm/jvm_test.go b/detectors/java4shell/internal/jvm/jvm_test.go new file mode 100644 index 0000000..6e121b6 --- /dev/null +++ b/detectors/java4shell/internal/jvm/jvm_test.go @@ -0,0 +1,237 @@ +package jvm + +import ( + "bytes" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" +) + +func TestInspect(t *testing.T) { + for _, c := range []struct { + name, path string + lib testlib.Lib + arch Arch + version string + vbmi bool + }{ + {"elf x86-64", "/opt/java/openjdk/lib/server/libjvm.so", testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true}, X8664, "21.0.13+9-LTS", true}, + {"elf aarch64", "/opt/java/openjdk/lib/server/libjvm.so", testlib.Lib{Machine: "aarch64", Version: "21.0.13+9-LTS"}, AArch64, "21.0.13+9-LTS", false}, + {"pe", "C:/Program Files/Java/jdk-21/bin/server/jvm.dll", testlib.Lib{Format: "pe", OS: "windows", Version: "21.0.13+9-LTS", VBMI: true}, X8664, "21.0.13+9-LTS", true}, + {"macho", "/Library/Java/JavaVirtualMachines/x/Contents/Home/lib/server/libjvm.dylib", testlib.Lib{Format: "macho", OS: "bsd", Version: "17.0.21+9"}, X8664, "17.0.21+9", false}, + {"java 8", "/usr/lib/jvm/java-8/jre/lib/amd64/server/libjvm.so", testlib.Lib{Version: "1.8.0_452-b09"}, X8664, "1.8.0_452-b09", false}, + } { + l, ok := Inspect(c.path, testlib.Build(c.lib)) + if !ok { + t.Fatalf("%s: not inspected", c.name) + } + if !l.Has(c.arch) || l.JREVersion != c.version || l.VBMIStubs != c.vbmi || !l.HotSpot() { + t.Errorf("%s: got %+v", c.name, l) + } + } + fat, ok := Inspect("/x/lib/server/libjvm.dylib", testlib.Build(testlib.Lib{Format: "fat", Version: "21.0.13+9"})) + if !ok || !fat.Has(X8664) || !fat.Has(AArch64) { + t.Errorf("universal binary: %+v", fat) + } + if _, ok := Inspect("/x/lib/server/libfoo.so", testlib.Build(testlib.Lib{Version: "21"})); ok { + t.Error("a library with another name was inspected") + } + if _, ok := Inspect("/x/lib/server/libjvm.so", []byte("#!/bin/sh\necho")); ok { + t.Error("a script named libjvm.so was inspected") + } + // A Java class file has the universal binary's magic. + class := []byte{0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 65} + if _, ok := Inspect("/x/lib/server/libjvm.dylib", class); ok { + t.Error("a class file was taken for a universal binary") + } + j9, ok := Inspect("/opt/java/openjdk/lib/default/libj9vm29.so", testlib.Build(testlib.Lib{})) + if !ok || !j9.OpenJ9 || j9.HotSpot() { + t.Errorf("OpenJ9: %+v", j9) + } +} + +func TestInspectHostile(t *testing.T) { + // A version line with parentheses or spaces in the version is refused, + // and an over-long one does not match. + b := testlib.Build(testlib.Lib{Extra: "\x00OpenJDK 64-Bit Server VM (21 (x)) for linux-amd64 JRE (21)\x00" + strings.Repeat("A", 1000) + "VM (" + strings.Repeat("9", 500) + ") for linux-amd64 JRE (1)"}) + l, ok := Inspect("/a/lib/server/libjvm.so", b) + if !ok || l.JREVersion != "" { + t.Errorf("hostile version line read: %+v", l) + } + // Stub names must be whole names. + b = testlib.Build(testlib.Lib{Version: "17.0.5+8", Extra: "xlookup_lo_base64url\x00pack_vec_base64x\x00"}) + if l, _ := Inspect("/a/lib/server/libjvm.so", b); l.VBMIStubs { + t.Error("partial stub names counted") + } + // Truncated headers. + for _, h := range [][]byte{[]byte("\x7fELF"), []byte("MZ"), append([]byte("MZ"), bytes.Repeat([]byte{0xff}, 62)...), {0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 3}} { + if _, ok := Inspect("/a/lib/server/libjvm.so", h); ok { + t.Errorf("truncated header %x accepted", h) + } + } +} + +func TestRoot(t *testing.T) { + for in, want := range map[string]string{ + "/opt/java/openjdk/lib/server/libjvm.so": "/opt/java/openjdk", + "/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server/libjvm.so": "/usr/lib/jvm/java-8-openjdk-amd64/jre", + "C:/Program Files/Java/jdk-21/bin/server/jvm.dll": "C:/Program Files/Java/jdk-21", + "/Library/Java/JavaVirtualMachines/t/Contents/Home/lib/server/libjvm.dylib": "/Library/Java/JavaVirtualMachines/t/Contents/Home", + "/opt/java/openjdk/lib/default/libj9vm29.so": "/opt/java/openjdk", + "/opt/java/openjdk/lib/libjvm.so": "/opt/java/openjdk", + } { + if got, ok := Root(in); !ok || got != want { + t.Errorf("Root(%s) = %q %v, want %q", in, got, ok, want) + } + } + if _, ok := Root("/tmp/libjvm.so"); ok { + t.Error("a stray libjvm.so got a runtime root") + } +} + +func TestRelease(t *testing.T) { + r, ok := ParseRelease(testlib.Release("JAVA_VERSION", "21.0.13", "JAVA_RUNTIME_VERSION", "21.0.13+9-LTS", "OS_ARCH", "aarch64", "JVM_VARIANT", "Openj9", "MODULES", "java.base java.se")) + if !ok || r.Version() != "21.0.13+9-LTS" || r.Arch() != AArch64 || !r.OpenJ9() || r.JLinked() { + t.Errorf("release: %v", r) + } + jl, ok := ParseRelease([]byte("JAVA_VERSION=\"21.0.13\"\nMODULES=\"java.base java.logging\"\n")) + if !ok || !jl.JLinked() || jl.Version() != "21.0.13" || jl.Arch() != "" { + t.Errorf("jlink release: %v", jl) + } + if _, ok := ParseRelease(bytes.Repeat([]byte("JAVA_VERSION=\"21\"\n"), 10000)); ok { + t.Error("a huge release file was read") + } + if _, ok := ParseRelease([]byte("IMPLEMENTOR=\"x\"\n")); ok { + t.Error("a release file without JAVA_VERSION was read") + } + // The first value of a repeated key wins: a forged second line does not + // replace it. + r, _ = ParseRelease([]byte("JAVA_VERSION=\"21.0.13\"\nJAVA_VERSION=\"21.0.13.1\"\n")) + if r.Version() != "21.0.13" { + t.Errorf("repeated key: %v", r.Version()) + } +} + +func TestOptions(t *testing.T) { + for _, c := range []struct { + in string + want bool + }{ + {"-XX:-UseBASE64Intrinsics", true}, + {"-Xmx1g -XX:UseAVX=2", true}, + {"-XX:UseAVX=3", false}, + {"-XX:-UseBASE64Intrinsics -XX:+UseBASE64Intrinsics", false}, + {"-XX:+UseBASE64Intrinsics -XX:-UseBASE64Intrinsics", true}, + {"-XX:UseBASE64Intrinsics=false", true}, + {"'-XX:-UseBASE64Intrinsics'", true}, + {"-XX:-UseBASE64IntrinsicsX", false}, + {"-XX:UseAVX=two", false}, + {"", false}, + } { + var o Options + o.Apply(c.in, "test") + if got, how := o.Mitigates(); got != c.want || got && how == "" { + t.Errorf("%q: %v %q", c.in, got, how) + } + } + // _JAVA_OPTIONS overrides the command line, which overrides + // JAVA_TOOL_OPTIONS. + env := map[string]string{"JAVA_TOOL_OPTIONS": "-XX:-UseBASE64Intrinsics", "_JAVA_OPTIONS": "-XX:+UseBASE64Intrinsics"} + if ok, _ := FromEnv(env, nil, 21, nil).Mitigates(); ok { + t.Error("_JAVA_OPTIONS did not override") + } + env = map[string]string{"JDK_JAVA_OPTIONS": "-XX:-UseBASE64Intrinsics"} + if ok, _ := FromEnv(env, nil, 8, nil).Mitigates(); ok { + t.Error("JDK_JAVA_OPTIONS counted for Java 8") + } + env = map[string]string{"JAVA_OPTS": "-XX:-UseBASE64Intrinsics"} + if ok, _ := FromEnv(env, nil, 21, nil).Mitigates(); ok { + t.Error("JAVA_OPTS counted without a script that passes it on") + } + if ok, _ := FromEnv(env, nil, 21, map[string]bool{"JAVA_OPTS": true}).Mitigates(); !ok { + t.Error("JAVA_OPTS not counted when the script passes it on") + } +} + +func TestJavaOptions(t *testing.T) { + for _, c := range []struct { + cmd []string + want string + ok bool + }{ + {[]string{"java", "-XX:-UseBASE64Intrinsics", "-jar", "app.jar", "-XX:+UseBASE64Intrinsics"}, "-XX:-UseBASE64Intrinsics", true}, + {[]string{"/opt/java/openjdk/bin/java", "-cp", "-XX:UseAVX=2", "Main"}, "", true}, + {[]string{"sh", "-c", "exec java -XX:UseAVX=2 -jar /app.jar"}, "-XX:UseAVX=2", true}, + {[]string{"catalina.sh", "run"}, "", false}, + } { + got, ok := JavaOptions(c.cmd) + if ok != c.ok || strings.Join(got, " ") != c.want { + t.Errorf("%v: %v %v", c.cmd, got, ok) + } + } +} + +func TestSettings(t *testing.T) { + s, ok := ReadSetting("/usr/share/elasticsearch/config/jvm.options.d/j4s.options", []byte("# c\n17-:-XX:-UseBASE64Intrinsics\n-Xmx1g\n")) + if !ok || s.Scope != "/usr/share/elasticsearch" { + t.Fatalf("jvm.options: %+v", s) + } + if m, _ := s.Options(21).Mitigates(); !m { + t.Error("jvm.options line for 17- not applied to 21") + } + s, _ = ReadSetting("/opt/es/config/jvm.options", []byte("8-11:-XX:-UseBASE64Intrinsics\n")) + if m, _ := s.Options(21).Mitigates(); m { + t.Error("jvm.options line for 8-11 applied to 21") + } + s, ok = ReadSetting("/opt/atlassian/jira/bin/setenv.sh", []byte("JVM_SUPPORT_RECOMMENDED_ARGS=\"-XX:-UseBASE64Intrinsics\"\n# -XX:+UseBASE64Intrinsics\n")) + if !ok || s.Scope != "/opt/atlassian/jira" { + t.Fatalf("setenv: %+v", s) + } + if m, _ := s.Options(17).Mitigates(); !m { + t.Error("setenv.sh mitigation not read (or the comment counted)") + } + s, ok = ReadSetting("/etc/systemd/system/app.service", []byte("[Service]\nEnvironment=\"JAVA_TOOL_OPTIONS=-XX:UseAVX=2\" FOO=bar\nExecStart=/opt/app/jre/bin/java -jar /opt/app/app.jar\n")) + if !ok || s.Unit != "app.service" || s.Exec != "/opt/app/jre/bin/java" { + t.Fatalf("systemd: %+v", s) + } + if m, _ := s.Options(17).Mitigates(); !m { + t.Error("systemd Environment not read") + } + if _, ok := ReadSetting("/home/u/app.service", []byte("x")); ok { + t.Error("a unit outside systemd's directories was read") + } + if _, ok := ReadSetting("/opt/x/bin/setenv.sh", bytes.Repeat([]byte("a"), 2<<20)); ok { + t.Error("a huge settings file was read") + } +} + +func FuzzInspect(f *testing.F) { + f.Add("/a/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "21.0.13+9", VBMI: true})) + f.Add("/a/lib/server/libjvm.dylib", testlib.Build(testlib.Lib{Format: "fat"})) + f.Add("/a/bin/server/jvm.dll", testlib.Build(testlib.Lib{Format: "pe", Version: "17.0.6+10"})) + f.Fuzz(func(t *testing.T, p string, b []byte) { + l, ok := Inspect(p, b) + if ok && (l == nil || len(l.Archs) == 0) { + t.Fatal("inspected without an architecture") + } + }) +} + +func FuzzSettings(f *testing.F) { + f.Add("/opt/x/config/jvm.options", []byte("17-:-XX:-UseBASE64Intrinsics\n")) + f.Add("/etc/systemd/system/a.service", []byte("Environment=\"JAVA_TOOL_OPTIONS=-XX:UseAVX=2\"\nExecStart=sh -c 'java -XX:UseAVX=1'\n")) + f.Add("/opt/x/bin/setenv.sh", []byte("CATALINA_OPTS=\"$CATALINA_OPTS -XX:-UseBASE64Intrinsics\"\n")) + f.Fuzz(func(t *testing.T, p string, b []byte) { + s, ok := ReadSetting(p, b) + if !ok { + return + } + for _, feat := range []int{0, 8, 17, 21} { + s.Options(feat).Mitigates() + } + var o Options + o.Apply(string(b), "fuzz") + JavaOptions(Words(string(b))) + }) +} diff --git a/detectors/java4shell/internal/testlib/testlib.go b/detectors/java4shell/internal/testlib/testlib.go new file mode 100644 index 0000000..11dded2 --- /dev/null +++ b/detectors/java4shell/internal/testlib/testlib.go @@ -0,0 +1,78 @@ +// Package testlib builds small stand-ins for Java VM libraries for tests: an +// executable header for the architecture, the HotSpot version line and, +// optionally, the AVX-512 VBMI decode stubs' names. +package testlib + +import ( + "encoding/binary" + "fmt" +) + +// Lib describes a fake VM library. +type Lib struct { + Format string // elf (default), pe, macho, fat + Machine string // x86-64 (default), aarch64, x86 + Version string // "" for no version line + OS string // linux (default) + VBMI bool + VMName string // OpenJDK 64-Bit Server VM (default) + Extra string // more bytes +} + +// Build returns the file's bytes. +func Build(l Lib) []byte { + if l.Machine == "" { + l.Machine = "x86-64" + } + if l.OS == "" { + l.OS = "linux" + } + if l.VMName == "" { + l.VMName = "OpenJDK 64-Bit Server VM" + } + var b []byte + switch l.Format { + case "pe": + b = make([]byte, 0x100) + b[0], b[1] = 'M', 'Z' + binary.LittleEndian.PutUint32(b[60:], 0x80) + copy(b[0x80:], "PE\x00\x00") + m := map[string]uint16{"x86-64": 0x8664, "aarch64": 0xaa64, "x86": 0x14c}[l.Machine] + binary.LittleEndian.PutUint16(b[0x84:], m) + case "macho": + b = make([]byte, 32) + binary.LittleEndian.PutUint32(b, 0xfeedfacf) + binary.LittleEndian.PutUint32(b[4:], map[string]uint32{"x86-64": 0x01000007, "aarch64": 0x0100000c}[l.Machine]) + case "fat": + b = make([]byte, 8+2*20) + binary.BigEndian.PutUint32(b, 0xcafebabe) + binary.BigEndian.PutUint32(b[4:], 2) + binary.BigEndian.PutUint32(b[8:], 0x01000007) + binary.BigEndian.PutUint32(b[28:], 0x0100000c) + default: + b = make([]byte, 64) + copy(b, "\x7fELF\x02\x01\x01") + m := map[string]uint16{"x86-64": 0x3e, "aarch64": 0xb7, "x86": 3}[l.Machine] + binary.LittleEndian.PutUint16(b[18:], m) + } + cpu := map[string]string{"x86-64": "amd64", "aarch64": "aarch64", "x86": "x86"}[l.Machine] + if l.Version != "" { + b = append(b, 0) + b = append(b, fmt.Sprintf("%s (%s) for %s-%s JRE (%s), built on 2026-10-20T00:00:00Z by \"admin\" with gcc 11.3.0", l.VMName, l.Version, l.OS, cpu, l.Version)...) + b = append(b, 0) + } + if l.VBMI { + b = append(b, "lookup_lo_base64\x00lookup_hi_base64\x00pack_vec_base64\x00join_0_1_base64\x00"...) + } + b = append(b, l.Extra...) + return b +} + +// Release returns a release file. +func Release(kv ...string) []byte { + var out []byte + for i := 0; i+1 < len(kv); i += 2 { + out = append(out, fmt.Sprintf("%s=%q\n", kv[i], kv[i+1])...) + } + return out +} diff --git a/detectors/java4shell/java4shell_test.go b/detectors/java4shell/java4shell_test.go new file mode 100644 index 0000000..fd9fc33 --- /dev/null +++ b/detectors/java4shell/java4shell_test.go @@ -0,0 +1,153 @@ +package java4shell_test + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" + "github.com/DefectDojo/earlylight/internal/cli" + "github.com/DefectDojo/earlylight/internal/engine" +) + +var cfg = cli.Config{Tool: "earlylight", Version: "test", Summary: "test"} + +func write(t *testing.T, root, rel string, data []byte) { + t.Helper() + p := filepath.Join(root, rel) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, data, 0o644); err != nil { + t.Fatal(err) + } +} + +type report struct { + Targets []struct { + Error string `json:"error"` + Findings []engine.Finding `json:"findings"` + Annotations map[string]any `json:"annotations"` + } `json:"targets"` +} + +func run(t *testing.T, args ...string) (report, int) { + t.Helper() + var out, errb bytes.Buffer + full := append([]string{args[0], args[1], "--format", "json", "--detector", "java4shell", "--show-cleared"}, args[2:]...) + code := cli.Run(cfg, full, &out, &errb) + var r report + if err := json.Unmarshal(out.Bytes(), &r); err != nil { + t.Fatalf("%v\n%s\n%s", err, out.String(), errb.String()) + } + return r, code +} + +func byPath(r report) map[string]engine.Finding { + m := map[string]engine.Finding{} + for _, f := range r.Targets[0].Findings { + m[f.Path] = f + } + return m +} + +func TestScanFS(t *testing.T) { + root := t.TempDir() + write(t, root, "opt/java/openjdk/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true})) + write(t, root, "opt/java/openjdk/release", testlib.Release("JAVA_VERSION", "21.0.13", "IMPLEMENTOR", "Eclipse Adoptium", "OS_ARCH", "x86_64")) + write(t, root, "opt/fixed/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "25.0.5.1+2-LTS", VBMI: true})) + write(t, root, "opt/arm/lib/server/libjvm.so", testlib.Build(testlib.Lib{Machine: "aarch64", Version: "21.0.13+9-LTS"})) + write(t, root, "opt/atlassian/confluence/jre/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "17.0.12+7", VBMI: true})) + write(t, root, "opt/atlassian/confluence/bin/setenv.sh", []byte("CATALINA_OPTS=\"-XX:-UseBASE64Intrinsics ${CATALINA_OPTS}\"\n")) + write(t, root, "var/log/app/hs_err_pid42.log", []byte("# JRE version: OpenJDK Runtime Environment (21.0.13+9) (build 21.0.13+9-LTS)\n# Problematic frame:\n# v ~StubRoutines::decodeBlock\nCPU: total 8, avx512f, avx512bw, avx512_vbmi, bmi2\n")) + r, code := run(t, "scan", "fs", "--as-root", root) + if r.Targets[0].Error != "" { + t.Fatal(r.Targets[0].Error) + } + fs := byPath(r) + if f := fs["/opt/java/openjdk"]; f.Kind != java4shell.KindRuntime || f.Verdict != engine.Vulnerable || f.Facts["vendor"] != "Eclipse Adoptium" || f.Facts["fixed_in"] != "21.0.13.1" { + t.Errorf("temurin: %+v", f) + } + if f := fs["/opt/fixed"]; f.Verdict != engine.Fixed || f.Facts["status"] != "fixed" { + t.Errorf("fixed: %+v", f) + } + if f := fs["/opt/arm"]; f.Verdict != engine.Fixed || f.Facts["status"] != "not-affected" || !strings.Contains(f.Reason, "aarch64") { + t.Errorf("arm: %+v", f) + } + if f := fs["/opt/atlassian/confluence/jre"]; f.Kind != java4shell.KindBundled || f.Verdict != engine.Inactive || f.Facts["status"] != "mitigated" || f.Fix == "" { + t.Errorf("confluence: %+v", f) + } + if code != 1 { + t.Errorf("exit %d, want 1", code) + } + if _, ok := r.Targets[0].Annotations["java4shell_crash_logs"]; !ok { + t.Error("crash log not annotated") + } + if _, ok := r.Targets[0].Annotations["java4shell_scanner_cpu"]; !ok { + t.Error("scanner CPU not annotated") + } +} + +func TestHostileFS(t *testing.T) { + root := t.TempDir() + // A huge release file claiming a fixed version, next to an unfixed VM. + write(t, root, "opt/a/lib/server/libjvm.so", testlib.Build(testlib.Lib{})) + write(t, root, "opt/a/release", append([]byte("JAVA_VERSION=\"21.0.13.1\"\n"), bytes.Repeat([]byte("# padding\n"), 20000)...)) + // A forged small release file: the VM library decides. + write(t, root, "opt/b/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "21.0.13+9", VBMI: true})) + write(t, root, "opt/b/release", testlib.Release("JAVA_VERSION", "21.0.13.1")) + // Symlink loops around a runtime. + if err := os.Symlink("loop2", filepath.Join(root, "opt/loop1")); err != nil { + t.Fatal(err) + } + if err := os.Symlink("loop1", filepath.Join(root, "opt/loop2")); err != nil { + t.Fatal(err) + } + if err := os.Symlink(".", filepath.Join(root, "opt/b/lib/self")); err != nil { + t.Fatal(err) + } + r, _ := run(t, "scan", "fs", "--as-root", root) + fs := byPath(r) + if f := fs["/opt/a"]; f.Verdict != engine.Unknown || !strings.Contains(f.Reason, "64 KiB") { + t.Errorf("huge release: %+v", f) + } + if f := fs["/opt/b"]; f.Verdict != engine.Vulnerable || f.Facts["release_file_version"] != "21.0.13.1" { + t.Errorf("forged release: %+v", f) + } + if len(fs) != 2 { + t.Errorf("findings: %+v", fs) + } +} + +func TestNoJava(t *testing.T) { + root := t.TempDir() + write(t, root, "etc/hostname", []byte("x\n")) + r, code := run(t, "scan", "fs", "--as-root", root) + if len(r.Targets[0].Findings) != 0 || code != 0 { + t.Errorf("findings without Java: %+v (exit %d)", r.Targets[0].Findings, code) + } +} + +func TestManifest(t *testing.T) { + d := &java4shell.Detector{} + if err := d.Load(); err != nil { + t.Fatal(err) + } + m := d.Manifest() + seen := map[string]bool{} + for _, k := range m.Kinds { + if seen[k.ID] { + t.Errorf("duplicate kind %s", k.ID) + } + seen[k.ID] = true + } + for _, k := range []string{java4shell.KindRuntime, java4shell.KindBundled, java4shell.KindImage, java4shell.KindImagePin, java4shell.KindJavaPin, java4shell.KindLine, java4shell.KindPackage, java4shell.KindNotChecked} { + if !seen[k] { + t.Errorf("kind %s not in the manifest", k) + } + } +} From e9a55c26edd0d7543f152a0919f44d83e786c851 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Tue, 17 Nov 2026 22:55:44 +0000 Subject: [PATCH 004/119] java4shell: source-tree scan and fix tests, fuzzers in CI Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 4 + .../java4shell/internal/repo/repo_test.go | 268 ++++++++++++++++++ 2 files changed, 272 insertions(+) create mode 100644 detectors/java4shell/internal/repo/repo_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 15bcb44..c79c14b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,6 +33,10 @@ jobs: go test ./detectors/sshole/internal/assess -run '^$' -fuzz '^FuzzAccounts$' -fuzztime 30s go test ./detectors/sshole/internal/assess -run '^$' -fuzz '^FuzzStartup$' -fuzztime 30s go test ./detectors/sshole/internal/repo -run '^$' -fuzz '^FuzzScanText$' -fuzztime 30s + go test ./detectors/java4shell/internal/jvm -run '^$' -fuzz '^FuzzInspect$' -fuzztime 30s + go test ./detectors/java4shell/internal/jvm -run '^$' -fuzz '^FuzzSettings$' -fuzztime 30s + go test ./detectors/java4shell/internal/knowledge -run '^$' -fuzz '^FuzzParse$' -fuzztime 20s + go test ./detectors/java4shell/internal/repo -run '^$' -fuzz '^FuzzScanText$' -fuzztime 30s for f in FuzzParseDpkgStatus FuzzParseAPKInstalled FuzzParseHeaderBlob FuzzReadBDB FuzzReadNDB FuzzResolver; do go test ./detectors/php2shell/internal/pkgdb -run '^$' -fuzz "^$f\$" -fuzztime 15s done diff --git a/detectors/java4shell/internal/repo/repo_test.go b/detectors/java4shell/internal/repo/repo_test.go new file mode 100644 index 0000000..11a6cde --- /dev/null +++ b/detectors/java4shell/internal/repo/repo_test.go @@ -0,0 +1,268 @@ +package repo + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" +) + +func tree(t *testing.T, files map[string]string) string { + t.Helper() + root := t.TempDir() + for rel, s := range files { + p := filepath.Join(root, rel) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(s), 0o644); err != nil { + t.Fatal(err) + } + } + return root +} + +func scan(t *testing.T, root string) Result { + t.Helper() + res, err := Scan(context.Background(), root, Options{}) + if err != nil { + t.Fatal(err) + } + return res +} + +func find(res Result, file string, line int) (Finding, bool) { + for _, f := range res.Findings { + if f.File == file && f.Line == line { + return f, true + } + } + return Finding{}, false +} + +func TestJudgeTag(t *testing.T) { + fam := func(repo string) Family { + f, _, ok := FamilyOf(repo + ":x") + if !ok { + t.Fatalf("no family %s", repo) + } + return f + } + for _, c := range []struct { + image string + want knowledge.Status + }{ + {"eclipse-temurin:21.0.13_9-jre-alpine", knowledge.Vulnerable}, + {"eclipse-temurin:21.0.13.1_2-jre", knowledge.Fixed}, + {"eclipse-temurin:21-jre", knowledge.Unknown}, + {"eclipse-temurin:21.0.12.1_1-jdk", knowledge.Vulnerable}, + {"eclipse-temurin:17.0.5_8-jre", knowledge.NotAffected}, + {"eclipse-temurin:17-jre", knowledge.Unknown}, + {"eclipse-temurin:11-jre", knowledge.NotAffected}, + {"eclipse-temurin:24-jre", knowledge.Vulnerable}, + {"amazoncorretto:21.0.12-al2023", knowledge.Vulnerable}, + {"amazoncorretto:21.0.13-al2023", knowledge.Unknown}, + {"amazoncorretto:21", knowledge.Unknown}, + {"azul/zulu-openjdk:21.0.12.1-21.52-jre", knowledge.Vulnerable}, + {"bellsoft/liberica-openjre-debian:21.0.13-9", knowledge.Vulnerable}, + {"bellsoft/liberica-openjre-debian:21.0.13", knowledge.Unknown}, + {"openjdk:17.0.2-jdk", knowledge.NotAffected}, + {"openjdk:18.0.2.1", knowledge.Vulnerable}, + {"sapmachine:21.0.13.1", knowledge.Fixed}, + {"docker.io/library/eclipse-temurin:25.0.5_8-jre", knowledge.Vulnerable}, + } { + repo, tag := repoName(c.image) + tv, ok := fam(repo).ParseTag(tag) + if !ok { + t.Errorf("%s: tag not read", c.image) + continue + } + if got, why := JudgeTag(tv); got != c.want || why == "" { + t.Errorf("%s: %s (%s), want %s", c.image, got, why, c.want) + } + } + if f, tag, _ := FamilyOf("eclipse-temurin:latest"); f.Repo != "eclipse-temurin" { + t.Error("family") + } else if _, ok := f.ParseTag(tag); ok { + t.Error("latest read as a version") + } +} + +func TestScanTree(t *testing.T) { + root := tree(t, map[string]string{ + "Dockerfile": "FROM eclipse-temurin:21.0.13_9-jre-alpine AS run\nRUN apk add --no-cache curl\n", + "svc/Dockerfile": "ARG JAVA=21.0.12.1_1-jdk\nFROM eclipse-temurin:${JAVA} AS build\nENV JAVA_TOOL_OPTIONS=\"-XX:-UseBASE64Intrinsics\"\n" + + "FROM ubuntu:24.04\nRUN apt-get update && apt-get install -y openjdk-21-jre-headless\nRUN apt-get install -y openjdk-17-jre-headless=17.0.21+9-1~deb12u1\nRUN apk add openjdk24\n", + "compose.yaml": "services:\n app:\n image: amazoncorretto:21.0.12-al2023\n environment:\n JAVA_TOOL_OPTIONS: -XX:UseAVX=2\n" + + " jira:\n image: atlassian/jira-software:9.12\n web:\n image: nginx:1.27\n floating:\n image: eclipse-temurin:21-jre\n j9:\n image: ibm-semeru-runtimes:open-21-jre\n", + "k8s/deploy.yaml": "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: x\nspec:\n template:\n spec:\n containers:\n - name: a\n image: sapmachine:21.0.12\n", + ".java-version": "21.0.5\n", + ".sdkmanrc": "java=17.0.13-tem\n", + ".tool-versions": "nodejs 22\njava corretto-21.0.13.1.2\n", + "mise.toml": "[tools]\njava = \"temurin-23.0.2\"\n", + ".github/workflows/ci.yml": "jobs:\n b:\n steps:\n - uses: actions/setup-java@v4\n with:\n distribution: corretto\n java-version: '21.0.5'\n" + + " - uses: actions/setup-java@v4\n with:\n distribution: temurin\n java-version: ${{ matrix.java }}\n - uses: actions/setup-java@v4\n with:\n distribution: temurin\n java-version: '17'\n", + "build.gradle.kts": "java { toolchain { languageVersion.set(JavaLanguageVersion.of(22)) } }\njib { from { image = \"eclipse-temurin:25.0.5_8-jre\" } }\n", + "pom.xml": "maven-enforcer-plugin\n[17.0.13,)\n\n", + "project.toml": "[[build.env]]\nname = \"BP_JVM_VERSION\"\nvalue = \"21\"\n", + }) + res := scan(t, root) + check := func(file string, line int, rule, status string) Finding { + t.Helper() + f, ok := find(res, file, line) + if !ok { + t.Errorf("%s:%d: no finding (have %d)", file, line, len(res.Findings)) + for _, x := range res.Findings { + t.Logf(" %s:%d %s %s %s", x.File, x.Line, x.Rule, x.Status, x.Message) + } + return f + } + if f.Rule != rule || f.Status != status { + t.Errorf("%s:%d: %s %s (%s), want %s %s", file, line, f.Rule, f.Status, f.Message, rule, status) + } + return f + } + if f := check("Dockerfile", 1, RuleImagePin, StatusVulnerable); !f.Fixable || f.Props["fixed_in"] != "21.0.13.1" { + t.Errorf("Dockerfile pin: %+v", f) + } + check("svc/Dockerfile", 2, RuleImagePin, StatusMitigated) + check("svc/Dockerfile", 5, RulePackage, StatusVulnerable) + if f := check("svc/Dockerfile", 6, RulePackage, StatusVulnerable); f.Level != "error" { + t.Errorf("pinned package level %s", f.Level) + } + check("svc/Dockerfile", 7, RuleLine, StatusVulnerable) + check("compose.yaml", 3, RuleImagePin, StatusMitigated) + if f := check("compose.yaml", 7, RuleNotChecked, StatusUnknown); f.Pull != "atlassian/jira-software:9.12" { + t.Errorf("jira pull: %+v", f) + } + if f := check("compose.yaml", 11, RuleNotChecked, StatusUnknown); f.Pull == "" { + t.Errorf("floating pull: %+v", f) + } + if _, ok := find(res, "compose.yaml", 9); ok { + t.Error("nginx reported") + } + if _, ok := find(res, "compose.yaml", 13); ok { + t.Error("OpenJ9 image reported") + } + check("k8s/deploy.yaml", 10, RuleImagePin, StatusVulnerable) + check(".java-version", 1, RuleJavaPin, StatusVulnerable) + check(".sdkmanrc", 1, RuleJavaPin, StatusVulnerable) + if _, ok := find(res, ".tool-versions", 2); ok { + t.Error("a fixed Corretto pin reported") + } + check("mise.toml", 2, RuleLine, StatusVulnerable) + if f := check(".github/workflows/ci.yml", 7, RuleJavaPin, StatusVulnerable); !f.Fixable { + t.Errorf("setup-java corretto not fixable: %+v", f) + } + check(".github/workflows/ci.yml", 11, RuleNotChecked, StatusUnknown) + if _, ok := find(res, ".github/workflows/ci.yml", 15); ok { + t.Error("a moving setup-java version of a fixed line reported") + } + check("build.gradle.kts", 1, RuleLine, StatusVulnerable) + check("build.gradle.kts", 2, RuleImagePin, StatusVulnerable) + check("pom.xml", 2, RuleJavaPin, StatusUnknown) + if _, ok := find(res, "project.toml", 3); ok { + t.Error("BP_JVM_VERSION 21 reported") + } +} + +func TestPlatforms(t *testing.T) { + root := tree(t, map[string]string{"Dockerfile": "FROM eclipse-temurin:21.0.13_9-jre\n"}) + res, _ := Scan(context.Background(), root, Options{Platforms: []string{"linux/arm64"}}) + if len(res.Findings) != 0 { + t.Errorf("arm64-only build reported: %+v", res.Findings) + } +} + +func TestPlanTag(t *testing.T) { + root := tree(t, map[string]string{ + "Dockerfile": "ARG BASE=eclipse-temurin:21.0.13_9-jre-alpine\nFROM ${BASE}\nCMD [\"java\",\"-jar\",\"/a.jar\"]\n", + }) + res := scan(t, root) + f, ok := find(res, "Dockerfile", 2) + if !ok || !f.Fixable { + t.Fatalf("finding: %+v", res.Findings) + } + verified := "" + reg := Registry{ + Tags: func(_ context.Context, repo string) ([]string, error) { + if repo != "eclipse-temurin" { + t.Errorf("listed %s", repo) + } + return []string{"21.0.13_9-jre-alpine", "21.0.13.1_2-jre", "21.0.13.1_2-jre-alpine-3.22", "21.0.13.1_2-jre-alpine", "21.0.13.1_3-jre-alpine", "21.0.14_1-jre-alpine", "25.0.5.1_2-jre-alpine"}, nil + }, + Verify: func(_ context.Context, cur, target string) (string, error) { + verified = target + return "sha256:abc", nil + }, + } + ch, err := Plan(context.Background(), root, f, reg, Options{}) + if err != nil { + t.Fatal(err) + } + if verified != "eclipse-temurin:21.0.13.1_2-jre-alpine" || ch.Line != 1 || ch.New != "ARG BASE=eclipse-temurin:21.0.13.1_2-jre-alpine" { + t.Fatalf("plan: %+v (verified %s)", ch, verified) + } + if err := Apply(root, ch); err != nil { + t.Fatal(err) + } + if res := scan(t, root); len(res.Findings) != 0 { + t.Errorf("after the fix: %+v", res.Findings) + } + // No fixed tag published: declined with the reason. + root = tree(t, map[string]string{"Dockerfile": "FROM eclipse-temurin:17.0.21_9-jdk\n"}) + f, _ = find(scan(t, root), "Dockerfile", 1) + reg.Tags = func(context.Context, string) ([]string, error) { return []string{"17.0.21_9-jdk", "17-jdk"}, nil } + if _, err := Plan(context.Background(), root, f, reg, Options{}); err == nil || !strings.Contains(err.Error(), "no published tag") { + t.Errorf("no fixed tag: %v", err) + } + // Offline: declined. + if _, err := Plan(context.Background(), root, f, Registry{}, Options{}); err == nil || !strings.Contains(err.Error(), "registry") { + t.Errorf("offline: %v", err) + } +} + +func TestPlanSetupJava(t *testing.T) { + root := tree(t, map[string]string{".github/workflows/ci.yml": "jobs:\n b:\n steps:\n - uses: actions/setup-java@v4\n with:\n distribution: 'corretto'\n java-version: '21.0.5'\n"}) + res := scan(t, root) + f, ok := find(res, ".github/workflows/ci.yml", 7) + if !ok { + t.Fatalf("%+v", res.Findings) + } + ch, err := Plan(context.Background(), root, f, Registry{}, Options{}) + if err != nil { + t.Fatal(err) + } + if ch.New != " java-version: '21'" { + t.Errorf("plan: %+v", ch) + } +} + +func FuzzScanText(f *testing.F) { + f.Add("Dockerfile", "FROM eclipse-temurin:21.0.13_9-jre\nRUN apt-get install -y openjdk-21-jre=21.0.5+11-1\nENV JAVA_TOOL_OPTIONS=-XX:UseAVX=2\n") + f.Add(".github/workflows/a.yml", "jobs:\n a:\n steps:\n - uses: actions/setup-java@v4\n with:\n java-version: |\n 17\n 21.0.5\n") + f.Add("pom.xml", "[17.0.1,)eclipse-temurin:21.0.1_12-jre") + f.Add(".tool-versions", "java corretto-21.0.5.11.1\n") + f.Add("compose.yaml", "services:\n a:\n image: amazoncorretto:21.0.1\n environment: [\"JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics\"]\n") + f.Fuzz(func(t *testing.T, name, text string) { + if strings.ContainsAny(name, "/\\\x00") || name == "" || name == "." || name == ".." || len(text) > 1<<16 { + return + } + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, name), []byte(text), 0o644); err != nil { + return + } + res, err := Scan(context.Background(), root, Options{}) + if err != nil { + t.Fatal(err) + } + for _, x := range res.Findings { + if x.Message == "" || x.Status == "" { + t.Fatalf("finding without message or status: %+v", x) + } + } + }) +} From 9c2e11d64c4b8362244078e7003434d90abd276d Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Tue, 17 Nov 2026 22:58:41 +0000 Subject: [PATCH 005/119] java4shell: record the observed out-of-bounds write per release and mitigation in FACTS.md Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/FACTS.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/detectors/java4shell/FACTS.md b/detectors/java4shell/FACTS.md index e48cd63..c8dc9ea 100644 --- a/detectors/java4shell/FACTS.md +++ b/detectors/java4shell/FACTS.md @@ -10,7 +10,8 @@ not something a source states. | Fact | Source | | --- | --- | | The fix is JDK-8393212 "Base64 optimization improvements", 4 added lines in `generate_base64_decodeBlock()` in `src/hotspot/cpu/x86/stubGenerator_x86_64.cpp`: before the final 1 to 63 byte fragment of the AVX-512 VBMI path, `cmpl(length, 4); jcc(less, L_bruteForce)` ("A padded Base64 tail shorter than one complete block is handled by Java"). Authored 2026-10-13 by Tobias Hartmann, reviewed by rhalade, mschoene (the OpenJDK vulnerability group's reviewers), chagedorn, rcastanedalo | openjdk/jdk commit [`5177a70b385c16f26ede191fdac7aaba0bed0f8b`](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b), pushed 2026-11-16 | -| What the unfixed code does with a 1 to 3 byte tail that ends in `=`: `output_size` is 0, `L_padding` decrements it to -1, `bzhiq(output_mask, -1, output_size)` with an index of 255 keeps all 64 mask bits, and the masked `evmovdqub` stores 64 bytes at `dest + dp`: a write of up to 64 bytes past the output the caller sized. **Inferred** from reading the stub; no source states the impact in words | same file, lines around `L_finalBit` and `L_padding` | +| What the unfixed code does with a 1 to 3 byte tail that ends in `=`: `output_size` is 0, `L_padding` decrements it to -1, `bzhiq(output_mask, -1, output_size)` with an index of 255 keeps all 64 mask bits, and the masked `evmovdqub` stores 64 bytes at `dest + dp`: a write of up to 64 bytes past the output the caller sized. Read from the stub, and observed (next row); no vendor source states the impact in words | same file, lines around `L_finalBit` and `L_padding` | +| **Observed** on an AMD EPYC 9B14 (Zen 4, with avx512f, avx512bw, avx512vbmi and bmi2), 2026-11-17: after C2 compiles the decoder, `Base64.getDecoder().decode(src, dst)` of a malformed input that ends in a 1 to 3 character fragment with `=` (for example 64 valid characters then `A=`) writes bytes into `dst` past the decoded output. Seen on Temurin 18.0.2.1, 20.0.2, 17.0.6, 17.0.21, 21.0.2, 21.0.13 and 25.0.5; not seen on Temurin 17.0.5 or on SapMachine 21.0.13.1 (the fixed release); not seen on 21.0.13 started with `-XX:-UseBASE64Intrinsics` or with `-XX:UseAVX=2`. On 17.0.x to 20 the input has to be longer than 128 bytes, on 21 and later longer than 31 bytes: the 17u stub enters the AVX-512 path only above 128 bytes (`cmpl(length, 128)`), the 21u stub above 31. With an output array sized by `decode(byte[])` the write goes past the array into the heap. The test program is not in this repository | local run, `eclipse-temurin` images and the SapMachine 21.0.13.1 tarball (sha256 `6cb4df18…949ae9`, matching the GitHub release asset digest) | | CVE-2026-114938 is listed with CVSS 8.1, component hotspot/compiler, in Amazon Corretto's changelogs of 2026-11-17 | [corretto-17 CHANGELOG 17.0.21.1.2](https://github.com/corretto/corretto-17/blob/17.0.21.1.2/CHANGELOG.md), [corretto-21 21.0.13.1.2](https://github.com/corretto/corretto-21/blob/21.0.13.1.2/CHANGELOG.md), [corretto-25 25.0.5.1.2](https://github.com/corretto/corretto-25/blob/25.0.5.1.2/CHANGELOG.md), [corretto-27 27.0.1.1.4](https://github.com/corretto/corretto-27/blob/27.0.1.1.4/CHANGELOG.md) | | CVE-2026-114938 is JDK-8393212. **Inferred**: the Corretto changelogs list CVEs by component, not by JDK bug. Each fixed release carries two hotspot/compiler fixes (8393212 and 8390694 "Enhance vector masks"; 21u, 25u and 27u also 8390852 "Improve integer compression") and lists two or three hotspot/compiler CVEs. The brief's description (AVX-512 VBMI Base64 decode, mitigated by `-XX:-UseBASE64Intrinsics`) matches only 8393212. The OpenJDK advisory page that would state the mapping could not be reached from the research host | as above; openjdk.org unreachable | | The vulnerable path runs only when the CPU reports AVX-512 VBMI, AVX-512BW and BMI2 and HotSpot keeps them enabled: `if (VM_Version::supports_avx512_vbmi() && VM_Version::supports_avx512bw() && VM_Version::supports_bmi2())`. AVX-512 features need AVX-512F, so the four CPU flags are `avx512f avx512bw avx512vbmi bmi2` | stubGenerator_x86_64.cpp at the fix commit | From 817730ea66e2710e75e34d466e469fcfebc39cc6 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Tue, 17 Nov 2026 23:30:06 +0000 Subject: [PATCH 006/119] java4shell: parity fixtures, results and README parity/java4shell.py checks 33 cases (vendor images per line, arm64 and every platform of a multi-arch image, the fixed SapMachine 21.0.13.1, a jlink image, bundled product runtimes, Alpine, Debian and Ubuntu packages, mitigations, hostile inputs, a filesystem scan and an offline source tree) against verdicts from FACTS.md: 33/33 match. A Dockerfile stage's JAVA_TOOL_OPTIONS mitigation now also covers the packages it installs. Co-Authored-By: Claude Opus 5.5 --- README.md | 11 +- detectors/java4shell/internal/repo/repo.go | 28 +- .../java4shell/internal/repo/repo_test.go | 4 +- detectors/java4shell/java4shell.go | 2 +- parity/JAVA4SHELL-RESULTS.md | 41 ++ parity/java4shell.py | 129 ++++ parity/java4shell/alpine-pkg.Dockerfile | 3 + parity/java4shell/bundled.Dockerfile | 8 + parity/java4shell/cases.json | 601 ++++++++++++++++++ parity/java4shell/debian-pkg.Dockerfile | 3 + parity/java4shell/hostile.Dockerfile | 12 + parity/java4shell/jlink.Dockerfile | 6 + parity/java4shell/mitigated-env.Dockerfile | 3 + parity/java4shell/mitigated-useavx.Dockerfile | 3 + parity/java4shell/reenabled.Dockerfile | 3 + .../java4shell/repo/.github/workflows/ci.yml | 12 + parity/java4shell/repo/.java-version | 1 + parity/java4shell/repo/.sdkmanrc | 1 + parity/java4shell/repo/.tool-versions | 1 + parity/java4shell/repo/Dockerfile | 3 + parity/java4shell/repo/Dockerfile.pkg | 3 + parity/java4shell/repo/build.gradle.kts | 8 + parity/java4shell/repo/compose.yaml | 13 + parity/java4shell/repo/k8s/deployment.yaml | 10 + parity/java4shell/sapmachine-fixed.Dockerfile | 6 + parity/java4shell/tomcat.Dockerfile | 3 + parity/java4shell/ubuntu-pkg.Dockerfile | 3 + 27 files changed, 916 insertions(+), 5 deletions(-) create mode 100644 parity/JAVA4SHELL-RESULTS.md create mode 100644 parity/java4shell.py create mode 100644 parity/java4shell/alpine-pkg.Dockerfile create mode 100644 parity/java4shell/bundled.Dockerfile create mode 100644 parity/java4shell/cases.json create mode 100644 parity/java4shell/debian-pkg.Dockerfile create mode 100644 parity/java4shell/hostile.Dockerfile create mode 100644 parity/java4shell/jlink.Dockerfile create mode 100644 parity/java4shell/mitigated-env.Dockerfile create mode 100644 parity/java4shell/mitigated-useavx.Dockerfile create mode 100644 parity/java4shell/reenabled.Dockerfile create mode 100644 parity/java4shell/repo/.github/workflows/ci.yml create mode 100644 parity/java4shell/repo/.java-version create mode 100644 parity/java4shell/repo/.sdkmanrc create mode 100644 parity/java4shell/repo/.tool-versions create mode 100644 parity/java4shell/repo/Dockerfile create mode 100644 parity/java4shell/repo/Dockerfile.pkg create mode 100644 parity/java4shell/repo/build.gradle.kts create mode 100644 parity/java4shell/repo/compose.yaml create mode 100644 parity/java4shell/repo/k8s/deployment.yaml create mode 100644 parity/java4shell/sapmachine-fixed.Dockerfile create mode 100644 parity/java4shell/tomcat.Dockerfile create mode 100644 parity/java4shell/ubuntu-pkg.Dockerfile diff --git a/README.md b/README.md index 6f9ea5a..a0b5f43 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,9 @@ One engine for DefectDojo's emerging-vulnerability scanners. Each new vulnerabil | `php2shell` | PHP runtimes vulnerable to CVE-2026-109618 and CVE-2026-109619 ("PHP2Shell"), fixed in PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12 ([GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w), [GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp)). A packaged PHP is judged by its vendor's backport data, never by the version it reports. Also checks the images a source tree builds on and deploys, and can rewrite them to fixed images | `fs`, `image`, `repo`, `fix` | | `brotli` | Brotli decoders vulnerable to CVE-2026-111497 ("Node2Shell", "Broccoli2Shell"), Brotli 1.0.3 through 1.2.0, fixed in 1.0.10, 1.1.1 and 1.2.1 ([GHSA-9v8h-qqgm-4m35](https://github.com/advisories/GHSA-9v8h-qqgm-4m35)): system `libbrotlidec` and every copy bundled into other software (Node.js, .NET, Bun, Electron, Envoy and Istio, Python wheels such as Pillow, pyarrow, duckdb, pycurl and PyMuPDF, brotli4j, and more), on Linux, Windows and macOS. A decoder is judged first by the error code the fix added, so vendor backports are recognised without distribution data; a build that strips it by its own version stamp or by its code, which returns that error code only once fixed. In a source tree it finds the Node.js, .NET and Bun releases and the bundling packages a project pins, and `fix` moves each to the fixed release | `fs`, `image`, `repo`, `fix` | | `sshole` | \*sshole, the OpenSSH password authentication bypass on musl libc fixed in OpenSSH 10.6p2 and in Alpine's openssh packages of November 5, 2026 ([release notes](https://www.openssh.org/releasenotes.html#10.6p2), [writeup](https://sshhole.com)). On musl, sshd from 7.3p1 to 10.6p1 compares an account's password field of `*` with the `*` that crypt returns when it fails, so a crafted password logs in to that account. It judges each installed sshd by its C library, its release and the apk database (Alpine backports keep the release number), then checks what the target's `sshd_config` (Include, Match, PasswordAuthentication, AuthenticationMethods, PermitRootLogin, AllowUsers and the rest) and account files make reachable, and reports the accounts. In an image it also reads the command (`sshd -o` and `-f`) and the startup scripts it runs (entrypoints, s6, cont-init.d), and reports a server as exposed when a startup script turns password logins on, sets a `*` field or sets passwords. OpenWrt's opkg database and its backports (23.05, 24.10, 25.12) count like Alpine's. PAM-checked builds (`UsePAM yes`) are not affected. On a live server it reads the banner and the offered methods and never sends a password. In a source tree it finds Dockerfiles that install an OpenSSH server on Alpine without the fix (package lists in `ARG` and `ENV` too), Ansible apk tasks, Buildroot, OpenWrt and Yocto configurations that build one on musl, and anything that sets a password field to `*`. It also pulls the images the tree references (through the guarded transport, with the command a Compose service or Kubernetes container sets) and judges them like `scan image`. `fix` adds the fixed release floor (in the variable when the list is one), moves an end-of-life Alpine base to a tag on the nearest fixed Alpine release (`alpine:3.14` to `3.16`, `python:3.9-alpine3.14` to `3.9-alpine3.16` after checking that image) as a labelled upgrade, adds upstream commit 4353fdc43 as a patch scoped to the OpenSSH versions it applies to (Buildroot `BR2_GLOBAL_PATCH_DIR`, a version-specific Yocto bbappend), sets Ansible tasks to `state: latest`, and changes `*` to `*NP*` | `fs`, `image`, `host`, `repo`, `fix` | +| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64 (JDK-8393212), fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 on November 15, 2026 ([fix](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b), [knowledge table](detectors/java4shell/FACTS.md)). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512 VBMI (Intel Ice Lake and later, AMD Zen 4 and later). The decoder came with JDK 18 and 17.0.6; Java 8, 11 and 17.0.0 to 17.0.5 do not have it, and Java 18 to 20, 22 to 24 and 26 received no fix. It finds every Java runtime by its VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others). Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; every platform of a multi-arch image is judged on its own), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness and never overrides the library. No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version. OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or `-XX:UseAVX=2` (or lower) in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is reported as mitigated (still to update), never as fixed; `_JAVA_OPTIONS` turning the intrinsic back on undoes it. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context, never as a clearance. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft and Oracle images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`) after reading it, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | -The detectors ported from standalone scanners also build as standalone binaries under the names people search for: `emudhra-scan` and `php2shell-scan`. They keep their original commands, flags and exit status rules. `brotli` and `sshole` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`). +The detectors ported from standalone scanners also build as standalone binaries under the names people search for: `emudhra-scan` and `php2shell-scan`. They keep their original commands, flags and exit status rules. `brotli`, `sshole` and `java4shell` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`, `--detector java4shell`). ## Install @@ -50,6 +51,10 @@ sudo earlylight scan fs --detector sshole / # this machine's sshd earlylight scan host --detector sshole bastion.example:22 # banner and offered methods; sends no password earlylight scan repo --detector sshole . # Dockerfiles, scripts and Ansible tasks earlylight fix --detector sshole --dry-run . # fixed apk floors, "*" to "*NP*" +earlylight scan image --detector java4shell --platform all eclipse-temurin:21-jre # Java runtimes, per platform +sudo earlylight scan fs --detector java4shell / # every JDK, JRE and bundled runtime on this machine +earlylight scan repo --detector java4shell . # Java images, versions, toolchains and packages a tree pins +earlylight fix --detector java4shell --dry-run . # moves to published fixed images, after reading them earlylight scan image --platform all myorg/app:prod # every platform the image has sudo earlylight scan fs / # this machine earlylight scan fs --as-root /host # a host mounted elsewhere @@ -113,6 +118,7 @@ The engine enforces one rule for every detector: a finding can only be `fixed`, | `detectors/php2shell` | Adapter, `verbatim.go` from php2shell-scan's command line, and `internal/` copied verbatim from php2shell-scan | | `detectors/brotli` | Adapter, plus `internal/fingerprint` (what a binary proves: the decoder's error table, its tables and code, exports and version stamps), `internal/assess` (the verdict and fix for one file) and `internal/pins` (pins and bundling packages in a source tree, and their verified edits), which know nothing about the engine | | `detectors/sshole` | Adapter and live-host probe, plus `internal/assess` (what an sshd binary proves, musl's shadow lookup and crypt failures, sshd's salt choice, sshd_config with Include and Match, and the verdict) and `internal/repo` (Dockerfiles, scripts and YAML in a source tree, and their verified edits), which know nothing about the engine | +| `detectors/java4shell` | Adapter, plus `internal/knowledge` (the release data and version judgement, sourced in `FACTS.md`), `internal/jvm` (what a VM library, release file and JVM option source prove), `internal/assess` (the verdict for each runtime: product, package, mitigation) and `internal/repo` (Java images, versions and packages in a source tree, and their verified edits), which know nothing about the engine | | `internal/refs` | Image references in Dockerfiles, Compose, Kubernetes, Helm values and CI files (moved from php2shell, unchanged, so every detector can read them) | | `parity/` | Proves each port gives the same results as its standalone scanner | | `brand/` | The Early Light logo, favicons, avatar and social preview | @@ -127,6 +133,7 @@ Every port must give exactly the verdicts of the scanner it came from before it - `parity/brotli.py` has no standalone scanner to compare with, so it checks every decoder in 38 images against the vendor's own fix status: Node.js, .NET, Bun, Envoy and curl images before and after their October 2026 releases, distribution packages pinned to their exact unfixed and backported builds, and the Python wheels ([BROTLI-RESULTS.md](parity/BROTLI-RESULTS.md)). - `parity/brotli_files.py` checks 73 release binaries and packages, unpacked and never run: Node.js, .NET and Bun for Windows and macOS, seven Electron releases, Envoy and Istio, and the packages that bundle the decoder ([BROTLI-FILES-RESULTS.md](parity/BROTLI-FILES-RESULTS.md)). A WebAssembly build of the decoder is the one case it cannot settle: it is reported as unknown. - `parity/sshole.py` builds ten images from `parity/sshole/` (Alpine with the unfixed and the fixed package, password logins off, UsePAM on, root with PermitRootLogin, a Match on address, the current Alpine release, Debian, an entrypoint that turns password logins on at start, and `sshd -o` in the image command) and checks each verdict against the expected one ([SSHOLE-RESULTS.md](parity/SSHOLE-RESULTS.md)). The expected verdicts come from the upstream fix, musl's crypt and shadow code, and the Alpine package that shipped it. +- `parity/java4shell.py` checks 33 cases against verdicts taken from [FACTS.md](detectors/java4shell/FACTS.md): Temurin 8, 11, 17.0.5, 17.0.6, 17.0.21 (Alpine), 18, 20, 21 (also arm64, every platform, UBI 9), 25 and 27, Corretto (an Amazon Linux rpm and Alpine), Zulu, Liberica, SapMachine, Semeru, Elasticsearch's bundled JDK, the fixed SapMachine 21.0.13.1, a jlink image, bundled product runtimes with and without `setenv.sh`, Alpine, Debian and Ubuntu packages, environment and Tomcat mitigations and one that is undone, hostile release files and symlink loops, a filesystem scan and an offline source tree ([JAVA4SHELL-RESULTS.md](parity/JAVA4SHELL-RESULTS.md)). - `parity/php.py` runs php2shell-scan, this repo's php2shell-scan and Early Light over php2shell-scan's validation matrix: official images, distribution packages, source builds and hostile images. Each finding's complete record is compared field by field. It also covers filesystem scans at and below a system root, repository scans, `fix --dry-run`, and every detector at once ([PHP-RESULTS.md](parity/PHP-RESULTS.md)). ## Adding a detector @@ -146,6 +153,8 @@ go test ./internal/archive -run '^$' -fuzz '^FuzzWalk$' -fuzztime 60s go test ./detectors/emudhra/internal/detect -run '^$' -fuzz '^FuzzScan$' -fuzztime 60s go test ./detectors/sshole/internal/assess -run '^$' -fuzz '^FuzzConfig$' -fuzztime 60s go test ./detectors/sshole/internal/repo -run '^$' -fuzz '^FuzzScanText$' -fuzztime 60s +go test ./detectors/java4shell/internal/jvm -run '^$' -fuzz '^FuzzInspect$' -fuzztime 60s +go test ./detectors/java4shell/internal/repo -run '^$' -fuzz '^FuzzScanText$' -fuzztime 60s govulncheck ./... python3 parity/parity.py path/to/emudhra-scan path/to/earlylight python3 parity/php.py path/to/php2shell-scan ./php2shell-scan ./earlylight path/to/emudhra-scan cases.json diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 0e4434d..594c425 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -350,8 +350,12 @@ func (s *scanner) judgeVersion(rel string, line, col int, verText, source, vendo if l.Fixed == nil && tv.Nums[0] > 17 { rule, level = RuleLine, "error" } + msg := fmt.Sprintf("%s selects Java %s, without the Java4Shell fix", source, verText) + if rule == RuleLine { + msg = fmt.Sprintf("%s selects Java %s, a line that received no Java4Shell fix", source, verText) + } s.add(Finding{Rule: rule, File: rel, Line: line, Level: level, Status: StatusVulnerable, Reason: why, - Message: fmt.Sprintf("%s selects Java %s, without the Java4Shell fix", source, verText), + Message: msg, Fix: pinFix(tv.Nums[0], source), Props: props}) case knowledge.Unknown: l, ok := knowledge.LineOf(tv.Nums[0]) @@ -700,6 +704,25 @@ var ( func (s *scanner) dockerfile(rel, text string) { ls := lines(text) from := 0 + stageStart := len(s.findings) + // endStage marks the packages a stage installs as mitigated when the + // stage sets the mitigation (before or after the install: ENV applies + // to the image the stage makes). + endStage := func() { + how, ok := s.mitigated[fmt.Sprintf("%s:%d", rel, from)] + if !ok { + return + } + for k := stageStart; k < len(s.findings); k++ { + f := &s.findings[k] + if f.File == rel && f.Rule == RulePackage && f.Status == StatusVulnerable { + f.Status, f.Level = StatusMitigated, "note" + f.Reason += "; " + how + f.Message += ", mitigated by the stage's JVM options until it is updated" + } + } + } + defer endStage() for i := 0; i < len(ls); i++ { l := ls[i] // Join continuation lines for matching; report the first line. @@ -712,7 +735,8 @@ func (s *scanner) dockerfile(rel, text string) { trim := strings.TrimSpace(full) switch { case fromLine.MatchString(trim): - from = i + 1 + endStage() + from, stageStart = i+1, len(s.findings) case envJTO.MatchString(trim): var o jvm.Options body := envJTO.ReplaceAllString(trim, "") diff --git a/detectors/java4shell/internal/repo/repo_test.go b/detectors/java4shell/internal/repo/repo_test.go index 11a6cde..5494eb6 100644 --- a/detectors/java4shell/internal/repo/repo_test.go +++ b/detectors/java4shell/internal/repo/repo_test.go @@ -95,7 +95,8 @@ func TestScanTree(t *testing.T) { root := tree(t, map[string]string{ "Dockerfile": "FROM eclipse-temurin:21.0.13_9-jre-alpine AS run\nRUN apk add --no-cache curl\n", "svc/Dockerfile": "ARG JAVA=21.0.12.1_1-jdk\nFROM eclipse-temurin:${JAVA} AS build\nENV JAVA_TOOL_OPTIONS=\"-XX:-UseBASE64Intrinsics\"\n" + - "FROM ubuntu:24.04\nRUN apt-get update && apt-get install -y openjdk-21-jre-headless\nRUN apt-get install -y openjdk-17-jre-headless=17.0.21+9-1~deb12u1\nRUN apk add openjdk24\n", + "FROM ubuntu:24.04\nRUN apt-get update && apt-get install -y openjdk-21-jre-headless\nRUN apt-get install -y openjdk-17-jre-headless=17.0.21+9-1~deb12u1\nRUN apk add openjdk24\n" + + "FROM debian:12\nRUN apt-get install -y openjdk-25-jre-headless\nENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics\n", "compose.yaml": "services:\n app:\n image: amazoncorretto:21.0.12-al2023\n environment:\n JAVA_TOOL_OPTIONS: -XX:UseAVX=2\n" + " jira:\n image: atlassian/jira-software:9.12\n web:\n image: nginx:1.27\n floating:\n image: eclipse-temurin:21-jre\n j9:\n image: ibm-semeru-runtimes:open-21-jre\n", "k8s/deploy.yaml": "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: x\nspec:\n template:\n spec:\n containers:\n - name: a\n image: sapmachine:21.0.12\n", @@ -130,6 +131,7 @@ func TestScanTree(t *testing.T) { } check("svc/Dockerfile", 2, RuleImagePin, StatusMitigated) check("svc/Dockerfile", 5, RulePackage, StatusVulnerable) + check("svc/Dockerfile", 9, RulePackage, StatusMitigated) if f := check("svc/Dockerfile", 6, RulePackage, StatusVulnerable); f.Level != "error" { t.Errorf("pinned package level %s", f.Level) } diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 4a6a370..7a10b53 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -112,7 +112,7 @@ func isScript(head []byte) bool { return len(head) > 2 && head[0] == '#' && head // keep reports the package databases owners are read from. func keep(p string) bool { switch p { - case "/lib/apk/db/installed", "/usr/lib/apk/db/installed", "/var/lib/dpkg/status", "/etc/os-release", "/usr/lib/os-release": + case "/lib/apk/db/installed", "/usr/lib/apk/db/installed", "/var/lib/dpkg/status": return true } return assess.IsDpkgList(p) diff --git a/parity/JAVA4SHELL-RESULTS.md b/parity/JAVA4SHELL-RESULTS.md new file mode 100644 index 0000000..c486be7 --- /dev/null +++ b/parity/JAVA4SHELL-RESULTS.md @@ -0,0 +1,41 @@ +# Java4Shell fixture results + +Generated by `parity/java4shell.py`. Each row's expected findings come from [FACTS.md](../detectors/java4shell/FACTS.md). Registry images are scanned by tag; the digest scanned is listed. + +| Case | What | Result | Findings (platform, path, kind, verdict, status) | +| --- | --- | --- | --- | +| temurin-8 | Temurin 8: no Base64 decode intrinsic
`eclipse-temurin:8u512-b09-jre`
linux/amd64 sha256:9b84aee27144e52f023cb1895b9579519806890f7fc989f89c4e735f51287745 | pass | linux/amd64 /opt/java/openjdk runtime fixed not-affected | +| temurin-11 | Temurin 11: no Base64 decode intrinsic
`eclipse-temurin:11.0.33_10-jre`
linux/amd64 sha256:81296a4bedf616c682869254cd55e4a3bff824498d318fcef224e76237e5f69b | pass | linux/amd64 /opt/java/openjdk runtime fixed not-affected | +| temurin-17.0.5 | Temurin 17.0.5, the last 17 update before the decoder (8268276 came in 17.0.6)
`eclipse-temurin:17.0.5_8-jre`
linux/amd64 sha256:402c656f078bc116a6db1e2e23b08c6f4a78920a2c804ea4c2d3e197f1d6b47c | pass | linux/amd64 /opt/java/openjdk runtime fixed not-affected | +| temurin-17.0.6 | Temurin 17.0.6, the first 17 update with the decoder
`eclipse-temurin:17.0.6_10-jre`
linux/amd64 sha256:7dacdab7c335d90cf4e110f5744ca27d5a3ed87901a7c08022c8c12055438bd2 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | +| temurin-17.0.21-alpine | Temurin 17.0.21 on Alpine (musl), before 17.0.21.1
`eclipse-temurin:17.0.21_9-jre-alpine`
linux/amd64 sha256:df2fcd61a7987cfd3514756f2cb6c6e940fdd8076bdfd4e362121850e6893a3f | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | +| temurin-18 | Temurin 18.0.2.1: end of life, no fix
`eclipse-temurin:18.0.2.1_1-jre`
linux/amd64 sha256:0d503e979d1b0c61d122a26985e23e42e87741198fd967c0c1efeefbd240ff95 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | +| temurin-20 | Temurin 20.0.2: end of life, no fix
`eclipse-temurin:20.0.2_9-jre`
linux/amd64 sha256:db32cb29a978fa782ef97bf3a39f4955295712ebff305839c3faaf64f5c5b22b | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | +| temurin-21 | Temurin 21.0.13, before 21.0.13.1
`eclipse-temurin:21.0.13_9-jre`
linux/amd64 sha256:15ed0883abf7550992a343740223a8bab2292e7db126986cde97c0be58aeb06f | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | +| temurin-21-arm64 | Temurin 21.0.13 for linux/arm64: only x86-64 has the decoder
`eclipse-temurin:21.0.13_9-jre`
linux/arm64/v8 sha256:4a541e56af0ae9a1ff20cdbf43e400864542116b0e7804b37f51be4c574f2057 | pass | linux/arm64/v8 /opt/java/openjdk runtime fixed not-affected | +| temurin-21-all | Temurin 21.0.13, every platform of the multi-arch image (Linux and the two Windows Server images, whose layers name C:\ as /Files)
`eclipse-temurin:21.0.13_9-jre`
linux/amd64 sha256:15ed0883abf7550992a343740223a8bab2292e7db126986cde97c0be58aeb06f
linux/arm64/v8 sha256:4a541e56af0ae9a1ff20cdbf43e400864542116b0e7804b37f51be4c574f2057
linux/ppc64le sha256:189a1d03c2789f872b201886a783632fb7c3e8d503110efa19fb08c47b45f05f
linux/s390x sha256:e1542725522c2fe226e7915012cf0aad5751fb29540528776ce77982cbd1785b
windows/amd64 sha256:47e645496b5244c0fe56534299fbd826cfc4b5626635db8076ea445f8d0a80e2
windows/amd64 sha256:85cc6d636a02ce992461587b5d27d00dd511859ecaaed1e1e0e1f93b44ccb0ab | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable
linux/arm64/v8 /opt/java/openjdk runtime fixed not-affected
linux/ppc64le /opt/java/openjdk runtime fixed not-affected
linux/s390x /opt/java/openjdk runtime fixed not-affected
windows/amd64 /Files/openjdk-21 runtime vulnerable vulnerable
windows/amd64 /Files/openjdk-21 runtime vulnerable vulnerable | +| temurin-21-ubi9 | Temurin 21.0.13 on UBI 9 minimal
`eclipse-temurin:21.0.13_9-jre-ubi9-minimal`
linux/amd64 sha256:17e523f3696b36177c5c9a44399f8a4a4634229fdf3f14d4c7582d2597931a1d | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | +| temurin-25 | Temurin 25.0.5, before 25.0.5.1
`eclipse-temurin:25.0.5_8-jre`
linux/amd64 sha256:fa681c5833ecc085202c0923e909f9de888d80d22a7f38d6c51268ae5978c1d7 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | +| temurin-27 | Temurin 27.0.1.0.2, before 27.0.1.1
`eclipse-temurin:27.0.1.0-jre`
linux/amd64 sha256:2719c23ca6855fed092edd3f47fbea2e6870bfd00fa4e10b2077126d551bca28 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | +| corretto-21-al2023 | Amazon Corretto 21.0.13.0.11, an rpm on Amazon Linux 2023, before 21.0.13.1.2
`amazoncorretto:21.0.13-al2023-headless`
linux/amd64 sha256:21a9456bd7fee7045c545bf089e63ffc69ceb7d594b3c5bfb25bace199d3f566 | pass | linux/amd64 /usr/lib/jvm/java-21-amazon-corretto.x86_64 runtime vulnerable vulnerable | +| corretto-17-alpine | Amazon Corretto 17.0.21 on Alpine, before 17.0.21.1.2
`amazoncorretto:17.0.21-alpine3.22`
linux/amd64 sha256:92cdff306e26329894ef0fab79f8d120ac0acc08f3b675206b66a7da85316043 | pass | linux/amd64 /usr/lib/jvm/java-17-amazon-corretto runtime vulnerable vulnerable | +| zulu-21 | Azul Zulu 21.0.13.0.3 (the October CA-only release)
`azul/zulu-openjdk:21.0.13.0.3-jre`
linux/amd64 sha256:bad3fa28d3265b6912b78f85b71d6774dab86dc83a656287c4a2e46f84ac5b3b | pass | linux/amd64 /usr/lib/jvm/zulu21-ca-amd64 runtime vulnerable vulnerable | +| liberica-21 | BellSoft Liberica 21.0.13.0.3
`bellsoft/liberica-openjre-debian:21.0.13.0.3`
linux/amd64 sha256:c5f59f695bc1ae8a588c88c60aef901ed3fc66a7d4ba1b44d2b83cc007c9cb86 | pass | linux/amd64 /usr/lib/jvm/jre-21.0.13.0.3-bellsoft-x86_64 runtime vulnerable vulnerable | +| sapmachine-21 | SapMachine 21.0.13.0.3, before 21.0.13.1
`sapmachine:21.0.13.0.3-jre-ubuntu-noble`
linux/amd64 sha256:2d8895467d35e0f0c938fc8ba94a02792d1720ce738637969e342193c7dac16f | pass | linux/amd64 /usr/lib/jvm/sapmachine-21 runtime vulnerable vulnerable | +| semeru-21 | IBM Semeru 21 (OpenJ9, not HotSpot)
`ibm-semeru-runtimes:open-21-jre`
linux/amd64 sha256:c60bbee4f364698fcf1361f3adde6b9b5faabe70b8c6cc8c179ba3f551a4616c | pass | linux/amd64 /opt/java/openjdk runtime fixed not-affected | +| elasticsearch | Elasticsearch 9.5.5, which bundles its own JDK
`elasticsearch:9.5.5`
linux/amd64 sha256:4f963521f1ac85a08b27f2ac1c864697c9729ade989ed49d2a143cf5f79c222f | pass | linux/amd64 /usr/share/elasticsearch/jdk bundled-runtime vulnerable vulnerable | +| sapmachine-fixed | SapMachine 21.0.13.1 (fixed), unpacked from its release tarball | pass | linux/amd64 /opt/sapmachine runtime fixed fixed | +| jlink | jlink runtime made from Temurin 21.0.13 | pass | linux/amd64 /app/runtime runtime vulnerable vulnerable | +| bundled | Two products bundling Temurin 17.0.21; Jira's setenv.sh sets -XX:-UseBASE64Intrinsics | pass | linux/amd64 /opt/atlassian/confluence/jre bundled-runtime vulnerable vulnerable
linux/amd64 /opt/atlassian/jira/jre bundled-runtime inactive mitigated | +| alpine-pkg | Alpine 3.23 openjdk21-jre-headless (21.0.13.0.3_p1-r0, no fixed package) | pass | linux/amd64 /usr/lib/jvm/java-21-openjdk runtime vulnerable vulnerable | +| debian-pkg | Debian 12 openjdk-17-jre-headless (17.0.21+9-1~deb12u1, no fixed package) | pass | linux/amd64 /usr/lib/jvm/java-17-openjdk-amd64 runtime vulnerable vulnerable | +| ubuntu-pkg | Ubuntu 24.04 openjdk-25-jre-headless (25.0.5.0.3, no fixed package) | pass | linux/amd64 /usr/lib/jvm/java-25-openjdk-amd64 runtime vulnerable vulnerable | +| mitigated-env | Temurin 21.0.13 with ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics | pass | linux/amd64 /opt/java/openjdk runtime inactive mitigated | +| mitigated-useavx | Temurin 25.0.5 with ENV JDK_JAVA_OPTIONS=-XX:UseAVX=2 | pass | linux/amd64 /opt/java/openjdk runtime inactive mitigated | +| reenabled | JAVA_TOOL_OPTIONS mitigation undone by _JAVA_OPTIONS | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | +| tomcat | Tomcat 10.1 on Temurin 21 with CATALINA_OPTS=-XX:-UseBASE64Intrinsics (catalina.sh passes it on) | pass | linux/amd64 /opt/java/openjdk runtime inactive mitigated | +| hostile | Forged and 200 KiB release files over an unfixed VM library, a text file named libjvm.so, symlink loops | pass | linux/amd64 /opt/forged runtime vulnerable vulnerable
linux/amd64 /opt/huge runtime vulnerable vulnerable | +| debian-pkg-fs | The debian-pkg image exported and scanned as a filesystem | pass | fs /usr/lib/jvm/java-17-openjdk-amd64 runtime vulnerable vulnerable | +| repo | Source tree, offline: Dockerfiles, Compose, Kubernetes, setup-java, version files, Gradle | pass | .github/workflows/ci.yml:12 java-line vulnerable
.github/workflows/ci.yml:8 java-pin vulnerable
.java-version:1 java-pin vulnerable
.sdkmanrc:1 java-pin vulnerable
Dockerfile.pkg:2 os-package inactive
Dockerfile:1 image-pin vulnerable
build.gradle.kts:3 java-line vulnerable
build.gradle.kts:7 image-pin vulnerable
compose.yaml:13 not-checked unknown
compose.yaml:3 image-pin vulnerable
compose.yaml:5 image-pin inactive
k8s/deployment.yaml:10 image-pin vulnerable | + +33/33 cases match. diff --git a/parity/java4shell.py b/parity/java4shell.py new file mode 100644 index 0000000..12c37ac --- /dev/null +++ b/parity/java4shell.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Check the java4shell detector against Java runtimes whose status is known. + +usage: python3 parity/java4shell.py path/to/earlylight [case ...] + +Needs Docker and registry access. Cases are in parity/java4shell/cases.json: +published images (scanned from the registry by tag, the digest recorded), +images built from parity/java4shell/*.Dockerfile (scanned from `docker save` +archives), one built image exported and scanned as a filesystem, and a +source tree scanned offline. Each case's findings are compared with the +expected [platform, path, kind, verdict, status] rows, which come from +FACTS.md (fixed releases, the release that introduced the decoder, OpenJ9, +architecture), not from earlier runs. Writes parity/JAVA4SHELL-RESULTS.md. +""" +import json +import os +import subprocess +import sys +import tarfile +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +CASES = os.path.join(HERE, "java4shell") + + +def scan(tool, args): + # Flags go before the target: the command line stops reading flags there. + out = subprocess.run([tool] + args[:2] + ["--detector", "java4shell", "--format", "json", "--show-cleared"] + args[2:], + capture_output=True, text=True) + try: + return json.loads(out.stdout) + except json.JSONDecodeError: + return {"targets": [{"error": (out.stderr or out.stdout).strip()[:300]}]} + + +def rows(report, repo=False): + got, digests = [], [] + for t in report.get("targets", []): + if t.get("error"): + got.append(["error", t["error"][:120], "", "", ""]) + if t.get("digest"): + digests.append(t.get("platform", "") + " " + t["digest"]) + for f in t.get("findings", []): + if repo: + got.append([f["path"] + ":" + str(f.get("line", 0)), f["kind"], f["verdict"]]) + else: + got.append([t.get("platform", ""), f["path"], f["kind"], f["verdict"], f.get("facts", {}).get("status", "")]) + return got, digests + + +def safe_extract(tar, dest): + # The exported image is ours, but keep members inside dest anyway. + for m in tar.getmembers(): + p = os.path.realpath(os.path.join(dest, m.name)) + if not p.startswith(os.path.realpath(dest) + os.sep) or m.isdev(): + continue + try: + tar.extract(m, dest, set_attrs=False, filter="fully_trusted") + except (OSError, tarfile.TarError): + pass + + +def run_case(tool, c, tmp): + kind = c["mode"] + if kind == "registry": + args = ["scan", "image"] + if c.get("platform"): + args += ["--platform", c["platform"]] + return rows(scan(tool, args + [c["ref"]])) + if kind == "repo": + return rows(scan(tool, ["scan", "repo", "--offline", os.path.join(CASES, c["dir"])]), repo=True) + tag = "earlylight-parity-java4shell:" + c["name"] + subprocess.run(["docker", "build", "-q", "-t", tag, "-f", os.path.join(CASES, c["dockerfile"]), CASES], + check=True, stdout=subprocess.DEVNULL) + if kind == "build": + tar = os.path.join(tmp, c["name"] + ".tar") + subprocess.run(["docker", "save", tag, "-o", tar], check=True) + return rows(scan(tool, ["scan", "image", "docker-archive:" + tar])) + # kind == "fs": export the container filesystem and scan it as a system root. + cid = subprocess.run(["docker", "create", tag], check=True, capture_output=True, text=True).stdout.strip() + try: + tar = os.path.join(tmp, c["name"] + "-fs.tar") + subprocess.run(["docker", "export", cid, "-o", tar], check=True) + finally: + subprocess.run(["docker", "rm", cid], check=True, stdout=subprocess.DEVNULL) + root = os.path.join(tmp, c["name"] + "-root") + os.makedirs(root) + with tarfile.open(tar) as t: + safe_extract(t, root) + got, _ = rows(scan(tool, ["scan", "fs", "--as-root", root])) + return [["fs"] + g[1:] for g in got], [] + + +def main(): + if len(sys.argv) < 2: + sys.exit(__doc__) + tool = os.path.abspath(sys.argv[1]) + only = set(sys.argv[2:]) + cases = json.load(open(os.path.join(CASES, "cases.json"))) + results, failed = [], 0 + with tempfile.TemporaryDirectory() as tmp: + for c in cases: + if only and c["name"] not in only: + continue + got, digests = run_case(tool, c, tmp) + want = c["expected"] + ok = sorted(got) == sorted(want) + failed += not ok + results.append((c, ok, got, want, digests)) + print(("pass " if ok else "FAIL ") + c["name"], flush=True) + if only: + sys.exit(1 if failed else 0) + with open(os.path.join(HERE, "JAVA4SHELL-RESULTS.md"), "w") as f: + f.write("# Java4Shell fixture results\n\nGenerated by `parity/java4shell.py`. Each row's expected findings come from " + "[FACTS.md](../detectors/java4shell/FACTS.md). Registry images are scanned by tag; the digest scanned is listed.\n\n" + "| Case | What | Result | Findings (platform, path, kind, verdict, status) |\n| --- | --- | --- | --- |\n") + for c, ok, got, want, digests in results: + cell = "
".join(" ".join(str(x) for x in g if x) for g in sorted(got)) or "none" + what = c["what"] + if c.get("ref"): + what += "
`" + c["ref"] + "`" + "".join("
" + d for d in digests) + f.write(f"| {c['name']} | {what} | {'pass' if ok else 'FAIL (want ' + json.dumps(want) + ')'} | {cell} |\n") + f.write(f"\n{len(results) - failed}/{len(results)} cases match.\n") + print(f"{len(results) - failed}/{len(results)} cases match") + sys.exit(1 if failed else 0) + + +if __name__ == "__main__": + main() diff --git a/parity/java4shell/alpine-pkg.Dockerfile b/parity/java4shell/alpine-pkg.Dockerfile new file mode 100644 index 0000000..8f11322 --- /dev/null +++ b/parity/java4shell/alpine-pkg.Dockerfile @@ -0,0 +1,3 @@ +# Alpine's openjdk21 package (21.0.13.0.3_p1-r0 in 3.23 on 2026-11-17: no fix yet). +FROM alpine:3.23 +RUN apk add --no-cache openjdk21-jre-headless diff --git a/parity/java4shell/bundled.Dockerfile b/parity/java4shell/bundled.Dockerfile new file mode 100644 index 0000000..3b7278f --- /dev/null +++ b/parity/java4shell/bundled.Dockerfile @@ -0,0 +1,8 @@ +# A product that ships its own runtime (the Atlassian layout), with a +# setenv.sh that sets the mitigation for Jira only, next to a Confluence +# without it. +FROM eclipse-temurin:17.0.21_9-jre AS jre +FROM debian:12-slim +COPY --from=jre /opt/java/openjdk /opt/atlassian/jira/jre +COPY --from=jre /opt/java/openjdk /opt/atlassian/confluence/jre +RUN mkdir -p /opt/atlassian/jira/bin && echo 'JVM_SUPPORT_RECOMMENDED_ARGS="-XX:-UseBASE64Intrinsics"' > /opt/atlassian/jira/bin/setenv.sh diff --git a/parity/java4shell/cases.json b/parity/java4shell/cases.json new file mode 100644 index 0000000..b3a53ae --- /dev/null +++ b/parity/java4shell/cases.json @@ -0,0 +1,601 @@ +[ + { + "name": "temurin-8", + "what": "Temurin 8: no Base64 decode intrinsic", + "mode": "registry", + "ref": "eclipse-temurin:8u512-b09-jre", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "fixed", + "not-affected" + ] + ] + }, + { + "name": "temurin-11", + "what": "Temurin 11: no Base64 decode intrinsic", + "mode": "registry", + "ref": "eclipse-temurin:11.0.33_10-jre", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "fixed", + "not-affected" + ] + ] + }, + { + "name": "temurin-17.0.5", + "what": "Temurin 17.0.5, the last 17 update before the decoder (8268276 came in 17.0.6)", + "mode": "registry", + "ref": "eclipse-temurin:17.0.5_8-jre", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "fixed", + "not-affected" + ] + ] + }, + { + "name": "temurin-17.0.6", + "what": "Temurin 17.0.6, the first 17 update with the decoder", + "mode": "registry", + "ref": "eclipse-temurin:17.0.6_10-jre", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "temurin-17.0.21-alpine", + "what": "Temurin 17.0.21 on Alpine (musl), before 17.0.21.1", + "mode": "registry", + "ref": "eclipse-temurin:17.0.21_9-jre-alpine", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "temurin-18", + "what": "Temurin 18.0.2.1: end of life, no fix", + "mode": "registry", + "ref": "eclipse-temurin:18.0.2.1_1-jre", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "temurin-20", + "what": "Temurin 20.0.2: end of life, no fix", + "mode": "registry", + "ref": "eclipse-temurin:20.0.2_9-jre", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "temurin-21", + "what": "Temurin 21.0.13, before 21.0.13.1", + "mode": "registry", + "ref": "eclipse-temurin:21.0.13_9-jre", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "temurin-21-arm64", + "what": "Temurin 21.0.13 for linux/arm64: only x86-64 has the decoder", + "mode": "registry", + "ref": "eclipse-temurin:21.0.13_9-jre", + "expected": [ + [ + "linux/arm64/v8", + "/opt/java/openjdk", + "runtime", + "fixed", + "not-affected" + ] + ], + "platform": "linux/arm64" + }, + { + "name": "temurin-21-all", + "what": "Temurin 21.0.13, every platform of the multi-arch image (Linux and the two Windows Server images, whose layers name C:\\ as /Files)", + "mode": "registry", + "ref": "eclipse-temurin:21.0.13_9-jre", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "vulnerable", + "vulnerable" + ], + [ + "linux/arm64/v8", + "/opt/java/openjdk", + "runtime", + "fixed", + "not-affected" + ], + [ + "linux/ppc64le", + "/opt/java/openjdk", + "runtime", + "fixed", + "not-affected" + ], + [ + "linux/s390x", + "/opt/java/openjdk", + "runtime", + "fixed", + "not-affected" + ], + [ + "windows/amd64", + "/Files/openjdk-21", + "runtime", + "vulnerable", + "vulnerable" + ], + [ + "windows/amd64", + "/Files/openjdk-21", + "runtime", + "vulnerable", + "vulnerable" + ] + ], + "platform": "all" + }, + { + "name": "temurin-21-ubi9", + "what": "Temurin 21.0.13 on UBI 9 minimal", + "mode": "registry", + "ref": "eclipse-temurin:21.0.13_9-jre-ubi9-minimal", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "temurin-25", + "what": "Temurin 25.0.5, before 25.0.5.1", + "mode": "registry", + "ref": "eclipse-temurin:25.0.5_8-jre", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "temurin-27", + "what": "Temurin 27.0.1.0.2, before 27.0.1.1", + "mode": "registry", + "ref": "eclipse-temurin:27.0.1.0-jre", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "corretto-21-al2023", + "what": "Amazon Corretto 21.0.13.0.11, an rpm on Amazon Linux 2023, before 21.0.13.1.2", + "mode": "registry", + "ref": "amazoncorretto:21.0.13-al2023-headless", + "expected": [ + [ + "linux/amd64", + "/usr/lib/jvm/java-21-amazon-corretto.x86_64", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "corretto-17-alpine", + "what": "Amazon Corretto 17.0.21 on Alpine, before 17.0.21.1.2", + "mode": "registry", + "ref": "amazoncorretto:17.0.21-alpine3.22", + "expected": [ + [ + "linux/amd64", + "/usr/lib/jvm/java-17-amazon-corretto", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "zulu-21", + "what": "Azul Zulu 21.0.13.0.3 (the October CA-only release)", + "mode": "registry", + "ref": "azul/zulu-openjdk:21.0.13.0.3-jre", + "expected": [ + [ + "linux/amd64", + "/usr/lib/jvm/zulu21-ca-amd64", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "liberica-21", + "what": "BellSoft Liberica 21.0.13.0.3", + "mode": "registry", + "ref": "bellsoft/liberica-openjre-debian:21.0.13.0.3", + "expected": [ + [ + "linux/amd64", + "/usr/lib/jvm/jre-21.0.13.0.3-bellsoft-x86_64", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "sapmachine-21", + "what": "SapMachine 21.0.13.0.3, before 21.0.13.1", + "mode": "registry", + "ref": "sapmachine:21.0.13.0.3-jre-ubuntu-noble", + "expected": [ + [ + "linux/amd64", + "/usr/lib/jvm/sapmachine-21", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "semeru-21", + "what": "IBM Semeru 21 (OpenJ9, not HotSpot)", + "mode": "registry", + "ref": "ibm-semeru-runtimes:open-21-jre", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "fixed", + "not-affected" + ] + ] + }, + { + "name": "elasticsearch", + "what": "Elasticsearch 9.5.5, which bundles its own JDK", + "mode": "registry", + "ref": "elasticsearch:9.5.5", + "expected": [ + [ + "linux/amd64", + "/usr/share/elasticsearch/jdk", + "bundled-runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "sapmachine-fixed", + "what": "SapMachine 21.0.13.1 (fixed), unpacked from its release tarball", + "mode": "build", + "dockerfile": "sapmachine-fixed.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/opt/sapmachine", + "runtime", + "fixed", + "fixed" + ] + ] + }, + { + "name": "jlink", + "what": "jlink runtime made from Temurin 21.0.13", + "mode": "build", + "dockerfile": "jlink.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/app/runtime", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "bundled", + "what": "Two products bundling Temurin 17.0.21; Jira's setenv.sh sets -XX:-UseBASE64Intrinsics", + "mode": "build", + "dockerfile": "bundled.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/opt/atlassian/jira/jre", + "bundled-runtime", + "inactive", + "mitigated" + ], + [ + "linux/amd64", + "/opt/atlassian/confluence/jre", + "bundled-runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "alpine-pkg", + "what": "Alpine 3.23 openjdk21-jre-headless (21.0.13.0.3_p1-r0, no fixed package)", + "mode": "build", + "dockerfile": "alpine-pkg.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/lib/jvm/java-21-openjdk", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "debian-pkg", + "what": "Debian 12 openjdk-17-jre-headless (17.0.21+9-1~deb12u1, no fixed package)", + "mode": "build", + "dockerfile": "debian-pkg.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/lib/jvm/java-17-openjdk-amd64", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "ubuntu-pkg", + "what": "Ubuntu 24.04 openjdk-25-jre-headless (25.0.5.0.3, no fixed package)", + "mode": "build", + "dockerfile": "ubuntu-pkg.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/lib/jvm/java-25-openjdk-amd64", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "mitigated-env", + "what": "Temurin 21.0.13 with ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics", + "mode": "build", + "dockerfile": "mitigated-env.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "inactive", + "mitigated" + ] + ] + }, + { + "name": "mitigated-useavx", + "what": "Temurin 25.0.5 with ENV JDK_JAVA_OPTIONS=-XX:UseAVX=2", + "mode": "build", + "dockerfile": "mitigated-useavx.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "inactive", + "mitigated" + ] + ] + }, + { + "name": "reenabled", + "what": "JAVA_TOOL_OPTIONS mitigation undone by _JAVA_OPTIONS", + "mode": "build", + "dockerfile": "reenabled.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "tomcat", + "what": "Tomcat 10.1 on Temurin 21 with CATALINA_OPTS=-XX:-UseBASE64Intrinsics (catalina.sh passes it on)", + "mode": "build", + "dockerfile": "tomcat.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "inactive", + "mitigated" + ] + ] + }, + { + "name": "hostile", + "what": "Forged and 200 KiB release files over an unfixed VM library, a text file named libjvm.so, symlink loops", + "mode": "build", + "dockerfile": "hostile.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/opt/forged", + "runtime", + "vulnerable", + "vulnerable" + ], + [ + "linux/amd64", + "/opt/huge", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "debian-pkg-fs", + "what": "The debian-pkg image exported and scanned as a filesystem", + "mode": "fs", + "dockerfile": "debian-pkg.Dockerfile", + "expected": [ + [ + "fs", + "/usr/lib/jvm/java-17-openjdk-amd64", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, + { + "name": "repo", + "what": "Source tree, offline: Dockerfiles, Compose, Kubernetes, setup-java, version files, Gradle", + "mode": "repo", + "dir": "repo", + "expected": [ + [ + ".github/workflows/ci.yml:8", + "java-pin", + "vulnerable" + ], + [ + ".github/workflows/ci.yml:12", + "java-line", + "vulnerable" + ], + [ + ".java-version:1", + "java-pin", + "vulnerable" + ], + [ + ".sdkmanrc:1", + "java-pin", + "vulnerable" + ], + [ + "Dockerfile:1", + "image-pin", + "vulnerable" + ], + [ + "Dockerfile.pkg:2", + "os-package", + "inactive" + ], + [ + "build.gradle.kts:3", + "java-line", + "vulnerable" + ], + [ + "build.gradle.kts:7", + "image-pin", + "vulnerable" + ], + [ + "compose.yaml:3", + "image-pin", + "vulnerable" + ], + [ + "compose.yaml:5", + "image-pin", + "inactive" + ], + [ + "compose.yaml:13", + "not-checked", + "unknown" + ], + [ + "k8s/deployment.yaml:10", + "image-pin", + "vulnerable" + ] + ] + } +] \ No newline at end of file diff --git a/parity/java4shell/debian-pkg.Dockerfile b/parity/java4shell/debian-pkg.Dockerfile new file mode 100644 index 0000000..5b0f1ff --- /dev/null +++ b/parity/java4shell/debian-pkg.Dockerfile @@ -0,0 +1,3 @@ +# Debian 12's openjdk-17 package (17.0.21+9-1~deb12u1 on 2026-11-17: no fix yet). +FROM debian:12-slim +RUN apt-get update && apt-get install -y --no-install-recommends openjdk-17-jre-headless && rm -rf /var/lib/apt/lists/* diff --git a/parity/java4shell/hostile.Dockerfile b/parity/java4shell/hostile.Dockerfile new file mode 100644 index 0000000..f4580ab --- /dev/null +++ b/parity/java4shell/hostile.Dockerfile @@ -0,0 +1,12 @@ +# Hostile inputs: a real unfixed VM library under a forged release file that +# claims the fix, another under a 200 KiB release file, a text file named +# libjvm.so, symbolic link loops and a self-referencing directory link. +FROM eclipse-temurin:21.0.13_9-jre AS jre +FROM debian:12-slim +COPY --from=jre /opt/java/openjdk/lib/server/libjvm.so /opt/forged/lib/server/libjvm.so +COPY --from=jre /opt/java/openjdk/lib/server/libjvm.so /opt/huge/lib/server/libjvm.so +RUN printf 'JAVA_VERSION="21.0.13.1"\nJAVA_RUNTIME_VERSION="21.0.13.1+2-LTS"\nIMPLEMENTOR="Forged"\nOS_ARCH="aarch64"\n' > /opt/forged/release \ + && (printf 'JAVA_VERSION="21.0.13.1"\n'; head -c 204800 /dev/zero | tr '\0' '#') > /opt/huge/release \ + && mkdir -p /opt/fake/lib/server && echo 'not a library' > /opt/fake/lib/server/libjvm.so \ + && ln -s loop2 /opt/loop1 && ln -s loop1 /opt/loop2 && ln -s . /opt/forged/lib/self \ + && ln -s /opt/forged /opt/forged/lib/server/up diff --git a/parity/java4shell/jlink.Dockerfile b/parity/java4shell/jlink.Dockerfile new file mode 100644 index 0000000..98c04ef --- /dev/null +++ b/parity/java4shell/jlink.Dockerfile @@ -0,0 +1,6 @@ +# A custom runtime made with jlink from Temurin 21.0.13 (unfixed): its +# release file keeps only JAVA_VERSION and MODULES. +FROM eclipse-temurin:21.0.13_9-jdk AS build +RUN jlink --add-modules java.base,java.logging --strip-debug --no-header-files --no-man-pages --output /rt +FROM debian:12-slim +COPY --from=build /rt /app/runtime diff --git a/parity/java4shell/mitigated-env.Dockerfile b/parity/java4shell/mitigated-env.Dockerfile new file mode 100644 index 0000000..df17e9f --- /dev/null +++ b/parity/java4shell/mitigated-env.Dockerfile @@ -0,0 +1,3 @@ +# Unfixed Temurin 21 with the mitigation in the image's JAVA_TOOL_OPTIONS. +FROM eclipse-temurin:21.0.13_9-jre +ENV JAVA_TOOL_OPTIONS="-Xss1m -XX:-UseBASE64Intrinsics" diff --git a/parity/java4shell/mitigated-useavx.Dockerfile b/parity/java4shell/mitigated-useavx.Dockerfile new file mode 100644 index 0000000..98dc2de --- /dev/null +++ b/parity/java4shell/mitigated-useavx.Dockerfile @@ -0,0 +1,3 @@ +# Unfixed Temurin 25 with AVX-512 turned off through JDK_JAVA_OPTIONS. +FROM eclipse-temurin:25.0.5_8-jre +ENV JDK_JAVA_OPTIONS="-XX:UseAVX=2" diff --git a/parity/java4shell/reenabled.Dockerfile b/parity/java4shell/reenabled.Dockerfile new file mode 100644 index 0000000..97381d1 --- /dev/null +++ b/parity/java4shell/reenabled.Dockerfile @@ -0,0 +1,3 @@ +# The mitigation in JAVA_TOOL_OPTIONS, undone by _JAVA_OPTIONS (applied last). +FROM eclipse-temurin:21.0.13_9-jre +ENV JAVA_TOOL_OPTIONS="-XX:-UseBASE64Intrinsics" _JAVA_OPTIONS="-XX:+UseBASE64Intrinsics" diff --git a/parity/java4shell/repo/.github/workflows/ci.yml b/parity/java4shell/repo/.github/workflows/ci.yml new file mode 100644 index 0000000..e23b6d6 --- /dev/null +++ b/parity/java4shell/repo/.github/workflows/ci.yml @@ -0,0 +1,12 @@ +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/setup-java@v4 + with: + distribution: corretto + java-version: "21.0.5" + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "24" diff --git a/parity/java4shell/repo/.java-version b/parity/java4shell/repo/.java-version new file mode 100644 index 0000000..baf3ee0 --- /dev/null +++ b/parity/java4shell/repo/.java-version @@ -0,0 +1 @@ +21.0.5 diff --git a/parity/java4shell/repo/.sdkmanrc b/parity/java4shell/repo/.sdkmanrc new file mode 100644 index 0000000..ae4f91d --- /dev/null +++ b/parity/java4shell/repo/.sdkmanrc @@ -0,0 +1 @@ +java=25.0.1-tem diff --git a/parity/java4shell/repo/.tool-versions b/parity/java4shell/repo/.tool-versions new file mode 100644 index 0000000..c7b1771 --- /dev/null +++ b/parity/java4shell/repo/.tool-versions @@ -0,0 +1 @@ +java corretto-21.0.13.1.2 diff --git a/parity/java4shell/repo/Dockerfile b/parity/java4shell/repo/Dockerfile new file mode 100644 index 0000000..63f8afc --- /dev/null +++ b/parity/java4shell/repo/Dockerfile @@ -0,0 +1,3 @@ +FROM eclipse-temurin:21.0.13_9-jre-alpine +COPY app.jar /app.jar +CMD ["java", "-jar", "/app.jar"] diff --git a/parity/java4shell/repo/Dockerfile.pkg b/parity/java4shell/repo/Dockerfile.pkg new file mode 100644 index 0000000..635701f --- /dev/null +++ b/parity/java4shell/repo/Dockerfile.pkg @@ -0,0 +1,3 @@ +FROM ubuntu:24.04 +RUN apt-get update && apt-get install -y --no-install-recommends openjdk-21-jre-headless +ENV JAVA_TOOL_OPTIONS="-XX:-UseBASE64Intrinsics" diff --git a/parity/java4shell/repo/build.gradle.kts b/parity/java4shell/repo/build.gradle.kts new file mode 100644 index 0000000..10dd10b --- /dev/null +++ b/parity/java4shell/repo/build.gradle.kts @@ -0,0 +1,8 @@ +java { + toolchain { + languageVersion = JavaLanguageVersion.of(23) + } +} +jib { + from { image = "eclipse-temurin:17.0.21_9-jre" } +} diff --git a/parity/java4shell/repo/compose.yaml b/parity/java4shell/repo/compose.yaml new file mode 100644 index 0000000..735bb57 --- /dev/null +++ b/parity/java4shell/repo/compose.yaml @@ -0,0 +1,13 @@ +services: + api: + image: amazoncorretto:21.0.12-al2023 + worker: + image: amazoncorretto:21.0.12-al2023 + environment: + JAVA_TOOL_OPTIONS: "-XX:UseAVX=2" + old: + image: eclipse-temurin:17.0.5_8-jre + j9: + image: ibm-semeru-runtimes:open-21-jre + latest: + image: eclipse-temurin:21-jre diff --git a/parity/java4shell/repo/k8s/deployment.yaml b/parity/java4shell/repo/k8s/deployment.yaml new file mode 100644 index 0000000..f0dd9b8 --- /dev/null +++ b/parity/java4shell/repo/k8s/deployment.yaml @@ -0,0 +1,10 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: app +spec: + template: + spec: + containers: + - name: app + image: bellsoft/liberica-openjre-debian:21.0.13-9 diff --git a/parity/java4shell/sapmachine-fixed.Dockerfile b/parity/java4shell/sapmachine-fixed.Dockerfile new file mode 100644 index 0000000..ec84ca3 --- /dev/null +++ b/parity/java4shell/sapmachine-fixed.Dockerfile @@ -0,0 +1,6 @@ +# SapMachine 21.0.13.1, the first 21 release with the Java4Shell fix +# (released 2026-11-17), unpacked from its GitHub release tarball. +FROM debian:12-slim +ADD --checksum=sha256:6cb4df182dc9efd3cd37722517832e402cd1beed4f7e3d4d9b58abeb3e949ae9 \ + https://github.com/SAP/SapMachine/releases/download/sapmachine-21.0.13.1/sapmachine-jre-21.0.13.1_linux-x64_bin.tar.gz /tmp/sap.tgz +RUN mkdir -p /opt/sapmachine && tar xzf /tmp/sap.tgz -C /opt/sapmachine --strip-components=1 && rm /tmp/sap.tgz diff --git a/parity/java4shell/tomcat.Dockerfile b/parity/java4shell/tomcat.Dockerfile new file mode 100644 index 0000000..cb95f34 --- /dev/null +++ b/parity/java4shell/tomcat.Dockerfile @@ -0,0 +1,3 @@ +# Tomcat's own image runs catalina.sh, which passes CATALINA_OPTS on. +FROM tomcat:10.1-jre21-temurin +ENV CATALINA_OPTS="-XX:-UseBASE64Intrinsics" diff --git a/parity/java4shell/ubuntu-pkg.Dockerfile b/parity/java4shell/ubuntu-pkg.Dockerfile new file mode 100644 index 0000000..0f19884 --- /dev/null +++ b/parity/java4shell/ubuntu-pkg.Dockerfile @@ -0,0 +1,3 @@ +# Ubuntu 24.04's openjdk-25 package (25.0.5.0.3+1-3~24.04.1: no fix yet). +FROM ubuntu:24.04 +RUN apt-get update && apt-get install -y --no-install-recommends openjdk-25-jre-headless && rm -rf /var/lib/apt/lists/* From f8f171f025627b8ff78eb88262b4a07324a49fc9 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Tue, 17 Nov 2026 23:35:05 +0000 Subject: [PATCH 007/119] java4shell: Tomcat setenv.sh covers the JVM catalina.sh starts A setenv.sh configures the JVM its start script launches (JAVA_HOME or JRE_HOME, or java on PATH), not only runtimes inside the product directory, when the container's command runs that script. The parity runner can rerun named cases and update only their rows, since Docker Hub's anonymous pull limit can stop a full run part way: 34/34 match. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- .../java4shell/internal/assess/assess.go | 50 ++++++++++++++++++- .../java4shell/internal/assess/assess_test.go | 17 +++++++ parity/JAVA4SHELL-RESULTS.md | 3 +- parity/java4shell.py | 35 +++++++++---- parity/java4shell/cases.json | 15 ++++++ parity/java4shell/tomcat-setenv.Dockerfile | 4 ++ 7 files changed, 111 insertions(+), 15 deletions(-) create mode 100644 parity/java4shell/tomcat-setenv.Dockerfile diff --git a/README.md b/README.md index a0b5f43..0fb7301 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ Every port must give exactly the verdicts of the scanner it came from before it - `parity/brotli.py` has no standalone scanner to compare with, so it checks every decoder in 38 images against the vendor's own fix status: Node.js, .NET, Bun, Envoy and curl images before and after their October 2026 releases, distribution packages pinned to their exact unfixed and backported builds, and the Python wheels ([BROTLI-RESULTS.md](parity/BROTLI-RESULTS.md)). - `parity/brotli_files.py` checks 73 release binaries and packages, unpacked and never run: Node.js, .NET and Bun for Windows and macOS, seven Electron releases, Envoy and Istio, and the packages that bundle the decoder ([BROTLI-FILES-RESULTS.md](parity/BROTLI-FILES-RESULTS.md)). A WebAssembly build of the decoder is the one case it cannot settle: it is reported as unknown. - `parity/sshole.py` builds ten images from `parity/sshole/` (Alpine with the unfixed and the fixed package, password logins off, UsePAM on, root with PermitRootLogin, a Match on address, the current Alpine release, Debian, an entrypoint that turns password logins on at start, and `sshd -o` in the image command) and checks each verdict against the expected one ([SSHOLE-RESULTS.md](parity/SSHOLE-RESULTS.md)). The expected verdicts come from the upstream fix, musl's crypt and shadow code, and the Alpine package that shipped it. -- `parity/java4shell.py` checks 33 cases against verdicts taken from [FACTS.md](detectors/java4shell/FACTS.md): Temurin 8, 11, 17.0.5, 17.0.6, 17.0.21 (Alpine), 18, 20, 21 (also arm64, every platform, UBI 9), 25 and 27, Corretto (an Amazon Linux rpm and Alpine), Zulu, Liberica, SapMachine, Semeru, Elasticsearch's bundled JDK, the fixed SapMachine 21.0.13.1, a jlink image, bundled product runtimes with and without `setenv.sh`, Alpine, Debian and Ubuntu packages, environment and Tomcat mitigations and one that is undone, hostile release files and symlink loops, a filesystem scan and an offline source tree ([JAVA4SHELL-RESULTS.md](parity/JAVA4SHELL-RESULTS.md)). +- `parity/java4shell.py` checks 34 cases against verdicts taken from [FACTS.md](detectors/java4shell/FACTS.md): Temurin 8, 11, 17.0.5, 17.0.6, 17.0.21 (Alpine), 18, 20, 21 (also arm64, every platform, UBI 9), 25 and 27, Corretto (an Amazon Linux rpm and Alpine), Zulu, Liberica, SapMachine, Semeru, Elasticsearch's bundled JDK, the fixed SapMachine 21.0.13.1, a jlink image, bundled product runtimes with and without `setenv.sh`, Alpine, Debian and Ubuntu packages, environment, Tomcat CATALINA_OPTS and setenv.sh mitigations and one that is undone, hostile release files and symlink loops, a filesystem scan and an offline source tree ([JAVA4SHELL-RESULTS.md](parity/JAVA4SHELL-RESULTS.md)). - `parity/php.py` runs php2shell-scan, this repo's php2shell-scan and Early Light over php2shell-scan's validation matrix: official images, distribution packages, source builds and hostile images. Each finding's complete record is compared field by field. It also covers filesystem scans at and below a system root, repository scans, `fix --dry-run`, and every detector at once ([PHP-RESULTS.md](parity/PHP-RESULTS.md)). ## Adding a detector diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index a08f9df..8f58cc1 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -321,10 +321,12 @@ func mitigation(in Input, env map[string]string, root string, feature int, f *Fi } } for _, s := range in.Settings { - if s.Kind == "systemd" || s.Scope == "" || !within(root, s.Scope) { + if s.Kind == "systemd" || s.Scope == "" { continue } - s.ApplyTo(&o, feature) + if within(root, s.Scope) || in.Env != nil && launches(in, env, s) && javaHomeIs(in, env, root) { + s.ApplyTo(&o, feature) + } } if in.Env != nil { if v, ok := env["_JAVA_OPTIONS"]; ok { @@ -385,6 +387,50 @@ func commandRuns(in Input, env map[string]string, root string) bool { return false } +// launches reports whether the container's command starts the product a +// settings file configures: its own start script, or catalina.sh of the +// CATALINA_HOME or CATALINA_BASE it sits in. +func launches(in Input, env map[string]string, s jvm.Setting) bool { + for _, w := range in.Command { + if !strings.Contains(w, "/") { + if path.Base(w) == "catalina.sh" && (env["CATALINA_HOME"] == s.Scope || env["CATALINA_BASE"] == s.Scope) { + return true + } + continue + } + p := w + if in.Resolve != nil { + p = in.Resolve(w) + } + if within(p, s.Scope) { + return true + } + } + return false +} + +// javaHomeIs reports whether a start script would run this runtime: the +// one JAVA_HOME or JRE_HOME names, or without them the java on PATH. +func javaHomeIs(in Input, env map[string]string, root string) bool { + res := func(p string) string { + if in.Resolve != nil { + return in.Resolve(p) + } + return p + } + for _, k := range []string{"JRE_HOME", "JAVA_HOME"} { + if h := strings.TrimSuffix(env[k], "/"); h != "" { + return h == root || res(h) == res(root) + } + } + for _, d := range strings.Split(env["PATH"], ":") { + if d != "" && res(d+"/java") == res(root+"/bin/java") { + return true + } + } + return false +} + // scriptVarsOf lists the script variables the container's command passes // on: catalina.sh passes CATALINA_OPTS and JAVA_OPTS, and a startup script // passes the ones it names. diff --git a/detectors/java4shell/internal/assess/assess_test.go b/detectors/java4shell/internal/assess/assess_test.go index 9179e2a..9cd5f1b 100644 --- a/detectors/java4shell/internal/assess/assess_test.go +++ b/detectors/java4shell/internal/assess/assess_test.go @@ -228,6 +228,23 @@ func TestMitigations(t *testing.T) { } } + // Tomcat's setenv.sh covers the JVM catalina.sh starts (JAVA_HOME), when + // the container runs it. + tset, _ := jvm.ReadSetting("/usr/local/tomcat/bin/setenv.sh", []byte(`CATALINA_OPTS="$CATALINA_OPTS -XX:-UseBASE64Intrinsics"`)) + in = Input{Libraries: []*jvm.Library{vulnLib(t, temurin)}, Settings: []jvm.Setting{tset}, + Env: []string{"CATALINA_HOME=/usr/local/tomcat", "JAVA_HOME=/opt/java/openjdk"}, Command: []string{"catalina.sh", "run"}} + if f := one(t, in); f.Status != Mitigated || !strings.Contains(f.Reason, "setenv.sh") { + t.Errorf("tomcat setenv.sh: %+v", f) + } + in.Command = []string{"java", "-jar", "/app.jar"} + if f := one(t, in); f.Status != Vulnerable { + t.Errorf("tomcat setenv.sh without catalina.sh: %+v", f) + } + in.Command, in.Env = []string{"catalina.sh", "run"}, []string{"CATALINA_HOME=/usr/local/tomcat", "JAVA_HOME=/usr/lib/jvm/other"} + if f := one(t, in); f.Status != Vulnerable { + t.Errorf("tomcat setenv.sh for another JAVA_HOME: %+v", f) + } + // A systemd unit covers a bundled runtime of the product it starts; // for a shared runtime it is recorded, not counted. unit, _ := jvm.ReadSetting("/etc/systemd/system/jira.service", []byte("Environment=JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics\nExecStart=/opt/atlassian/jira/bin/start-jira.sh -fg\n")) diff --git a/parity/JAVA4SHELL-RESULTS.md b/parity/JAVA4SHELL-RESULTS.md index c486be7..5e623cd 100644 --- a/parity/JAVA4SHELL-RESULTS.md +++ b/parity/JAVA4SHELL-RESULTS.md @@ -34,8 +34,9 @@ Generated by `parity/java4shell.py`. Each row's expected findings come from [FAC | mitigated-useavx | Temurin 25.0.5 with ENV JDK_JAVA_OPTIONS=-XX:UseAVX=2 | pass | linux/amd64 /opt/java/openjdk runtime inactive mitigated | | reenabled | JAVA_TOOL_OPTIONS mitigation undone by _JAVA_OPTIONS | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | | tomcat | Tomcat 10.1 on Temurin 21 with CATALINA_OPTS=-XX:-UseBASE64Intrinsics (catalina.sh passes it on) | pass | linux/amd64 /opt/java/openjdk runtime inactive mitigated | +| tomcat-setenv | Tomcat 10.1 on Temurin 21 with -XX:-UseBASE64Intrinsics in bin/setenv.sh (catalina.sh starts JAVA_HOME's JVM) | pass | linux/amd64 /opt/java/openjdk runtime inactive mitigated | | hostile | Forged and 200 KiB release files over an unfixed VM library, a text file named libjvm.so, symlink loops | pass | linux/amd64 /opt/forged runtime vulnerable vulnerable
linux/amd64 /opt/huge runtime vulnerable vulnerable | | debian-pkg-fs | The debian-pkg image exported and scanned as a filesystem | pass | fs /usr/lib/jvm/java-17-openjdk-amd64 runtime vulnerable vulnerable | | repo | Source tree, offline: Dockerfiles, Compose, Kubernetes, setup-java, version files, Gradle | pass | .github/workflows/ci.yml:12 java-line vulnerable
.github/workflows/ci.yml:8 java-pin vulnerable
.java-version:1 java-pin vulnerable
.sdkmanrc:1 java-pin vulnerable
Dockerfile.pkg:2 os-package inactive
Dockerfile:1 image-pin vulnerable
build.gradle.kts:3 java-line vulnerable
build.gradle.kts:7 image-pin vulnerable
compose.yaml:13 not-checked unknown
compose.yaml:3 image-pin vulnerable
compose.yaml:5 image-pin inactive
k8s/deployment.yaml:10 image-pin vulnerable | -33/33 cases match. +34/34 cases match. diff --git a/parity/java4shell.py b/parity/java4shell.py index 12c37ac..716316e 100644 --- a/parity/java4shell.py +++ b/parity/java4shell.py @@ -3,6 +3,9 @@ usage: python3 parity/java4shell.py path/to/earlylight [case ...] +With case names, only those run and only their rows of the results file +change. + Needs Docker and registry access. Cases are in parity/java4shell/cases.json: published images (scanned from the registry by tag, the digest recorded), images built from parity/java4shell/*.Dockerfile (scanned from `docker save` @@ -108,20 +111,30 @@ def main(): failed += not ok results.append((c, ok, got, want, digests)) print(("pass " if ok else "FAIL ") + c["name"], flush=True) - if only: - sys.exit(1 if failed else 0) - with open(os.path.join(HERE, "JAVA4SHELL-RESULTS.md"), "w") as f: + # Named cases update their own rows and keep the others' (a registry's + # pull limit can stop a full run part way). + path = os.path.join(HERE, "JAVA4SHELL-RESULTS.md") + lines = {} + if only and os.path.exists(path): + for l in open(path): + if l.startswith("| ") and not l.startswith("| Case") and not l.startswith("| ---"): + lines[l.split(" | ")[0][2:]] = l + for c, ok, got, want, digests in results: + cell = "
".join(" ".join(str(x) for x in g if x) for g in sorted(got)) or "none" + what = c["what"] + if c.get("ref"): + what += "
`" + c["ref"] + "`" + "".join("
" + d for d in digests) + lines[c["name"]] = f"| {c['name']} | {what} | {'pass' if ok else 'FAIL (want ' + json.dumps(want) + ')'} | {cell} |\n" + order = [c["name"] for c in cases if c["name"] in lines] + passed = sum(1 for n in order if lines[n].split(" | ")[2] == "pass") + with open(path, "w") as f: f.write("# Java4Shell fixture results\n\nGenerated by `parity/java4shell.py`. Each row's expected findings come from " "[FACTS.md](../detectors/java4shell/FACTS.md). Registry images are scanned by tag; the digest scanned is listed.\n\n" "| Case | What | Result | Findings (platform, path, kind, verdict, status) |\n| --- | --- | --- | --- |\n") - for c, ok, got, want, digests in results: - cell = "
".join(" ".join(str(x) for x in g if x) for g in sorted(got)) or "none" - what = c["what"] - if c.get("ref"): - what += "
`" + c["ref"] + "`" + "".join("
" + d for d in digests) - f.write(f"| {c['name']} | {what} | {'pass' if ok else 'FAIL (want ' + json.dumps(want) + ')'} | {cell} |\n") - f.write(f"\n{len(results) - failed}/{len(results)} cases match.\n") - print(f"{len(results) - failed}/{len(results)} cases match") + for n in order: + f.write(lines[n]) + f.write(f"\n{passed}/{len(order)} cases match.\n") + print(f"{passed}/{len(order)} cases match") sys.exit(1 if failed else 0) diff --git a/parity/java4shell/cases.json b/parity/java4shell/cases.json index b3a53ae..0332fc7 100644 --- a/parity/java4shell/cases.json +++ b/parity/java4shell/cases.json @@ -493,6 +493,21 @@ ] ] }, + { + "name": "tomcat-setenv", + "what": "Tomcat 10.1 on Temurin 21 with -XX:-UseBASE64Intrinsics in bin/setenv.sh (catalina.sh starts JAVA_HOME's JVM)", + "mode": "build", + "dockerfile": "tomcat-setenv.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "inactive", + "mitigated" + ] + ] + }, { "name": "hostile", "what": "Forged and 200 KiB release files over an unfixed VM library, a text file named libjvm.so, symlink loops", diff --git a/parity/java4shell/tomcat-setenv.Dockerfile b/parity/java4shell/tomcat-setenv.Dockerfile new file mode 100644 index 0000000..406304f --- /dev/null +++ b/parity/java4shell/tomcat-setenv.Dockerfile @@ -0,0 +1,4 @@ +# Tomcat's own image with the mitigation in bin/setenv.sh, which catalina.sh +# reads before it starts the JVM that JAVA_HOME names. +FROM tomcat:10.1-jre21-temurin +RUN echo 'CATALINA_OPTS="$CATALINA_OPTS -XX:-UseBASE64Intrinsics"' > /usr/local/tomcat/bin/setenv.sh From 2b2e44fa0f5fc64ffa06f2737cc626d0da477879 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Tue, 17 Nov 2026 23:46:43 +0000 Subject: [PATCH 008/119] java4shell: fixes from an independent review - Corretto versions with its build number in the fourth place (21.0.13.11) are no longer judged fixed: CorrettoJava reads them, and Judge reports any fourth number above 3 as unknown - a Dockerfile stage's mitigation is decided from the last ENV of each variable, so a later _JAVA_OPTIONS or JAVA_TOOL_OPTIONS undoes it - CATALINA_OPTS and other script variables cover only the JVM the script starts (JAVA_HOME, JRE_HOME or PATH) - systemd: only JVM-read variables count, HotSpot's order applies (_JAVA_OPTIONS last), and unit files and drop-ins are merged by systemd's precedence before judging - settings files in general directories (/etc, /usr/local, /opt) and product directories of /opt, /app or /usr are refused as scopes - shell comments in setenv.sh are ignored - the VM version line is searched only around " JRE (", so large printable files cannot make the regex scan from every position - setup-java early-access versions are not judged; the fixed tag with the lowest build is chosen numerically Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/assess/assess.go | 9 +- .../java4shell/internal/assess/assess_test.go | 2 +- .../java4shell/internal/assess/product.go | 24 ++- .../java4shell/internal/assess/review_test.go | 96 +++++++++++ detectors/java4shell/internal/jvm/jvm.go | 24 ++- detectors/java4shell/internal/jvm/jvm_test.go | 14 ++ detectors/java4shell/internal/jvm/settings.go | 152 ++++++++++++++++-- .../internal/knowledge/knowledge.go | 10 ++ .../internal/knowledge/knowledge_test.go | 1 + detectors/java4shell/internal/repo/images.go | 5 + detectors/java4shell/internal/repo/plan.go | 10 +- detectors/java4shell/internal/repo/repo.go | 65 +++++--- .../java4shell/internal/repo/review_test.go | 56 +++++++ 13 files changed, 417 insertions(+), 51 deletions(-) create mode 100644 detectors/java4shell/internal/assess/review_test.go create mode 100644 detectors/java4shell/internal/repo/review_test.go diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index 8f58cc1..b380a61 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -308,9 +308,11 @@ func mitigation(in Input, env map[string]string, root string, feature int, f *Fi o.Apply(v, "the image's JDK_JAVA_OPTIONS") } // Script variables count when the container's command passes them on. + // They reach only the JVM the script starts: the one JAVA_HOME or + // JRE_HOME names, or the java on PATH. vars := scriptVarsOf(in) for _, n := range jvm.ScriptVars { - if v, ok := env[n]; ok && vars[n] { + if v, ok := env[n]; ok && vars[n] && javaHomeIs(in, env, root) { o.Apply(v, "the image's "+n+" (passed on by the container's start script)") } } @@ -338,10 +340,7 @@ func mitigation(in Input, env map[string]string, root string, feature int, f *Fi } // systemd units: they cover the service, and the runtime only when it // is bundled in the product the service starts. - for _, s := range in.Settings { - if s.Kind != "systemd" { - continue - } + for _, s := range jvm.MergeUnits(in.Settings) { so := s.Options(feature) ok, how := so.Mitigates() if !ok || s.Exec == "" { diff --git a/detectors/java4shell/internal/assess/assess_test.go b/detectors/java4shell/internal/assess/assess_test.go index 9cd5f1b..ccae267 100644 --- a/detectors/java4shell/internal/assess/assess_test.go +++ b/detectors/java4shell/internal/assess/assess_test.go @@ -204,7 +204,7 @@ func TestMitigations(t *testing.T) { // CATALINA_OPTS counts when the container runs catalina.sh. in = base() - in.Env = []string{"CATALINA_OPTS=-XX:-UseBASE64Intrinsics"} + in.Env = []string{"CATALINA_OPTS=-XX:-UseBASE64Intrinsics", "JAVA_HOME=/opt/java/openjdk"} if f := one(t, in); f.Status != Vulnerable { t.Errorf("CATALINA_OPTS without catalina.sh: %+v", f) } diff --git a/detectors/java4shell/internal/assess/product.go b/detectors/java4shell/internal/assess/product.go index f63b7ec..ea75b38 100644 --- a/detectors/java4shell/internal/assess/product.go +++ b/detectors/java4shell/internal/assess/product.go @@ -37,6 +37,11 @@ var products = []struct{ part, name string }{ {"/cassandra", "Apache Cassandra"}, {"/neo4j", "Neo4j"}, {"/gitbucket", "GitBucket"}, {"/rundeck", "Rundeck"}, } +// notProduct are directories too general to be a product's install +// directory. +var notProduct = map[string]bool{"/": true, "/opt": true, "/usr": true, "/usr/local": true, "/usr/share": true, "/usr/lib": true, + "/srv": true, "/home": true, "/root": true, "/app": true, "/var": true, "/var/lib": true, "/Applications": true, "C:/Program Files": true} + // standard reports a runtime installed on its own. func standard(root string) bool { for _, p := range standardPlaces { @@ -55,9 +60,7 @@ func Product(root string) (name, dir string, ok bool) { } dir = root // A macOS runtime: .app/Contents/jbr/Contents/Home. - if strings.HasSuffix(dir, "/Contents/Home") { - dir = strings.TrimSuffix(dir, "/Contents/Home") - } + dir = strings.TrimSuffix(dir, "/Contents/Home") if !runtimeDirs[path.Base(dir)] { // Products also nest it one level deeper (lib/runtime/jre, // app/third-party/java/). @@ -68,10 +71,19 @@ func Product(root string) (name, dir string, ok bool) { dir = path.Dir(dir) } dir = path.Dir(dir) - for _, x := range []string{"/third-party", "/app", "/lib", "/Contents"} { - dir = strings.TrimSuffix(dir, x) + // Only the layouts that put the runtime below such a directory. + if path.Base(dir) == "third-party" { + dir = path.Dir(dir) + if path.Base(dir) == "app" { + dir = path.Dir(dir) + } + } + if b := path.Base(dir); b == "Contents" && strings.HasSuffix(path.Dir(dir), ".app") { + dir = path.Dir(dir) } - if dir == "/" || dir == "." || dir == "" { + if notProduct[dir] || strings.Count(dir, "/") < 2 && !strings.Contains(dir, ":") { + // /opt/jre, /app/jre, /usr/jre: a runtime in a general directory, + // not part of a product. return "", "", false } for _, p := range products { diff --git a/detectors/java4shell/internal/assess/review_test.go b/detectors/java4shell/internal/assess/review_test.go new file mode 100644 index 0000000..f1905b7 --- /dev/null +++ b/detectors/java4shell/internal/assess/review_test.go @@ -0,0 +1,96 @@ +package assess + +import ( + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" +) + +// Regressions from the independent review: mitigations that covered more +// than they do. +func TestReviewMitigationScope(t *testing.T) { + setting := func(p, text string) jvm.Setting { + t.Helper() + s, ok := jvm.ReadSetting(p, []byte(text)) + if !ok { + t.Fatalf("%s not read", p) + } + return s + } + status := func(in Input, root string) Status { + t.Helper() + for _, f := range Run(in) { + if f.Path == root { + return f.Status + } + } + t.Fatalf("no finding for %s", root) + return "" + } + + // catalina.sh passes CATALINA_OPTS only to the JVM JAVA_HOME names. + in := Input{Libraries: []*jvm.Library{vulnLib(t, temurin), vulnLib(t, "/opt/other/jre")}, + Env: []string{"CATALINA_OPTS=-XX:-UseBASE64Intrinsics", "JAVA_HOME=/opt/java/openjdk"}, Command: []string{"catalina.sh", "run"}} + if status(in, temurin) != Mitigated || status(in, "/opt/other/jre") != Vulnerable { + t.Error("CATALINA_OPTS covered a runtime catalina.sh does not start") + } + + // systemd: JAVA_OPTS does not reach a java ExecStart. + unit := setting("/etc/systemd/system/a.service", "Environment=JAVA_OPTS=-XX:-UseBASE64Intrinsics\nExecStart=/opt/acme/jre/bin/java -jar /opt/acme/a.jar\n") + in = Input{Libraries: []*jvm.Library{vulnLib(t, "/opt/acme/jre")}, Settings: []jvm.Setting{unit}} + if s := status(in, "/opt/acme/jre"); s != Vulnerable { + t.Errorf("JAVA_OPTS with a java ExecStart: %s", s) + } + // _JAVA_OPTIONS overrides the command line, wherever it is written. + unit = setting("/etc/systemd/system/a.service", "Environment=_JAVA_OPTIONS=-XX:+UseBASE64Intrinsics\nExecStart=/opt/acme/jre/bin/java -XX:-UseBASE64Intrinsics -jar /opt/acme/a.jar\n") + in.Settings = []jvm.Setting{unit} + if s := status(in, "/opt/acme/jre"); s != Vulnerable { + t.Errorf("_JAVA_OPTIONS in a unit: %s", s) + } + // A drop-in that resets JAVA_TOOL_OPTIONS undoes the unit's mitigation. + base := setting("/usr/lib/systemd/system/a.service", "Environment=JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics\nExecStart=/opt/acme/bin/run.sh\n") + drop := setting("/etc/systemd/system/a.service.d/override.conf", "[Service]\nEnvironment=JAVA_TOOL_OPTIONS=-Xmx1g\n") + in.Settings = []jvm.Setting{base, drop} + if s := status(in, "/opt/acme/jre"); s != Vulnerable { + t.Errorf("drop-in reset: %s", s) + } + in.Settings = []jvm.Setting{base} + if s := status(in, "/opt/acme/jre"); s != Mitigated { + t.Errorf("unit without the drop-in: %s", s) + } + // A full unit in /etc replaces the one in /usr/lib. + over := setting("/etc/systemd/system/a.service", "ExecStart=/opt/acme/bin/run.sh\n") + in.Settings = []jvm.Setting{base, over} + if s := status(in, "/opt/acme/jre"); s != Vulnerable { + t.Errorf("/etc override: %s", s) + } + + // /opt/app/jre belongs to /opt/app, never to /opt. + if name, dir, ok := Product("/opt/app/jre"); ok && dir != "/opt/app" { + t.Errorf("Product(/opt/app/jre) = %q %q", name, dir) + } + if _, _, ok := Product("/opt/jre"); ok { + t.Error("/opt/jre taken for a product in /opt") + } + other := setting("/etc/systemd/system/other.service", "Environment=JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics\nExecStart=/opt/other/bin/run.sh\n") + in = Input{Libraries: []*jvm.Library{vulnLib(t, "/opt/app/jre")}, Settings: []jvm.Setting{other}} + if s := status(in, "/opt/app/jre"); s != Vulnerable { + t.Errorf("another service's unit: %s", s) + } + + // Settings files in general directories configure nothing by place. + for _, p := range []string{"/etc/jvm.options", "/usr/local/bin/setenv.sh", "/opt/bin/setenv.sh"} { + s := setting(p, "-XX:-UseBASE64Intrinsics\nX=\"-XX:-UseBASE64Intrinsics\"\n") + in = Input{Libraries: []*jvm.Library{vulnLib(t, "/usr/local/openjdk-21")}, Settings: []jvm.Setting{s}} + if st := status(in, "/usr/local/openjdk-21"); st != Vulnerable { + t.Errorf("%s covered a runtime outside its product: %s", p, st) + } + } + + // A commented-out option is not set. + s := setting("/opt/atlassian/jira/bin/setenv.sh", "JVM_SUPPORT_RECOMMENDED_ARGS=\"-Xmx2g\" # was: -XX:-UseBASE64Intrinsics\n") + in = Input{Libraries: []*jvm.Library{vulnLib(t, "/opt/atlassian/jira/jre")}, Settings: []jvm.Setting{s}} + if st := status(in, "/opt/atlassian/jira/jre"); st != Vulnerable { + t.Errorf("commented option: %s", st) + } +} diff --git a/detectors/java4shell/internal/jvm/jvm.go b/detectors/java4shell/internal/jvm/jvm.go index b063c8b..61a29b3 100644 --- a/detectors/java4shell/internal/jvm/jvm.go +++ b/detectors/java4shell/internal/jvm/jvm.go @@ -102,7 +102,7 @@ func Inspect(p string, data []byte) (*Library, bool) { if len(b) > maxScan { b = b[:maxScan] } - if m := vmLine.FindSubmatch(b); m != nil { + if m := findVMLine(b); m != nil { l.VMName, l.VMVersion, l.JREVersion = string(m[1]), string(m[2]), string(m[5]) l.Platform = string(m[3]) + "-" + string(m[4]) } @@ -113,6 +113,28 @@ func Inspect(p string, data []byte) (*Library, bool) { return l, true } +// findVMLine looks for the version line only around the literal " JRE (", +// so a large file of printable text cannot make the regular expression +// scan it all from every position. +func findVMLine(b []byte) [][]byte { + const before, after, maxHits = 260, 100, 4096 + anchor := []byte(" JRE (") + off := 0 + for hits := 0; hits < maxHits; hits++ { + i := bytes.Index(b[off:], anchor) + if i < 0 { + return nil + } + at := off + i + lo, hi := max(0, at-before), min(len(b), at+len(anchor)+after) + if m := vmLine.FindSubmatch(b[lo:hi]); m != nil { + return m + } + off = at + len(anchor) + } + return nil +} + // header reads an executable header: the format and the architectures. func header(b []byte) (string, []Arch) { switch { diff --git a/detectors/java4shell/internal/jvm/jvm_test.go b/detectors/java4shell/internal/jvm/jvm_test.go index 6e121b6..9a075ce 100644 --- a/detectors/java4shell/internal/jvm/jvm_test.go +++ b/detectors/java4shell/internal/jvm/jvm_test.go @@ -4,6 +4,7 @@ import ( "bytes" "strings" "testing" + "time" "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" ) @@ -235,3 +236,16 @@ func FuzzSettings(f *testing.F) { JavaOptions(Words(string(b))) }) } + +func TestInspectLargePrintable(t *testing.T) { + // Printable text everywhere used to make the version-line search scan + // from every position. + b := append(testlib.Build(testlib.Lib{}), bytes.Repeat([]byte("VM (1) for a-b JRE x "), (16<<20)/21)...) + start := time.Now() + if l, ok := Inspect("/a/lib/server/libjvm.so", b); !ok || l.JREVersion != "" { + t.Fatalf("%+v", l) + } + if d := time.Since(start); d > 5*time.Second { + t.Errorf("16 MiB of printable text took %s", d) + } +} diff --git a/detectors/java4shell/internal/jvm/settings.go b/detectors/java4shell/internal/jvm/settings.go index ad93594..5d6af84 100644 --- a/detectors/java4shell/internal/jvm/settings.go +++ b/detectors/java4shell/internal/jvm/settings.go @@ -3,6 +3,7 @@ package jvm import ( "path" "regexp" + "sort" "strconv" "strings" ) @@ -20,9 +21,13 @@ type Setting struct { Unit string `json:"unit,omitempty"` // Exec is the program a systemd unit starts. Exec string `json:"exec,omitempty"` - // Env are the JVM option variables a systemd unit sets. - Env map[string]string `json:"env,omitempty"` - lines []optLine + // Env are the JVM option variables a systemd unit sets, and ExecOpts + // the JVM options its ExecStart gives java. + Env map[string]string `json:"env,omitempty"` + ExecOpts []string `json:"exec_options,omitempty"` + // ExecSet is true when the file sets ExecStart (a drop-in may not). + ExecSet bool `json:"-"` + lines []optLine } // optLine is one option, with the Java releases it applies to @@ -40,8 +45,26 @@ func (s Setting) Options(feature int) Options { return o } -// ApplyTo applies the file's options, in order, on top of o. +// ApplyTo applies the file's options, in order, on top of o. For a +// systemd unit the order is HotSpot's: JAVA_TOOL_OPTIONS, JDK_JAVA_OPTIONS, +// the command line, then _JAVA_OPTIONS. func (s Setting) ApplyTo(o *Options, feature int) { + if s.Kind == "systemd" { + env := map[string]string{} + for k, v := range s.Env { + if k != "_JAVA_OPTIONS" { + env[k] = v + } + } + *o = FromEnv(env, nil, feature, nil) + for _, w := range s.ExecOpts { + o.ApplyWord(w, s.File) + } + if v, ok := s.Env["_JAVA_OPTIONS"]; ok { + o.Apply(v, "_JAVA_OPTIONS in "+s.File) + } + return + } for _, l := range s.lines { if feature > 0 && (l.lo > 0 && feature < l.lo || l.hi > 0 && feature > l.hi) { continue @@ -51,7 +74,7 @@ func (s Setting) ApplyTo(o *Options, feature int) { } // Mentions reports whether the file sets either option at all. -func (s Setting) Mentions() bool { return len(s.lines) > 0 } +func (s Setting) Mentions() bool { return len(s.lines) > 0 || len(s.ExecOpts) > 0 || len(s.Env) > 0 } // SettingKind classifies a path, "" when it is not a settings file. func SettingKind(p string) string { @@ -102,7 +125,7 @@ func ReadSetting(p string, b []byte) (Setting, bool) { if path.Base(dir) == "bin" { dir = path.Dir(dir) } - s.Scope = dir + s.Scope = scopeOrNone(dir) case "jvm.options": if path.Base(dir) == "jvm.options.d" { dir = path.Dir(dir) @@ -110,7 +133,7 @@ func ReadSetting(p string, b []byte) (Setting, bool) { if b := path.Base(dir); b == "config" || b == "conf" || b == "etc" { dir = path.Dir(dir) } - s.Scope = dir + s.Scope = scopeOrNone(dir) case "systemd": u := path.Base(p) if strings.HasSuffix(dir, ".service.d") { @@ -142,7 +165,7 @@ func ReadSetting(p string, b []byte) (Setting, bool) { s.lines = append(s.lines, optLine{lo, hi, strings.TrimSpace(line)}) } case "setenv": - for _, w := range xxRE.FindAllString(line, -1) { + for _, w := range xxRE.FindAllString(stripComment(line), -1) { s.lines = append(s.lines, optLine{0, 0, w}) } case "systemd": @@ -152,6 +175,106 @@ func ReadSetting(p string, b []byte) (Setting, bool) { return s, true } +// broadDirs are directories too general to be one product's: a settings +// file there configures no runtime by its place. +var broadDirs = map[string]bool{"/": true, ".": true, "": true, "/usr": true, "/usr/local": true, "/usr/share": true, "/usr/lib": true, + "/opt": true, "/etc": true, "/var": true, "/srv": true, "/home": true, "/root": true, "/app": true, "/usr/local/share": true, "/var/lib": true} + +func scopeOrNone(dir string) string { + if broadDirs[dir] { + return "" + } + return dir +} + +// stripComment drops a shell comment: a "#" that starts a word, outside +// quotes. +func stripComment(line string) string { + var q byte + for i := 0; i < len(line); i++ { + c := line[i] + switch { + case q != 0: + if c == q { + q = 0 + } + case c == '"' || c == '\'': + q = c + case c == '\\': + i++ + case c == '#' && (i == 0 || line[i-1] == ' ' || line[i-1] == '\t' || line[i-1] == ';'): + return line[:i] + } + } + return line +} + +// MergeUnits joins systemd unit files the way systemd does: the unit file +// from the directory with the highest precedence (/etc, then /run, then +// /usr/local/lib, /usr/lib, /lib), then its drop-ins in name order, later +// assignments replacing earlier ones. It returns one setting per unit. +func MergeUnits(settings []Setting) []Setting { + rank := func(p string) int { + for i, d := range []string{"/etc/systemd/system/", "/run/systemd/system/", "/usr/local/lib/systemd/system/", "/usr/lib/systemd/system/", "/lib/systemd/system/"} { + if strings.HasPrefix(p, d) { + return i + } + } + return 9 + } + mains := map[string]Setting{} + drops := map[string][]Setting{} + for _, s := range settings { + if s.Kind != "systemd" { + continue + } + if strings.HasSuffix(path.Dir(s.File), ".service.d") { + drops[s.Unit] = append(drops[s.Unit], s) + continue + } + if m, ok := mains[s.Unit]; !ok || rank(s.File) < rank(m.File) { + mains[s.Unit] = s + } + } + var out []Setting + units := map[string]bool{} + for u := range mains { + units[u] = true + } + for u := range drops { + units[u] = true + } + names := make([]string, 0, len(units)) + for u := range units { + names = append(names, u) + } + sort.Strings(names) + for _, u := range names { + m := mains[u] + merged := Setting{File: m.File, Kind: "systemd", Unit: u, Exec: m.Exec, ExecOpts: m.ExecOpts, ExecSet: m.ExecSet, Env: map[string]string{}} + for k, v := range m.Env { + merged.Env[k] = v + } + ds := drops[u] + sort.SliceStable(ds, func(i, j int) bool { return path.Base(ds[i].File) < path.Base(ds[j].File) }) + for _, d := range ds { + if merged.File == "" { + merged.File = d.File + } else { + merged.File += ", " + d.File + } + for k, v := range d.Env { + merged.Env[k] = v + } + if d.ExecSet { + merged.Exec, merged.ExecOpts, merged.ExecSet = d.Exec, d.ExecOpts, true + } + } + out = append(out, merged) + } + return out +} + func (s *Setting) systemdLine(line string) { k, v, ok := strings.Cut(line, "=") if !ok { @@ -159,32 +282,33 @@ func (s *Setting) systemdLine(line string) { } switch strings.TrimSpace(k) { case "Environment": + // Only the variables the JVM itself reads: a script variable such + // as JAVA_OPTS reaches java only through a start script. for _, a := range Words(v) { name, val, ok := strings.Cut(a, "=") if !ok { continue } - for _, n := range append(append([]string{}, EnvVars...), ScriptVars...) { + for _, n := range EnvVars { if name == n { s.Env[name] = val - for _, w := range xxRE.FindAllString(val, -1) { - s.lines = append(s.lines, optLine{0, 0, w}) - } } } } case "ExecStart": v = strings.TrimSpace(v) + s.ExecSet = true + s.Exec, s.ExecOpts = "", nil v = strings.TrimLeft(v, "-@:+!") ws := Words(v) if len(ws) == 0 { - return + return // "ExecStart=" resets the command } s.Exec = ws[0] if opts, ok := JavaOptions(ws); ok { for _, w := range opts { if xxRE.MatchString(w) { - s.lines = append(s.lines, optLine{0, 0, w}) + s.ExecOpts = append(s.ExecOpts, w) } } } diff --git a/detectors/java4shell/internal/knowledge/knowledge.go b/detectors/java4shell/internal/knowledge/knowledge.go index 611ab0b..e19b184 100644 --- a/detectors/java4shell/internal/knowledge/knowledge.go +++ b/detectors/java4shell/internal/knowledge/knowledge.go @@ -206,6 +206,10 @@ const ( firstVBMIDecode = 17 ) +// maxPatch is the largest fourth version number taken as an OpenJDK patch +// release. +const maxPatch = 3 + // LineOf returns the release line of a feature release. func LineOf(feature int) (Line, bool) { for _, l := range Lines { @@ -257,6 +261,12 @@ func Judge(v Version) (Status, string) { if !ok { return Unknown, fmt.Sprintf("Java %s is not in this detector's release data", ver) } + if len(v.Nums) >= 4 && v.Nums[3] > maxPatch { + // OpenJDK patch numbers are small (17.0.8.1, 21.0.13.1); a larger + // fourth number is a vendor's build number (Amazon Corretto's + // 21.0.13.11), which says nothing about the patch. + return Unknown, fmt.Sprintf("Java %s: the fourth number looks like a vendor build number, not an OpenJDK patch release, so the version does not show whether %s is in", ver, Bug) + } if l.Introduced != nil { c := Compare(v.Nums, l.Introduced) if c < 0 || c == 0 && v.EA && v.Build >= 0 && v.Build < l.IntroducedBuild { diff --git a/detectors/java4shell/internal/knowledge/knowledge_test.go b/detectors/java4shell/internal/knowledge/knowledge_test.go index 7fb32f5..c3212a5 100644 --- a/detectors/java4shell/internal/knowledge/knowledge_test.go +++ b/detectors/java4shell/internal/knowledge/knowledge_test.go @@ -61,6 +61,7 @@ func TestJudge(t *testing.T) { {"21.0.13.0.3+1", Vulnerable}, {"21.0.13.1+2", Fixed}, {"21.0.14+1", Unknown}, + {"21.0.13.11", Unknown}, // Corretto's build number in the fourth place {"24.0.2+12", Vulnerable}, {"25.0.5+8", Vulnerable}, {"25.0.5.1+2", Fixed}, diff --git a/detectors/java4shell/internal/repo/images.go b/detectors/java4shell/internal/repo/images.go index 0490ec7..19b859e 100644 --- a/detectors/java4shell/internal/repo/images.go +++ b/detectors/java4shell/internal/repo/images.go @@ -122,6 +122,11 @@ func (f Family) ParseTag(tag string) (TagVersion, bool) { if tv.Nums[0] < 8 || tv.Nums[0] > 99 { return TagVersion{}, false } + if f.Repo == "amazoncorretto" && len(tv.Nums) >= 4 && tv.Nums[3] > 3 { + // Corretto's own build number in the fourth place: the Java + // version is the first three, exactly. + tv.Nums, tv.Exact = tv.Nums[:3], true + } if f.exact != nil { if b := f.exact.FindString(rest); b != "" { b = strings.TrimSuffix(b, "-") diff --git a/detectors/java4shell/internal/repo/plan.go b/detectors/java4shell/internal/repo/plan.go index a334b61..5057d96 100644 --- a/detectors/java4shell/internal/repo/plan.go +++ b/detectors/java4shell/internal/repo/plan.go @@ -82,11 +82,19 @@ func target(tags []string, e *pinEdit) (string, bool) { if c := knowledge.Compare(cs[i].tv.Nums, cs[j].tv.Nums); c != 0 { return c < 0 } - return cs[i].tv.Build < cs[j].tv.Build + return buildNum(cs[i].tv.Build) < buildNum(cs[j].tv.Build) }) return cs[0].tag, true } +// buildNum is the number in a tag's build part ("_10", "-9"), so _10 sorts +// after _2. +func buildNum(b string) int { + n := 0 + fmt.Sscanf(strings.TrimLeft(b, "_-"), "%d", &n) + return n +} + func planTag(ctx context.Context, root string, f Finding, reg Registry, opts Options) (*Change, error) { e, r := f.edit, f.ref if r == nil { diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 594c425..0103400 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -382,7 +382,11 @@ func (s *scanner) javaVersionFile(rel, text string) { continue } if m := versionInText.FindStringIndex(l); m != nil { - s.judgeVersion(rel, i+1, m[0], l[m[0]:m[1]], ".java-version", vendorWord(l)) + ver := l[m[0]:m[1]] + if vendorWord(l) == "corretto" { + ver = CorrettoJava(ver) + } + s.judgeVersion(rel, i+1, m[0], ver, ".java-version", vendorWord(l)) } return // jenv reads the first line } @@ -430,16 +434,29 @@ func (s *scanner) asdfValue(rel string, line int, value, source string) { } ver := m[2] if m[1] == "corretto" { - // corretto-21.0.5.11.1: the fourth number is Corretto's build when - // the fifth is 1. Keep the Java part. - parts := strings.Split(ver, ".") - if len(parts) == 5 && parts[3] != "1" && parts[3] != "0" { - ver = strings.Join(parts[:3], ".") - } + ver = CorrettoJava(strings.TrimSuffix(ver, ".")) } s.judgeVersion(rel, line, 0, strings.TrimSuffix(ver, "."), source, m[1]) } +// CorrettoJava turns an Amazon Corretto version into the Java version it +// ships. Corretto has written its build number in the fourth place +// (21.0.5.11.1: Java 21.0.5, build 11) and, since the out-of-band releases, +// the OpenJDK patch number there (21.0.13.1.2: Java 21.0.13.1, build 2). +// OpenJDK patch numbers are small, so a fourth number above 3 is a build. +func CorrettoJava(ver string) string { + parts := strings.Split(ver, ".") + if len(parts) >= 4 { + n := 0 + fmt.Sscanf(parts[3], "%d", &n) + if n > 3 { + return strings.Join(parts[:3], ".") + } + return strings.Join(parts[:4], ".") + } + return ver +} + func (s *scanner) toolVersions(rel, text string) { for i, l := range lines(text) { f := strings.Fields(l) @@ -524,7 +541,10 @@ func (s *scanner) workflow(rel string, b []byte) { func (s *scanner) setupJava(rel string, v *yaml.Node, dist string, text []string) { ver := strings.TrimSpace(v.Value) - ver = strings.TrimSuffix(strings.TrimSuffix(ver, "-ea"), ".x") + if strings.HasSuffix(ver, "-ea") { + return // an early-access build: not a release this data judges + } + ver = strings.TrimSuffix(ver, ".x") m := versionInText.FindString(ver) if m == "" || m != ver && !strings.HasPrefix(ver, m+"+") { return @@ -708,11 +728,15 @@ func (s *scanner) dockerfile(rel, text string) { // endStage marks the packages a stage installs as mitigated when the // stage sets the mitigation (before or after the install: ENV applies // to the image the stage makes). + stageEnv := map[string]string{} endStage := func() { - how, ok := s.mitigated[fmt.Sprintf("%s:%d", rel, from)] - if !ok { + o := jvm.FromEnv(stageEnv, nil, 17, nil) + ok, how := o.Mitigates() + if !ok || from == 0 { return } + how = strings.Replace(how, "(from ", "(from ENV in "+rel+": ", 1) + s.mitigated[fmt.Sprintf("%s:%d", rel, from)] = how for k := stageStart; k < len(s.findings); k++ { f := &s.findings[k] if f.File == rel && f.Rule == RulePackage && f.Status == StatusVulnerable { @@ -736,23 +760,15 @@ func (s *scanner) dockerfile(rel, text string) { switch { case fromLine.MatchString(trim): endStage() - from, stageStart = i+1, len(s.findings) + from, stageStart, stageEnv = i+1, len(s.findings), map[string]string{} case envJTO.MatchString(trim): - var o jvm.Options + // The last ENV of each variable in the stage is what the + // image keeps; the mitigation is decided when the stage ends. body := envJTO.ReplaceAllString(trim, "") for _, kv := range jvm.Words(body) { - k, v, ok := strings.Cut(kv, "=") - if !ok { - continue + if k, v, ok := strings.Cut(kv, "="); ok { + stageEnv[k] = v } - for _, n := range jvm.EnvVars { - if k == n { - o.Apply(v, "ENV "+k+" in "+rel) - } - } - } - if ok, how := o.Mitigates(); ok && from > 0 { - s.mitigated[fmt.Sprintf("%s:%d", rel, from)] = how } case strings.HasPrefix(strings.ToUpper(trim), "RUN "): s.packages(rel, i+1, trim) @@ -824,6 +840,9 @@ func (s *scanner) packages(rel string, line int, run string) { up = up[i+1:] } up = strings.ReplaceAll(up, "_p", "+") + if strings.Contains(h.name, "corretto") { + up = CorrettoJava(up) + } if v, ok := knowledge.Parse(up); ok { if st, why := knowledge.Judge(v); st == knowledge.Vulnerable { s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "error", Status: StatusVulnerable, Reason: why, diff --git a/detectors/java4shell/internal/repo/review_test.go b/detectors/java4shell/internal/repo/review_test.go new file mode 100644 index 0000000..bc8dce8 --- /dev/null +++ b/detectors/java4shell/internal/repo/review_test.go @@ -0,0 +1,56 @@ +package repo + +import ( + "testing" +) + +// Regressions from the independent review. +func TestReviewRepo(t *testing.T) { + root := tree(t, map[string]string{ + "a/Dockerfile": "FROM eclipse-temurin:21.0.13_9-jre\nENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics\nENV _JAVA_OPTIONS=-XX:+UseBASE64Intrinsics\n", + "b/Dockerfile": "FROM eclipse-temurin:21.0.13_9-jre\nENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics\nENV JAVA_TOOL_OPTIONS=-Xmx1g\n", + "c/Dockerfile": "FROM amazonlinux:2023\nRUN dnf install -y java-21-amazon-corretto-headless-1:21.0.13.11-1\n", + "d/Dockerfile": "FROM amazoncorretto:21.0.13.11\n", + "e/.tool-versions": "java corretto-21.0.13.11\n", + "f/.java-version": "corretto-21.0.13.11.1\n", + "g/.tool-versions": "java corretto-21.0.13.1.2\n", + }) + res := scan(t, root) + for _, c := range []struct { + file string + line int + rule string + status string + }{ + {"a/Dockerfile", 1, RuleImagePin, StatusVulnerable}, + {"b/Dockerfile", 1, RuleImagePin, StatusVulnerable}, + {"c/Dockerfile", 2, RulePackage, StatusVulnerable}, + {"d/Dockerfile", 1, RuleImagePin, StatusVulnerable}, + {"e/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"f/.java-version", 1, RuleJavaPin, StatusVulnerable}, + } { + f, ok := find(res, c.file, c.line) + if !ok || f.Rule != c.rule || f.Status != c.status { + t.Errorf("%s:%d: %+v (found %v), want %s %s", c.file, c.line, f, ok, c.rule, c.status) + } + } + if f, ok := find(res, "g/.tool-versions", 1); ok { + t.Errorf("fixed Corretto reported: %+v", f) + } + if CorrettoJava("21.0.5.11.1") != "21.0.5" || CorrettoJava("21.0.13.1.2") != "21.0.13.1" || CorrettoJava("21.0.13.0.11") != "21.0.13.0" { + t.Error("CorrettoJava") + } + + // setup-java early access is not judged or rewritten. + root = tree(t, map[string]string{".github/workflows/a.yml": "jobs:\n a:\n steps:\n - uses: actions/setup-java@v4\n with:\n distribution: corretto\n java-version: '21.0.13-ea'\n"}) + if res := scan(t, root); len(res.Findings) != 0 { + t.Errorf("early access: %+v", res.Findings) + } + + // The first fixed build sorts numerically. + e := &pinEdit{family: Families[0], feature: 21} + e.tv, _ = Families[0].ParseTag("21.0.13_9-jre") + if got, _ := target([]string{"21.0.13.1_10-jre", "21.0.13.1_2-jre"}, e); got != "21.0.13.1_2-jre" { + t.Errorf("target %s", got) + } +} From abd7c2199e44158e6fdac4fed723221d44aeff21 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 00:17:46 +0000 Subject: [PATCH 009/119] java4shell: the lead's advisory facts, Oracle's Java 8 Performance Pack, Corretto's republished tags - FACTS.md: the public writeups as relayed by the lead (Calif, Semgrep): CVSS 9.2, the trigger, the products shown exploitable, Oracle's affected builds including 8u511b33-perf, the ARM caveat for -XX:UseAVX=2, indicators; vendor status rechecked 2026-11-18 - a Java 8 VM library that carries the AVX-512 decoder's stubs (Oracle's Performance Pack backport) is vulnerable up to 8u511, unknown above - severity 9.2, advisories led by Calif's; PingFederate, Spinnaker and Gerrit recognised as products - Amazon republished amazoncorretto:21.0.13-* and 17.0.21-* with the fixed builds: fix can now move a Corretto pin to the fixed update's tag, after reading it; parity keeps the old images pinned by digest and expects the new tags fixed (36/36) Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- detectors/java4shell/FACTS.md | 24 ++++++++++-- .../java4shell/internal/assess/assess.go | 17 +++++++-- .../java4shell/internal/assess/assess_test.go | 3 ++ .../java4shell/internal/assess/product.go | 1 + .../internal/knowledge/knowledge.go | 17 +++++++++ .../internal/knowledge/knowledge_test.go | 1 + detectors/java4shell/internal/repo/images.go | 2 +- detectors/java4shell/internal/repo/plan.go | 20 +++++++--- .../java4shell/internal/repo/review_test.go | 12 ++++++ detectors/java4shell/java4shell.go | 24 +++++++----- detectors/java4shell/repo.go | 8 ++-- parity/JAVA4SHELL-RESULTS.md | 8 ++-- parity/java4shell/cases.json | 38 +++++++++++++++++-- 14 files changed, 144 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 0fb7301..6f6bd66 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ One engine for DefectDojo's emerging-vulnerability scanners. Each new vulnerabil | `php2shell` | PHP runtimes vulnerable to CVE-2026-109618 and CVE-2026-109619 ("PHP2Shell"), fixed in PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12 ([GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w), [GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp)). A packaged PHP is judged by its vendor's backport data, never by the version it reports. Also checks the images a source tree builds on and deploys, and can rewrite them to fixed images | `fs`, `image`, `repo`, `fix` | | `brotli` | Brotli decoders vulnerable to CVE-2026-111497 ("Node2Shell", "Broccoli2Shell"), Brotli 1.0.3 through 1.2.0, fixed in 1.0.10, 1.1.1 and 1.2.1 ([GHSA-9v8h-qqgm-4m35](https://github.com/advisories/GHSA-9v8h-qqgm-4m35)): system `libbrotlidec` and every copy bundled into other software (Node.js, .NET, Bun, Electron, Envoy and Istio, Python wheels such as Pillow, pyarrow, duckdb, pycurl and PyMuPDF, brotli4j, and more), on Linux, Windows and macOS. A decoder is judged first by the error code the fix added, so vendor backports are recognised without distribution data; a build that strips it by its own version stamp or by its code, which returns that error code only once fixed. In a source tree it finds the Node.js, .NET and Bun releases and the bundling packages a project pins, and `fix` moves each to the fixed release | `fs`, `image`, `repo`, `fix` | | `sshole` | \*sshole, the OpenSSH password authentication bypass on musl libc fixed in OpenSSH 10.6p2 and in Alpine's openssh packages of November 5, 2026 ([release notes](https://www.openssh.org/releasenotes.html#10.6p2), [writeup](https://sshhole.com)). On musl, sshd from 7.3p1 to 10.6p1 compares an account's password field of `*` with the `*` that crypt returns when it fails, so a crafted password logs in to that account. It judges each installed sshd by its C library, its release and the apk database (Alpine backports keep the release number), then checks what the target's `sshd_config` (Include, Match, PasswordAuthentication, AuthenticationMethods, PermitRootLogin, AllowUsers and the rest) and account files make reachable, and reports the accounts. In an image it also reads the command (`sshd -o` and `-f`) and the startup scripts it runs (entrypoints, s6, cont-init.d), and reports a server as exposed when a startup script turns password logins on, sets a `*` field or sets passwords. OpenWrt's opkg database and its backports (23.05, 24.10, 25.12) count like Alpine's. PAM-checked builds (`UsePAM yes`) are not affected. On a live server it reads the banner and the offered methods and never sends a password. In a source tree it finds Dockerfiles that install an OpenSSH server on Alpine without the fix (package lists in `ARG` and `ENV` too), Ansible apk tasks, Buildroot, OpenWrt and Yocto configurations that build one on musl, and anything that sets a password field to `*`. It also pulls the images the tree references (through the guarded transport, with the command a Compose service or Kubernetes container sets) and judges them like `scan image`. `fix` adds the fixed release floor (in the variable when the list is one), moves an end-of-life Alpine base to a tag on the nearest fixed Alpine release (`alpine:3.14` to `3.16`, `python:3.9-alpine3.14` to `3.9-alpine3.16` after checking that image) as a labelled upgrade, adds upstream commit 4353fdc43 as a patch scoped to the OpenSSH versions it applies to (Buildroot `BR2_GLOBAL_PATCH_DIR`, a version-specific Yocto bbappend), sets Ansible tasks to `state: latest`, and changes `*` to `*NP*` | `fs`, `image`, `host`, `repo`, `fix` | -| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64 (JDK-8393212), fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 on November 15, 2026 ([fix](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b), [knowledge table](detectors/java4shell/FACTS.md)). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512 VBMI (Intel Ice Lake and later, AMD Zen 4 and later). The decoder came with JDK 18 and 17.0.6; Java 8, 11 and 17.0.0 to 17.0.5 do not have it, and Java 18 to 20, 22 to 24 and 26 received no fix. It finds every Java runtime by its VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others). Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; every platform of a multi-arch image is judged on its own), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness and never overrides the library. No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version. OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or `-XX:UseAVX=2` (or lower) in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is reported as mitigated (still to update), never as fixed; `_JAVA_OPTIONS` turning the intrinsic back on undoes it. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context, never as a clearance. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft and Oracle images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`) after reading it, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | +| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64 (JDK-8393212), fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 on November 15, 2026 ([fix](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b), [knowledge table](detectors/java4shell/FACTS.md)). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel Ice Lake and later, AMD Zen 4 and later); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds every Java runtime by its VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others). Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; every platform of a multi-arch image is judged on its own), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness and never overrides the library. No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version. OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is reported as mitigated (still to update), never as fixed; `_JAVA_OPTIONS` turning the intrinsic back on undoes it. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context, never as a clearance. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft and Oracle images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | The detectors ported from standalone scanners also build as standalone binaries under the names people search for: `emudhra-scan` and `php2shell-scan`. They keep their original commands, flags and exit status rules. `brotli`, `sshole` and `java4shell` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`, `--detector java4shell`). @@ -133,7 +133,7 @@ Every port must give exactly the verdicts of the scanner it came from before it - `parity/brotli.py` has no standalone scanner to compare with, so it checks every decoder in 38 images against the vendor's own fix status: Node.js, .NET, Bun, Envoy and curl images before and after their October 2026 releases, distribution packages pinned to their exact unfixed and backported builds, and the Python wheels ([BROTLI-RESULTS.md](parity/BROTLI-RESULTS.md)). - `parity/brotli_files.py` checks 73 release binaries and packages, unpacked and never run: Node.js, .NET and Bun for Windows and macOS, seven Electron releases, Envoy and Istio, and the packages that bundle the decoder ([BROTLI-FILES-RESULTS.md](parity/BROTLI-FILES-RESULTS.md)). A WebAssembly build of the decoder is the one case it cannot settle: it is reported as unknown. - `parity/sshole.py` builds ten images from `parity/sshole/` (Alpine with the unfixed and the fixed package, password logins off, UsePAM on, root with PermitRootLogin, a Match on address, the current Alpine release, Debian, an entrypoint that turns password logins on at start, and `sshd -o` in the image command) and checks each verdict against the expected one ([SSHOLE-RESULTS.md](parity/SSHOLE-RESULTS.md)). The expected verdicts come from the upstream fix, musl's crypt and shadow code, and the Alpine package that shipped it. -- `parity/java4shell.py` checks 34 cases against verdicts taken from [FACTS.md](detectors/java4shell/FACTS.md): Temurin 8, 11, 17.0.5, 17.0.6, 17.0.21 (Alpine), 18, 20, 21 (also arm64, every platform, UBI 9), 25 and 27, Corretto (an Amazon Linux rpm and Alpine), Zulu, Liberica, SapMachine, Semeru, Elasticsearch's bundled JDK, the fixed SapMachine 21.0.13.1, a jlink image, bundled product runtimes with and without `setenv.sh`, Alpine, Debian and Ubuntu packages, environment, Tomcat CATALINA_OPTS and setenv.sh mitigations and one that is undone, hostile release files and symlink loops, a filesystem scan and an offline source tree ([JAVA4SHELL-RESULTS.md](parity/JAVA4SHELL-RESULTS.md)). +- `parity/java4shell.py` checks 36 cases against verdicts taken from [FACTS.md](detectors/java4shell/FACTS.md): Temurin 8, 11, 17.0.5, 17.0.6, 17.0.21 (Alpine), 18, 20, 21 (also arm64, every platform, UBI 9), 25 and 27, Corretto (an Amazon Linux rpm and Alpine, before and after Amazon republished their tags with the fix), Zulu, Liberica, SapMachine, Semeru, Elasticsearch's bundled JDK, the fixed SapMachine 21.0.13.1, a jlink image, bundled product runtimes with and without `setenv.sh`, Alpine, Debian and Ubuntu packages, environment, Tomcat CATALINA_OPTS and setenv.sh mitigations and one that is undone, hostile release files and symlink loops, a filesystem scan and an offline source tree ([JAVA4SHELL-RESULTS.md](parity/JAVA4SHELL-RESULTS.md)). - `parity/php.py` runs php2shell-scan, this repo's php2shell-scan and Early Light over php2shell-scan's validation matrix: official images, distribution packages, source builds and hostile images. Each finding's complete record is compared field by field. It also covers filesystem scans at and below a system root, repository scans, `fix --dry-run`, and every detector at once ([PHP-RESULTS.md](parity/PHP-RESULTS.md)). ## Adding a detector diff --git a/detectors/java4shell/FACTS.md b/detectors/java4shell/FACTS.md index c8dc9ea..ead4aac 100644 --- a/detectors/java4shell/FACTS.md +++ b/detectors/java4shell/FACTS.md @@ -13,7 +13,7 @@ not something a source states. | What the unfixed code does with a 1 to 3 byte tail that ends in `=`: `output_size` is 0, `L_padding` decrements it to -1, `bzhiq(output_mask, -1, output_size)` with an index of 255 keeps all 64 mask bits, and the masked `evmovdqub` stores 64 bytes at `dest + dp`: a write of up to 64 bytes past the output the caller sized. Read from the stub, and observed (next row); no vendor source states the impact in words | same file, lines around `L_finalBit` and `L_padding` | | **Observed** on an AMD EPYC 9B14 (Zen 4, with avx512f, avx512bw, avx512vbmi and bmi2), 2026-11-17: after C2 compiles the decoder, `Base64.getDecoder().decode(src, dst)` of a malformed input that ends in a 1 to 3 character fragment with `=` (for example 64 valid characters then `A=`) writes bytes into `dst` past the decoded output. Seen on Temurin 18.0.2.1, 20.0.2, 17.0.6, 17.0.21, 21.0.2, 21.0.13 and 25.0.5; not seen on Temurin 17.0.5 or on SapMachine 21.0.13.1 (the fixed release); not seen on 21.0.13 started with `-XX:-UseBASE64Intrinsics` or with `-XX:UseAVX=2`. On 17.0.x to 20 the input has to be longer than 128 bytes, on 21 and later longer than 31 bytes: the 17u stub enters the AVX-512 path only above 128 bytes (`cmpl(length, 128)`), the 21u stub above 31. With an output array sized by `decode(byte[])` the write goes past the array into the heap. The test program is not in this repository | local run, `eclipse-temurin` images and the SapMachine 21.0.13.1 tarball (sha256 `6cb4df18…949ae9`, matching the GitHub release asset digest) | | CVE-2026-114938 is listed with CVSS 8.1, component hotspot/compiler, in Amazon Corretto's changelogs of 2026-11-17 | [corretto-17 CHANGELOG 17.0.21.1.2](https://github.com/corretto/corretto-17/blob/17.0.21.1.2/CHANGELOG.md), [corretto-21 21.0.13.1.2](https://github.com/corretto/corretto-21/blob/21.0.13.1.2/CHANGELOG.md), [corretto-25 25.0.5.1.2](https://github.com/corretto/corretto-25/blob/25.0.5.1.2/CHANGELOG.md), [corretto-27 27.0.1.1.4](https://github.com/corretto/corretto-27/blob/27.0.1.1.4/CHANGELOG.md) | -| CVE-2026-114938 is JDK-8393212. **Inferred**: the Corretto changelogs list CVEs by component, not by JDK bug. Each fixed release carries two hotspot/compiler fixes (8393212 and 8390694 "Enhance vector masks"; 21u, 25u and 27u also 8390852 "Improve integer compression") and lists two or three hotspot/compiler CVEs. The brief's description (AVX-512 VBMI Base64 decode, mitigated by `-XX:-UseBASE64Intrinsics`) matches only 8393212. The OpenJDK advisory page that would state the mapping could not be reached from the research host | as above; openjdk.org unreachable | +| CVE-2026-114938 is JDK-8393212. The Corretto changelogs list CVEs by component, not by JDK bug, and the OpenJDK advisory that states the mapping could not be read (HTTP 403 for the lead, unreachable here). The public writeups (lead's sources below) describe exactly the code 8393212 changes: the output mask computed from length and padding, `output_len` underflowing on a padding-only tail, `bzhiq(-1, output_len)` giving all ones and `evmovdqub` writing all 64 bytes. **Inferred from that match**, not stated by a source | Corretto changelogs; Calif and Semgrep writeups as relayed by the lead | | The vulnerable path runs only when the CPU reports AVX-512 VBMI, AVX-512BW and BMI2 and HotSpot keeps them enabled: `if (VM_Version::supports_avx512_vbmi() && VM_Version::supports_avx512bw() && VM_Version::supports_bmi2())`. AVX-512 features need AVX-512F, so the four CPU flags are `avx512f avx512bw avx512vbmi bmi2` | stubGenerator_x86_64.cpp at the fix commit | | MIME decoding (`isMIME`) skips the AVX-512 path; standard and URL-safe decoding use it | same function, `cmpl(isMIME, 0)` | | `-XX:UseAVX=0/1/2` clears every AVX-512 feature, VBMI included, so the path is not generated | `src/hotspot/cpu/x86/vm_version_x86.cpp`, `if (UseAVX < 3)` block (jdk17u-dev and jdk HEAD) | @@ -21,6 +21,22 @@ not something a source states. | Only x86-64 HotSpot has this stub. AArch64, PPC and RISC-V have their own decode intrinsics (8256245, 8248188, 8314124) with different code. 32-bit x86 (`stubGenerator_x86_32.cpp`) has no decode intrinsic | jdk17u-dev and jdk21u-dev trees; `git log --grep` in openjdk/jdk | | OpenJ9 (IBM Semeru) does not contain HotSpot: its `lib/server/libjvm.so` is a 97 KB redirector and the VM is `libj9vm29.so`. Whether OpenJ9 has a comparable bug of its own is **not known** | `ibm-semeru-runtimes:open-21-jre` image, release file `JVM_VARIANT="Openj9"` | +## From the public writeups (relayed by the lead, 2026-11-17) + +The lead read these; they could not be fetched from the research host. Facts here are as the lead reported them. + +| Fact | Source | +| --- | --- | +| Named Java4Shell, credited to Calif. CVSS 9.2 (Corretto's changelogs list 8.1; the detector reports 9.2, the discoverer's score) | [Calif advisory](https://calif.io/java4shell/), [Semgrep blog](https://semgrep.dev/blog/2026/java4shell-openjdk-base64-vulnerability) | +| Trigger: 64 `A` then `=` (on 17: 128 `A` then `=`); a 65-byte input decoded into a 50-byte buffer is written 62 bytes past its end. Reached only after the intrinsic is JIT-compiled. Matches what was observed here (65 and 129 byte inputs) | same | +| Pre-authentication remote code execution shown on default configurations of Keycloak, Jira, Confluence, JFrog Artifactory, Jenkins and PingFederate; post-authentication on Kafka, Solr, Elasticsearch, Gerrit and Spinnaker; Struts and Spring Boot sample apps; and a client-side variant (a Java client opening TLS to a malicious server). Chain details withheld | same, and posts by Charles Carmakal (Mandiant) and Semgrep | +| Affected: OpenJDK 17.0.6 and later on x86-64 CPUs with avx512f, avx512bw, avx512vbmi and bmi2; ARM64 not affected; every distribution. Oracle Java SE builds named as affected: **8u511b33-perf**, 17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3 (for 8, only the Performance Pack build). The 8u-perf build carries a backport of the decoder; **no fixed 8u-perf version is known**. The detector reports a Java 8 VM library that carries the decoder's stubs as vulnerable up to update 511 and unknown above it | same; Oracle alert cspunov2026 (403 for the lead) | +| Oracle and OpenJDK released fixes on 2026-11-17 (Oracle alert "cspunov2026"); the lead had no fixed versions per line. They are established above from the OpenJDK repositories and vendor releases | lead | +| Mitigations: `-XX:-UseBASE64Intrinsics` (preferred, for example through `JAVA_TOOL_OPTIONS`), or `-XX:UseAVX=2` on x86-64 only: **an ARM JVM refuses to start with it** | same | +| CPU check: `grep -m1 '^flags' /proc/cpuinfo \| tr ' ' '\n' \| grep -E '^(avx512f\|avx512bw\|avx512vbmi\|bmi2)$'` (all four needed); Kubernetes node label `feature.node.kubernetes.io/cpu-cpuid.AVX512VBMI: "true"` (Node Feature Discovery) | Calif | +| Indicators (not proof): `hs_err_pid*.log` crash files and bursts of `IllegalArgumentException` from `java.util.Base64$Decoder`. No network signature or IOCs published | same | +| SCA and dependency scanners do not report it: it is in the JDK runtime, not a library | same | + ## Where the vulnerable path came from | Line | First release with the AVX-512 VBMI decode path | Source | @@ -29,7 +45,7 @@ not something a source states. | 17 | 17.0.6 (backport 2022-11-09, first tag `jdk-17.0.6+3`, first GA `jdk-17.0.6-ga`). 17.0.0 to 17.0.5 have no x86 decode intrinsic | openjdk/jdk17u-dev `07050b000c` ("Backport-of: c37988d0793b") | | 11 | never: jdk11u-dev has no Base64 decode intrinsic (only 8205528, AVX-512 encode) | openjdk/jdk11u-dev `git log --grep base64` | | 8 | never: jdk8u-dev has no Base64 intrinsics | openjdk/jdk8u-dev `git log --grep base64` | -| vendor builds of 8, 11 or 17.0.0-17.0.5 | **not known** whether any vendor backported 8268276 into them. The detector checks the libjvm for the VBMI decode stubs' names and reports unknown when an "unaffected" version carries them | n/a | +| vendor builds of 8, 11 or 17.0.0-17.0.5 | Oracle's Java 8 Performance Pack (8u511b33-perf) carries the decoder (see above); other vendor backports are **not known**. The detector checks the libjvm for the VBMI decode stubs' names: a Java 8 build that carries them is vulnerable up to update 511 and unknown above it; an 11 or 17.0.0-17.0.5 build that carries them is unknown | lead's sources | ## Fixed releases @@ -45,11 +61,11 @@ not something a source states. | 17.0.22, 21.0.14, 25.0.6 (January 2027 updates) | **not known**: the -dev repositories (HEAD of 2026-11-17, tags up to `+2`) do not have the fix yet. Embargoed fixes usually reach -dev at the next release; that is an expectation, not a fact, so these versions are reported as unknown | openjdk/jdk17u-dev, jdk21u-dev, jdk25u-dev HEAD | | 17.0.21.0.2 / .0.3, 21.0.13.0.2 / .0.3, 25.0.5.0.2 / .0.3, 27.0.1.0.2 / .0.3 | **not fixed**: these October 2026 out-of-band releases carry CA changes only (8395142, 8395690) | -dev repo tags `jdk-*.0.3+*` | -## Vendors and distributions (2026-11-17) +## Vendors and distributions (2026-11-17, rechecked 2026-11-18) | Vendor | Status | Source | | --- | --- | --- | -| Amazon Corretto | fixed: 17.0.21.1.2, 21.0.13.1.2, 25.0.5.1.2, 27.0.1.1.4 (all 2026-11-17, each "Import jdk-…1+2/+4", CVE-2026-114938 listed). Corretto 8 and 11: no release after October (not affected) | GitHub releases API, CHANGELOG.md of each tag | +| Amazon Corretto | fixed: 17.0.21.1.2, 21.0.13.1.2, 25.0.5.1.2, 27.0.1.1.4 (all 2026-11-17, each "Import jdk-…1+2/+4", CVE-2026-114938 listed). Corretto 8 and 11: no release after October (not affected). **Docker Hub, 2026-11-18:** Amazon republished the existing `amazoncorretto:21.0.13-*` and `17.0.21-*` tags with the fixed builds (the images report 21.0.13.1+2 and 17.0.21.1+2); there are no `.1` tags. A Corretto tag of the fixed update therefore names whichever build was pushed last, and the detector reads the image | GitHub releases API, CHANGELOG.md of each tag; images scanned by this detector (parity cases corretto-*) | | SapMachine | releases 17.0.21.1, 21.0.13.1, 25.0.5.1, 27.0.1.1 published 2026-11-17 (the release page names no CVE) | GitHub releases API, SAP/SapMachine | | Eclipse Temurin | **not fixed yet**: no `jdk-17.0.21.1+2`, `jdk-21.0.13.1+2`, `jdk-25.0.5.1+2` or `jdk-27.0.1.1+4` release in adoptium/temurinNN-binaries; Docker Hub `eclipse-temurin` newest tags are 17.0.21_9, 21.0.13_9, 25.0.5_8, 27.0.1.0 | GitHub API, registry-1.docker.io tag list | | Azul Zulu, BellSoft Liberica, Microsoft, Oracle | **not checked**: their sites could not be reached from the research host. Docker Hub `azul/zulu-openjdk` and `bellsoft/liberica-openjdk-debian` newest tags are 27.0.1.0.3 / 21.0.13.0.3 (not fixed) | registry-1.docker.io tag list | diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index b380a61..cb9c52d 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -208,8 +208,16 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi switch ks { case knowledge.NotAffected: if read && lib.VBMIStubs { - return f.set(Unknown, fmt.Sprintf("Java %s should predate the AVX-512 VBMI Base64 decoder, but this VM library carries its stubs: a vendor backport, and whether it has the fix is not known", v), - what+" carries the AVX-512 VBMI Base64 decoder of later releases") + bs, bwhy := knowledge.JudgeBackport(v) + f.Release = bs + if bs == knowledge.Vulnerable { + if ok, how := mitigation(in, env, root, v.Feature(), &f); ok { + f.Mitigation = how + return f.set(Mitigated, bwhy+"; "+how, what+" carries a backported AVX-512 VBMI Base64 decoder without the fix, mitigated by its JVM options until it is updated") + } + return f.set(Vulnerable, bwhy, what+" carries a backported AVX-512 VBMI Base64 decoder and is vulnerable to Java4Shell") + } + return f.set(Unknown, bwhy, what+" carries the AVX-512 VBMI Base64 decoder of later releases") } if !read { return f.set(NotAffected, kwhy+" (judged by the release file: no HotSpot version line was found in the VM library)", what+" is not affected by Java4Shell") @@ -468,7 +476,10 @@ func fixText(f Finding, v knowledge.Version, ok bool) string { interim = " The JVM options keep the vulnerable decoder from running until then; keep them until it is updated." } target := "a release with the fix (17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later on the same update)" - if ok { + if ok && v.Feature() < 17 { + // A backported decoder (Oracle's Java 8 Performance Pack). + target = fmt.Sprintf("a build of Java %d from the same vendor with the fix (none was known on %s), or one without the backported AVX-512 decoder", v.Feature(), knowledge.Checked) + } else if ok { if fx := knowledge.FixedVersion(v.Feature()); fx != "" { target = fx + " or later of the same update" } else if v.Feature() >= 17 { diff --git a/detectors/java4shell/internal/assess/assess_test.go b/detectors/java4shell/internal/assess/assess_test.go index ccae267..df460d9 100644 --- a/detectors/java4shell/internal/assess/assess_test.go +++ b/detectors/java4shell/internal/assess/assess_test.go @@ -48,6 +48,9 @@ func TestVerdicts(t *testing.T) { {"17.0.5", testlib.Lib{Version: "17.0.5+8"}, NotAffected}, {"17.0.5 with a vendor backport of the decoder", testlib.Lib{Version: "17.0.5+8", VBMI: true}, Unknown}, {"11", testlib.Lib{Version: "11.0.33+10"}, NotAffected}, + {"11 with a vendor backport of the decoder", testlib.Lib{Version: "11.0.33+10", VBMI: true}, Unknown}, + {"Oracle 8u511 Performance Pack", testlib.Lib{Version: "1.8.0_511-perf-b33", VBMI: true}, Vulnerable}, + {"Java 8 backport newer than any known affected build", testlib.Lib{Version: "1.8.0_521-perf-b05", VBMI: true}, Unknown}, {"8", testlib.Lib{Version: "1.8.0_512-b09"}, NotAffected}, {"aarch64", testlib.Lib{Machine: "aarch64", Version: "21.0.13+9-LTS"}, NotAffected}, {"x86 32-bit", testlib.Lib{Machine: "x86", Version: "21.0.13+9-LTS"}, NotAffected}, diff --git a/detectors/java4shell/internal/assess/product.go b/detectors/java4shell/internal/assess/product.go index ea75b38..b3db62a 100644 --- a/detectors/java4shell/internal/assess/product.go +++ b/detectors/java4shell/internal/assess/product.go @@ -34,6 +34,7 @@ var products = []struct{ part, name string }{ {"/jenkins", "Jenkins"}, {"/solr", "Apache Solr"}, {"/kafka", "Apache Kafka"}, {"/confluent", "Confluent Platform"}, {"/BurpSuite", "Burp Suite"}, {"Burp Suite", "Burp Suite"}, {"/dbeaver", "DBeaver"}, {"DBeaver", "DBeaver"}, {"/eclipse", "Eclipse IDE"}, {"/netbeans", "Apache NetBeans"}, {"/minecraft", "Minecraft"}, {"/tableau", "Tableau"}, {"/MATLAB", "MATLAB"}, + {"/pingfederate", "PingFederate"}, {"/pingaccess", "PingAccess"}, {"/spinnaker", "Spinnaker"}, {"/gerrit", "Gerrit"}, {"/cassandra", "Apache Cassandra"}, {"/neo4j", "Neo4j"}, {"/gitbucket", "GitBucket"}, {"/rundeck", "Rundeck"}, } diff --git a/detectors/java4shell/internal/knowledge/knowledge.go b/detectors/java4shell/internal/knowledge/knowledge.go index e19b184..dda59ae 100644 --- a/detectors/java4shell/internal/knowledge/knowledge.go +++ b/detectors/java4shell/internal/knowledge/knowledge.go @@ -210,6 +210,23 @@ const ( // release. const maxPatch = 3 +// Backports are lines whose OpenJDK releases do not have the decoder but +// whose vendor builds do: the last update known to carry the decoder +// without the fix. Oracle names Java SE 8u511b33-perf (its Performance +// Pack build of Java 8) as affected; no fixed 8u-perf build is known. +var Backports = map[int][]int{8: {8, 0, 511}} + +// JudgeBackport judges a runtime of a line without the decoder whose VM +// library carries it anyway (a vendor backport such as Oracle's Java 8 +// Performance Pack). +func JudgeBackport(v Version) (Status, string) { + last, ok := Backports[v.Feature()] + if ok && Compare(v.Nums, last) <= 0 { + return Vulnerable, fmt.Sprintf("Java %s carries the AVX-512 VBMI Base64 decoder as a vendor backport (Oracle names Java SE 8u511b33-perf as affected), and no fixed build of it was known on %s", v, Checked) + } + return Unknown, fmt.Sprintf("Java %s should predate the AVX-512 VBMI Base64 decoder, but this VM library carries its stubs: a vendor backport, and whether it has the fix is not known", v) +} + // LineOf returns the release line of a feature release. func LineOf(feature int) (Line, bool) { for _, l := range Lines { diff --git a/detectors/java4shell/internal/knowledge/knowledge_test.go b/detectors/java4shell/internal/knowledge/knowledge_test.go index c3212a5..91d159c 100644 --- a/detectors/java4shell/internal/knowledge/knowledge_test.go +++ b/detectors/java4shell/internal/knowledge/knowledge_test.go @@ -17,6 +17,7 @@ func TestParse(t *testing.T) { {"17.0.21+9-1-deb12u1-Debian", "17.0.21", 9, false}, {"1.8.0_452-b09", "8.0.452", 9, false}, {"1.8.0_452", "8.0.452", -1, false}, + {"1.8.0_511-perf-b33", "8.0.511", 33, false}, {"28-ea+24", "28", 24, true}, {"17.0.6-ea+2", "17.0.6", 2, true}, {"25.0.5", "25.0.5", -1, false}, diff --git a/detectors/java4shell/internal/repo/images.go b/detectors/java4shell/internal/repo/images.go index 19b859e..ba49918 100644 --- a/detectors/java4shell/internal/repo/images.go +++ b/detectors/java4shell/internal/repo/images.go @@ -195,7 +195,7 @@ var javaish = []string{"java", "jdk", "jre", "temurin", "corretto", "zulu", "lib "maven", "gradle", "tomcat", "jetty", "wildfly", "jboss", "keycloak", "jenkins", "atlassian", "jira", "confluence", "bitbucket", "bamboo", "elasticsearch", "logstash", "opensearch", "kafka", "zookeeper", "solr", "cassandra", "neo4j", "sonarqube", "sonatype", "nexus", "artifactory", "spring", "quarkus", "liberty", "payara", "glassfish", "flink", "spark", "hadoop", "hive", "trino", "presto", - "druid", "pinot", "nifi", "activemq", "teamcity", "youtrack", "gerrit", "minecraft", "openliberty", "websphere", "weblogic", "distroless/java"} + "druid", "pinot", "nifi", "activemq", "teamcity", "youtrack", "gerrit", "pingfederate", "pingidentity", "spinnaker", "struts", "minecraft", "openliberty", "websphere", "weblogic", "distroless/java"} // Javaish reports an image whose name suggests a Java runtime. func Javaish(image string) bool { diff --git a/detectors/java4shell/internal/repo/plan.go b/detectors/java4shell/internal/repo/plan.go index 5057d96..2695236 100644 --- a/detectors/java4shell/internal/repo/plan.go +++ b/detectors/java4shell/internal/repo/plan.go @@ -61,24 +61,34 @@ func Plan(ctx context.Context, root string, f Finding, reg Registry, opts Option // style that has the fix. func target(tags []string, e *pinEdit) (string, bool) { type cand struct { - tag string - tv TagVersion + tag string + tv TagVersion + moving bool } + fixed, _ := knowledge.LineOf(e.feature) var cs []cand for _, t := range tags { tv, ok := e.family.ParseTag(t) if !ok || tv.Variant != e.tv.Variant || tv.Exact != e.tv.Exact || tv.Nums[0] != e.feature || len(tv.Nums) < 3 { continue } - if st, _ := JudgeTag(tv); st != knowledge.Fixed { - continue + switch st, _ := JudgeTag(tv); { + case st == knowledge.Fixed: + cs = append(cs, cand{t, tv, false}) + case !tv.Exact && fixed.Fixed != nil && len(tv.Nums) == 3 && knowledge.Compare(tv.Nums, fixed.Fixed[:3]) == 0: + // A moving tag of the fixed update (Corretto republishes + // "21.0.13" with 21.0.13.1.2): only reading the image shows + // which release it holds, and Verify does. + cs = append(cs, cand{t, tv, true}) } - cs = append(cs, cand{t, tv}) } if len(cs) == 0 { return "", false } sort.Slice(cs, func(i, j int) bool { + if cs[i].moving != cs[j].moving { + return !cs[i].moving + } if c := knowledge.Compare(cs[i].tv.Nums, cs[j].tv.Nums); c != 0 { return c < 0 } diff --git a/detectors/java4shell/internal/repo/review_test.go b/detectors/java4shell/internal/repo/review_test.go index bc8dce8..c95ea09 100644 --- a/detectors/java4shell/internal/repo/review_test.go +++ b/detectors/java4shell/internal/repo/review_test.go @@ -53,4 +53,16 @@ func TestReviewRepo(t *testing.T) { if got, _ := target([]string{"21.0.13.1_10-jre", "21.0.13.1_2-jre"}, e); got != "21.0.13.1_2-jre" { t.Errorf("target %s", got) } + + // Corretto: the moving tag of the fixed update is a candidate (the + // image is read before any edit), after tags that name the fix. + c := &pinEdit{feature: 21} + c.family, _, _ = FamilyOf("amazoncorretto:x") + c.tv, _ = c.family.ParseTag("21.0.12-al2023") + if got, _ := target([]string{"21.0.12-al2023", "21.0.13-al2023", "21.0.13-alpine", "21-al2023", "21.0.14-al2023"}, c); got != "21.0.13-al2023" { + t.Errorf("corretto target %q", got) + } + if got, _ := target([]string{"21.0.13-al2023", "21.0.13.1-al2023"}, c); got != "21.0.13.1-al2023" { + t.Errorf("corretto target prefers the named fix: %q", got) + } } diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 7a10b53..7d98c96 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -48,12 +48,15 @@ type Detector struct{} func init() { engine.Register(&Detector{}) } -const about = " HotSpot's AVX-512 VBMI Base64 decoder (x86-64, JDK 18 and later, 17.0.6 and later) writes up to 64 bytes" + - " past its output when the input ends in a padded fragment shorter than four characters, so a Java program that" + - " decodes untrusted Base64 (tokens, headers, certificates, JSON) can have its heap corrupted once the decoder is" + - " compiled. It runs on CPUs with AVX-512 VBMI (Intel Ice Lake and later, AMD Zen 4 and later). Fixed in OpenJDK" + - " 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 (JDK-8393212); Java 18 to 20, 22 to 24 and 26 received no fix." + - " -XX:-UseBASE64Intrinsics or -XX:UseAVX=2 keep the decoder from being generated until the runtime is updated." +const about = " HotSpot's AVX-512 VBMI Base64 decoder (x86-64, JDK 18 and later, 17.0.6 and later, and Oracle's Java 8" + + " Performance Pack) writes up to 64 bytes past its output when the input ends in a padded fragment shorter than four" + + " characters (64 'A' then '=' is enough), so a Java program that decodes untrusted Base64 (tokens, headers," + + " certificates, JSON) can have its heap corrupted once the decoder is compiled: pre-authentication remote code" + + " execution was shown on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. It runs on CPUs" + + " with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel Ice Lake and later, AMD Zen 4 and later, common on cloud" + + " instances). Fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 (JDK-8393212); Java 18 to 20, 22 to 24" + + " and 26 received no fix. -XX:-UseBASE64Intrinsics (or, on x86-64 only, -XX:UseAVX=2) keeps the decoder from being" + + " generated until the runtime is updated." // Manifest describes the detector. func (d *Detector) Manifest() engine.Manifest { @@ -63,16 +66,19 @@ func (d *Detector) Manifest() engine.Manifest { Title: "Java4Shell: HotSpot AVX-512 Base64 decoder out-of-bounds write (" + knowledge.CVE + ")", CVEs: []string{knowledge.CVE}, Advisories: []string{ + "https://calif.io/java4shell/", + "https://openjdk.org/groups/vulnerability/advisories/2026-11-17", + "https://www.oracle.com/security-alerts/cspunov2026.html", "https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b", - "https://openjdk.org/groups/vulnerability/advisories/", + "https://semgrep.dev/blog/2026/java4shell-openjdk-base64-vulnerability", "https://github.com/corretto/corretto-21/blob/21.0.13.1.2/CHANGELOG.md", }, Disclosed: "2026-11-17", Targets: []engine.TargetKind{engine.Filesystem, engine.Image, engine.Repository}, Kinds: append([]engine.Kind{ - {ID: KindRuntime, Title: "Java runtime vulnerable to Java4Shell", Level: "error", SecuritySeverity: "8.1", CWEs: cwe, + {ID: KindRuntime, Title: "Java runtime vulnerable to Java4Shell", Level: "error", SecuritySeverity: "9.2", CWEs: cwe, Description: "A HotSpot Java runtime for x86-64 with the AVX-512 VBMI Base64 decoder and without the fix: an installed JDK or JRE, a packaged OpenJDK, a jlink image or a runtime in a container image." + about}, - {ID: KindBundled, Title: "Java runtime bundled in a product is vulnerable to Java4Shell", Level: "error", SecuritySeverity: "8.1", CWEs: cwe, + {ID: KindBundled, Title: "Java runtime bundled in a product is vulnerable to Java4Shell", Level: "error", SecuritySeverity: "9.2", CWEs: cwe, Description: "A Java runtime that a product ships inside its own install directory (Atlassian Jira and Confluence, Elasticsearch, Artifactory, JetBrains IDEs and others) without the fix. Updating the operating system's Java does not fix it: upgrade the product." + about}, }, repoKinds()...), Tags: []string{"security", "java", "openjdk", "hotspot", "Java4Shell"}, diff --git a/detectors/java4shell/repo.go b/detectors/java4shell/repo.go index 47935b2..b949188 100644 --- a/detectors/java4shell/repo.go +++ b/detectors/java4shell/repo.go @@ -33,15 +33,15 @@ const ( func repoKinds() []engine.Kind { cwe := []string{"CWE-787"} return []engine.Kind{ - {ID: KindImagePin, Title: "Source tree uses a Java image without the Java4Shell fix", Level: "error", SecuritySeverity: "8.1", CWEs: cwe, + {ID: KindImagePin, Title: "Source tree uses a Java image without the Java4Shell fix", Level: "error", SecuritySeverity: "9.2", CWEs: cwe, Description: "A Dockerfile, Compose, Kubernetes, Helm values, CI or Jib file names a Java runtime image (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine and others) whose tag is a Java release without the fix."}, - {ID: KindImage, Title: "Image the source tree uses holds a Java runtime vulnerable to Java4Shell", Level: "error", SecuritySeverity: "8.1", CWEs: cwe, + {ID: KindImage, Title: "Image the source tree uses holds a Java runtime vulnerable to Java4Shell", Level: "error", SecuritySeverity: "9.2", CWEs: cwe, Description: "An image the tree builds on or deploys, read from its registry for linux/amd64 and judged as scan image does: a moving tag, or a product image (Jira, Elasticsearch, Jenkins...) that carries its own runtime."}, {ID: KindJavaPin, Title: "Source tree pins a Java release without the Java4Shell fix", Level: "warning", SecuritySeverity: "6.5", CWEs: cwe, Description: "A version file (.java-version, .sdkmanrc, .tool-versions, mise), a GitHub Actions setup-java step, a buildpack setting or a Maven Enforcer floor that selects or allows a Java release without the fix."}, - {ID: KindLine, Title: "Source tree selects a Java line that received no Java4Shell fix", Level: "error", SecuritySeverity: "8.1", CWEs: cwe, + {ID: KindLine, Title: "Source tree selects a Java line that received no Java4Shell fix", Level: "error", SecuritySeverity: "9.2", CWEs: cwe, Description: "A toolchain, version file, CI step, buildpack, image or package of Java 18, 19, 20, 22, 23, 24 or 26: those lines are end of life and received no fix."}, - {ID: KindPackage, Title: "Dockerfile installs a distribution OpenJDK package without the Java4Shell fix", Level: "error", SecuritySeverity: "8.1", CWEs: cwe, + {ID: KindPackage, Title: "Dockerfile installs a distribution OpenJDK package without the Java4Shell fix", Level: "error", SecuritySeverity: "9.2", CWEs: cwe, Description: "An apt, apk, dnf, yum or microdnf install of an OpenJDK 17 or later package pinned to a release without the fix, or without a version while the distribution had no fixed package."}, {ID: KindNotChecked, Title: "Java runtime not checked for the Java4Shell fix", Level: "note", Description: "An image whose tag does not name one Java release (a moving tag, a product image) that was not read, a workflow expression, or a file that could not be read. It is not known to be safe."}, diff --git a/parity/JAVA4SHELL-RESULTS.md b/parity/JAVA4SHELL-RESULTS.md index 5e623cd..824b4c3 100644 --- a/parity/JAVA4SHELL-RESULTS.md +++ b/parity/JAVA4SHELL-RESULTS.md @@ -17,8 +17,10 @@ Generated by `parity/java4shell.py`. Each row's expected findings come from [FAC | temurin-21-ubi9 | Temurin 21.0.13 on UBI 9 minimal
`eclipse-temurin:21.0.13_9-jre-ubi9-minimal`
linux/amd64 sha256:17e523f3696b36177c5c9a44399f8a4a4634229fdf3f14d4c7582d2597931a1d | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | | temurin-25 | Temurin 25.0.5, before 25.0.5.1
`eclipse-temurin:25.0.5_8-jre`
linux/amd64 sha256:fa681c5833ecc085202c0923e909f9de888d80d22a7f38d6c51268ae5978c1d7 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | | temurin-27 | Temurin 27.0.1.0.2, before 27.0.1.1
`eclipse-temurin:27.0.1.0-jre`
linux/amd64 sha256:2719c23ca6855fed092edd3f47fbea2e6870bfd00fa4e10b2077126d551bca28 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | -| corretto-21-al2023 | Amazon Corretto 21.0.13.0.11, an rpm on Amazon Linux 2023, before 21.0.13.1.2
`amazoncorretto:21.0.13-al2023-headless`
linux/amd64 sha256:21a9456bd7fee7045c545bf089e63ffc69ceb7d594b3c5bfb25bace199d3f566 | pass | linux/amd64 /usr/lib/jvm/java-21-amazon-corretto.x86_64 runtime vulnerable vulnerable | -| corretto-17-alpine | Amazon Corretto 17.0.21 on Alpine, before 17.0.21.1.2
`amazoncorretto:17.0.21-alpine3.22`
linux/amd64 sha256:92cdff306e26329894ef0fab79f8d120ac0acc08f3b675206b66a7da85316043 | pass | linux/amd64 /usr/lib/jvm/java-17-amazon-corretto runtime vulnerable vulnerable | +| corretto-21-al2023-unfixed | Amazon Corretto 21.0.13.0.11, an rpm on Amazon Linux 2023 (the amazoncorretto:21.0.13-al2023-headless image of 2026-11-17, pinned by digest)
`amazoncorretto@sha256:21a9456bd7fee7045c545bf089e63ffc69ceb7d594b3c5bfb25bace199d3f566`
linux/amd64 sha256:21a9456bd7fee7045c545bf089e63ffc69ceb7d594b3c5bfb25bace199d3f566 | pass | linux/amd64 /usr/lib/jvm/java-21-amazon-corretto.x86_64 runtime vulnerable vulnerable | +| corretto-21-al2023 | amazoncorretto:21.0.13-al2023-headless as republished on 2026-11-18 with Corretto 21.0.13.1.2 (the tag 21.0.13 moves to the out-of-band release)
`amazoncorretto:21.0.13-al2023-headless`
linux/amd64 sha256:47cbd3767e95fd412adbb9c81ce371574bc8f67eebddc9ef319c25c6d0c0a601 | pass | linux/amd64 /usr/lib/jvm/java-21-amazon-corretto.x86_64 runtime fixed fixed | +| corretto-17-alpine-unfixed | Amazon Corretto 17.0.21 on Alpine (the amazoncorretto:17.0.21-alpine3.22 image of 2026-11-17, pinned by digest)
`amazoncorretto@sha256:92cdff306e26329894ef0fab79f8d120ac0acc08f3b675206b66a7da85316043`
linux/amd64 sha256:92cdff306e26329894ef0fab79f8d120ac0acc08f3b675206b66a7da85316043 | pass | linux/amd64 /usr/lib/jvm/java-17-amazon-corretto runtime vulnerable vulnerable | +| corretto-17-alpine | amazoncorretto:17.0.21-alpine3.22 as republished on 2026-11-18 with Corretto 17.0.21.1.2
`amazoncorretto:17.0.21-alpine3.22`
linux/amd64 sha256:e6d108efd17fd318481c1db6ab6f8a79d0823c77408ae4d4d1fb7c6b9e201a1e | pass | linux/amd64 /usr/lib/jvm/java-17-amazon-corretto runtime fixed fixed | | zulu-21 | Azul Zulu 21.0.13.0.3 (the October CA-only release)
`azul/zulu-openjdk:21.0.13.0.3-jre`
linux/amd64 sha256:bad3fa28d3265b6912b78f85b71d6774dab86dc83a656287c4a2e46f84ac5b3b | pass | linux/amd64 /usr/lib/jvm/zulu21-ca-amd64 runtime vulnerable vulnerable | | liberica-21 | BellSoft Liberica 21.0.13.0.3
`bellsoft/liberica-openjre-debian:21.0.13.0.3`
linux/amd64 sha256:c5f59f695bc1ae8a588c88c60aef901ed3fc66a7d4ba1b44d2b83cc007c9cb86 | pass | linux/amd64 /usr/lib/jvm/jre-21.0.13.0.3-bellsoft-x86_64 runtime vulnerable vulnerable | | sapmachine-21 | SapMachine 21.0.13.0.3, before 21.0.13.1
`sapmachine:21.0.13.0.3-jre-ubuntu-noble`
linux/amd64 sha256:2d8895467d35e0f0c938fc8ba94a02792d1720ce738637969e342193c7dac16f | pass | linux/amd64 /usr/lib/jvm/sapmachine-21 runtime vulnerable vulnerable | @@ -39,4 +41,4 @@ Generated by `parity/java4shell.py`. Each row's expected findings come from [FAC | debian-pkg-fs | The debian-pkg image exported and scanned as a filesystem | pass | fs /usr/lib/jvm/java-17-openjdk-amd64 runtime vulnerable vulnerable | | repo | Source tree, offline: Dockerfiles, Compose, Kubernetes, setup-java, version files, Gradle | pass | .github/workflows/ci.yml:12 java-line vulnerable
.github/workflows/ci.yml:8 java-pin vulnerable
.java-version:1 java-pin vulnerable
.sdkmanrc:1 java-pin vulnerable
Dockerfile.pkg:2 os-package inactive
Dockerfile:1 image-pin vulnerable
build.gradle.kts:3 java-line vulnerable
build.gradle.kts:7 image-pin vulnerable
compose.yaml:13 not-checked unknown
compose.yaml:3 image-pin vulnerable
compose.yaml:5 image-pin inactive
k8s/deployment.yaml:10 image-pin vulnerable | -34/34 cases match. +36/36 cases match. diff --git a/parity/java4shell/cases.json b/parity/java4shell/cases.json index 0332fc7..ecb1b6c 100644 --- a/parity/java4shell/cases.json +++ b/parity/java4shell/cases.json @@ -231,9 +231,24 @@ ] ] }, + { + "name": "corretto-21-al2023-unfixed", + "what": "Amazon Corretto 21.0.13.0.11, an rpm on Amazon Linux 2023 (the amazoncorretto:21.0.13-al2023-headless image of 2026-11-17, pinned by digest)", + "mode": "registry", + "ref": "amazoncorretto@sha256:21a9456bd7fee7045c545bf089e63ffc69ceb7d594b3c5bfb25bace199d3f566", + "expected": [ + [ + "linux/amd64", + "/usr/lib/jvm/java-21-amazon-corretto.x86_64", + "runtime", + "vulnerable", + "vulnerable" + ] + ] + }, { "name": "corretto-21-al2023", - "what": "Amazon Corretto 21.0.13.0.11, an rpm on Amazon Linux 2023, before 21.0.13.1.2", + "what": "amazoncorretto:21.0.13-al2023-headless as republished on 2026-11-18 with Corretto 21.0.13.1.2 (the tag 21.0.13 moves to the out-of-band release)", "mode": "registry", "ref": "amazoncorretto:21.0.13-al2023-headless", "expected": [ @@ -241,6 +256,21 @@ "linux/amd64", "/usr/lib/jvm/java-21-amazon-corretto.x86_64", "runtime", + "fixed", + "fixed" + ] + ] + }, + { + "name": "corretto-17-alpine-unfixed", + "what": "Amazon Corretto 17.0.21 on Alpine (the amazoncorretto:17.0.21-alpine3.22 image of 2026-11-17, pinned by digest)", + "mode": "registry", + "ref": "amazoncorretto@sha256:92cdff306e26329894ef0fab79f8d120ac0acc08f3b675206b66a7da85316043", + "expected": [ + [ + "linux/amd64", + "/usr/lib/jvm/java-17-amazon-corretto", + "runtime", "vulnerable", "vulnerable" ] @@ -248,7 +278,7 @@ }, { "name": "corretto-17-alpine", - "what": "Amazon Corretto 17.0.21 on Alpine, before 17.0.21.1.2", + "what": "amazoncorretto:17.0.21-alpine3.22 as republished on 2026-11-18 with Corretto 17.0.21.1.2", "mode": "registry", "ref": "amazoncorretto:17.0.21-alpine3.22", "expected": [ @@ -256,8 +286,8 @@ "linux/amd64", "/usr/lib/jvm/java-17-amazon-corretto", "runtime", - "vulnerable", - "vulnerable" + "fixed", + "fixed" ] ] }, From 142c8243f32f0c30da50eec84757f323983ff210 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 01:28:14 +0000 Subject: [PATCH 010/119] java4shell: read musl version lines; never clear on the release file alone Review findings 1 and 6. HotSpot on musl names its platform linux-amd64-musl, which the version-line pattern refused, so Alpine runtimes were judged by their release file. A release file now never clears a runtime alone, four bytes 'j9vm' no longer make a library OpenJ9 (the redirector has no decoder stubs and names OPENJ9_JAVA_OPTIONS), and a release file that names OpenJ9 next to a HotSpot library that was read makes the verdict unknown. Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/assess/assess.go | 30 +++++++++++--- .../java4shell/internal/assess/assess_test.go | 2 +- .../internal/assess/review2_test.go | 41 +++++++++++++++++++ detectors/java4shell/internal/jvm/jvm.go | 10 +++-- .../java4shell/internal/jvm/review2_test.go | 24 +++++++++++ .../java4shell/internal/testlib/testlib.go | 4 ++ 6 files changed, 101 insertions(+), 10 deletions(-) create mode 100644 detectors/java4shell/internal/assess/review2_test.go create mode 100644 detectors/java4shell/internal/jvm/review2_test.go diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index cb9c52d..3fa2ab0 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -186,7 +186,16 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi } what := describe(f, v, vok) + hotspot := false + for _, l := range libs { + if l.HotSpot() { + hotspot = true + } + } switch { + case openj9 && hotspot: + return f.set(Unknown, "the runtime's files contradict each other: a HotSpot VM library was read, but the release file or another VM library names OpenJ9", + what+": HotSpot and OpenJ9 evidence disagree") case openj9: return f.set(NotAffected, "an OpenJ9 VM: the vulnerable decoder is HotSpot code that OpenJ9 does not contain", what+" runs the OpenJ9 VM, not HotSpot") @@ -205,6 +214,15 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi ks, kwhy := knowledge.Judge(v) f.Release = ks read := lib.HotSpot() // the stub names are only meaningful in a HotSpot library that was read + if !read && ks != knowledge.Vulnerable { + // Only the release file states the version, and a release file is + // text anyone can write: it never clears a runtime alone. + why := fmt.Sprintf("the VM library's version line could not be read, and the release file alone (Java %s) does not prove the runtime is safe", v) + if lib.VBMIStubs { + why = fmt.Sprintf("the VM library carries the AVX-512 VBMI Base64 decoder, but its version line could not be read; the release file alone (Java %s) does not prove the fix", v) + } + return f.set(Unknown, why, what+": version not readable from the VM library") + } switch ks { case knowledge.NotAffected: if read && lib.VBMIStubs { @@ -475,24 +493,24 @@ func fixText(f Finding, v knowledge.Version, ok bool) string { if f.Status == Mitigated { interim = " The JVM options keep the vulnerable decoder from running until then; keep them until it is updated." } - target := "a release with the fix (17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later on the same update)" + target := "a Java release with the fix (17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later on the same update)" if ok && v.Feature() < 17 { // A backported decoder (Oracle's Java 8 Performance Pack). target = fmt.Sprintf("a build of Java %d from the same vendor with the fix (none was known on %s), or one without the backported AVX-512 decoder", v.Feature(), knowledge.Checked) } else if ok { if fx := knowledge.FixedVersion(v.Feature()); fx != "" { - target = fx + " or later of the same update" + target = "Java " + fx + " or later of the same update" } else if v.Feature() >= 17 { - target = "a supported release with the fix, such as " + knowledge.Upgrade(v.Feature()) + " (Java " + fmt.Sprint(v.Feature()) + " received none)" + target = "a supported Java release with the fix, such as " + knowledge.Upgrade(v.Feature()) + " (Java " + fmt.Sprint(v.Feature()) + " received none)" } } switch { case f.Product != "": - return fmt.Sprintf("Upgrade %s to a release that bundles Java %s; its own runtime is not updated by the operating system's Java packages.%s", f.Product, target, interim) + return fmt.Sprintf("Upgrade %s to a release that bundles %s; its own runtime is not updated by the operating system's Java packages.%s", f.Product, target, interim) case f.Package != nil: - return fmt.Sprintf("Update the %s package to Java %s: %s (%s).%s", f.Package.Name, target, upgradeLine(*f.Package), distroStatus(*f.Package), interim) + return fmt.Sprintf("Update the %s package to %s: %s (%s).%s", f.Package.Name, target, upgradeLine(*f.Package), distroStatus(*f.Package), interim) case f.JLinked: return fmt.Sprintf("Rebuild this jlink image from a JDK at %s.%s", target, interim) } - return fmt.Sprintf("Update this runtime to Java %s (Amazon Corretto and SapMachine published theirs on 2026-11-17; check your vendor).%s", target, interim) + return fmt.Sprintf("Update this runtime to %s (Amazon Corretto and SapMachine published theirs on 2026-11-17; check your vendor).%s", target, interim) } diff --git a/detectors/java4shell/internal/assess/assess_test.go b/detectors/java4shell/internal/assess/assess_test.go index df460d9..af8b5fa 100644 --- a/detectors/java4shell/internal/assess/assess_test.go +++ b/detectors/java4shell/internal/assess/assess_test.go @@ -99,7 +99,7 @@ func TestReleaseFile(t *testing.T) { } // Java 8 JDK: the release file one level above jre/. in = Input{ - Libraries: []*jvm.Library{lib(t, "/usr/lib/jvm/j8/jre/lib/amd64/server/libjvm.so", testlib.Lib{})}, + Libraries: []*jvm.Library{lib(t, "/usr/lib/jvm/j8/jre/lib/amd64/server/libjvm.so", testlib.Lib{Version: "1.8.0_452-b09"})}, Releases: map[string]jvm.Release{"/usr/lib/jvm/j8": rel(t, "JAVA_VERSION", "1.8.0_452")}, } if f := one(t, in); f.Status != NotAffected { diff --git a/detectors/java4shell/internal/assess/review2_test.go b/detectors/java4shell/internal/assess/review2_test.go new file mode 100644 index 0000000..833c442 --- /dev/null +++ b/detectors/java4shell/internal/assess/review2_test.go @@ -0,0 +1,41 @@ +package assess + +import ( + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" +) + +// Review finding 1: the release file alone never clears a runtime whose VM +// library carries the decoder. +func TestReleaseAloneDoesNotClear(t *testing.T) { + musl := Input{ + Libraries: []*jvm.Library{lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true, Musl: true})}, + Releases: map[string]jvm.Release{temurin: rel(t, "JAVA_VERSION", "21.0.13.1", "JAVA_RUNTIME_VERSION", "21.0.13.1+2-LTS")}, + } + if f := one(t, musl); f.Status != Vulnerable || f.VersionFrom != "vm-library" { + t.Errorf("musl library with a forged release: %s from %s", f.Status, f.VersionFrom) + } + for _, v := range []string{"21.0.13.1", "11.0.20"} { + in := Input{ + Libraries: []*jvm.Library{lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{VBMI: true})}, + Releases: map[string]jvm.Release{temurin: rel(t, "JAVA_VERSION", v)}, + } + if f := one(t, in); f.Status != Unknown { + t.Errorf("unreadable library with the decoder, release %s: %s (%s)", v, f.Status, f.Reason) + } + } +} + +// Review finding 6: a release file that contradicts a HotSpot library that +// was read makes the verdict unknown. +func TestReleaseContradiction(t *testing.T) { + in := Input{ + Libraries: []*jvm.Library{lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true})}, + Releases: map[string]jvm.Release{temurin: rel(t, "JAVA_VERSION", "21.0.13", "JVM_VARIANT", "Openj9")}, + } + if f := one(t, in); f.Status != Unknown { + t.Errorf("HotSpot library, OpenJ9 release: %s (%s)", f.Status, f.Reason) + } +} diff --git a/detectors/java4shell/internal/jvm/jvm.go b/detectors/java4shell/internal/jvm/jvm.go index 61a29b3..be6cbd1 100644 --- a/detectors/java4shell/internal/jvm/jvm.go +++ b/detectors/java4shell/internal/jvm/jvm.go @@ -79,8 +79,9 @@ func IsLibraryName(base string) bool { } // vmLine is the version line HotSpot compiles in. JDK 8 has the same shape -// ("... JRE (1.8.0_452-b09)"). -var vmLine = regexp.MustCompile(`([A-Za-z][ -~]{2,80}?VM) \(([0-9][!-'*-~]{0,60})\) for ([a-z0-9_]{1,20})-([a-z0-9_]{1,20}) JRE \(([0-9][!-'*-~]{0,80})\)`) +// ("... JRE (1.8.0_452-b09)"), and musl builds name their platform +// linux-amd64-musl. +var vmLine = regexp.MustCompile(`([A-Za-z][ -~]{2,80}?VM) \(([0-9][!-'*-~]{0,60})\) for ([a-z0-9_]{1,20})-([a-z0-9_]{1,20}(?:-[a-z0-9_]{1,20})?) JRE \(([0-9][!-'*-~]{0,80})\)`) // maxScan bounds how much of a file the version line is looked for in: it // sits in read-only data, and a libjvm is under 64 MiB. @@ -107,7 +108,10 @@ func Inspect(p string, data []byte) (*Library, bool) { l.Platform = string(m[3]) + "-" + string(m[4]) } l.VBMIStubs = bytes.Contains(b, []byte("lookup_lo_base64\x00")) && bytes.Contains(b, []byte("pack_vec_base64\x00")) - if IsOpenJ9Name(base) || l.VMName == "" && (bytes.Contains(b, []byte("OPENJ9_JAVA_OPTIONS")) || bytes.Contains(b, []byte("j9vm"))) { + // OpenJ9: its VM library by name, or its lib/server redirector, which + // has no HotSpot version line, no HotSpot decoder stubs and names + // OPENJ9_JAVA_OPTIONS. + if IsOpenJ9Name(base) || l.VMName == "" && !l.VBMIStubs && bytes.Contains(b, []byte("OPENJ9_JAVA_OPTIONS")) { l.OpenJ9 = true } return l, true diff --git a/detectors/java4shell/internal/jvm/review2_test.go b/detectors/java4shell/internal/jvm/review2_test.go new file mode 100644 index 0000000..0eca09b --- /dev/null +++ b/detectors/java4shell/internal/jvm/review2_test.go @@ -0,0 +1,24 @@ +package jvm + +import ( + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" +) + +// Review finding 1: musl builds name their platform linux-amd64-musl. +func TestInspectMusl(t *testing.T) { + l, ok := Inspect("/opt/java/openjdk/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true, Musl: true, Extra: "\x00j9vm\x00"})) + if !ok || !l.HotSpot() || l.JREVersion != "21.0.13+9-LTS" || l.Platform != "linux-amd64-musl" { + t.Fatalf("musl: %+v", l) + } + if l.OpenJ9 { + t.Error("the bytes j9vm made a HotSpot library OpenJ9") + } + // Without a readable version line, four bytes do not make it OpenJ9 + // when the HotSpot decoder stubs are there. + l, _ = Inspect("/opt/java/openjdk/lib/server/libjvm.so", testlib.Build(testlib.Lib{VBMI: true, Extra: "\x00j9vm\x00"})) + if l.OpenJ9 { + t.Error("an unreadable HotSpot library with j9vm bytes taken for OpenJ9") + } +} diff --git a/detectors/java4shell/internal/testlib/testlib.go b/detectors/java4shell/internal/testlib/testlib.go index 11dded2..34c9473 100644 --- a/detectors/java4shell/internal/testlib/testlib.go +++ b/detectors/java4shell/internal/testlib/testlib.go @@ -17,6 +17,7 @@ type Lib struct { VBMI bool VMName string // OpenJDK 64-Bit Server VM (default) Extra string // more bytes + Musl bool // the platform is --musl, as on Alpine } // Build returns the file's bytes. @@ -56,6 +57,9 @@ func Build(l Lib) []byte { binary.LittleEndian.PutUint16(b[18:], m) } cpu := map[string]string{"x86-64": "amd64", "aarch64": "aarch64", "x86": "x86"}[l.Machine] + if l.Musl { + cpu += "-musl" + } if l.Version != "" { b = append(b, 0) b = append(b, fmt.Sprintf("%s (%s) for %s-%s JRE (%s), built on 2026-10-20T00:00:00Z by \"admin\" with gcc 11.3.0", l.VMName, l.Version, l.OS, cpu, l.Version)...) From 024e7816e557b91df3c97b079b793dd21f885f74 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 01:29:51 +0000 Subject: [PATCH 011/119] java4shell: builds before the fixed build and pre-release JDKs are not fixed Review findings 2, 12 (JDK 28 updates) and 13. The release data now has the first build of each fixed release with the fix (17.0.21.1+2, 21.0.13.1+2, 25.0.5.1+2, 27.0.1.1+4; checked in the openjdk update repositories and recorded in FACTS.md): +0 and +1 lack it. Any pre-release identifier (beta, internal) and adhoc builds count as pre-release. A version older than the fixed update is vulnerable whatever its fourth number. Temurin tags carry the OpenJDK build, so fix never moves to a fixed release's earlier build, and a JDK 28 update is unknown, not early access. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/FACTS.md | 1 + .../internal/knowledge/knowledge.go | 66 ++++++++++++------- .../internal/knowledge/knowledge_test.go | 2 +- .../internal/knowledge/review2_test.go | 44 +++++++++++++ detectors/java4shell/internal/repo/images.go | 18 ++++- detectors/java4shell/internal/repo/plan.go | 3 + detectors/java4shell/internal/repo/repo.go | 2 +- .../java4shell/internal/repo/review_test.go | 16 +++++ detectors/java4shell/java4shell.go | 2 +- 9 files changed, 124 insertions(+), 30 deletions(-) create mode 100644 detectors/java4shell/internal/knowledge/review2_test.go diff --git a/detectors/java4shell/FACTS.md b/detectors/java4shell/FACTS.md index ead4aac..170d43a 100644 --- a/detectors/java4shell/FACTS.md +++ b/detectors/java4shell/FACTS.md @@ -55,6 +55,7 @@ The lead read these; they could not be fetched from the research host. Facts her | OpenJDK 21 | **21.0.13.1** (`jdk-21.0.13.1+2`, `-ga`, 2026-11-15) | openjdk/jdk21u branch `jdk21.0.13.1`, commit `8e115fb5c7` | | OpenJDK 25 | **25.0.5.1** (`jdk-25.0.5.1+2`, `-ga`, 2026-11-15) | openjdk/jdk25u branch `jdk25.0.5.1`, commit `25bb7d35dc` | | OpenJDK 27 | **27.0.1.1** (`jdk-27.0.1.1+4`, `-ga`) | openjdk/jdk27u branch `jdk27.0.1.1`, commit `564fc7de7e`; master also has it. The `jdk27.0.2` branch does **not** have it yet | +| Builds of the fixed releases before the fix landed | **not fixed**: `jdk-17.0.21.1+0` (2026-10-27) and `+1` (2026-11-02), `jdk-21.0.13.1+0` and `+1`, `jdk-25.0.5.1+0` and `+1` do not contain the `cmpl(length, 4)` guard; `+2` (2026-11-15) does. `jdk-27.0.1.1+0` does not; `jdk-27.0.1.1+4` does (27u has no `+1` to `+3` tags). The detector's fixed build per line: 17.0.21.1+2, 21.0.13.1+2, 25.0.5.1+2, 27.0.1.1+4; a version named without its build (a GA tag, a version file) is taken as the GA build. Pre-release and self-built JDKs (`-ea`, `-beta`, `-internal`, `adhoc`) are never judged fixed | `git show :src/hotspot/cpu/x86/stubGenerator_x86_64.cpp` in openjdk/jdk17u, jdk21u, jdk25u, jdk27u, checked 2026-11-18 | | OpenJDK 26 | **no fix**: last release 26.0.2.1 (2026-07), `jdk26u` master unchanged since 2026-08-18 and without the fix | openjdk/jdk26u | | 18, 19, 20, 22, 23, 24 | **no fix** (end of life) | n/a | | JDK 28 (early access) | fix pushed to mainline 2026-11-16; `jdk-28+24` does **not** have it; no later build tagged yet | openjdk/jdk tags | diff --git a/detectors/java4shell/internal/knowledge/knowledge.go b/detectors/java4shell/internal/knowledge/knowledge.go index dda59ae..a49f048 100644 --- a/detectors/java4shell/internal/knowledge/knowledge.go +++ b/detectors/java4shell/internal/knowledge/knowledge.go @@ -37,8 +37,8 @@ const ( // after "+" and whether it is an early-access build. type Version struct { Nums []int - Build int // -1 when absent - EA bool + Build int // -1 when absent + EA bool // a pre-release or self-built JDK: -ea, -beta, -internal, adhoc Raw string } @@ -123,12 +123,17 @@ func Parse(s string) (Version, bool) { if i := strings.IndexByte(r, '+'); i >= 0 { pre, rest = r[:i], r[i:] } - v.EA = strings.HasPrefix(pre, "ea") + // Any pre-release identifier: ea, beta, internal, a build date. + v.EA = pre != "" } if r, ok := strings.CutPrefix(rest, "+"); ok { if b, _ := leadingInt(r); b >= 0 { v.Build = b } + // A self-built JDK ("+0-adhoc.root.jdk17u") is not a release. + if strings.Contains(r, "adhoc") { + v.EA = true + } } return v, true } @@ -176,25 +181,28 @@ type Line struct { Introduced []int // IntroducedBuild is the first build of Introduced that has it (17.0.6+3). IntroducedBuild int - // Fixed is the first release with the fix (nil: none). - Fixed []int + // Fixed is the first release with the fix (nil: none), and FixedBuild + // the first build of it that has the fix: earlier builds of the same + // release (17.0.21.1+0 and +1) do not. + Fixed []int + FixedBuild int // Note is why the line has no fix, or other context. Note string } // Lines is the release data, newest last. FACTS.md gives the sources. var Lines = []Line{ - {Feature: 17, Introduced: []int{17, 0, 6}, IntroducedBuild: 3, Fixed: []int{17, 0, 21, 1}}, + {Feature: 17, Introduced: []int{17, 0, 6}, IntroducedBuild: 3, Fixed: []int{17, 0, 21, 1}, FixedBuild: 2}, {Feature: 18, Note: "JDK 18 is end of life and received no fix"}, {Feature: 19, Note: "JDK 19 is end of life and received no fix"}, {Feature: 20, Note: "JDK 20 is end of life and received no fix"}, - {Feature: 21, Fixed: []int{21, 0, 13, 1}}, + {Feature: 21, Fixed: []int{21, 0, 13, 1}, FixedBuild: 2}, {Feature: 22, Note: "JDK 22 is end of life and received no fix"}, {Feature: 23, Note: "JDK 23 is end of life and received no fix"}, {Feature: 24, Note: "JDK 24 is end of life and received no fix"}, - {Feature: 25, Fixed: []int{25, 0, 5, 1}}, + {Feature: 25, Fixed: []int{25, 0, 5, 1}, FixedBuild: 2}, {Feature: 26, Note: "JDK 26 is end of life (last release 26.0.2.1) and received no fix"}, - {Feature: 27, Fixed: []int{27, 0, 1, 1}}, + {Feature: 27, Fixed: []int{27, 0, 1, 1}, FixedBuild: 4}, } // EAFeature is the line in early access, and the last EA build known to @@ -266,11 +274,13 @@ func Judge(v Version) (Status, string) { return Unknown, "the version could not be read" case f < firstVBMIDecode: return NotAffected, fmt.Sprintf("Java %s: OpenJDK %d has no x86-64 Base64 decode intrinsic, so it does not have the vulnerable AVX-512 code", ver, f) + case f == EAFeature && len(v.Nums) > 1: + return Unknown, fmt.Sprintf("Java %s is an update of JDK %d, which had no release when this detector's data was checked (%s)", ver, f, Checked) case f == EAFeature: if v.Build >= 0 && v.Build <= EALastUnfixed { - return Vulnerable, fmt.Sprintf("JDK %d early-access build %d: the fix reached mainline after jdk-28+%d", f, v.Build, EALastUnfixed) + return Vulnerable, fmt.Sprintf("JDK %d build %d: the fix reached mainline after jdk-28+%d", f, v.Build, EALastUnfixed) } - return Unknown, fmt.Sprintf("JDK %d early-access build %s: the fix reached mainline on 2026-11-16, after jdk-28+%d; check that this build includes %s", f, buildText(v), EALastUnfixed, Bug) + return Unknown, fmt.Sprintf("JDK %d build %s: the fix reached mainline on 2026-11-16, after jdk-28+%d; check that this build includes %s", f, buildText(v), EALastUnfixed, Bug) case f > newestFeature: return Unknown, fmt.Sprintf("Java %s is newer than this detector's release data (%s)", ver, Checked) } @@ -278,12 +288,6 @@ func Judge(v Version) (Status, string) { if !ok { return Unknown, fmt.Sprintf("Java %s is not in this detector's release data", ver) } - if len(v.Nums) >= 4 && v.Nums[3] > maxPatch { - // OpenJDK patch numbers are small (17.0.8.1, 21.0.13.1); a larger - // fourth number is a vendor's build number (Amazon Corretto's - // 21.0.13.11), which says nothing about the patch. - return Unknown, fmt.Sprintf("Java %s: the fourth number looks like a vendor build number, not an OpenJDK patch release, so the version does not show whether %s is in", ver, Bug) - } if l.Introduced != nil { c := Compare(v.Nums, l.Introduced) if c < 0 || c == 0 && v.EA && v.Build >= 0 && v.Build < l.IntroducedBuild { @@ -293,17 +297,31 @@ func Judge(v Version) (Status, string) { if l.Fixed == nil { return Vulnerable, fmt.Sprintf("Java %s has the AVX-512 VBMI Base64 decoder without the fix: %s", ver, l.Note) } - if Compare(v.Nums, l.Fixed) < 0 { + // The update first (17.0.21 of 17.0.21.1): older is unfixed whatever + // follows it. + upd := v.Nums[:min(3, len(v.Nums))] + switch c := Compare(upd, l.Fixed[:3]); { + case c < 0: return Vulnerable, fmt.Sprintf("Java %s is older than %s, the first %d release with the fix (%s)", ver, join(l.Fixed), f, Bug) - } - // Releases of the same update as the fix (17.0.21.1, 17.0.21.2) carry - // it. A later update (17.0.22) was not released when the data was - // checked, and its development builds did not have the fix yet. - if len(v.Nums) >= 3 && len(l.Fixed) >= 3 && v.Nums[2] > l.Fixed[2] || len(v.Nums) >= 2 && v.Nums[1] > l.Fixed[1] { + case c > 0: + // A later update (17.0.22) was not released when the data was + // checked, and its development builds did not have the fix yet. return Unknown, fmt.Sprintf("Java %s is a later update than %s; it was not released when this detector's data was checked (%s), and the %d update repository did not have %s yet: check its release notes", ver, join(l.Fixed), Checked, f, Bug) } + if len(v.Nums) >= 4 && v.Nums[3] > maxPatch { + // OpenJDK patch numbers are small (17.0.8.1, 21.0.13.1); a larger + // fourth number is a vendor's build number (Amazon Corretto's + // 21.0.13.11), which says nothing about the patch. + return Unknown, fmt.Sprintf("Java %s: the fourth number looks like a vendor build number, not an OpenJDK patch release, so the version does not show whether %s is in", ver, Bug) + } + switch c := Compare(v.Nums, l.Fixed); { + case c < 0: + return Vulnerable, fmt.Sprintf("Java %s is older than %s, the first %d release with the fix (%s)", ver, join(l.Fixed), f, Bug) + case c == 0 && v.Build >= 0 && v.Build < l.FixedBuild: + return Vulnerable, fmt.Sprintf("Java %s build %d predates the fix: it reached %s in build %d (%s)", ver, v.Build, join(l.Fixed), l.FixedBuild, Bug) + } if v.EA { - return Unknown, fmt.Sprintf("Java %s is an early-access build; check that it includes %s", ver, Bug) + return Unknown, fmt.Sprintf("Java %s is a pre-release or self-built JDK; check that it includes %s", ver, Bug) } return Fixed, fmt.Sprintf("Java %s is at or past %s, the first %d release with the fix (%s)", ver, join(l.Fixed), f, Bug) } diff --git a/detectors/java4shell/internal/knowledge/knowledge_test.go b/detectors/java4shell/internal/knowledge/knowledge_test.go index 91d159c..d45927f 100644 --- a/detectors/java4shell/internal/knowledge/knowledge_test.go +++ b/detectors/java4shell/internal/knowledge/knowledge_test.go @@ -23,7 +23,7 @@ func TestParse(t *testing.T) { {"25.0.5", "25.0.5", -1, false}, {"21", "21", -1, false}, {"11.0.33+7", "11.0.33", 7, false}, - {"21.0.13-internal+0-adhoc.root.src", "21.0.13", 0, false}, + {"21.0.13-internal+0-adhoc.root.src", "21.0.13", 0, true}, } { v, ok := Parse(c.in) if !ok || v.String() != c.nums || v.Build != c.build || v.EA != c.ea { diff --git a/detectors/java4shell/internal/knowledge/review2_test.go b/detectors/java4shell/internal/knowledge/review2_test.go new file mode 100644 index 0000000..29be026 --- /dev/null +++ b/detectors/java4shell/internal/knowledge/review2_test.go @@ -0,0 +1,44 @@ +package knowledge + +import "testing" + +// Review findings 2, 12 and 13. +func TestReviewBuilds(t *testing.T) { + for _, c := range []struct { + v string + want Status + }{ + // Builds of the fixed release before the fix landed (+2; 27: +4). + {"17.0.21.1+0", Vulnerable}, + {"17.0.21.1+1", Vulnerable}, + {"17.0.21.1+2", Fixed}, + {"21.0.13.1+1-LTS", Vulnerable}, + {"21.0.13.1+2-LTS", Fixed}, + {"25.0.5.1+1", Vulnerable}, + {"25.0.5.1+2", Fixed}, + {"27.0.1.1+0", Vulnerable}, + {"27.0.1.1+3", Vulnerable}, + {"27.0.1.1+4", Fixed}, + {"17.0.21.1", Fixed}, // a release named without its build is the GA + {"17.0.21.2+1", Fixed}, + // Pre-release builds are not judged fixed. + {"21.0.13.1-beta+1-202611100000", Vulnerable}, + {"21.0.13.1-beta+2-202611150000", Unknown}, + {"17.0.21.1-internal+0-adhoc.root.jdk17u", Vulnerable}, + {"17.0.21.1-internal+2-adhoc.root.jdk17u", Unknown}, + {"17.0.21.1+2-adhoc.builder.jdk", Unknown}, + // Older than the fix whatever the fourth number means. + {"21.0.2.13.1", Vulnerable}, + // A JDK 28 update release is not an early-access build. + {"28.0.1+2", Unknown}, + {"28+24", Vulnerable}, + } { + v, ok := Parse(c.v) + if !ok { + t.Fatalf("Parse(%q) failed", c.v) + } + if got, why := Judge(v); got != c.want { + t.Errorf("Judge(%s) = %s (%s), want %s", c.v, got, why, c.want) + } + } +} diff --git a/detectors/java4shell/internal/repo/images.go b/detectors/java4shell/internal/repo/images.go index ba49918..5f310db 100644 --- a/detectors/java4shell/internal/repo/images.go +++ b/detectors/java4shell/internal/repo/images.go @@ -1,6 +1,7 @@ package repo import ( + "fmt" "regexp" "strconv" "strings" @@ -17,6 +18,9 @@ type Family struct { OpenJ9 bool // Prefix comes before the version in the tag ("open-" for Semeru). Prefix string + // OpenJDKBuild is true when the build in the tag is OpenJDK's build + // number (Temurin's "_9"); other vendors' tag builds are their own. + OpenJDKBuild bool // exact reports whether the text after the version pins one release // (Temurin's "_9", Liberica's "-10", Zulu's "-21.52"), so the version // has no further numbers. @@ -31,7 +35,7 @@ var ( // Families are the runtime images this detector reads tags of. var Families = []Family{ - {Repo: "eclipse-temurin", Vendor: "Eclipse Temurin", exact: temurinBuild}, + {Repo: "eclipse-temurin", Vendor: "Eclipse Temurin", exact: temurinBuild, OpenJDKBuild: true}, {Repo: "amazoncorretto", Vendor: "Amazon Corretto"}, {Repo: "openjdk", Vendor: "OpenJDK (the deprecated official image)"}, {Repo: "sapmachine", Vendor: "SapMachine"}, @@ -94,6 +98,9 @@ type TagVersion struct { // Text is the version as written in the tag, Variant what follows it // (and its build), for finding the same variant of another release. Text, Build, Variant string + // OpenJDKBuild is the OpenJDK build number the tag names, -1 when it + // names none (a vendor's own build number, or no build). + OpenJDKBuild int } // ParseTag reads the Java release a family's tag names. ok is false for a @@ -111,7 +118,7 @@ func (f Family) ParseTag(tag string) (TagVersion, bool) { if rest != "" && rest[0] >= '0' && rest[0] <= '9' { return TagVersion{}, false } - tv := TagVersion{Text: m, Variant: rest} + tv := TagVersion{Text: m, Variant: rest, OpenJDKBuild: -1} for _, p := range strings.Split(m, ".") { n, err := strconv.Atoi(p) if err != nil { @@ -131,6 +138,11 @@ func (f Family) ParseTag(tag string) (TagVersion, bool) { if b := f.exact.FindString(rest); b != "" { b = strings.TrimSuffix(b, "-") tv.Exact, tv.Build, tv.Variant = true, b, rest[len(b):] + if f.OpenJDKBuild { + n := 0 + fmt.Sscanf(strings.TrimLeft(b, "_-"), "%d", &n) + tv.OpenJDKBuild = n + } } } return tv, true @@ -146,7 +158,7 @@ func JudgeTag(tv TagVersion) (knowledge.Status, string) { what = "the tag names the newest Java " + tv.Text + " release at build time" } if tv.Exact || feature < 17 { - st, why := knowledge.Judge(knowledge.Version{Nums: nums, Build: -1}) + st, why := knowledge.Judge(knowledge.Version{Nums: nums, Build: tv.OpenJDKBuild}) return st, what + ": " + why } l, ok := knowledge.LineOf(feature) diff --git a/detectors/java4shell/internal/repo/plan.go b/detectors/java4shell/internal/repo/plan.go index 2695236..291bb0a 100644 --- a/detectors/java4shell/internal/repo/plan.go +++ b/detectors/java4shell/internal/repo/plan.go @@ -75,6 +75,9 @@ func target(tags []string, e *pinEdit) (string, bool) { switch st, _ := JudgeTag(tv); { case st == knowledge.Fixed: cs = append(cs, cand{t, tv, false}) + case st == knowledge.Vulnerable: + // Below the fix, or a build of the fixed release before the + // fix landed (21.0.13.1_1): never a target. case !tv.Exact && fixed.Fixed != nil && len(tv.Nums) == 3 && knowledge.Compare(tv.Nums, fixed.Fixed[:3]) == 0: // A moving tag of the fixed update (Corretto republishes // "21.0.13" with 21.0.13.1.2): only reading the image shows diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 0103400..c289871 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -323,7 +323,7 @@ var versionInText = regexp.MustCompile(`(\d{1,3}(?:\.\d{1,9}){0,5})`) // moving pin (the newest release of that line) and is reported only when // its line has no fix at all. func (s *scanner) judgeVersion(rel string, line, col int, verText, source, vendor string) { - tv := TagVersion{Text: verText, Exact: strings.Count(verText, ".") >= 2} + tv := TagVersion{Text: verText, Exact: strings.Count(verText, ".") >= 2, OpenJDKBuild: -1} for _, p := range strings.Split(verText, ".") { n := 0 fmt.Sscanf(p, "%d", &n) diff --git a/detectors/java4shell/internal/repo/review_test.go b/detectors/java4shell/internal/repo/review_test.go index c95ea09..89d7b9b 100644 --- a/detectors/java4shell/internal/repo/review_test.go +++ b/detectors/java4shell/internal/repo/review_test.go @@ -66,3 +66,19 @@ func TestReviewRepo(t *testing.T) { t.Errorf("corretto target prefers the named fix: %q", got) } } + +// Review finding 2: fix never picks a build below the fixed build. +func TestTargetBelowFixedBuild(t *testing.T) { + e := &pinEdit{family: Families[0], feature: 21} + e.tv, _ = Families[0].ParseTag("21.0.13_9-jre") + if got, ok := target([]string{"21.0.13.1_1-jre"}, e); ok { + t.Errorf("picked %s, a build without the fix", got) + } + if got, _ := target([]string{"21.0.13.1_1-jre", "21.0.13.1_2-jre"}, e); got != "21.0.13.1_2-jre" { + t.Errorf("picked %s", got) + } + tv, _ := Families[0].ParseTag("21.0.13.1_1-jre") + if st, why := JudgeTag(tv); st != "vulnerable" { + t.Errorf("21.0.13.1_1: %s (%s)", st, why) + } +} diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 7d98c96..5e33deb 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -90,7 +90,7 @@ func (d *Detector) Manifest() engine.Manifest { func (d *Detector) Load() error { prev := 0 for _, l := range knowledge.Lines { - if l.Feature <= prev || l.Fixed == nil && l.Note == "" || l.Fixed != nil && l.Fixed[0] != l.Feature { + if l.Feature <= prev || l.Fixed == nil && l.Note == "" || l.Fixed != nil && (l.Fixed[0] != l.Feature || l.FixedBuild < 1) { return fmt.Errorf("release data for Java %d contradicts itself", l.Feature) } prev = l.Feature From d03d317f0fc4dd9514a484e1dae9dfacc8391fe5 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 01:30:39 +0000 Subject: [PATCH 012/119] java4shell: a mitigated runtime stays vulnerable Review finding 3, as the lead decided: JVM options that keep the decoder from being generated are recorded on the finding (status mitigated, the option and where it was set) and the finding stays vulnerable, so it is shown by default and counts in the exit status. fix also moves mitigated pins. Parity expectations and README follow. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- detectors/java4shell/internal/repo/plan.go | 2 +- detectors/java4shell/internal/repo/refscan.go | 2 +- detectors/java4shell/internal/repo/repo.go | 3 ++- detectors/java4shell/java4shell.go | 6 ++++-- detectors/java4shell/java4shell_test.go | 2 +- detectors/java4shell/repo.go | 18 +++++++--------- detectors/java4shell/review2_test.go | 21 +++++++++++++++++++ parity/java4shell/cases.json | 14 ++++++------- 9 files changed, 46 insertions(+), 24 deletions(-) create mode 100644 detectors/java4shell/review2_test.go diff --git a/README.md b/README.md index 6f6bd66..7f1011a 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ One engine for DefectDojo's emerging-vulnerability scanners. Each new vulnerabil | `php2shell` | PHP runtimes vulnerable to CVE-2026-109618 and CVE-2026-109619 ("PHP2Shell"), fixed in PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12 ([GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w), [GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp)). A packaged PHP is judged by its vendor's backport data, never by the version it reports. Also checks the images a source tree builds on and deploys, and can rewrite them to fixed images | `fs`, `image`, `repo`, `fix` | | `brotli` | Brotli decoders vulnerable to CVE-2026-111497 ("Node2Shell", "Broccoli2Shell"), Brotli 1.0.3 through 1.2.0, fixed in 1.0.10, 1.1.1 and 1.2.1 ([GHSA-9v8h-qqgm-4m35](https://github.com/advisories/GHSA-9v8h-qqgm-4m35)): system `libbrotlidec` and every copy bundled into other software (Node.js, .NET, Bun, Electron, Envoy and Istio, Python wheels such as Pillow, pyarrow, duckdb, pycurl and PyMuPDF, brotli4j, and more), on Linux, Windows and macOS. A decoder is judged first by the error code the fix added, so vendor backports are recognised without distribution data; a build that strips it by its own version stamp or by its code, which returns that error code only once fixed. In a source tree it finds the Node.js, .NET and Bun releases and the bundling packages a project pins, and `fix` moves each to the fixed release | `fs`, `image`, `repo`, `fix` | | `sshole` | \*sshole, the OpenSSH password authentication bypass on musl libc fixed in OpenSSH 10.6p2 and in Alpine's openssh packages of November 5, 2026 ([release notes](https://www.openssh.org/releasenotes.html#10.6p2), [writeup](https://sshhole.com)). On musl, sshd from 7.3p1 to 10.6p1 compares an account's password field of `*` with the `*` that crypt returns when it fails, so a crafted password logs in to that account. It judges each installed sshd by its C library, its release and the apk database (Alpine backports keep the release number), then checks what the target's `sshd_config` (Include, Match, PasswordAuthentication, AuthenticationMethods, PermitRootLogin, AllowUsers and the rest) and account files make reachable, and reports the accounts. In an image it also reads the command (`sshd -o` and `-f`) and the startup scripts it runs (entrypoints, s6, cont-init.d), and reports a server as exposed when a startup script turns password logins on, sets a `*` field or sets passwords. OpenWrt's opkg database and its backports (23.05, 24.10, 25.12) count like Alpine's. PAM-checked builds (`UsePAM yes`) are not affected. On a live server it reads the banner and the offered methods and never sends a password. In a source tree it finds Dockerfiles that install an OpenSSH server on Alpine without the fix (package lists in `ARG` and `ENV` too), Ansible apk tasks, Buildroot, OpenWrt and Yocto configurations that build one on musl, and anything that sets a password field to `*`. It also pulls the images the tree references (through the guarded transport, with the command a Compose service or Kubernetes container sets) and judges them like `scan image`. `fix` adds the fixed release floor (in the variable when the list is one), moves an end-of-life Alpine base to a tag on the nearest fixed Alpine release (`alpine:3.14` to `3.16`, `python:3.9-alpine3.14` to `3.9-alpine3.16` after checking that image) as a labelled upgrade, adds upstream commit 4353fdc43 as a patch scoped to the OpenSSH versions it applies to (Buildroot `BR2_GLOBAL_PATCH_DIR`, a version-specific Yocto bbappend), sets Ansible tasks to `state: latest`, and changes `*` to `*NP*` | `fs`, `image`, `host`, `repo`, `fix` | -| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64 (JDK-8393212), fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 on November 15, 2026 ([fix](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b), [knowledge table](detectors/java4shell/FACTS.md)). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel Ice Lake and later, AMD Zen 4 and later); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds every Java runtime by its VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others). Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; every platform of a multi-arch image is judged on its own), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness and never overrides the library. No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version. OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is reported as mitigated (still to update), never as fixed; `_JAVA_OPTIONS` turning the intrinsic back on undoes it. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context, never as a clearance. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft and Oracle images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | +| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64 (JDK-8393212), fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 on November 15, 2026 ([fix](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b), [knowledge table](detectors/java4shell/FACTS.md)). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel Ice Lake and later, AMD Zen 4 and later); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds every Java runtime by its VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others). Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; every platform of a multi-arch image is judged on its own), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness and never overrides the library. No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version. OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is recorded as a mitigation on a finding that stays vulnerable (status `mitigated`, counted in the exit status): the options can be overridden where the runtime is deployed, and the runtime still needs the update; `_JAVA_OPTIONS` turning the intrinsic back on undoes it. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context, never as a clearance. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft and Oracle images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | The detectors ported from standalone scanners also build as standalone binaries under the names people search for: `emudhra-scan` and `php2shell-scan`. They keep their original commands, flags and exit status rules. `brotli`, `sshole` and `java4shell` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`, `--detector java4shell`). diff --git a/detectors/java4shell/internal/repo/plan.go b/detectors/java4shell/internal/repo/plan.go index 291bb0a..aa9652e 100644 --- a/detectors/java4shell/internal/repo/plan.go +++ b/detectors/java4shell/internal/repo/plan.go @@ -215,7 +215,7 @@ func planLine(ctx context.Context, root string, f Finding, file string, line, co had[key(x)]++ } for _, x := range after.Findings { - if x.File == f.File && x.Line == f.Line && x.Rule == f.Rule && x.Status != StatusMitigated { + if x.File == f.File && x.Line == f.Line && x.Rule == f.Rule { return nil, declined("after the edit, line %d of %s still selects a release without the fix; change it by hand", f.Line, f.File) } if had[key(x)] == 0 && x.Level != "note" { diff --git a/detectors/java4shell/internal/repo/refscan.go b/detectors/java4shell/internal/repo/refscan.go index af8abfb..11eab55 100644 --- a/detectors/java4shell/internal/repo/refscan.go +++ b/detectors/java4shell/internal/repo/refscan.go @@ -95,7 +95,7 @@ func (s *scanner) judgeRef(r refs.Ref, opts Options) { f.Fix = fmt.Sprintf("Java %d received no fix: move to a supported release with the fix, such as %s (a major upgrade: test it).", feature, knowledge.Upgrade(feature)) } if mit != "" { - f.Status, f.Level = StatusMitigated, "note" + f.Status = StatusMitigated f.Reason = why + "; " + mit f.Message += ", mitigated by its JVM options until it is updated" } diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index c289871..48ec13a 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -740,7 +740,8 @@ func (s *scanner) dockerfile(rel, text string) { for k := stageStart; k < len(s.findings); k++ { f := &s.findings[k] if f.File == rel && f.Rule == RulePackage && f.Status == StatusVulnerable { - f.Status, f.Level = StatusMitigated, "note" + f.Status = StatusMitigated + f.Props["mitigation"] = how f.Reason += "; " + how f.Message += ", mitigated by the stage's JVM options until it is updated" } diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 5e33deb..9503ea3 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -268,8 +268,10 @@ var verdicts = map[assess.Status]engine.Verdict{ assess.Vulnerable: engine.Vulnerable, assess.Fixed: engine.Fixed, assess.NotAffected: engine.Fixed, - assess.Mitigated: engine.Inactive, - assess.Unknown: engine.Unknown, + // Mitigated is not cleared: the options can be overridden where the + // runtime is deployed, and the runtime still needs the update. + assess.Mitigated: engine.Vulnerable, + assess.Unknown: engine.Unknown, } func finding(x assess.Finding) engine.Finding { diff --git a/detectors/java4shell/java4shell_test.go b/detectors/java4shell/java4shell_test.go index fd9fc33..1944905 100644 --- a/detectors/java4shell/java4shell_test.go +++ b/detectors/java4shell/java4shell_test.go @@ -78,7 +78,7 @@ func TestScanFS(t *testing.T) { if f := fs["/opt/arm"]; f.Verdict != engine.Fixed || f.Facts["status"] != "not-affected" || !strings.Contains(f.Reason, "aarch64") { t.Errorf("arm: %+v", f) } - if f := fs["/opt/atlassian/confluence/jre"]; f.Kind != java4shell.KindBundled || f.Verdict != engine.Inactive || f.Facts["status"] != "mitigated" || f.Fix == "" { + if f := fs["/opt/atlassian/confluence/jre"]; f.Kind != java4shell.KindBundled || f.Verdict != engine.Vulnerable || f.Facts["status"] != "mitigated" || f.Fix == "" { t.Errorf("confluence: %+v", f) } if code != 1 { diff --git a/detectors/java4shell/repo.go b/detectors/java4shell/repo.go index b949188..0fcaadc 100644 --- a/detectors/java4shell/repo.go +++ b/detectors/java4shell/repo.go @@ -83,8 +83,6 @@ func repoFinding(f repo.Finding) engine.Finding { switch f.Status { case repo.StatusUnknown: v = engine.Unknown - case repo.StatusMitigated: - v = engine.Inactive } if reason == "" && v != engine.Vulnerable { reason = "not decided" @@ -93,6 +91,9 @@ func repoFinding(f repo.Finding) engine.Finding { for k, val := range f.Props { facts[k] = val } + if f.Status == repo.StatusMitigated { + facts["status"] = "mitigated" // still vulnerable: a fact, not a clearance + } out := engine.Finding{Kind: f.Rule, Path: f.File, Line: f.Line, Verdict: v, Reason: reason, Message: f.Message, Method: "source", Facts: facts, Fix: f.Fix, CVEs: []engine.CVEResult{{ID: knowledge.CVE, Verdict: v, Reason: reason}}} if f.Level == "warning" { @@ -139,10 +140,9 @@ func (d *Detector) pulled(dir string, f repo.Finding, o engine.Options, cache ma g.Facts["image"], g.Facts["runtime"] = img, x.Path g.Message = fmt.Sprintf("image %s: %s: %s", img, x.Path, x.Message) if mit := f.Props["mitigation"]; mit != "" && x.Verdict == engine.Vulnerable { - g.Verdict = engine.Inactive - g.Reason = x.Reason + "; " + mit - g.Message += ", mitigated by its JVM options until it is updated" - g.CVEs = []engine.CVEResult{{ID: knowledge.CVE, Verdict: g.Verdict, Reason: g.Reason}} + // Still vulnerable: the options are a mitigation, recorded as a fact. + g.Facts["status"], g.Facts["mitigation"] = "mitigated", mit + g.Message += "; the deployment sets a mitigation until it is updated" } g.Fix = x.Fix + " Use a release of " + img + " built with the fix (or rebuild it), then redeploy." out = append(out, g) @@ -187,9 +187,6 @@ func (d *Detector) Fix(ctx context.Context, dirs []string, o engine.Options, std } dummy := &engine.Target{} for _, g := range d.pulled(dir, f, o, pulls, dummy) { - if g.Verdict == engine.Inactive { - continue - } fmt.Fprintf(stdout, "not fixed %s %s\n %s\n", where, repo.Printable(g.Message), repo.Printable(g.Fix)) if g.Facts["product"] != "" && f.Props["mitigation"] == "" && strings.HasSuffix(strings.ToLower(f.File), "dockerfile") { fmt.Fprintf(stdout, " optional interim mitigation (not applied):\n %s\n", repo.Printable(repo.Mitigation(f.File, f.Line))) @@ -198,7 +195,8 @@ func (d *Detector) Fix(ctx context.Context, dirs []string, o engine.Options, std } continue } - if f.Status == repo.StatusMitigated || f.Level == "note" && f.Rule != repo.RuleNotChecked { + // A mitigated pin still needs the update, so fix moves it too. + if f.Level == "note" && f.Rule != repo.RuleNotChecked && f.Status != repo.StatusMitigated { continue } if f.Rule == repo.RuleNotChecked { diff --git a/detectors/java4shell/review2_test.go b/detectors/java4shell/review2_test.go new file mode 100644 index 0000000..e559696 --- /dev/null +++ b/detectors/java4shell/review2_test.go @@ -0,0 +1,21 @@ +package java4shell_test + +import ( + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// Review finding 3: a mitigated runtime stays on the list (vulnerable, with +// the mitigation as a fact) and the scan exits 1. +func TestMitigatedIsNotCleared(t *testing.T) { + root := t.TempDir() + write(t, root, "opt/atlassian/jira/jre/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true})) + write(t, root, "opt/atlassian/jira/bin/setenv.sh", []byte("JVM_SUPPORT_RECOMMENDED_ARGS=\"-XX:-UseBASE64Intrinsics\"\n")) + r, code := run(t, "scan", "fs", "--as-root", root) + f := byPath(r)["/opt/atlassian/jira/jre"] + if f.Verdict != engine.Vulnerable || f.Facts["status"] != "mitigated" || f.Facts["mitigation"] == "" || code != 1 { + t.Errorf("mitigated: %s %q exit %d", f.Verdict, f.Facts["status"], code) + } +} diff --git a/parity/java4shell/cases.json b/parity/java4shell/cases.json index ecb1b6c..b0ecd87 100644 --- a/parity/java4shell/cases.json +++ b/parity/java4shell/cases.json @@ -406,7 +406,7 @@ "linux/amd64", "/opt/atlassian/jira/jre", "bundled-runtime", - "inactive", + "vulnerable", "mitigated" ], [ @@ -473,7 +473,7 @@ "linux/amd64", "/opt/java/openjdk", "runtime", - "inactive", + "vulnerable", "mitigated" ] ] @@ -488,7 +488,7 @@ "linux/amd64", "/opt/java/openjdk", "runtime", - "inactive", + "vulnerable", "mitigated" ] ] @@ -518,7 +518,7 @@ "linux/amd64", "/opt/java/openjdk", "runtime", - "inactive", + "vulnerable", "mitigated" ] ] @@ -533,7 +533,7 @@ "linux/amd64", "/opt/java/openjdk", "runtime", - "inactive", + "vulnerable", "mitigated" ] ] @@ -609,7 +609,7 @@ [ "Dockerfile.pkg:2", "os-package", - "inactive" + "vulnerable" ], [ "build.gradle.kts:3", @@ -629,7 +629,7 @@ [ "compose.yaml:5", "image-pin", - "inactive" + "vulnerable" ], [ "compose.yaml:13", From 300fa30a768030643f8be1e3135f78691fbc4d9b Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 01:32:23 +0000 Subject: [PATCH 013/119] java4shell: a command that turns the decoder back on voids the mitigation Review findings 4 and 9. Words of the container command that turn the intrinsic back on (-XX:+UseBASE64Intrinsics, -XX:UseAVX=3 or higher) now count wherever the java they start is: a sh -c script, a java this scan cannot tie to a runtime. A java @argfile makes a mitigation unprovable. _JAVA_OPTIONS still applies last. In a source tree the same holds for a Dockerfile stage's ENTRYPOINT and CMD and a Compose service's or Kubernetes container's command and args. Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/assess/assess.go | 14 +++++ .../internal/assess/review2_test.go | 30 +++++++++++ detectors/java4shell/internal/jvm/options.go | 41 +++++++++++++++ detectors/java4shell/internal/repo/refscan.go | 21 +++++++- detectors/java4shell/internal/repo/repo.go | 51 ++++++++++++++++++- .../java4shell/internal/repo/review_test.go | 21 ++++++++ 6 files changed, 175 insertions(+), 3 deletions(-) diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index 3fa2ab0..e2fbb20 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -326,6 +326,7 @@ func owner(in Input, root string, lib *jvm.Library) (Package, bool) { func mitigation(in Input, env map[string]string, root string, feature int, f *Finding) (bool, string) { // Settings files of the product the runtime is bundled in. var o jvm.Options + var b64, avx, argfile bool if in.Env != nil { if v, ok := env["JAVA_TOOL_OPTIONS"]; ok { o.Apply(v, "the image's JAVA_TOOL_OPTIONS") @@ -347,6 +348,13 @@ func mitigation(in Input, env map[string]string, root string, feature int, f *Fi o.ApplyWord(w, "the container's command") } } + // Words that turn the decoder back on count wherever the command + // starts java (a "sh -c" script, a java this scan cannot place): + // a mitigation has to hold for every launch. + b64, avx, argfile = jvm.Undoes(jvm.CommandWords(in.Command)) + if argfile { + return false, "" + } } for _, s := range in.Settings { if s.Kind == "systemd" || s.Scope == "" { @@ -356,6 +364,12 @@ func mitigation(in Input, env map[string]string, root string, feature int, f *Fi s.ApplyTo(&o, feature) } } + if b64 { + o.ApplyWord("-XX:+UseBASE64Intrinsics", "the container's command") + } + if avx { + o.ApplyWord("-XX:UseAVX=3", "the container's command") + } if in.Env != nil { if v, ok := env["_JAVA_OPTIONS"]; ok { o.Apply(v, "the image's _JAVA_OPTIONS") diff --git a/detectors/java4shell/internal/assess/review2_test.go b/detectors/java4shell/internal/assess/review2_test.go index 833c442..1e24af0 100644 --- a/detectors/java4shell/internal/assess/review2_test.go +++ b/detectors/java4shell/internal/assess/review2_test.go @@ -39,3 +39,33 @@ func TestReleaseContradiction(t *testing.T) { t.Errorf("HotSpot library, OpenJ9 release: %s (%s)", f.Status, f.Reason) } } + +// Review finding 4: a command that turns the intrinsic back on voids the +// image's mitigation, even when it cannot be tied to one runtime. +func TestCommandReenables(t *testing.T) { + for _, c := range []struct { + env string + cmd []string + }{ + {"JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics", []string{"/bin/sh", "-c", "exec java -XX:+UseBASE64Intrinsics -jar /app.jar"}}, + {"JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics", []string{"java", "-XX:+UseBASE64Intrinsics", "-jar", "/app.jar"}}, // no PATH in the image config + {"JAVA_TOOL_OPTIONS=-XX:UseAVX=2", []string{"java", "-XX:UseAVX=3", "-jar", "/app.jar"}}, + {"JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics", []string{"java", "@/app/jvm.args", "-jar", "/app.jar"}}, // options from a file this scan cannot see + } { + in := Input{Libraries: []*jvm.Library{vulnLib(t, temurin)}, Env: []string{c.env}, Command: c.cmd} + if f := one(t, in); f.Status != Vulnerable || f.Mitigation != "" { + t.Errorf("%q: %s (%s)", c.cmd, f.Status, f.Mitigation) + } + } + // Turning AVX-512 back on leaves -XX:-UseBASE64Intrinsics in force. + in := Input{Libraries: []*jvm.Library{vulnLib(t, temurin)}, Env: []string{"JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics"}, Command: []string{"java", "-XX:UseAVX=3", "-jar", "/a.jar"}} + if f := one(t, in); f.Status != Mitigated { + t.Errorf("UseAVX=3 with -UseBASE64Intrinsics: %s", f.Status) + } + // _JAVA_OPTIONS is applied after the command line, so it still holds. + in = Input{Libraries: []*jvm.Library{vulnLib(t, temurin)}, Env: []string{"_JAVA_OPTIONS=-XX:-UseBASE64Intrinsics"}, + Command: []string{"/bin/sh", "-c", "exec java -XX:+UseBASE64Intrinsics -jar /app.jar"}} + if f := one(t, in); f.Status != Mitigated { + t.Errorf("_JAVA_OPTIONS after the command: %s", f.Status) + } +} diff --git a/detectors/java4shell/internal/jvm/options.go b/detectors/java4shell/internal/jvm/options.go index 6ebfbd0..1dfe33f 100644 --- a/detectors/java4shell/internal/jvm/options.go +++ b/detectors/java4shell/internal/jvm/options.go @@ -203,3 +203,44 @@ func baseName(p string) string { } return strings.TrimSuffix(strings.ToLower(p), ".exe") } + +// CommandWords returns every word of a container command, with the words +// of a "sh -c" script split out. +func CommandWords(cmd []string) []string { + if len(cmd) > 1024 { + cmd = cmd[:1024] + } + var out []string + for i, w := range cmd { + if i > 0 && cmd[i-1] == "-c" && i >= 2 { + if b := baseName(cmd[i-2]); b == "sh" || b == "bash" || b == "ash" || b == "dash" { + out = append(out, Words(w)...) + continue + } + } + out = append(out, w) + } + return out +} + +// Undoes reports what in a command or option text can turn the decoder +// back on, wherever the java it starts is: -XX:+UseBASE64Intrinsics, +// -XX:UseAVX=3 or higher, or a java @argfile this scan cannot read. +func Undoes(words []string) (base64, avx, argfile bool) { + java := false + for _, w := range words { + switch { + case baseName(w) == "java": + java = true + case w == "-XX:+UseBASE64Intrinsics" || w == "-XX:UseBASE64Intrinsics=true": + base64 = true + case strings.HasPrefix(w, "-XX:UseAVX="): + if n, err := strconv.Atoi(strings.TrimPrefix(w, "-XX:UseAVX=")); err != nil || n >= 3 { + avx = true + } + case java && strings.HasPrefix(w, "@") && len(w) > 1: + argfile = true + } + } + return +} diff --git a/detectors/java4shell/internal/repo/refscan.go b/detectors/java4shell/internal/repo/refscan.go index 11eab55..8997802 100644 --- a/detectors/java4shell/internal/repo/refscan.go +++ b/detectors/java4shell/internal/repo/refscan.go @@ -159,7 +159,26 @@ func EnvMitigation(root string, r refs.Ref, overlay map[string][]byte) string { } } } - o := jvm.FromEnv(env, nil, 17, nil) + // The command the file sets can turn the decoder back on. + var cmd []string + for _, k := range []string{"entrypoint", "command", "args"} { + n := mapGet(m, k) + switch { + case n == nil: + case n.Kind == yaml.SequenceNode: + var arr []string + for _, c := range n.Content { + arr = append(arr, c.Value) + } + cmd = append(cmd, jvm.CommandWords(arr)...) + case n.Kind == yaml.ScalarNode: + cmd = append(cmd, jvm.Words(n.Value)...) + } + } + if len(cmd) > 0 && !strings.Contains(strings.Join(cmd, " "), "java") { + cmd = append([]string{"java"}, cmd...) // Kubernetes args go to the image's own java entrypoint + } + o := undo(jvm.FromEnv(withoutJavaOptions(env), nil, 17, nil), cmd, env) if ok, how := o.Mitigates(); ok { return strings.Replace(how, "(from ", "(from "+r.File+" ", 1) } diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 48ec13a..0df9ce5 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -20,6 +20,7 @@ package repo import ( "context" + "encoding/json" "errors" "fmt" "io/fs" @@ -718,6 +719,7 @@ var ( apkJava = regexp.MustCompile(`\b(openjdk(\d{1,2})(?:-jre|-jdk|-jre-headless|-jmods)?)(?:[=~><]+([^\s;&|]+))?`) rpmJava = regexp.MustCompile(`\b(java-(\d{1,2})-(?:openjdk|amazon-corretto)(?:-headless|-devel)?)(?:-(\d[\w.:-]*))?`) envJTO = regexp.MustCompile(`(?i)^\s*ENV\s+`) + cmdLine = regexp.MustCompile(`(?i)^\s*(?:ENTRYPOINT|CMD)\s+`) fromLine = regexp.MustCompile(`(?i)^\s*FROM\s`) ) @@ -729,8 +731,9 @@ func (s *scanner) dockerfile(rel, text string) { // stage sets the mitigation (before or after the install: ENV applies // to the image the stage makes). stageEnv := map[string]string{} + var stageCmd []string // ENTRYPOINT and CMD words of the stage endStage := func() { - o := jvm.FromEnv(stageEnv, nil, 17, nil) + o := undo(jvm.FromEnv(withoutJavaOptions(stageEnv), nil, 17, nil), stageCmd, stageEnv) ok, how := o.Mitigates() if !ok || from == 0 { return @@ -761,7 +764,9 @@ func (s *scanner) dockerfile(rel, text string) { switch { case fromLine.MatchString(trim): endStage() - from, stageStart, stageEnv = i+1, len(s.findings), map[string]string{} + from, stageStart, stageEnv, stageCmd = i+1, len(s.findings), map[string]string{}, nil + case cmdLine.MatchString(trim): + stageCmd = append(stageCmd, commandWords(cmdLine.ReplaceAllString(trim, ""))...) case envJTO.MatchString(trim): // The last ENV of each variable in the stage is what the // image keeps; the mitigation is decided when the stage ends. @@ -887,3 +892,45 @@ func mapGet(m *yaml.Node, key string) *yaml.Node { } return nil } + +// commandWords reads a Dockerfile ENTRYPOINT or CMD: the JSON form or the +// shell form. +func commandWords(text string) []string { + text = strings.TrimSpace(text) + var arr []string + if strings.HasPrefix(text, "[") && json.Unmarshal([]byte(text), &arr) == nil { + return jvm.CommandWords(arr) + } + return jvm.Words(text) +} + +// withoutJavaOptions drops _JAVA_OPTIONS, which undo applies last. +func withoutJavaOptions(env map[string]string) map[string]string { + out := map[string]string{} + for k, v := range env { + if k != "_JAVA_OPTIONS" { + out[k] = v + } + } + return out +} + +// undo applies what a command can turn back on (its words count wherever +// the java it starts is) and then _JAVA_OPTIONS, which HotSpot applies +// last. A java @argfile makes the result unknowable: no mitigation. +func undo(o jvm.Options, cmd []string, env map[string]string) jvm.Options { + b64, avx, argfile := jvm.Undoes(cmd) + if argfile { + return jvm.Options{} + } + if b64 { + o.ApplyWord("-XX:+UseBASE64Intrinsics", "the command") + } + if avx { + o.ApplyWord("-XX:UseAVX=3", "the command") + } + if v, ok := env["_JAVA_OPTIONS"]; ok { + o.Apply(v, "_JAVA_OPTIONS") + } + return o +} diff --git a/detectors/java4shell/internal/repo/review_test.go b/detectors/java4shell/internal/repo/review_test.go index 89d7b9b..d907df3 100644 --- a/detectors/java4shell/internal/repo/review_test.go +++ b/detectors/java4shell/internal/repo/review_test.go @@ -82,3 +82,24 @@ func TestTargetBelowFixedBuild(t *testing.T) { t.Errorf("21.0.13.1_1: %s (%s)", st, why) } } + +// Review finding 9: a command in the tree that turns the intrinsic back on +// voids the mitigation the stage or service sets. +func TestTreeCommandReenables(t *testing.T) { + root := tree(t, map[string]string{ + "a/Dockerfile": "FROM eclipse-temurin:21.0.13_9-jre\nENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics\nENTRYPOINT [\"java\",\"-XX:+UseBASE64Intrinsics\",\"-jar\",\"/a.jar\"]\n", + "b/Dockerfile": "FROM eclipse-temurin:21.0.13_9-jre\nENV JAVA_TOOL_OPTIONS=-XX:UseAVX=2\nCMD java -XX:UseAVX=3 -jar /a.jar\n", + "compose.yaml": "services:\n a:\n image: amazoncorretto:21.0.12-al2023\n environment:\n JAVA_TOOL_OPTIONS: -XX:-UseBASE64Intrinsics\n command: [\"java\", \"-XX:+UseBASE64Intrinsics\", \"-jar\", \"/a.jar\"]\n", + "k8s.yaml": "apiVersion: v1\nkind: Pod\nmetadata:\n name: a\nspec:\n containers:\n - name: a\n image: amazoncorretto:21.0.12-al2023\n env:\n - name: JAVA_TOOL_OPTIONS\n value: -XX:-UseBASE64Intrinsics\n args: [\"-XX:+UseBASE64Intrinsics\"]\n", + }) + res := scan(t, root) + for _, c := range []struct { + file string + line int + }{{"a/Dockerfile", 1}, {"b/Dockerfile", 1}, {"compose.yaml", 3}, {"k8s.yaml", 8}} { + f, ok := find(res, c.file, c.line) + if !ok || f.Status != StatusVulnerable || f.Props["mitigation"] != "" { + t.Errorf("%s:%d: %+v (found %v)", c.file, c.line, f, ok) + } + } +} From 0545fd2a22996c169ab3d35fa5bcd0736b849666 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 01:33:52 +0000 Subject: [PATCH 014/119] java4shell: settings files count only what the launcher passes to java Review finding 5. setenv.sh is read as assignments to the variables a start script passes to java (CATALINA_OPTS, JAVA_OPTS, JVM_SUPPORT_RECOMMENDED_ARGS, the JVM's own variables...): the last assignment wins, $VAR appends, other variables and echo text do not count, and a file that sets one of them under a condition, loop or function counts for nothing. setenv.bat is read the same way and only for Windows runtimes. Cassandra's jvmNN-*.options apply to Java NN only. Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/assess/assess.go | 2 +- .../internal/assess/review2_test.go | 14 ++ .../java4shell/internal/jvm/review2_test.go | 46 ++++++ detectors/java4shell/internal/jvm/settings.go | 144 +++++++++++++++++- 4 files changed, 199 insertions(+), 7 deletions(-) diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index e2fbb20..0c43857 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -357,7 +357,7 @@ func mitigation(in Input, env map[string]string, root string, feature int, f *Fi } } for _, s := range in.Settings { - if s.Kind == "systemd" || s.Scope == "" { + if s.Kind == "systemd" || s.Scope == "" || s.WindowsOnly && (f.Library == nil || f.Library.Format != "pe") { continue } if within(root, s.Scope) || in.Env != nil && launches(in, env, s) && javaHomeIs(in, env, root) { diff --git a/detectors/java4shell/internal/assess/review2_test.go b/detectors/java4shell/internal/assess/review2_test.go index 1e24af0..e26af24 100644 --- a/detectors/java4shell/internal/assess/review2_test.go +++ b/detectors/java4shell/internal/assess/review2_test.go @@ -69,3 +69,17 @@ func TestCommandReenables(t *testing.T) { t.Errorf("_JAVA_OPTIONS after the command: %s", f.Status) } } + +// Review finding 5: a Windows batch file does not cover a Linux runtime. +func TestBatchFileWindowsOnly(t *testing.T) { + bat, _ := jvm.ReadSetting("/opt/tomcat/bin/setenv.bat", []byte("set \"CATALINA_OPTS=-XX:-UseBASE64Intrinsics\"\n")) + in := Input{Libraries: []*jvm.Library{vulnLib(t, "/opt/tomcat/jre")}, Settings: []jvm.Setting{bat}} + if f := one(t, in); f.Status != Vulnerable { + t.Errorf("setenv.bat on Linux: %s", f.Status) + } + win := lib(t, "/opt/tomcat/jre/bin/server/jvm.dll", testlib.Lib{Format: "pe", OS: "windows", Version: "21.0.13+9-LTS", VBMI: true}) + in = Input{Libraries: []*jvm.Library{win}, Settings: []jvm.Setting{bat}} + if f := one(t, in); f.Status != Mitigated { + t.Errorf("setenv.bat on Windows: %s", f.Status) + } +} diff --git a/detectors/java4shell/internal/jvm/review2_test.go b/detectors/java4shell/internal/jvm/review2_test.go index 0eca09b..2adb9e2 100644 --- a/detectors/java4shell/internal/jvm/review2_test.go +++ b/detectors/java4shell/internal/jvm/review2_test.go @@ -22,3 +22,49 @@ func TestInspectMusl(t *testing.T) { t.Error("an unreadable HotSpot library with j9vm bytes taken for OpenJ9") } } + +// Review finding 5: only options a launcher variable ends up with count. +func TestSettingsOnlyWhatLaunches(t *testing.T) { + for _, text := range []string{ + "if [ \"$X\" = 1 ]; then JVM_SUPPORT_RECOMMENDED_ARGS=\"-XX:-UseBASE64Intrinsics\"; fi\n", + "if [ \"$X\" = 1 ]; then\n JVM_SUPPORT_RECOMMENDED_ARGS=\"-XX:-UseBASE64Intrinsics\"\nfi\n", + "OLD_OPTS=\"-XX:-UseBASE64Intrinsics\"\n", + "JAVA_OPTS=\"-XX:-UseBASE64Intrinsics\"\nJAVA_OPTS=\"-Xmx2g\"\n", + "echo \"to mitigate Java4Shell add -XX:-UseBASE64Intrinsics\"\n", + } { + s, ok := ReadSetting("/opt/atlassian/jira/bin/setenv.sh", []byte(text)) + if !ok { + t.Fatal("not read") + } + if m, _ := s.Options(21).Mitigates(); m { + t.Errorf("counted: %q", text) + } + } + for _, text := range []string{ + "JAVA_OPTS=\"-Xmx2g\"\nJAVA_OPTS=\"$JAVA_OPTS -XX:-UseBASE64Intrinsics\"\n", + "export CATALINA_OPTS=\"${CATALINA_OPTS} -XX:-UseBASE64Intrinsics\"\n", + "JVM_SUPPORT_RECOMMENDED_ARGS='-XX:-UseBASE64Intrinsics'\n", + } { + s, _ := ReadSetting("/opt/atlassian/jira/bin/setenv.sh", []byte(text)) + if m, _ := s.Options(21).Mitigates(); !m { + t.Errorf("not counted: %q", text) + } + } + // A Windows batch file applies to Windows runtimes only. + s, _ := ReadSetting("/opt/tomcat/bin/setenv.bat", []byte(":: set CATALINA_OPTS=-XX:-UseBASE64Intrinsics\nrem set JAVA_OPTS=-XX:-UseBASE64Intrinsics\n")) + if m, _ := s.Options(21).Mitigates(); m { + t.Error("batch comments counted") + } + s, _ = ReadSetting("/opt/tomcat/bin/setenv.bat", []byte("set \"CATALINA_OPTS=%CATALINA_OPTS% -XX:-UseBASE64Intrinsics\"\n")) + if m, _ := s.Options(21).Mitigates(); !m || !s.WindowsOnly { + t.Errorf("batch set: %v windows-only %v", m, s.WindowsOnly) + } + // Cassandra names the Java release in the file name. + s, _ = ReadSetting("/opt/cassandra/conf/jvm11-server.options", []byte("-XX:UseAVX=2\n")) + if m, _ := s.Options(21).Mitigates(); m { + t.Error("jvm11-server.options applied to Java 21") + } + if m, _ := s.Options(11).Mitigates(); !m { + t.Error("jvm11-server.options not applied to Java 11") + } +} diff --git a/detectors/java4shell/internal/jvm/settings.go b/detectors/java4shell/internal/jvm/settings.go index 5d6af84..f804d09 100644 --- a/detectors/java4shell/internal/jvm/settings.go +++ b/detectors/java4shell/internal/jvm/settings.go @@ -25,6 +25,9 @@ type Setting struct { // the JVM options its ExecStart gives java. Env map[string]string `json:"env,omitempty"` ExecOpts []string `json:"exec_options,omitempty"` + // WindowsOnly is a batch file (setenv.bat): it applies only to Windows + // runtimes. + WindowsOnly bool `json:"windows_only,omitempty"` // ExecSet is true when the file sets ExecStart (a drop-in may not). ExecSet bool `json:"-"` lines []optLine @@ -107,8 +110,13 @@ func systemdDir(p string) bool { const maxSetting = 1 << 20 var ( - xxRE = regexp.MustCompile(`-XX:(?:[+-]UseBASE64Intrinsics|UseBASE64Intrinsics=(?:true|false)|UseAVX=\d{1,2})\b`) - selectorRE = regexp.MustCompile(`^(\d{1,3})(-(\d{1,3})?)?:`) + xxRE = regexp.MustCompile(`-XX:(?:[+-]UseBASE64Intrinsics|UseBASE64Intrinsics=(?:true|false)|UseAVX=\d{1,2})\b`) + selectorRE = regexp.MustCompile(`^(\d{1,3})(-(\d{1,3})?)?:`) + fileReleaseRE = regexp.MustCompile(`^jvm(\d{1,2})-`) + assignRE = regexp.MustCompile(`^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$`) + batSetRE = regexp.MustCompile(`(?i)^set\s+"?([A-Za-z_][A-Za-z0-9_]*)=(.*?)"?\s*$`) + shVarRE = regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)`) + batVarRE = regexp.MustCompile(`%([A-Za-z_][A-Za-z0-9_]*)%`) ) // ReadSetting reads a settings file. ok is false when p is not one, or it @@ -143,6 +151,16 @@ func ReadSetting(p string, b []byte) (Setting, bool) { s.Unit = u s.Env = map[string]string{} } + if kind == "setenv" { + s.WindowsOnly = strings.HasSuffix(p, ".bat") + readSetenv(&s, string(b)) + return s, true + } + // Cassandra names the Java release a file is for: jvm11-server.options. + fileLo := 0 + if m := fileReleaseRE.FindStringSubmatch(path.Base(p)); m != nil && kind == "jvm.options" { + fileLo, _ = strconv.Atoi(m[1]) + } for _, raw := range strings.Split(string(b), "\n") { line := strings.TrimSpace(strings.TrimSuffix(raw, "\r")) if line == "" || line[0] == '#' || line[0] == ';' || strings.HasPrefix(strings.ToLower(line), "rem ") { @@ -161,13 +179,12 @@ func ReadSetting(p string, b []byte) (Setting, bool) { } line = line[len(m[0]):] } + if fileLo > 0 { + lo, hi = fileLo, fileLo + } if xxRE.MatchString(line) && strings.HasPrefix(line, "-XX:") { s.lines = append(s.lines, optLine{lo, hi, strings.TrimSpace(line)}) } - case "setenv": - for _, w := range xxRE.FindAllString(stripComment(line), -1) { - s.lines = append(s.lines, optLine{0, 0, w}) - } case "systemd": s.systemdLine(line) } @@ -314,3 +331,118 @@ func (s *Setting) systemdLine(line string) { } } } + +// launcherVars are the variables a start script passes to java. +func launcherVar(name string) bool { + for _, n := range EnvVars { + if n == name { + return true + } + } + for _, n := range ScriptVars { + if n == name { + return true + } + } + return false +} + +// shellControl are the words that make what follows conditional or +// repeated. +var shellControl = map[string]bool{"if": true, "then": true, "else": true, "elif": true, "fi": true, "case": true, "esac": true, + "for": true, "while": true, "until": true, "do": true, "done": true, "&&": true, "||": true, "{": true, "}": true, "function": true} + +// readSetenv reads a start script's settings file the way the script +// uses it: only the variables the launcher passes to java count, the last +// assignment wins ("$VAR ..." appends), and a file that sets one of them +// under a condition, in a loop or in a function counts for nothing, since +// which value java gets cannot be known without running it. Batch files +// (setenv.bat) are read the same way with "set NAME=value" and %NAME%. +func readSetenv(s *Setting, text string) { + vals := map[string]string{} + var order []string + depth := 0 + uncertain := false + for _, raw := range strings.Split(text, "\n") { + line := strings.TrimSpace(strings.TrimSuffix(raw, "\r")) + var name, value string + if s.WindowsOnly { + low := strings.ToLower(line) + if line == "" || strings.HasPrefix(low, "rem") && (len(low) == 3 || low[3] == ' ') || strings.HasPrefix(line, "::") || strings.HasPrefix(line, "@rem") { + continue + } + if strings.HasPrefix(low, "if ") || strings.HasPrefix(low, "for ") || strings.HasPrefix(low, "goto") || strings.HasPrefix(line, ":") || strings.Contains(line, "(") || strings.Contains(line, ")") { + for _, n := range append(append([]string{}, EnvVars...), ScriptVars...) { + if strings.Contains(line, n) { + uncertain = true + } + } + continue + } + m := batSetRE.FindStringSubmatch(line) + if m == nil { + continue + } + name = m[1] + value = batVarRE.ReplaceAllStringFunc(m[2], func(v string) string { return vals[strings.Trim(v, "%")] }) + } else { + line = strings.TrimSpace(stripComment(line)) + if line == "" { + continue + } + words := Words(line) + cond := depth > 0 + for _, w := range words { + w = strings.TrimSuffix(w, ";") + if shellControl[w] { + cond = true + } + switch w { + case "if", "case", "for", "while", "until": + depth++ + case "fi", "esac", "done": + if depth > 0 { + depth-- + } + } + } + m := assignRE.FindStringSubmatch(line) + if m == nil { + if cond { + for _, n := range append(append([]string{}, EnvVars...), ScriptVars...) { + if strings.Contains(line, n+"=") { + uncertain = true + } + } + } + continue + } + if cond { + if launcherVar(m[1]) { + uncertain = true + } + continue + } + name = m[1] + value = strings.Join(Words(m[2]), " ") + value = shVarRE.ReplaceAllStringFunc(value, func(v string) string { + return vals[strings.Trim(v, "${}")] + }) + } + if !launcherVar(name) { + continue + } + if _, seen := vals[name]; !seen { + order = append(order, name) + } + vals[name] = value + } + if uncertain { + return + } + for _, n := range order { + for _, w := range xxRE.FindAllString(vals[n], -1) { + s.lines = append(s.lines, optLine{0, 0, w}) + } + } +} From 1fdfa6ebb3e55434a979bfc95337f8b91a372140 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 01:34:36 +0000 Subject: [PATCH 015/119] java4shell: cap what one target makes the detector keep Review finding 7. Release files, settings files, dpkg file lists (now kept only for their libjvm.so and release lines), start scripts and package data have count and total-byte caps. A target that reaches one records a problem, and its fixed and not-affected verdicts become unknown with the reason. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/java4shell.go | 66 ++++++++++++++++++++++++++-- detectors/java4shell/review2_test.go | 17 +++++++ 2 files changed, 80 insertions(+), 3 deletions(-) diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 9503ea3..6e656dd 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -132,6 +132,13 @@ const ( maxHsErrs = 64 maxLibs = 4096 maxSetting = 1 << 20 + // Caps on what one target can make the detector keep: an image layer + // of many small files compresses to almost nothing. + maxReleases = 4096 + maxSettings = 4096 + maxLists = 512 + maxScripts = 8192 + maxKeptTotal = 128 << 20 ) // NewScan starts a filesystem or image scan. @@ -151,6 +158,19 @@ type scan struct { scripts map[string]map[string]bool crashes []crash dropped int + keptBytes int + // limits records the caps this target reached; a capped scan clears + // nothing. + limits []string +} + +func (s *scan) limit(what string) { + for _, l := range s.limits { + if l == what { + return + } + } + s.limits = append(s.limits, what) } func (s *scan) Visit(f engine.File) []engine.Skip { @@ -170,6 +190,10 @@ func (s *scan) Visit(f engine.File) []engine.Skip { return nil case base == "release": if !archive.IsExecutable(f.Data) { + if len(s.releases)+len(s.badReleases) >= maxReleases { + s.limit(fmt.Sprintf("more than %d release files", maxReleases)) + return nil + } if r, ok := jvm.ParseRelease(f.Data); ok { s.releases[path.Dir(f.Path)] = r } else if len(f.Data) > 64<<10 && bytes.Contains(f.Data[:min(len(f.Data), 4096)], []byte("JAVA_VERSION")) { @@ -184,15 +208,35 @@ func (s *scan) Visit(f engine.File) []engine.Skip { return nil } if k := jvm.SettingKind(f.Path); k != "" && len(f.Data) <= maxSetting { - if st, ok := jvm.ReadSetting(f.Path, f.Data); ok { + if len(s.settings) >= maxSettings { + s.limit(fmt.Sprintf("more than %d files that set JVM options", maxSettings)) + } else if st, ok := jvm.ReadSetting(f.Path, f.Data); ok { s.settings = append(s.settings, st) } } if keep(f.Path) && len(f.Data) <= maxKept { if assess.IsDpkgList(f.Path) { - s.lists[strings.TrimSuffix(path.Base(f.Path), ".list")] = f.Data + // Only the lines owners are looked up by. + var b []byte + for _, l := range bytes.Split(f.Data, []byte("\n")) { + if bytes.HasSuffix(l, []byte("/libjvm.so")) || bytes.HasSuffix(l, []byte("/release")) { + b = append(append(b, l...), '\n') + } + } + switch { + case len(s.lists) >= maxLists: + s.limit(fmt.Sprintf("more than %d dpkg file lists of Java packages", maxLists)) + case s.keptBytes+len(b) > maxKeptTotal: + s.limit(fmt.Sprintf("more than %d MiB of package data", maxKeptTotal>>20)) + default: + s.lists[strings.TrimSuffix(path.Base(f.Path), ".list")] = b + s.keptBytes += len(b) + } + } else if s.keptBytes+len(f.Data) > maxKeptTotal { + s.limit(fmt.Sprintf("more than %d MiB of package data", maxKeptTotal>>20)) } else { s.kept[f.Path] = f.Data + s.keptBytes += len(f.Data) } } if isScript(f.Data) && len(f.Data) <= maxScript { @@ -203,7 +247,11 @@ func (s *scan) Visit(f engine.File) []engine.Skip { } } if len(vars) > 0 { - s.scripts[f.Path] = vars + if len(s.scripts) >= maxScripts { + s.limit(fmt.Sprintf("more than %d start scripts that pass JVM options", maxScripts)) + } else { + s.scripts[f.Path] = vars + } } } return nil @@ -219,6 +267,9 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { ctx.Annotate("java4shell_crash_logs", s.crashes) } if len(s.libs) == 0 { + if len(s.limits) > 0 { + ctx.Problem("java4shell: the scan reached its limit on " + strings.Join(s.limits, " and ") + " for one target") + } return nil } links, _ := ctx.Links() @@ -253,9 +304,18 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { in.Command = ctx.Command() } cpu, haveCPU := thisCPU() + capped := "" + if len(s.limits) > 0 { + capped = "the scan reached its limit on " + strings.Join(s.limits, " and ") + " for one target, so package owners and JVM options may be missing: nothing is cleared" + ctx.Problem("java4shell: " + capped) + } var out []engine.Finding for _, x := range assess.Run(in) { f := finding(x) + if capped != "" && f.Verdict.Cleared() { + f.Verdict, f.Reason = engine.Unknown, f.Reason+"; but "+capped + f.CVEs = []engine.CVEResult{{ID: knowledge.CVE, Verdict: f.Verdict, Reason: f.Reason}} + } if haveCPU && s.kind == engine.Filesystem && x.Status == assess.Vulnerable { f.Facts["scanner_cpu_runs_it"] = yes(cpu.Affected) } diff --git a/detectors/java4shell/review2_test.go b/detectors/java4shell/review2_test.go index e559696..719cfa5 100644 --- a/detectors/java4shell/review2_test.go +++ b/detectors/java4shell/review2_test.go @@ -1,6 +1,8 @@ package java4shell_test import ( + "fmt" + "strings" "testing" "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" @@ -19,3 +21,18 @@ func TestMitigatedIsNotCleared(t *testing.T) { t.Errorf("mitigated: %s %q exit %d", f.Verdict, f.Facts["status"], code) } } + +// Review finding 7: what a target makes the detector keep is capped, and +// a capped scan clears nothing. +func TestKeptCaps(t *testing.T) { + root := t.TempDir() + write(t, root, "opt/fixed/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "21.0.13.1+2-LTS", VBMI: true})) + for i := 0; i < 600; i++ { + write(t, root, fmt.Sprintf("var/lib/dpkg/info/openjdk-%d.list", i), []byte("/usr/lib/jvm/x/lib/server/libjvm.so\n")) + } + r, _ := run(t, "scan", "fs", "--as-root", root) + f := byPath(r)["/opt/fixed"] + if f.Verdict != engine.Unknown || !strings.Contains(f.Reason, "limit") { + t.Errorf("capped scan: %s (%s)", f.Verdict, f.Reason) + } +} From e96edfa4a99eca9aa3459974d441239018265247 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 01:36:47 +0000 Subject: [PATCH 016/119] java4shell: more install syntax, vendor packages and version names Review findings 8, 11 and 12. Installs are recognised with flags before the verb (yum -y install, apk --no-cache add, apk -U add), vendor packages (temurin-21-jdk, zulu21-jdk, msopenjdk-21, sapmachine-21-jdk, Corretto) and default-jre are read, and a version range (17.*, ~17) counts as unpinned instead of as Java 17. An unpinned Corretto or SapMachine package is unknown (their fix is published, so it depends on when the image was built), not "the distribution had no fix"; a Java 28 package is not checked rather than "no fix". jenv names (temurin64-21.0.13), GraalVM's 22.3.r17 and Zulu's own numbers are handled, a moving setup-java Temurin version is reported, and a FROM --platform=linux/arm64 stage is skipped. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/internal/repo/refscan.go | 4 + detectors/java4shell/internal/repo/repo.go | 276 ++++++++++++------ .../java4shell/internal/repo/repo_test.go | 5 +- .../java4shell/internal/repo/review3_test.go | 68 +++++ 4 files changed, 266 insertions(+), 87 deletions(-) create mode 100644 detectors/java4shell/internal/repo/review3_test.go diff --git a/detectors/java4shell/internal/repo/refscan.go b/detectors/java4shell/internal/repo/refscan.go index 8997802..ca665ed 100644 --- a/detectors/java4shell/internal/repo/refscan.go +++ b/detectors/java4shell/internal/repo/refscan.go @@ -47,6 +47,10 @@ func (s *scanner) judgeRef(r refs.Ref, opts Options) { if img == "" || img == "scratch" || strings.Contains(img, "$") || !amd64(opts) { return } + // FROM --platform=linux/arm64: a stage that is not x86-64. + if p := r.Platform; p != "" && !strings.Contains(p, "$") && !strings.Contains(p, "amd64") && !strings.Contains(p, "x86_64") { + return + } mit := s.mitigationFor(r) props := map[string]string{"image": img} if mit != "" { diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 0df9ce5..dc45578 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -382,17 +382,32 @@ func (s *scanner) javaVersionFile(rel, text string) { if l == "" || strings.HasPrefix(l, "#") { continue } - if m := versionInText.FindStringIndex(l); m != nil { - ver := l[m[0]:m[1]] - if vendorWord(l) == "corretto" { - ver = CorrettoJava(ver) - } - s.judgeVersion(rel, i+1, m[0], ver, ".java-version", vendorWord(l)) + // jenv names: temurin64-21.0.13, openjdk64-17.0.21, 21.0.13. + m := jenvName.FindStringSubmatch(l) + if m == nil { + return } + ver := m[2] + if strings.HasPrefix(strings.ToLower(m[1]), "corretto") { + ver = CorrettoJava(ver) + } + s.judgeVersion(rel, i+1, 0, ver, ".java-version", vendorWord(l)) return // jenv reads the first line } } +var jenvName = regexp.MustCompile(`^(?:([A-Za-z][A-Za-z.]*?)(?:64)?-)?(\d{1,3}(?:\.\d{1,9}){0,5})(?:$|[^\d.])`) + +// ownNumbers notes a pin written in a vendor's own version numbers +// (Zulu 21.50.19, GraalVM 22.3.r17), which do not name the Java update. +func (s *scanner) ownNumbers(rel string, line int, value, source string) { + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, + Reason: "the vendor's own version number does not name the Java update", + Message: fmt.Sprintf("%s selects %s, written in the vendor's own version numbers: not checked for the Java4Shell fix", source, refs.CleanText(value, 80)), + Fix: "Check which Java update this release is built on: 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update have the fix.", + Props: map[string]string{"source": source, "current": refs.CleanText(value, 80)}}) +} + var sdkmanLine = regexp.MustCompile(`^\s*java\s*=\s*(\d[\w.]*?)(?:-([a-z]+))?\s*$`) var sdkmanVendors = map[string]string{"tem": "Eclipse Temurin", "amzn": "Amazon Corretto", "zulu": "Azul Zulu", "librca": "BellSoft Liberica", @@ -409,11 +424,10 @@ func (s *scanner) sdkmanrc(rel, text string) { if vendor == "" { vendor = m[2] } - if m[2] == "graalce" || m[2] == "graal" || m[2] == "nik" || m[2] == "mandrel" { - // GraalVM versions follow the JDK's only for 17 and later builds named so. - if !strings.Contains(m[1], ".") { - continue - } + if strings.Contains(m[1], ".r") || m[2] == "grl" || (m[2] == "graalce" || m[2] == "graal" || m[2] == "nik" || m[2] == "mandrel") && strings.Count(m[1], ".") < 2 { + // GraalVM 22.3.r17 and the like: GraalVM's numbers. + s.ownNumbers(rel, i+1, strings.TrimSpace(strings.SplitN(l, "=", 2)[1]), ".sdkmanrc") + continue } s.judgeVersion(rel, i+1, strings.Index(l, m[1]), m[1], ".sdkmanrc", vendor) } @@ -431,7 +445,8 @@ func (s *scanner) asdfValue(rel string, line int, value, source string) { } switch m[1] { case "zulu", "graalvm", "mandrel", "jetbrains": - return // their own version numbers + s.ownNumbers(rel, line, value, source) // their own version numbers + return } ver := m[2] if m[1] == "corretto" { @@ -556,6 +571,7 @@ func (s *scanner) setupJava(rel string, v *yaml.Node, dist string, text []string before := len(s.findings) s.judgeVersion(rel, v.Line, 0, m, "actions/setup-java", dist) if len(s.findings) == before { + s.movingSetupJava(rel, v, m, dist) return } f := &s.findings[len(s.findings)-1] @@ -578,6 +594,33 @@ func (s *scanner) setupJava(rel string, v *yaml.Node, dist string, text []string } } +// movingSetupJava judges a moving setup-java version of a line with a fix +// ("21"): it installs the distribution's newest release of that line when +// the job runs. +func (s *scanner) movingSetupJava(rel string, v *yaml.Node, ver, dist string) { + if strings.Count(ver, ".") >= 2 { + return + } + feature := atoi(ver) + l, ok := knowledge.LineOf(feature) + if !ok || l.Fixed == nil || publishedFix[dist] { + return + } + fx := knowledge.FixedVersion(feature) + props := map[string]string{"source": "actions/setup-java", "current": ver, "distribution": dist, "fixed_in": fx} + if dist == "temurin" || dist == "adopt" || dist == "adopt-hotspot" { + s.add(Finding{Rule: RuleJavaPin, File: rel, Line: v.Line, Level: "warning", Status: StatusVulnerable, Props: props, + Reason: fmt.Sprintf("Eclipse Temurin had published no Java %s as of %s, so the job installs a release without the fix", fx, knowledge.Checked), + Message: fmt.Sprintf("actions/setup-java installs the newest %s Java %d, which had no Java4Shell fix yet", orAny(dist), feature), + Fix: fmt.Sprintf("Rerun once Temurin publishes Java %s, or use distribution corretto or sapmachine, whose newest Java %d has the fix.", fx, feature)}) + return + } + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: v.Line, Level: "note", Status: StatusUnknown, Props: props, + Reason: fmt.Sprintf("whether %s had published Java %s could not be checked", orAny(dist), fx), + Message: fmt.Sprintf("actions/setup-java installs the newest %s Java %d: not checked for the Java4Shell fix", orAny(dist), feature), + Fix: fmt.Sprintf("Check that the installed release is Java %s or later.", fx)}) +} + func orAny(d string) string { if d == "" { return "selected" @@ -715,12 +758,15 @@ func (s *scanner) jibRef(rel string, line, col int, image string) { // ---- Dockerfiles: OS packages and the mitigation a stage sets var ( - aptJava = regexp.MustCompile(`\b(openjdk-(\d{1,2})-(?:jre|jdk)(?:-headless)?)(?:=([^\s;&|]+))?`) - apkJava = regexp.MustCompile(`\b(openjdk(\d{1,2})(?:-jre|-jdk|-jre-headless|-jmods)?)(?:[=~><]+([^\s;&|]+))?`) - rpmJava = regexp.MustCompile(`\b(java-(\d{1,2})-(?:openjdk|amazon-corretto)(?:-headless|-devel)?)(?:-(\d[\w.:-]*))?`) - envJTO = regexp.MustCompile(`(?i)^\s*ENV\s+`) - cmdLine = regexp.MustCompile(`(?i)^\s*(?:ENTRYPOINT|CMD)\s+`) - fromLine = regexp.MustCompile(`(?i)^\s*FROM\s`) + installRE = regexp.MustCompile(`\b(?:apt-get|apt|apk|dnf|yum|microdnf|tdnf|zypper)\b(?:\s+-{1,2}[\w=./:-]+)*\s+(?:install|add|in)\b`) + aptJava = regexp.MustCompile(`\b(openjdk-(\d{1,2})-(?:jre|jdk)(?:-headless)?)\b(=([^\s;&|]+))?`) + apkJava = regexp.MustCompile(`\b(openjdk(\d{1,2})(?:-jre|-jdk|-jre-headless|-jmods)?)(?:([=~><]+)([^\s;&|]+))?`) + rpmJava = regexp.MustCompile(`\b(java-(\d{1,2})-(openjdk|amazon-corretto)(?:-headless|-devel|-jdk)?)(?:-(\d[\w.:-]*))?`) + vendorJava = regexp.MustCompile(`\b((temurin|zulu|msopenjdk|sapmachine)-?(\d{1,2})(?:-ca)?(?:-(?:jdk|jre))?(?:-headless)?)\b(=([^\s;&|]+))?`) + defaultJava = regexp.MustCompile(`\b(default-(?:jre|jdk)(?:-headless)?)\b`) + envJTO = regexp.MustCompile(`(?i)^\s*ENV\s+`) + cmdLine = regexp.MustCompile(`(?i)^\s*(?:ENTRYPOINT|CMD)\s+`) + fromLine = regexp.MustCompile(`(?i)^\s*FROM\s`) ) func (s *scanner) dockerfile(rel, text string) { @@ -783,87 +829,149 @@ func (s *scanner) dockerfile(rel, text string) { } } -// packages finds distribution OpenJDK packages a RUN line installs. +// packages finds the OpenJDK packages a RUN line installs: distribution +// packages and the vendors' own (Temurin, Corretto, Zulu, Microsoft, +// SapMachine), with or without a version. func (s *scanner) packages(rel string, line int, run string) { - lower := run - installs := strings.Contains(lower, "apt-get install") || strings.Contains(lower, "apt install") || strings.Contains(lower, "apk add") || - strings.Contains(lower, "dnf install") || strings.Contains(lower, "yum install") || strings.Contains(lower, "microdnf install") || - strings.Contains(lower, "zypper in") - if !installs { + if !installRE.MatchString(run) { return } - type hit struct{ name, ver string } - var hits []struct { - hit - feature int - mgr string - } + var hits []pkgHit for _, m := range aptJava.FindAllStringSubmatch(run, -1) { - n := 0 - fmt.Sscanf(m[2], "%d", &n) - hits = append(hits, struct { - hit - feature int - mgr string - }{hit{m[1], m[3]}, n, "apt"}) + hits = append(hits, pkgHit{name: m[1], feature: atoi(m[2]), op: opOf(m[3]), ver: m[4], mgr: "apt", vendor: "distribution"}) } for _, m := range apkJava.FindAllStringSubmatch(run, -1) { - n := 0 - fmt.Sscanf(m[2], "%d", &n) - hits = append(hits, struct { - hit - feature int - mgr string - }{hit{m[1], m[3]}, n, "apk"}) + hits = append(hits, pkgHit{name: m[1], feature: atoi(m[2]), op: m[3], ver: m[4], mgr: "apk", vendor: "distribution"}) } for _, m := range rpmJava.FindAllStringSubmatch(run, -1) { - n := 0 - fmt.Sscanf(m[2], "%d", &n) - hits = append(hits, struct { - hit - feature int - mgr string - }{hit{m[1], m[3]}, n, "rpm"}) + v := "distribution" + if m[3] == "amazon-corretto" { + v = "corretto" + } + hits = append(hits, pkgHit{name: m[1], feature: atoi(m[2]), ver: m[4], mgr: "rpm", vendor: v}) + } + for _, m := range vendorJava.FindAllStringSubmatch(run, -1) { + hits = append(hits, pkgHit{name: m[1], feature: atoi(m[3]), op: opOf(m[4]), ver: m[5], mgr: "package", vendor: m[2]}) + } + for _, m := range defaultJava.FindAllStringSubmatch(run, -1) { + hits = append(hits, pkgHit{name: m[1], mgr: "apt", vendor: "distribution"}) } for _, h := range hits { - if h.feature < 17 { - continue // Java 8 and 11 packages are not affected - } - props := map[string]string{"package": h.name, "manager": h.mgr} - l, _ := knowledge.LineOf(h.feature) - if l.Fixed == nil { + s.judgePackage(rel, line, h) + } +} + +// pkgHit is one Java package an install names. +type pkgHit struct { + name, op, ver, mgr string + vendor string // distribution, corretto, temurin, zulu, msopenjdk, sapmachine + feature int // 0: the distribution's default (default-jre) +} + +func opOf(v string) string { + if v != "" { + return "=" + } + return "" +} + +func atoi(s string) int { + n := 0 + fmt.Sscanf(s, "%d", &n) + return n +} + +var vendorNames = map[string]string{"distribution": "the distribution", "corretto": "Amazon Corretto", "temurin": "Eclipse Temurin", + "zulu": "Azul Zulu", "msopenjdk": "Microsoft", "sapmachine": "SapMachine"} + +// pinnedVersion is the Java version a package pin fixes, or "" for a pin +// that matches several releases (17.*, ~17, 17). +func pinnedVersion(h pkgHit) string { + if h.ver == "" || strings.Contains(h.ver, "*") || strings.Contains(h.op, "~") || strings.ContainsAny(h.op, "<>") { + return "" + } + up := h.ver + if i := strings.IndexByte(up, ':'); i >= 0 { + up = up[i+1:] + } + up = strings.ReplaceAll(up, "_p", "+") + if h.vendor == "corretto" { + up = CorrettoJava(up) + } + v, ok := knowledge.Parse(up) + if !ok || len(v.Nums) < 3 { + return "" + } + return up +} + +func (s *scanner) judgePackage(rel string, line int, h pkgHit) { + if h.feature > 0 && h.feature < 17 { + return // Java 8 and 11 packages are not affected + } + props := map[string]string{"package": h.name, "manager": h.mgr} + who := vendorNames[h.vendor] + if h.feature > 0 { + l, ok := knowledge.LineOf(h.feature) + switch { + case !ok: + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: props, + Reason: fmt.Sprintf("Java %d is not in this detector's release data (%s)", h.feature, knowledge.Checked), + Message: fmt.Sprintf("installs %s, a Java %d package this detector has no release data for", h.name, h.feature)}) + return + case l.Fixed == nil: s.add(Finding{Rule: RuleLine, File: rel, Line: line, Level: "error", Status: StatusVulnerable, Reason: l.Note, Message: fmt.Sprintf("installs %s, a Java %d package: that line received no Java4Shell fix", h.name, h.feature), Fix: fmt.Sprintf("Install a supported Java package with the fix instead, such as %s.", knowledge.Upgrade(h.feature)), Props: props}) - continue + return } - fx := knowledge.FixedVersion(h.feature) - props["fixed_in"] = fx - if h.ver != "" { - props["current"] = h.ver - up := h.ver - if i := strings.IndexByte(up, ':'); i >= 0 { - up = up[i+1:] - } - up = strings.ReplaceAll(up, "_p", "+") - if strings.Contains(h.name, "corretto") { - up = CorrettoJava(up) - } - if v, ok := knowledge.Parse(up); ok { - if st, why := knowledge.Judge(v); st == knowledge.Vulnerable { - s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "error", Status: StatusVulnerable, Reason: why, - Message: fmt.Sprintf("pins %s to %s, without the Java4Shell fix", h.name, h.ver), - Fix: fmt.Sprintf("Pin %s to a package of Java %s or later once your distribution publishes it (none had as of %s), then rebuild. Until then set ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics in this stage.", h.name, fx, knowledge.Checked), - Props: props}) - } - } - continue + props["fixed_in"] = knowledge.FixedVersion(h.feature) + } + fx := props["fixed_in"] + if fx == "" { + fx = "a release with the fix" + } + if up := pinnedVersion(h); up != "" { + props["current"] = h.ver + v, _ := knowledge.Parse(up) + if st, why := knowledge.Judge(v); st == knowledge.Vulnerable { + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "error", Status: StatusVulnerable, Reason: why, + Message: fmt.Sprintf("pins %s to %s, without the Java4Shell fix", h.name, h.ver), + Fix: fmt.Sprintf("Pin %s to a package of Java %s or later once %s publishes it, then rebuild. Until then set ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics in this stage.", h.name, fx, who), + Props: props}) + } + return + } + if h.ver != "" { + props["current"] = h.ver + } + what := "without a version" + if h.ver != "" { + what = "with a version range (" + h.op + h.ver + ")" + } + switch h.vendor { + case "corretto", "sapmachine": + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: props, + Reason: fmt.Sprintf("%s published Java %s on 2026-11-17: an image built after that gets it, one built or cached before does not", who, fx), + Message: fmt.Sprintf("installs %s %s: whether the image has the Java4Shell fix depends on when it was built", h.name, what), + Fix: fmt.Sprintf("Rebuild without the layer cache, or pin %s to Java %s or later.", h.name, fx)}) + case "zulu", "msopenjdk": + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: props, + Reason: fmt.Sprintf("%s's fixed release could not be checked (%s)", who, knowledge.Checked), + Message: fmt.Sprintf("installs %s %s: not checked for the Java4Shell fix", h.name, what), + Fix: fmt.Sprintf("Check that %s's package is Java %s or later, then rebuild.", who, fx)}) + default: + reason := fmt.Sprintf("Debian, Ubuntu and Alpine had published no %s package with the fix as of %s (Red Hat's status was not checked), so a build today installs a release without it", fx, knowledge.Checked) + msg := fmt.Sprintf("installs %s %s: it gets whatever the distribution has, which had no Java4Shell fix yet", h.name, what) + if h.vendor == "temurin" { + reason = fmt.Sprintf("Eclipse Temurin had published no %s release as of %s, so a build today installs a release without it", fx, knowledge.Checked) + msg = fmt.Sprintf("installs %s %s: Temurin had no Java4Shell fix yet", h.name, what) + } + if h.feature == 0 { + msg = fmt.Sprintf("installs %s, the distribution's default OpenJDK (17 or later on current Debian and Ubuntu releases), which had no Java4Shell fix yet", h.name) } - s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "warning", Status: StatusVulnerable, - Reason: fmt.Sprintf("Debian, Ubuntu and Alpine had published no %s package with the fix as of %s (Red Hat's status was not checked), so a build today installs a release without it", fx, knowledge.Checked), - Message: fmt.Sprintf("installs %s without a version: it gets whatever the distribution has, which had no Java4Shell fix yet", h.name), - Fix: fmt.Sprintf("Rebuild once the distribution publishes Java %s or later and check the installed version; until then set ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics in this stage.", fx), - Props: props}) + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "warning", Status: StatusVulnerable, Reason: reason, Message: msg, Props: props, + Fix: fmt.Sprintf("Rebuild once %s publishes Java %s or later and check the installed version; until then set ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics in this stage.", who, fx)}) } } diff --git a/detectors/java4shell/internal/repo/repo_test.go b/detectors/java4shell/internal/repo/repo_test.go index 5494eb6..5df009c 100644 --- a/detectors/java4shell/internal/repo/repo_test.go +++ b/detectors/java4shell/internal/repo/repo_test.go @@ -160,9 +160,8 @@ func TestScanTree(t *testing.T) { t.Errorf("setup-java corretto not fixable: %+v", f) } check(".github/workflows/ci.yml", 11, RuleNotChecked, StatusUnknown) - if _, ok := find(res, ".github/workflows/ci.yml", 15); ok { - t.Error("a moving setup-java version of a fixed line reported") - } + // Temurin's newest 17 had no fix: the moving version is reported. + check(".github/workflows/ci.yml", 15, RuleJavaPin, StatusVulnerable) check("build.gradle.kts", 1, RuleLine, StatusVulnerable) check("build.gradle.kts", 2, RuleImagePin, StatusVulnerable) check("pom.xml", 2, RuleJavaPin, StatusUnknown) diff --git a/detectors/java4shell/internal/repo/review3_test.go b/detectors/java4shell/internal/repo/review3_test.go new file mode 100644 index 0000000..b96958d --- /dev/null +++ b/detectors/java4shell/internal/repo/review3_test.go @@ -0,0 +1,68 @@ +package repo + +import "testing" + +type want struct { + file string + line int + rule string + status string +} + +func checkAll(t *testing.T, res Result, ws []want) { + t.Helper() + for _, w := range ws { + f, ok := find(res, w.file, w.line) + if !ok || f.Rule != w.rule || f.Status != w.status { + t.Errorf("%s:%d: got %s %s (%s) found %v, want %s %s", w.file, w.line, f.Rule, f.Status, f.Message, ok, w.rule, w.status) + } + } +} + +// Review finding 8: installs written with flags first, partial versions and +// vendor packages. +func TestReviewPackages(t *testing.T) { + root := tree(t, map[string]string{ + "a/Dockerfile": "FROM rockylinux:9\nRUN yum -y install java-17-openjdk-headless\nRUN dnf -y install java-21-openjdk\nRUN microdnf -y install java-21-openjdk-headless\n", + "b/Dockerfile": "FROM debian:12\nRUN apt-get -y install openjdk-17-jre-headless\nRUN apt-get install -y openjdk-17-jdk=17.*\nRUN apt-get install -y default-jre-headless\nRUN apt-get install -y temurin-21-jdk\n", + "c/Dockerfile": "FROM alpine:3.23\nRUN apk --no-cache add openjdk21\nRUN apk -U add openjdk21-jre\nRUN apk add openjdk17~17\n", + }) + checkAll(t, scan(t, root), []want{ + {"a/Dockerfile", 2, RulePackage, StatusVulnerable}, {"a/Dockerfile", 3, RulePackage, StatusVulnerable}, {"a/Dockerfile", 4, RulePackage, StatusVulnerable}, + {"b/Dockerfile", 2, RulePackage, StatusVulnerable}, {"b/Dockerfile", 3, RulePackage, StatusVulnerable}, {"b/Dockerfile", 4, RulePackage, StatusVulnerable}, + {"b/Dockerfile", 5, RulePackage, StatusVulnerable}, + {"c/Dockerfile", 2, RulePackage, StatusVulnerable}, {"c/Dockerfile", 3, RulePackage, StatusVulnerable}, {"c/Dockerfile", 4, RulePackage, StatusVulnerable}, + }) +} + +// Review findings 11 and 12. +func TestReviewVersionNames(t *testing.T) { + root := tree(t, map[string]string{ + "a/.java-version": "temurin64-21.0.13\n", + "b/.java-version": "openjdk64-17.0.21\n", + "c/.sdkmanrc": "java=22.3.r17-nik\n", + "d/.sdkmanrc": "java=22.3.r17-grl\n", + "e/.tool-versions": "java zulu-21.50.19\n", + ".github/workflows/a.yml": "jobs:\n a:\n steps:\n - uses: actions/setup-java@v4\n with:\n distribution: temurin\n java-version: '21'\n" + + " - uses: actions/setup-java@v4\n with:\n distribution: corretto\n java-version: '21'\n", + "f/Dockerfile": "FROM amazonlinux:2023\nRUN dnf install -y java-21-amazon-corretto-headless\nRUN dnf install -y java-28-openjdk\n", + "g/Dockerfile": "FROM --platform=linux/arm64 eclipse-temurin:21.0.13_9-jre\n", + }) + res := scan(t, root) + checkAll(t, res, []want{ + {"a/.java-version", 1, RuleJavaPin, StatusVulnerable}, + {"b/.java-version", 1, RuleJavaPin, StatusVulnerable}, + {"c/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {"d/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {"e/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {".github/workflows/a.yml", 7, RuleJavaPin, StatusVulnerable}, + {"f/Dockerfile", 2, RulePackage, StatusUnknown}, + {"f/Dockerfile", 3, RuleNotChecked, StatusUnknown}, + }) + if f, ok := find(res, ".github/workflows/a.yml", 11); ok { + t.Errorf("setup-java corretto 21 reported: %+v", f) + } + if f, ok := find(res, "g/Dockerfile", 1); ok { + t.Errorf("an arm64 stage reported: %+v", f) + } +} From 66a412401cb615fcdff95adbd1578dd107cf2643 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 01:38:09 +0000 Subject: [PATCH 017/119] java4shell: fix states the checked digest, refuses shared ARGs, keeps the base OS Review finding 10. The summary of an image move gives the linux/amd64 digest that was checked, and for a republished tag (Corretto's 21.0.13) says to pull again and how to pin the digest. A tag that comes from a variable used elsewhere in the file is not edited. When the tag's variant does not name the base OS (-jre), the verifier reads the current image too and refuses a move to another distribution (the detector now annotates an image's os-release). The setup-java summary mentions check-latest for self-hosted runners. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/internal/repo/plan.go | 63 +++++++++++++++++-- .../java4shell/internal/repo/review4_test.go | 61 ++++++++++++++++++ detectors/java4shell/java4shell.go | 33 +++++++++- detectors/java4shell/repo.go | 18 ++++++ 4 files changed, 170 insertions(+), 5 deletions(-) create mode 100644 detectors/java4shell/internal/repo/review4_test.go diff --git a/detectors/java4shell/internal/repo/plan.go b/detectors/java4shell/internal/repo/plan.go index aa9652e..a48d22e 100644 --- a/detectors/java4shell/internal/repo/plan.go +++ b/detectors/java4shell/internal/repo/plan.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "path/filepath" + "regexp" "sort" "strings" "unicode" @@ -51,7 +52,7 @@ func Plan(ctx context.Context, root string, f Finding, reg Registry, opts Option return planTag(ctx, root, f, reg, opts) case "setup-java": return planLine(ctx, root, f, f.edit.file, f.edit.line, f.edit.col, f.edit.old, fmt.Sprint(f.edit.feature), opts, - fmt.Sprintf("Sets setup-java's java-version from %s to %d on line %d of %s: the %s distribution's newest Java %d release has the Java4Shell fix (%s), and setup-java installs it when the job runs.", + fmt.Sprintf("Sets setup-java's java-version from %s to %d on line %d of %s: the %s distribution's newest Java %d release has the Java4Shell fix (%s), and setup-java installs it when the job runs. On a self-hosted runner with Java %[6]d cached, add check-latest: true to the step so it fetches the newest release.", f.edit.old, f.edit.feature, f.edit.line, f.edit.file, f.Props["distribution"], f.edit.feature, knowledge.FixedVersion(f.edit.feature))) } return nil, declined("no automatic fix for this finding") @@ -153,7 +154,14 @@ func planTag(ctx context.Context, root string, f Finding, reg Registry, opts Opt file = r.File } col := part.Column - 1 + (start - off) - if _, err := reg.Verify(ctx, e.image, newImage); err != nil { + if part.Var != "" { + // Editing the variable changes every place that uses it. + if n, err := varUses(root, r.File, part.Var, opts); err != nil || n > 1 { + return nil, declined("%s gets its tag from %s, which %s uses in more than one place; change it by hand", e.image, part.Var, r.File) + } + } + digest, err := reg.Verify(ctx, e.image, newImage) + if err != nil { var d *Declined if errors.As(err, &d) { return nil, err @@ -164,9 +172,13 @@ func planTag(ctx context.Context, root string, f Finding, reg Registry, opts Opt if part.Var != "" { where = fmt.Sprintf(" (in the value of %s)", part.Var) } + moving := "" + if tv, ok := e.family.ParseTag(newTag); ok && !tv.Exact { + moving = fmt.Sprintf(" The tag %s is republished as %s releases new builds: pull it again when you rebuild and deploy (docker pull, imagePullPolicy: Always), since caches and nodes may still hold an older image under the same tag; to deploy exactly what was checked, pin it as %s@%s.", newTag, e.family.Vendor, newImage, digest) + } return planLine(ctx, root, f, file, part.Line, col, tag, newTag, opts, - fmt.Sprintf("Changes the image %s to %s on line %d of %s%s: the %s release of the same variant with the Java4Shell fix, read and checked on every platform the current tag has. Rebuild and redeploy.", - e.image, newImage, part.Line, file, where, e.family.Vendor)) + fmt.Sprintf("Changes the image %s to %s on line %d of %s%s: the %s release of the same variant with the Java4Shell fix, read and checked on every platform the current tag has (linux/amd64 digest checked: %s). Rebuild and redeploy.%s", + e.image, newImage, part.Line, file, where, e.family.Vendor, digest, moving)) } // planLine replaces old with repl at col on a line and rescans the file in @@ -299,3 +311,46 @@ func Printable(s string) string { func Mitigation(file string, line int) string { return fmt.Sprintf("%s: after line %d add\n ENV JAVA_TOOL_OPTIONS=\"-XX:-UseBASE64Intrinsics\"\n (append to any JAVA_TOOL_OPTIONS the image already sets; this keeps the vulnerable decoder from being generated until the product ships a fixed runtime)", file, line) } + +// varUses counts the places a Dockerfile, Compose file or .env file uses +// a variable ($VAR, ${VAR}). +func varUses(root, file, name string, opts Options) (int, error) { + b, ok := opts.Overlay[file] + if !ok { + var err error + if b, err = readFile(root, file); err != nil { + return 0, err + } + } + re := regexp.MustCompile(`\$\{?` + regexp.QuoteMeta(name) + `\b`) + return len(re.FindAllIndex(b, -1)), nil +} + +// baseOSWords name a base OS in a tag's variant. +var baseOSWords = []string{"alpine", "jammy", "noble", "focal", "resolute", "plucky", "ubuntu", "debian", "bookworm", "trixie", "bullseye", + "ubi", "al2023", "al2", "centos", "rocky", "alma", "windowsservercore", "nanoserver", "distroless", "wolfi", "chainguard"} + +// NamesBaseOS reports whether a tag's variant names the base OS, so two +// tags with the same variant are on the same one. +func NamesBaseOS(variant string) bool { + v := strings.ToLower(variant) + for _, w := range baseOSWords { + if strings.Contains(v, w) { + return true + } + } + return false +} + +// SameBase compares the base OS (ID and VERSION_ID of os-release) of the +// current image and its replacement, for tags whose variant does not name +// it: moving a deployment to another distribution is not this fix's call. +func SameBase(current, target string) error { + switch { + case current == "" || target == "": + return &Declined{Reason: "the base OS of the current or the new image could not be read, and the tag does not name it; change it by hand"} + case current != target: + return &Declined{Reason: fmt.Sprintf("the new image is on %s, the current one on %s; change it by hand", target, current)} + } + return nil +} diff --git a/detectors/java4shell/internal/repo/review4_test.go b/detectors/java4shell/internal/repo/review4_test.go new file mode 100644 index 0000000..769b244 --- /dev/null +++ b/detectors/java4shell/internal/repo/review4_test.go @@ -0,0 +1,61 @@ +package repo + +import ( + "context" + "strings" + "testing" +) + +func fakeRegistry(tags ...string) Registry { + return Registry{ + Tags: func(context.Context, string) ([]string, error) { return tags, nil }, + Verify: func(context.Context, string, string) (string, error) { return "sha256:0123abcd", nil }, + } +} + +// Review finding 10. +func TestReviewFixEdits(t *testing.T) { + // The verified digest and, for a republished tag, the re-pull warning + // are in the summary. + root := tree(t, map[string]string{"Dockerfile": "FROM amazoncorretto:21.0.12-al2023\n"}) + f, _ := find(scan(t, root), "Dockerfile", 1) + ch, err := Plan(context.Background(), root, f, fakeRegistry("21.0.13-al2023"), Options{}) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(ch.Summary, "sha256:0123abcd") || !strings.Contains(ch.Summary, "pull") { + t.Errorf("summary: %s", ch.Summary) + } + // An ARG the edit would change is used elsewhere too: declined. + root = tree(t, map[string]string{"Dockerfile": "ARG TAG=21.0.13_9-jre\nFROM eclipse-temurin:${TAG}\nRUN curl -o /a.jar https://example.invalid/agent-${TAG}.jar\n"}) + f, ok := find(scan(t, root), "Dockerfile", 2) + if !ok { + t.Fatal("no finding") + } + if _, err := Plan(context.Background(), root, f, fakeRegistry("21.0.13.1_2-jre"), Options{}); err == nil || !strings.Contains(err.Error(), "TAG") { + t.Errorf("ARG used elsewhere: %v", err) + } + // setup-java: the summary says check-latest. + root = tree(t, map[string]string{".github/workflows/a.yml": "jobs:\n a:\n steps:\n - uses: actions/setup-java@v4\n with:\n distribution: corretto\n java-version: '21.0.5'\n"}) + f, _ = find(scan(t, root), ".github/workflows/a.yml", 7) + if ch, err := Plan(context.Background(), root, f, Registry{}, Options{}); err != nil || !strings.Contains(ch.Summary, "check-latest") { + t.Errorf("setup-java summary: %v %v", ch, err) + } +} + +// Review finding 10: when a tag's variant does not name its base OS, the +// replacement must be on the same one. +func TestSameBase(t *testing.T) { + if !NamesBaseOS("-jre-alpine") || !NamesBaseOS("-al2023-headless") || NamesBaseOS("-jre") || NamesBaseOS("") { + t.Error("NamesBaseOS") + } + if err := SameBase("ubuntu 24.04", "ubuntu 26.04"); err == nil { + t.Error("different base accepted") + } + if err := SameBase("ubuntu 24.04", "ubuntu 24.04"); err != nil { + t.Error(err) + } + if err := SameBase("", "ubuntu 24.04"); err == nil { + t.Error("unknown base accepted") + } +} diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 6e656dd..f250eb1 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -118,7 +118,7 @@ func isScript(head []byte) bool { return len(head) > 2 && head[0] == '#' && head // keep reports the package databases owners are read from. func keep(p string) bool { switch p { - case "/lib/apk/db/installed", "/usr/lib/apk/db/installed", "/var/lib/dpkg/status": + case "/lib/apk/db/installed", "/usr/lib/apk/db/installed", "/var/lib/dpkg/status", "/etc/os-release", "/usr/lib/os-release": return true } return assess.IsDpkgList(p) @@ -266,6 +266,9 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { if len(s.crashes) > 0 { ctx.Annotate("java4shell_crash_logs", s.crashes) } + if osr := osRelease(s.kept["/etc/os-release"], s.kept["/usr/lib/os-release"]); osr != "" { + ctx.Annotate("java4shell_os", osr) + } if len(s.libs) == 0 { if len(s.limits) > 0 { ctx.Problem("java4shell: the scan reached its limit on " + strings.Join(s.limits, " and ") + " for one target") @@ -436,3 +439,31 @@ func (r resolver) resolve(p string) string { } return cur // a loop: as far as it got } + +// osRelease is "ID VERSION_ID" from os-release, for comparing the base OS +// of two images. +func osRelease(files ...[]byte) string { + for _, b := range files { + if len(b) == 0 || len(b) > 64<<10 { + continue + } + var id, ver string + for _, l := range strings.Split(string(b), "\n") { + k, v, ok := strings.Cut(strings.TrimSpace(l), "=") + if !ok { + continue + } + v = strings.Trim(v, "\"'") + switch k { + case "ID": + id = v + case "VERSION_ID": + ver = v + } + } + if id != "" { + return strings.TrimSpace(id + " " + ver) + } + } + return "" +} diff --git a/detectors/java4shell/repo.go b/detectors/java4shell/repo.go index 0fcaadc..6c38ba6 100644 --- a/detectors/java4shell/repo.go +++ b/detectors/java4shell/repo.go @@ -314,6 +314,16 @@ func (d *Detector) verifier(o engine.Options) func(ctx context.Context, current, if t.Error != "" { return "", fmt.Errorf("reading %s: %s", target, t.Error) } + // A tag whose variant does not name its base OS ("-jre") may move + // to another distribution between releases: compare them. + if fam, tag, ok := repo.FamilyOf(target); ok { + if tv, ok := fam.ParseTag(tag); !ok || !repo.NamesBaseOS(tv.Variant) { + c := engine.ScanImage([]engine.Detector{d}, current, engine.Options{Platform: "linux/amd64", MaxFileSize: o.MaxFileSize, Guarded: true, PublicOnly: o.PublicOnly}) + if err := repo.SameBase(annotation(c, "java4shell_os"), annotation(t, "java4shell_os")); err != nil { + return "", err + } + } + } if t.Incomplete != "" || t.Gaps() > 0 || len(t.Problems) > 0 { return "", &repo.Declined{Reason: fmt.Sprintf("%s could not be read in full; change it by hand", target)} } @@ -340,3 +350,11 @@ func (d *Detector) verifier(o engine.Options) func(ctx context.Context, current, return desc.Digest.String(), nil } } + +func annotation(t *engine.Target, key string) string { + if t == nil || t.Error != "" { + return "" + } + v, _ := t.Annotations[key].(string) + return v +} From 48cd30350c7af8669e731b94ac3bfc2acfbb934a Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 01:39:16 +0000 Subject: [PATCH 018/119] java4shell: partly read images, guarded platform lookup, JDK archives Review finding 14. A pulled image that was read only in part and showed no runtime is reported as not checked instead of dropping the reference. The verifier's platform lookups go through the guarded transport (and --public-registries-only) with the timeout, instead of image.Platforms. A Java runtime download inside a target (a JDK tar.gz or zip) is recorded as not scanned. fix summaries say the digest checked is the tag's. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/internal/repo/plan.go | 2 +- detectors/java4shell/java4shell.go | 9 +++ detectors/java4shell/pulled_internal_test.go | 43 ++++++++++++ detectors/java4shell/repo.go | 70 ++++++++++++++++++-- detectors/java4shell/review2_test.go | 14 ++++ 5 files changed, 130 insertions(+), 8 deletions(-) create mode 100644 detectors/java4shell/pulled_internal_test.go diff --git a/detectors/java4shell/internal/repo/plan.go b/detectors/java4shell/internal/repo/plan.go index a48d22e..0432962 100644 --- a/detectors/java4shell/internal/repo/plan.go +++ b/detectors/java4shell/internal/repo/plan.go @@ -177,7 +177,7 @@ func planTag(ctx context.Context, root string, f Finding, reg Registry, opts Opt moving = fmt.Sprintf(" The tag %s is republished as %s releases new builds: pull it again when you rebuild and deploy (docker pull, imagePullPolicy: Always), since caches and nodes may still hold an older image under the same tag; to deploy exactly what was checked, pin it as %s@%s.", newTag, e.family.Vendor, newImage, digest) } return planLine(ctx, root, f, file, part.Line, col, tag, newTag, opts, - fmt.Sprintf("Changes the image %s to %s on line %d of %s%s: the %s release of the same variant with the Java4Shell fix, read and checked on every platform the current tag has (linux/amd64 digest checked: %s). Rebuild and redeploy.%s", + fmt.Sprintf("Changes the image %s to %s on line %d of %s%s: the %s release of the same variant with the Java4Shell fix, read and checked on every platform the current tag has (digest checked: %s). Rebuild and redeploy.%s", e.image, newImage, part.Line, file, where, e.family.Vendor, digest, moving)) } diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index f250eb1..02e15fe 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -107,12 +107,19 @@ func (d *Detector) Wants(p string, head []byte, _ bool) bool { return archive.IsExecutable(head) case base == "release", keep(p), jvm.SettingKind(p) != "", hsErr.MatchString(base): return true + case jdkArchive.MatchString(base) && archive.IsArchive(head): + return true } return isScript(head) } var hsErr = regexp.MustCompile(`^hs_err_pid\d{1,10}\.log$`) +// jdkArchive names a Java runtime download (OpenJDK21U-jre_x64_linux_..., +// amazon-corretto-21-x64-linux-jdk.tar.gz, jdk-21_linux-x64_bin.tar.gz): +// a runtime that is not installed, which this detector does not unpack. +var jdkArchive = regexp.MustCompile(`(?i)(jdk|jre|corretto|zulu|temurin|liberica|sapmachine|semeru).*\.(tar\.gz|tgz|zip|tar\.xz|tar)$`) + func isScript(head []byte) bool { return len(head) > 2 && head[0] == '#' && head[1] == '!' } // keep reports the package databases owners are read from. @@ -201,6 +208,8 @@ func (s *scan) Visit(f engine.File) []engine.Skip { } } return nil + case jdkArchive.MatchString(base) && archive.IsArchive(f.Data): + return []engine.Skip{{Path: f.Path, Reason: "a Java runtime archive, not installed: java4shell does not unpack it; check the runtime it holds before installing it"}} case hsErr.MatchString(base): if len(s.crashes) < maxHsErrs && len(f.Data) <= maxHsErr { s.crashes = append(s.crashes, readCrash(f.Path, f.Data)) diff --git a/detectors/java4shell/pulled_internal_test.go b/detectors/java4shell/pulled_internal_test.go new file mode 100644 index 0000000..cee90be --- /dev/null +++ b/detectors/java4shell/pulled_internal_test.go @@ -0,0 +1,43 @@ +package java4shell + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/repo" + "github.com/DefectDojo/earlylight/internal/engine" + "github.com/DefectDojo/earlylight/internal/source" +) + +// Review finding 14: a pulled image that was read only in part, with no +// finding, does not make the reference vanish. +func TestPulledPartlyRead(t *testing.T) { + f := repo.Finding{Rule: repo.RuleNotChecked, File: "compose.yaml", Line: 3, Status: repo.StatusUnknown, Pull: "x/jira:9", Props: map[string]string{"image": "x/jira:9"}} + it := &engine.Target{Type: engine.Image, Skipped: []source.Skip{{Path: "/opt/atlassian/jira/jre/lib/server/libjvm.so", Reason: "larger than --max-file-size"}}} + got := fromPulled(f, it) + if len(got) != 1 || got[0].Verdict != engine.Unknown || !strings.Contains(got[0].Reason, "in full") { + t.Fatalf("partly read image: %+v", got) + } + it = &engine.Target{Type: engine.Image, Problems: []string{"a damaged package database"}} + if got := fromPulled(f, it); len(got) != 1 || got[0].Verdict != engine.Unknown { + t.Errorf("image with problems: %+v", got) + } + if got := fromPulled(f, &engine.Target{Type: engine.Image}); len(got) != 0 { + t.Errorf("image read in full with no Java runtime: %+v", got) + } +} + +// Review finding 14: the platform lookup goes through the guarded +// transport and has a deadline. +func TestPlatformsGuarded(t *testing.T) { + start := time.Now() + _, err := platforms(context.Background(), "169.254.169.254/library/x:1", engine.Options{Timeout: 5 * time.Second}) + if err == nil { + t.Fatal("a link-local registry was contacted") + } + if time.Since(start) > 10*time.Second { + t.Errorf("no deadline: %s", time.Since(start)) + } +} diff --git a/detectors/java4shell/repo.go b/detectors/java4shell/repo.go index 6c38ba6..f616bd8 100644 --- a/detectors/java4shell/repo.go +++ b/detectors/java4shell/repo.go @@ -14,7 +14,6 @@ import ( "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" "github.com/DefectDojo/earlylight/detectors/java4shell/internal/repo" "github.com/DefectDojo/earlylight/internal/engine" - "github.com/DefectDojo/earlylight/internal/image" "github.com/DefectDojo/earlylight/internal/netguard" "github.com/DefectDojo/earlylight/internal/refs" "github.com/DefectDojo/earlylight/internal/source" @@ -119,6 +118,14 @@ func (d *Detector) pulled(dir string, f repo.Finding, o engine.Options, cache ma it = engine.ScanImage([]engine.Detector{d}, img, engine.Options{Platform: "linux/amd64", MaxFileSize: o.MaxFileSize, Guarded: true, PublicOnly: o.PublicOnly}) cache[img] = it } + return fromPulled(f, it) +} + +// fromPulled turns what an image scan found into findings at the +// reference. An image read only in part, where nothing was found, is +// reported as not checked: no finding is not proof of no runtime. +func fromPulled(f repo.Finding, it *engine.Target) (out []engine.Finding) { + img := f.Pull if it.Error != "" { g := repoFinding(f) g.Message = fmt.Sprintf("image %s could not be read for Java4Shell: %s", img, refs.CleanText(it.Error, 300)) @@ -126,7 +133,15 @@ func (d *Detector) pulled(dir string, f repo.Finding, o engine.Options, cache ma g.CVEs[0].Reason = g.Reason return []engine.Finding{g} } - var out []engine.Finding + defer func() { + if len(out) == 0 && (it.Incomplete != "" || it.Gaps() > 0 || len(it.Problems) > 0) { + g := repoFinding(f) + g.Verdict, g.Reason = engine.Unknown, "the image could not be read in full, so a runtime in it may have been missed" + g.Message = fmt.Sprintf("image %s was read only in part (%d files not scanned, %d problems): not checked for Java4Shell", img, it.Gaps(), len(it.Problems)) + g.CVEs = []engine.CVEResult{{ID: knowledge.CVE, Verdict: g.Verdict, Reason: g.Reason}} + out = append(out, g) + } + }() for _, x := range it.Findings { if x.Verdict.Cleared() { continue @@ -150,6 +165,50 @@ func (d *Detector) pulled(dir string, f repo.Finding, o engine.Options, cache ma return out } +// platforms lists the platforms of an image through the guarded +// transport, within the timeout (image.Platforms uses neither). +func platforms(ctx context.Context, ref string, o engine.Options) ([]string, error) { + if err := registryRef(ref); err != nil { + return nil, err + } + r, err := name.ParseReference(ref) + if err != nil { + return nil, err + } + timeout := o.Timeout + if timeout <= 0 { + timeout = 60 * time.Second + } + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + desc, err := remote.Get(r, remote.WithContext(ctx), remote.WithTransport(netguard.Transport(o.PublicOnly)), remote.WithAuthFromKeychain(authn.DefaultKeychain)) + if err != nil { + return nil, err + } + if !desc.MediaType.IsIndex() { + return nil, nil + } + idx, err := desc.ImageIndex() + if err != nil { + return nil, err + } + m, err := idx.IndexManifest() + if err != nil { + return nil, err + } + var out []string + for _, d := range m.Manifests { + if d.Platform == nil || d.Platform.OS == "unknown" || d.Annotations["vnd.docker.reference.type"] == "attestation-manifest" { + continue + } + out = append(out, d.Platform.String()) + } + if len(out) == 0 { + return nil, fmt.Errorf("%s is an image index with no images", ref) + } + return out, nil +} + // Fix moves what can be moved to fixed releases: image tags to the first // published fixed tag of the same variant (read and checked first) and // setup-java versions to the moving major version for distributions whose @@ -293,11 +352,8 @@ func (d *Detector) verifier(o engine.Options) func(ctx context.Context, current, if err := registryRef(target); err != nil { return "", err } - var cur []string - if registryRef(current) == nil { - cur, _ = image.Platforms(current) // the current tag may be gone: judge the target on its own - } - tp, err := image.Platforms(target) + cur, _ := platforms(ctx, current, o) // the current tag may be gone: judge the target on its own + tp, err := platforms(ctx, target, o) if err != nil { return "", err } diff --git a/detectors/java4shell/review2_test.go b/detectors/java4shell/review2_test.go index 719cfa5..a94f896 100644 --- a/detectors/java4shell/review2_test.go +++ b/detectors/java4shell/review2_test.go @@ -1,11 +1,13 @@ package java4shell_test import ( + "bytes" "fmt" "strings" "testing" "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" + "github.com/DefectDojo/earlylight/internal/cli" "github.com/DefectDojo/earlylight/internal/engine" ) @@ -36,3 +38,15 @@ func TestKeptCaps(t *testing.T) { t.Errorf("capped scan: %s (%s)", f.Verdict, f.Reason) } } + +// Review finding 14: a JDK archive in the target is recorded as not +// scanned, not passed over in silence. +func TestJDKArchiveRecorded(t *testing.T) { + root := t.TempDir() + write(t, root, "opt/OpenJDK21U-jre_x64_linux_hotspot_21.0.13_9.tar.gz", []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03")) + var out, errb bytes.Buffer + cli.Run(cfg, []string{"scan", "fs", "--format", "json", "--detector", "java4shell", "--show-skipped", "--as-root", root}, &out, &errb) + if !strings.Contains(out.String(), "OpenJDK21U-jre_x64_linux_hotspot_21.0.13_9.tar.gz") { + t.Errorf("JDK archive not recorded: %s", out.String()) + } +} From a092f1311473d68a291b088dd34ac477e25af2af Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 01:40:21 +0000 Subject: [PATCH 019/119] java4shell: word the CVE-to-fix mapping as inferred and drop certainty claims Review finding 15. Outside FACTS.md, the mapping of CVE-2026-114938 to JDK-8393212 is worded as inferred (reasons name it through BugRef), a fixed runtime is "at or past the first release with the fix (judged by its version)", the CPU list no longer claims every Intel CPU from Ice Lake on, and README claims about the release file, finding runtimes and mitigations match what the detector does. The catalog lists only advisories that could be read; the OpenJDK and Oracle advisories are recorded in FACTS.md as unread. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 ++--- detectors/java4shell/FACTS.md | 7 ++++++ .../java4shell/internal/assess/assess.go | 4 ++-- .../internal/knowledge/knowledge.go | 23 +++++++++++-------- detectors/java4shell/internal/repo/plan.go | 2 +- detectors/java4shell/java4shell.go | 9 ++++---- 6 files changed, 31 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 7f1011a..5fb84a0 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ One engine for DefectDojo's emerging-vulnerability scanners. Each new vulnerabil | `php2shell` | PHP runtimes vulnerable to CVE-2026-109618 and CVE-2026-109619 ("PHP2Shell"), fixed in PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12 ([GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w), [GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp)). A packaged PHP is judged by its vendor's backport data, never by the version it reports. Also checks the images a source tree builds on and deploys, and can rewrite them to fixed images | `fs`, `image`, `repo`, `fix` | | `brotli` | Brotli decoders vulnerable to CVE-2026-111497 ("Node2Shell", "Broccoli2Shell"), Brotli 1.0.3 through 1.2.0, fixed in 1.0.10, 1.1.1 and 1.2.1 ([GHSA-9v8h-qqgm-4m35](https://github.com/advisories/GHSA-9v8h-qqgm-4m35)): system `libbrotlidec` and every copy bundled into other software (Node.js, .NET, Bun, Electron, Envoy and Istio, Python wheels such as Pillow, pyarrow, duckdb, pycurl and PyMuPDF, brotli4j, and more), on Linux, Windows and macOS. A decoder is judged first by the error code the fix added, so vendor backports are recognised without distribution data; a build that strips it by its own version stamp or by its code, which returns that error code only once fixed. In a source tree it finds the Node.js, .NET and Bun releases and the bundling packages a project pins, and `fix` moves each to the fixed release | `fs`, `image`, `repo`, `fix` | | `sshole` | \*sshole, the OpenSSH password authentication bypass on musl libc fixed in OpenSSH 10.6p2 and in Alpine's openssh packages of November 5, 2026 ([release notes](https://www.openssh.org/releasenotes.html#10.6p2), [writeup](https://sshhole.com)). On musl, sshd from 7.3p1 to 10.6p1 compares an account's password field of `*` with the `*` that crypt returns when it fails, so a crafted password logs in to that account. It judges each installed sshd by its C library, its release and the apk database (Alpine backports keep the release number), then checks what the target's `sshd_config` (Include, Match, PasswordAuthentication, AuthenticationMethods, PermitRootLogin, AllowUsers and the rest) and account files make reachable, and reports the accounts. In an image it also reads the command (`sshd -o` and `-f`) and the startup scripts it runs (entrypoints, s6, cont-init.d), and reports a server as exposed when a startup script turns password logins on, sets a `*` field or sets passwords. OpenWrt's opkg database and its backports (23.05, 24.10, 25.12) count like Alpine's. PAM-checked builds (`UsePAM yes`) are not affected. On a live server it reads the banner and the offered methods and never sends a password. In a source tree it finds Dockerfiles that install an OpenSSH server on Alpine without the fix (package lists in `ARG` and `ENV` too), Ansible apk tasks, Buildroot, OpenWrt and Yocto configurations that build one on musl, and anything that sets a password field to `*`. It also pulls the images the tree references (through the guarded transport, with the command a Compose service or Kubernetes container sets) and judges them like `scan image`. `fix` adds the fixed release floor (in the variable when the list is one), moves an end-of-life Alpine base to a tag on the nearest fixed Alpine release (`alpine:3.14` to `3.16`, `python:3.9-alpine3.14` to `3.9-alpine3.16` after checking that image) as a labelled upgrade, adds upstream commit 4353fdc43 as a patch scoped to the OpenSSH versions it applies to (Buildroot `BR2_GLOBAL_PATCH_DIR`, a version-specific Yocto bbappend), sets Ansible tasks to `state: latest`, and changes `*` to `*NP*` | `fs`, `image`, `host`, `repo`, `fix` | -| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64 (JDK-8393212), fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 on November 15, 2026 ([fix](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b), [knowledge table](detectors/java4shell/FACTS.md)). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel Ice Lake and later, AMD Zen 4 and later); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds every Java runtime by its VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others). Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; every platform of a multi-arch image is judged on its own), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness and never overrides the library. No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version. OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is recorded as a mitigation on a finding that stays vulnerable (status `mitigated`, counted in the exit status): the options can be overridden where the runtime is deployed, and the runtime still needs the update; `_JAVA_OPTIONS` turning the intrinsic back on undoes it. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context, never as a clearance. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft and Oracle images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | +| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64, fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 on November 15, 2026 by JDK-8393212 ([commit](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b); that this change is the CVE's fix is inferred from the public descriptions, since the OpenJDK advisory could not be read: see the [knowledge table](detectors/java4shell/FACTS.md)). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel server CPUs from Ice Lake on and some client CPUs, not Alder Lake or Raptor Lake; AMD Zen 4 and later); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds Java runtimes by their VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others); a JDK download packed in an archive is recorded as not scanned, not unpacked. Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; each platform of a multi-arch image is judged on its own with `--platform all`), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness: when the library's version line can be read, the library decides, a release file that contradicts it makes the verdict unknown, and a release file alone does not clear a runtime. No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version and build (the first fixed build of each release, such as 21.0.13.1+2; pre-release and self-built JDKs are not judged fixed). OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is recorded as a mitigation on a finding that stays vulnerable (status `mitigated`, counted in the exit status): the options can be overridden where the runtime is deployed, and the runtime still needs the update; `_JAVA_OPTIONS` turning the intrinsic back on undoes it. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context; neither clears a runtime. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft and Oracle images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | The detectors ported from standalone scanners also build as standalone binaries under the names people search for: `emudhra-scan` and `php2shell-scan`. They keep their original commands, flags and exit status rules. `brotli`, `sshole` and `java4shell` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`, `--detector java4shell`). @@ -52,7 +52,7 @@ earlylight scan host --detector sshole bastion.example:22 # banner and offered earlylight scan repo --detector sshole . # Dockerfiles, scripts and Ansible tasks earlylight fix --detector sshole --dry-run . # fixed apk floors, "*" to "*NP*" earlylight scan image --detector java4shell --platform all eclipse-temurin:21-jre # Java runtimes, per platform -sudo earlylight scan fs --detector java4shell / # every JDK, JRE and bundled runtime on this machine +sudo earlylight scan fs --detector java4shell / # the JDKs, JREs and bundled runtimes on this machine earlylight scan repo --detector java4shell . # Java images, versions, toolchains and packages a tree pins earlylight fix --detector java4shell --dry-run . # moves to published fixed images, after reading them earlylight scan image --platform all myorg/app:prod # every platform the image has @@ -133,7 +133,7 @@ Every port must give exactly the verdicts of the scanner it came from before it - `parity/brotli.py` has no standalone scanner to compare with, so it checks every decoder in 38 images against the vendor's own fix status: Node.js, .NET, Bun, Envoy and curl images before and after their October 2026 releases, distribution packages pinned to their exact unfixed and backported builds, and the Python wheels ([BROTLI-RESULTS.md](parity/BROTLI-RESULTS.md)). - `parity/brotli_files.py` checks 73 release binaries and packages, unpacked and never run: Node.js, .NET and Bun for Windows and macOS, seven Electron releases, Envoy and Istio, and the packages that bundle the decoder ([BROTLI-FILES-RESULTS.md](parity/BROTLI-FILES-RESULTS.md)). A WebAssembly build of the decoder is the one case it cannot settle: it is reported as unknown. - `parity/sshole.py` builds ten images from `parity/sshole/` (Alpine with the unfixed and the fixed package, password logins off, UsePAM on, root with PermitRootLogin, a Match on address, the current Alpine release, Debian, an entrypoint that turns password logins on at start, and `sshd -o` in the image command) and checks each verdict against the expected one ([SSHOLE-RESULTS.md](parity/SSHOLE-RESULTS.md)). The expected verdicts come from the upstream fix, musl's crypt and shadow code, and the Alpine package that shipped it. -- `parity/java4shell.py` checks 36 cases against verdicts taken from [FACTS.md](detectors/java4shell/FACTS.md): Temurin 8, 11, 17.0.5, 17.0.6, 17.0.21 (Alpine), 18, 20, 21 (also arm64, every platform, UBI 9), 25 and 27, Corretto (an Amazon Linux rpm and Alpine, before and after Amazon republished their tags with the fix), Zulu, Liberica, SapMachine, Semeru, Elasticsearch's bundled JDK, the fixed SapMachine 21.0.13.1, a jlink image, bundled product runtimes with and without `setenv.sh`, Alpine, Debian and Ubuntu packages, environment, Tomcat CATALINA_OPTS and setenv.sh mitigations and one that is undone, hostile release files and symlink loops, a filesystem scan and an offline source tree ([JAVA4SHELL-RESULTS.md](parity/JAVA4SHELL-RESULTS.md)). +- `parity/java4shell.py` checks 36 cases against verdicts taken from [FACTS.md](detectors/java4shell/FACTS.md): Temurin 8, 11, 17.0.5, 17.0.6, 17.0.21 (Alpine), 18, 20, 21 (also arm64, all platforms of the image, UBI 9), 25 and 27, Corretto (an Amazon Linux rpm and Alpine, before and after Amazon republished their tags with the fix), Zulu, Liberica, SapMachine, Semeru, Elasticsearch's bundled JDK, the fixed SapMachine 21.0.13.1, a jlink image, bundled product runtimes with and without `setenv.sh`, Alpine, Debian and Ubuntu packages, environment, Tomcat CATALINA_OPTS and setenv.sh mitigations and one that is undone, hostile release files and symlink loops, a filesystem scan and an offline source tree ([JAVA4SHELL-RESULTS.md](parity/JAVA4SHELL-RESULTS.md)). - `parity/php.py` runs php2shell-scan, this repo's php2shell-scan and Early Light over php2shell-scan's validation matrix: official images, distribution packages, source builds and hostile images. Each finding's complete record is compared field by field. It also covers filesystem scans at and below a system root, repository scans, `fix --dry-run`, and every detector at once ([PHP-RESULTS.md](parity/PHP-RESULTS.md)). ## Adding a detector diff --git a/detectors/java4shell/FACTS.md b/detectors/java4shell/FACTS.md index 170d43a..95d0674 100644 --- a/detectors/java4shell/FACTS.md +++ b/detectors/java4shell/FACTS.md @@ -76,6 +76,13 @@ The lead read these; they could not be fetched from the research host. Facts her | Alpine | **not fixed yet**: community openjdk17 17.0.21.0.3_p1-r0, openjdk21 21.0.13.0.3_p1-r0, openjdk25 25.0.5.0.3_p1-r0/-r1 (3.23, 3.24, edge); 3.21 and 3.22 carry older 17/21 | dl-cdn.alpinelinux.org APKINDEX | | Red Hat (RHEL, UBI) | **not checked**: access.redhat.com and registry.access.redhat.com unreachable | n/a | +## Advisory links + +The detector's catalog entry links only pages someone on this work could read: the Calif advisory and the Semgrep post (read by +the lead), the OpenJDK fix commit and Amazon Corretto's changelog. **Not read by anyone (HTTP 403 or unreachable):** the OpenJDK +advisory https://openjdk.org/groups/vulnerability/advisories/2026-11-17 and Oracle's alert +https://www.oracle.com/security-alerts/cspunov2026.html; they are listed here only. + ## How the detector uses this - The version that decides is the one inside the libjvm (` () for - JRE ()`), read from the binary, with the diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index 0c43857..18af1b3 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -242,13 +242,13 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi } return f.set(NotAffected, kwhy+"; its VM library has no AVX-512 VBMI decode stubs", what+" is not affected by Java4Shell") case knowledge.Fixed: - return f.set(Fixed, kwhy, what+" has the Java4Shell fix") + return f.set(Fixed, kwhy, what+" is at or past the first release with the Java4Shell fix (judged by its version)") case knowledge.Unknown: return f.set(Unknown, kwhy, what+": not known whether it has the Java4Shell fix") } // The release data says vulnerable. if read && !lib.VBMIStubs { - return f.set(Unknown, fmt.Sprintf("%s, but this VM library does not carry the AVX-512 VBMI Base64 decode stubs, which every affected OpenJDK build has: it may be built without them; check it", kwhy), + return f.set(Unknown, fmt.Sprintf("%s, but this VM library does not carry the AVX-512 VBMI Base64 decode stubs, which the affected builds checked so far all carry: it may be built without them; check it", kwhy), what+": release says vulnerable, VM library lacks the vulnerable decoder") } if !read { diff --git a/detectors/java4shell/internal/knowledge/knowledge.go b/detectors/java4shell/internal/knowledge/knowledge.go index a49f048..d7bc41e 100644 --- a/detectors/java4shell/internal/knowledge/knowledge.go +++ b/detectors/java4shell/internal/knowledge/knowledge.go @@ -12,9 +12,14 @@ import ( // CVE is the vulnerability this detector checks. const CVE = "CVE-2026-114938" -// Bug is the OpenJDK bug that fixed it. +// Bug is the OpenJDK change taken as the fix. The mapping is inferred: +// the OpenJDK advisory that would state it could not be read, and the +// public descriptions of the CVE match this change (FACTS.md). const Bug = "JDK-8393212" +// BugRef is how reasons name the fix. +const BugRef = "JDK-8393212, inferred to be this CVE's fix" + // Checked is the date the release data was last checked. const Checked = "2026-11-17" @@ -280,7 +285,7 @@ func Judge(v Version) (Status, string) { if v.Build >= 0 && v.Build <= EALastUnfixed { return Vulnerable, fmt.Sprintf("JDK %d build %d: the fix reached mainline after jdk-28+%d", f, v.Build, EALastUnfixed) } - return Unknown, fmt.Sprintf("JDK %d build %s: the fix reached mainline on 2026-11-16, after jdk-28+%d; check that this build includes %s", f, buildText(v), EALastUnfixed, Bug) + return Unknown, fmt.Sprintf("JDK %d build %s: the fix reached mainline on 2026-11-16, after jdk-28+%d; check that this build includes %s", f, buildText(v), EALastUnfixed, BugRef) case f > newestFeature: return Unknown, fmt.Sprintf("Java %s is newer than this detector's release data (%s)", ver, Checked) } @@ -302,28 +307,28 @@ func Judge(v Version) (Status, string) { upd := v.Nums[:min(3, len(v.Nums))] switch c := Compare(upd, l.Fixed[:3]); { case c < 0: - return Vulnerable, fmt.Sprintf("Java %s is older than %s, the first %d release with the fix (%s)", ver, join(l.Fixed), f, Bug) + return Vulnerable, fmt.Sprintf("Java %s is older than %s, the first %d release with the fix (%s)", ver, join(l.Fixed), f, BugRef) case c > 0: // A later update (17.0.22) was not released when the data was // checked, and its development builds did not have the fix yet. - return Unknown, fmt.Sprintf("Java %s is a later update than %s; it was not released when this detector's data was checked (%s), and the %d update repository did not have %s yet: check its release notes", ver, join(l.Fixed), Checked, f, Bug) + return Unknown, fmt.Sprintf("Java %s is a later update than %s; it was not released when this detector's data was checked (%s), and the %d update repository did not have %s yet: check its release notes", ver, join(l.Fixed), Checked, f, BugRef) } if len(v.Nums) >= 4 && v.Nums[3] > maxPatch { // OpenJDK patch numbers are small (17.0.8.1, 21.0.13.1); a larger // fourth number is a vendor's build number (Amazon Corretto's // 21.0.13.11), which says nothing about the patch. - return Unknown, fmt.Sprintf("Java %s: the fourth number looks like a vendor build number, not an OpenJDK patch release, so the version does not show whether %s is in", ver, Bug) + return Unknown, fmt.Sprintf("Java %s: the fourth number looks like a vendor build number, not an OpenJDK patch release, so the version does not show whether %s is in", ver, BugRef) } switch c := Compare(v.Nums, l.Fixed); { case c < 0: - return Vulnerable, fmt.Sprintf("Java %s is older than %s, the first %d release with the fix (%s)", ver, join(l.Fixed), f, Bug) + return Vulnerable, fmt.Sprintf("Java %s is older than %s, the first %d release with the fix (%s)", ver, join(l.Fixed), f, BugRef) case c == 0 && v.Build >= 0 && v.Build < l.FixedBuild: - return Vulnerable, fmt.Sprintf("Java %s build %d predates the fix: it reached %s in build %d (%s)", ver, v.Build, join(l.Fixed), l.FixedBuild, Bug) + return Vulnerable, fmt.Sprintf("Java %s build %d predates the fix: it reached %s in build %d (%s)", ver, v.Build, join(l.Fixed), l.FixedBuild, BugRef) } if v.EA { - return Unknown, fmt.Sprintf("Java %s is a pre-release or self-built JDK; check that it includes %s", ver, Bug) + return Unknown, fmt.Sprintf("Java %s is a pre-release or self-built JDK; check that it includes %s", ver, BugRef) } - return Fixed, fmt.Sprintf("Java %s is at or past %s, the first %d release with the fix (%s)", ver, join(l.Fixed), f, Bug) + return Fixed, fmt.Sprintf("Java %s is at or past %s, the first %d release with the fix (%s)", ver, join(l.Fixed), f, BugRef) } func buildText(v Version) string { diff --git a/detectors/java4shell/internal/repo/plan.go b/detectors/java4shell/internal/repo/plan.go index 0432962..8327ab8 100644 --- a/detectors/java4shell/internal/repo/plan.go +++ b/detectors/java4shell/internal/repo/plan.go @@ -177,7 +177,7 @@ func planTag(ctx context.Context, root string, f Finding, reg Registry, opts Opt moving = fmt.Sprintf(" The tag %s is republished as %s releases new builds: pull it again when you rebuild and deploy (docker pull, imagePullPolicy: Always), since caches and nodes may still hold an older image under the same tag; to deploy exactly what was checked, pin it as %s@%s.", newTag, e.family.Vendor, newImage, digest) } return planLine(ctx, root, f, file, part.Line, col, tag, newTag, opts, - fmt.Sprintf("Changes the image %s to %s on line %d of %s%s: the %s release of the same variant with the Java4Shell fix, read and checked on every platform the current tag has (digest checked: %s). Rebuild and redeploy.%s", + fmt.Sprintf("Changes the image %s to %s on line %d of %s%s: the %s release of the same variant with the Java4Shell fix, read on linux/amd64 and checked to be published for the platforms the current tag has (digest checked: %s). Rebuild and redeploy.%s", e.image, newImage, part.Line, file, where, e.family.Vendor, digest, moving)) } diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 02e15fe..2bcfe89 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -10,7 +10,7 @@ // whether it carries the AVX-512 VBMI decode stubs, with the release file as // a second witness. JVM options that keep the decoder from being generated // (-XX:-UseBASE64Intrinsics, -XX:UseAVX=2 or lower) are reported as a -// mitigation, never as a fix. In a source tree it finds the Java images, +// mitigation on a finding that stays vulnerable. In a source tree it finds the Java images, // versions and packages a project pins, and fix moves them to fixed // releases. // @@ -53,8 +53,9 @@ const about = " HotSpot's AVX-512 VBMI Base64 decoder (x86-64, JDK 18 and later, " characters (64 'A' then '=' is enough), so a Java program that decodes untrusted Base64 (tokens, headers," + " certificates, JSON) can have its heap corrupted once the decoder is compiled: pre-authentication remote code" + " execution was shown on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. It runs on CPUs" + - " with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel Ice Lake and later, AMD Zen 4 and later, common on cloud" + - " instances). Fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 (JDK-8393212); Java 18 to 20, 22 to 24" + + " with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel server CPUs from Ice Lake on and some client CPUs, not Alder" + + " Lake or Raptor Lake; AMD Zen 4 and later; common on cloud instances). Fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1" + + " and 27.0.1.1 (by JDK-8393212, the change the public descriptions of the CVE match); Java 18 to 20, 22 to 24" + " and 26 received no fix. -XX:-UseBASE64Intrinsics (or, on x86-64 only, -XX:UseAVX=2) keeps the decoder from being" + " generated until the runtime is updated." @@ -67,8 +68,6 @@ func (d *Detector) Manifest() engine.Manifest { CVEs: []string{knowledge.CVE}, Advisories: []string{ "https://calif.io/java4shell/", - "https://openjdk.org/groups/vulnerability/advisories/2026-11-17", - "https://www.oracle.com/security-alerts/cspunov2026.html", "https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b", "https://semgrep.dev/blog/2026/java4shell-openjdk-base64-vulnerability", "https://github.com/corretto/corretto-21/blob/21.0.13.1.2/CHANGELOG.md", From f9666e5bcee60e0e5cabb73536f739840a555e72 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 01:44:13 +0000 Subject: [PATCH 020/119] java4shell: registry-path tests, more fuzzers, crash-log bounds, dead code Review finding 16. Tests for tagLister, the verifier and pulled images against an in-memory registry; fuzzers for ParseRelease, APKOwners, DpkgOwners, readCrash and assess.Run (which checks that no fuzzed release file, environment, command or settings file clears an unfixed library that carries the decoder), added to CI. FuzzReadCrash found crash-log fields bounded in characters, not bytes: they are now clipped to bytes (its corpus entry is kept). Release.Arch, Setting.Mentions, Options.Set and Finding.Optional were unused and are removed. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 5 + detectors/java4shell/context.go | 19 ++- detectors/java4shell/crash_internal_test.go | 13 ++ .../java4shell/internal/assess/fuzz_test.go | 57 ++++++++ detectors/java4shell/internal/jvm/jvm.go | 23 ---- detectors/java4shell/internal/jvm/jvm_test.go | 4 +- detectors/java4shell/internal/jvm/options.go | 3 - .../java4shell/internal/jvm/review2_test.go | 17 +++ detectors/java4shell/internal/jvm/settings.go | 3 - detectors/java4shell/internal/repo/repo.go | 7 +- .../java4shell/registry_internal_test.go | 124 ++++++++++++++++++ .../fuzz/FuzzReadCrash/dfc88264e848b553 | 2 + 12 files changed, 239 insertions(+), 38 deletions(-) create mode 100644 detectors/java4shell/crash_internal_test.go create mode 100644 detectors/java4shell/internal/assess/fuzz_test.go create mode 100644 detectors/java4shell/registry_internal_test.go create mode 100644 detectors/java4shell/testdata/fuzz/FuzzReadCrash/dfc88264e848b553 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c79c14b..f46a670 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,6 +37,11 @@ jobs: go test ./detectors/java4shell/internal/jvm -run '^$' -fuzz '^FuzzSettings$' -fuzztime 30s go test ./detectors/java4shell/internal/knowledge -run '^$' -fuzz '^FuzzParse$' -fuzztime 20s go test ./detectors/java4shell/internal/repo -run '^$' -fuzz '^FuzzScanText$' -fuzztime 30s + go test ./detectors/java4shell/internal/jvm -run '^$' -fuzz '^FuzzParseRelease$' -fuzztime 15s + go test ./detectors/java4shell/internal/assess -run '^$' -fuzz '^FuzzAPKOwners$' -fuzztime 15s + go test ./detectors/java4shell/internal/assess -run '^$' -fuzz '^FuzzDpkgOwners$' -fuzztime 15s + go test ./detectors/java4shell/internal/assess -run '^$' -fuzz '^FuzzRun$' -fuzztime 30s + go test ./detectors/java4shell -run '^$' -fuzz '^FuzzReadCrash$' -fuzztime 15s for f in FuzzParseDpkgStatus FuzzParseAPKInstalled FuzzParseHeaderBlob FuzzReadBDB FuzzReadNDB FuzzResolver; do go test ./detectors/php2shell/internal/pkgdb -run '^$' -fuzz "^$f\$" -fuzztime 15s done diff --git a/detectors/java4shell/context.go b/detectors/java4shell/context.go index 9b046c4..a0d5041 100644 --- a/detectors/java4shell/context.go +++ b/detectors/java4shell/context.go @@ -4,6 +4,7 @@ import ( "regexp" "runtime" "strings" + "unicode/utf8" "golang.org/x/sys/cpu" ) @@ -58,10 +59,10 @@ var ( func readCrash(p string, b []byte) crash { c := crash{Path: p} if m := jreLine.FindSubmatch(b); m != nil { - c.Version = string(m[1]) + c.Version = clip(string(m[1]), 61) } if m := frameLine.FindSubmatch(b); m != nil { - c.Frame = strings.TrimSpace(string(m[1])) + c.Frame = clip(strings.TrimSpace(string(m[1])), 300) lf := strings.ToLower(c.Frame) c.Base64 = strings.Contains(lf, "base64") || strings.Contains(lf, "decodeblock") } @@ -70,3 +71,17 @@ func readCrash(p string, b []byte) crash { } return c } + +// clip bounds untrusted crash-log text in bytes (the patterns count +// characters), keeping it valid UTF-8. +func clip(s string, n int) string { + s = strings.ToValidUTF8(s, "?") + if len(s) <= n { + return s + } + s = s[:n] + for len(s) > 0 && !utf8.ValidString(s) { + s = s[:len(s)-1] + } + return s +} diff --git a/detectors/java4shell/crash_internal_test.go b/detectors/java4shell/crash_internal_test.go new file mode 100644 index 0000000..559fe39 --- /dev/null +++ b/detectors/java4shell/crash_internal_test.go @@ -0,0 +1,13 @@ +package java4shell + +import "testing" + +func FuzzReadCrash(f *testing.F) { + f.Add([]byte("# JRE version: OpenJDK Runtime Environment (21.0.13+9) (build 21.0.13+9-LTS)\n# Problematic frame:\n# v ~StubRoutines::decodeBlock\nCPU: total 8, avx512f, avx512_vbmi\n")) + f.Fuzz(func(t *testing.T, b []byte) { + c := readCrash("/tmp/hs_err_pid1.log", b) + if len(c.Frame) > 300 || len(c.Version) > 61 { + t.Fatalf("unbounded field: %d %d", len(c.Frame), len(c.Version)) + } + }) +} diff --git a/detectors/java4shell/internal/assess/fuzz_test.go b/detectors/java4shell/internal/assess/fuzz_test.go new file mode 100644 index 0000000..3aeb6c5 --- /dev/null +++ b/detectors/java4shell/internal/assess/fuzz_test.go @@ -0,0 +1,57 @@ +package assess + +import ( + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" +) + +func FuzzAPKOwners(f *testing.F) { + f.Add([]byte("P:openjdk17-jre-headless\nV:17.0.21.0.3_p1-r0\nF:usr/lib/jvm/java-17-openjdk/lib/server\nR:libjvm.so\n\n")) + f.Fuzz(func(t *testing.T, b []byte) { + for p, o := range APKOwners(b) { + if p == "" || o.Name == "" || o.Manager != "apk" { + t.Fatalf("bad owner %q %+v", p, o) + } + } + }) +} + +func FuzzDpkgOwners(f *testing.F) { + f.Add([]byte("Package: openjdk-17-jre-headless\nVersion: 17.0.21+9-1~deb12u1\n\n"), []byte("/usr/lib/jvm/java-17-openjdk-amd64/lib/server/libjvm.so\n")) + f.Fuzz(func(t *testing.T, status, list []byte) { + for p, o := range DpkgOwners(status, map[string][]byte{"openjdk-17-jre-headless:amd64": list}) { + if p == "" || o.Manager != "dpkg" { + t.Fatalf("bad owner %q %+v", p, o) + } + } + }) +} + +// FuzzRun judges a runtime made of fuzzed release text, environment, +// command and settings file: every verdict has a reason, and none is +// fixed or not affected when the VM library carries the decoder and +// states an unfixed version. +func FuzzRun(f *testing.F) { + f.Add("JAVA_VERSION=\"21.0.13.1\"\nJVM_VARIANT=\"Openj9\"\n", "JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics", "sh -c java -XX:+UseBASE64Intrinsics", "JAVA_OPTS=\"-XX:-UseBASE64Intrinsics\"\n") + f.Add("JAVA_VERSION=\"11.0.20\"\n", "_JAVA_OPTIONS=-XX:UseAVX=2", "catalina.sh run", "if true; then CATALINA_OPTS=-XX:UseAVX=1; fi\n") + f.Fuzz(func(t *testing.T, release, env, cmd, setenv string) { + lj, _ := jvm.Inspect("/opt/acme/jre/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true})) + in := Input{Libraries: []*jvm.Library{lj}, Env: []string{env, "JAVA_HOME=/opt/acme/jre"}, Command: jvm.Words(cmd), Releases: map[string]jvm.Release{}} + if r, ok := jvm.ParseRelease([]byte(release)); ok { + in.Releases["/opt/acme/jre"] = r + } + if s, ok := jvm.ReadSetting("/opt/acme/bin/setenv.sh", []byte(setenv)); ok { + in.Settings = []jvm.Setting{s} + } + for _, x := range Run(in) { + if x.Reason == "" || x.Message == "" { + t.Fatalf("no reason: %+v", x) + } + if x.Status == Fixed || x.Status == NotAffected { + t.Fatalf("an unfixed library with the decoder cleared: %s (%s)", x.Status, x.Reason) + } + } + }) +} diff --git a/detectors/java4shell/internal/jvm/jvm.go b/detectors/java4shell/internal/jvm/jvm.go index be6cbd1..3166384 100644 --- a/detectors/java4shell/internal/jvm/jvm.go +++ b/detectors/java4shell/internal/jvm/jvm.go @@ -306,29 +306,6 @@ func (r Release) Version() string { return r["JAVA_VERSION"] } -// Arch is the release file's OS_ARCH as an Arch, "" when it does not say. -func (r Release) Arch() Arch { - switch strings.ToLower(r["OS_ARCH"]) { - case "": - return "" - case "x86_64", "amd64", "x64": - return X8664 - case "aarch64", "arm64": - return AArch64 - case "x86", "i386", "i586", "i686": - return X86 - case "arm": - return ARM - case "ppc64le", "ppc64": - return PPC64 - case "s390x": - return S390X - case "riscv64": - return RISCV64 - } - return Other -} - // OpenJ9 reports a release file that names the OpenJ9 VM. func (r Release) OpenJ9() bool { return strings.EqualFold(r["JVM_VARIANT"], "openj9") } diff --git a/detectors/java4shell/internal/jvm/jvm_test.go b/detectors/java4shell/internal/jvm/jvm_test.go index 9a075ce..1c92d27 100644 --- a/detectors/java4shell/internal/jvm/jvm_test.go +++ b/detectors/java4shell/internal/jvm/jvm_test.go @@ -93,11 +93,11 @@ func TestRoot(t *testing.T) { func TestRelease(t *testing.T) { r, ok := ParseRelease(testlib.Release("JAVA_VERSION", "21.0.13", "JAVA_RUNTIME_VERSION", "21.0.13+9-LTS", "OS_ARCH", "aarch64", "JVM_VARIANT", "Openj9", "MODULES", "java.base java.se")) - if !ok || r.Version() != "21.0.13+9-LTS" || r.Arch() != AArch64 || !r.OpenJ9() || r.JLinked() { + if !ok || r.Version() != "21.0.13+9-LTS" || !r.OpenJ9() || r.JLinked() { t.Errorf("release: %v", r) } jl, ok := ParseRelease([]byte("JAVA_VERSION=\"21.0.13\"\nMODULES=\"java.base java.logging\"\n")) - if !ok || !jl.JLinked() || jl.Version() != "21.0.13" || jl.Arch() != "" { + if !ok || !jl.JLinked() || jl.Version() != "21.0.13" { t.Errorf("jlink release: %v", jl) } if _, ok := ParseRelease(bytes.Repeat([]byte("JAVA_VERSION=\"21\"\n"), 10000)); ok { diff --git a/detectors/java4shell/internal/jvm/options.go b/detectors/java4shell/internal/jvm/options.go index 1dfe33f..4a6e2f8 100644 --- a/detectors/java4shell/internal/jvm/options.go +++ b/detectors/java4shell/internal/jvm/options.go @@ -68,9 +68,6 @@ func (o Options) Mitigates() (bool, string) { return false, "" } -// Set reports whether either option was given at all. -func (o Options) Set() bool { return o.Base64 != nil || o.UseAVX != nil } - // Words splits an option string the way a shell or the JVM's option // variables do: on white space, with single and double quotes grouping. func Words(s string) []string { diff --git a/detectors/java4shell/internal/jvm/review2_test.go b/detectors/java4shell/internal/jvm/review2_test.go index 2adb9e2..f18b364 100644 --- a/detectors/java4shell/internal/jvm/review2_test.go +++ b/detectors/java4shell/internal/jvm/review2_test.go @@ -68,3 +68,20 @@ func TestSettingsOnlyWhatLaunches(t *testing.T) { t.Error("jvm11-server.options not applied to Java 11") } } + +func FuzzParseRelease(f *testing.F) { + f.Add([]byte("JAVA_VERSION=\"21.0.13\"\nJAVA_RUNTIME_VERSION=\"21.0.13+9-LTS\"\nOS_ARCH=\"x86_64\"\nMODULES=\"java.base\"\n")) + f.Add([]byte("JAVA_VERSION=21\r\nJVM_VARIANT=Openj9\n")) + f.Fuzz(func(t *testing.T, b []byte) { + r, ok := ParseRelease(b) + if !ok { + return + } + if r["JAVA_VERSION"] == "" { + t.Fatal("accepted without JAVA_VERSION") + } + _ = r.Version() + _ = r.OpenJ9() + _ = r.JLinked() + }) +} diff --git a/detectors/java4shell/internal/jvm/settings.go b/detectors/java4shell/internal/jvm/settings.go index f804d09..e6513a0 100644 --- a/detectors/java4shell/internal/jvm/settings.go +++ b/detectors/java4shell/internal/jvm/settings.go @@ -76,9 +76,6 @@ func (s Setting) ApplyTo(o *Options, feature int) { } } -// Mentions reports whether the file sets either option at all. -func (s Setting) Mentions() bool { return len(s.lines) > 0 || len(s.ExecOpts) > 0 || len(s.Env) > 0 } - // SettingKind classifies a path, "" when it is not a settings file. func SettingKind(p string) string { base := path.Base(p) diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index dc45578..3ba2bda 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -69,11 +69,8 @@ type Finding struct { // Pull is set for an image reference that only reading the image can // decide (a moving tag, a product image). Pull string `json:"pull,omitempty"` - // Optional is a clearly labelled edit fix offers but does not apply: the - // interim mitigation for an image whose runtime cannot be updated here. - Optional string `json:"optional,omitempty"` - ref *refs.Ref - edit *pinEdit + ref *refs.Ref + edit *pinEdit } // pinEdit locates a version or tag to replace on one line. diff --git a/detectors/java4shell/registry_internal_test.go b/detectors/java4shell/registry_internal_test.go new file mode 100644 index 0000000..554dd37 --- /dev/null +++ b/detectors/java4shell/registry_internal_test.go @@ -0,0 +1,124 @@ +package java4shell + +import ( + "archive/tar" + "bytes" + "context" + "io" + "log" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/google/go-containerregistry/pkg/name" + "github.com/google/go-containerregistry/pkg/registry" + v1 "github.com/google/go-containerregistry/pkg/v1" + "github.com/google/go-containerregistry/pkg/v1/empty" + "github.com/google/go-containerregistry/pkg/v1/mutate" + "github.com/google/go-containerregistry/pkg/v1/remote" + "github.com/google/go-containerregistry/pkg/v1/tarball" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/repo" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// pushImage pushes a one-layer linux/amd64 image holding files. +func pushImage(t *testing.T, ref string, files map[string][]byte) { + t.Helper() + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for p, b := range files { + if err := tw.WriteHeader(&tar.Header{Name: strings.TrimPrefix(p, "/"), Mode: 0o644, Size: int64(len(b)), Typeflag: tar.TypeReg}); err != nil { + t.Fatal(err) + } + tw.Write(b) + } + tw.Close() + data := buf.Bytes() + layer, err := tarball.LayerFromOpener(func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(data)), nil }) + if err != nil { + t.Fatal(err) + } + img, err := mutate.AppendLayers(empty.Image, layer) + if err != nil { + t.Fatal(err) + } + img, err = mutate.ConfigFile(img, &v1.ConfigFile{OS: "linux", Architecture: "amd64", Config: v1.Config{Env: []string{"PATH=/usr/bin"}}}) + if err != nil { + t.Fatal(err) + } + r, err := name.ParseReference(ref) + if err != nil { + t.Fatal(err) + } + if err := remote.Write(r, img); err != nil { + t.Fatal(err) + } +} + +func testRegistry(t *testing.T) string { + t.Helper() + srv := httptest.NewServer(registry.New(registry.Logger(log.New(io.Discard, "", 0)))) + t.Cleanup(srv.Close) + return strings.TrimPrefix(srv.URL, "http://") +} + +func runtimeFiles(version string) map[string][]byte { + return map[string][]byte{ + "/opt/java/openjdk/lib/server/libjvm.so": testlib.Build(testlib.Lib{Version: version, VBMI: true}), + "/etc/os-release": []byte("ID=ubuntu\nVERSION_ID=\"24.04\"\n"), + } +} + +// Review finding 16: tagLister, the verifier and pulled images, against an +// in-memory registry. +func TestRegistryPaths(t *testing.T) { + host := testRegistry(t) + cur := host + "/acme/java:21.0.13_9-jre" + fixed := host + "/acme/java:21.0.13.1_2-jre" + bad := host + "/acme/java:21.0.13.1_1-jre" + none := host + "/acme/java:no-runtime" + pushImage(t, cur, runtimeFiles("21.0.13+9-LTS")) + pushImage(t, fixed, runtimeFiles("21.0.13.1+2-LTS")) + pushImage(t, bad, runtimeFiles("21.0.13.1+1-LTS")) + pushImage(t, none, map[string][]byte{"/etc/os-release": []byte("ID=ubuntu\n")}) + + o := engine.Options{} + tags, err := tagLister(o)(context.Background(), host+"/acme/java") + if err != nil || len(tags) != 4 { + t.Fatalf("tags %v %v", tags, err) + } + + d := &Detector{} + verify := d.verifier(o) + if dg, err := verify(context.Background(), cur, fixed); err != nil || !strings.HasPrefix(dg, "sha256:") { + t.Errorf("fixed target: %q %v", dg, err) + } + for _, target := range []string{bad, none} { + _, err := verify(context.Background(), cur, target) + var dec *repo.Declined + if err == nil || !errorsAs(err, &dec) { + t.Errorf("%s accepted: %v", target, err) + } + } + + // A tree that deploys a product-like image: pulled and judged. + dir := t.TempDir() + os.WriteFile(filepath.Join(dir, "compose.yaml"), []byte("services:\n app:\n image: "+host+"/acme/jira:9\n"), 0o644) + pushImage(t, host+"/acme/jira:9", map[string][]byte{"/opt/atlassian/jira/jre/lib/server/libjvm.so": testlib.Build(testlib.Lib{Version: "17.0.21+9", VBMI: true})}) + tg := d.ScanRepo(context.Background(), dir, o) + if len(tg.Findings) != 1 || tg.Findings[0].Kind != KindImage || tg.Findings[0].Verdict != engine.Vulnerable || tg.Findings[0].Facts["product"] != "Atlassian Jira" { + t.Errorf("pulled: %+v", tg.Findings) + } +} + +func errorsAs(err error, d **repo.Declined) bool { + x, ok := err.(*repo.Declined) + if ok { + *d = x + } + return ok +} diff --git a/detectors/java4shell/testdata/fuzz/FuzzReadCrash/dfc88264e848b553 b/detectors/java4shell/testdata/fuzz/FuzzReadCrash/dfc88264e848b553 new file mode 100644 index 0000000..d2c61ee --- /dev/null +++ b/detectors/java4shell/testdata/fuzz/FuzzReadCrash/dfc88264e848b553 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("# Problematic frame:\n#00000000000000AA00AAAAAAAAA0A\x010Sȿ4\xb3O\x86\xe3\xb9\x05\xe6\xc4R\xc8^\v\f\x19\xee\xde\xd2>\xf8Jy\xa6\xa5_A\x19\xe8\xa5\x1fי\v\xe0\xe8\xf4\x11\xa8\xf4F\x8c\x9fDu?\xc3ߙ|Chܓ\xc5\f\x90\x89F\x93G\xeaF>t\xf1no\xb4\xa7x\b\xf9\xb57[\x1c\x1eE0\xdbH\xaeAr\x8b\xb3\x82\x1b\xf8Ӫ\x98\x918\x83\x1a¾\xff`\x0e\x84X\x8f~\x8e\xb1\x9c\xff\x8f;'4\xeb\xda\xd0\xe3\xea\xe0\"<\xad\xa9\x8e\x96\xa4\x86\x8br]\x9e\x8f\xa3\xb4\x1f\xa3\xd2\xdfS\xe93\x03CP\xc2\xfa\x19\xf9\x98\xdf\xf7\xa0OsQ˫\x1d\xf4{mͣ$\x8f\x1fzv\xd9lk\x19\xfaaH\x02ȓr:\x82h\x87@\x84-\t\xc6d\xe3\a\xb2`\x87\xe9\xc5\xccxo(\xe5E\x93\x13@\xa3%\xa1\xb3\xef)C\xe8\xf6\xe1\xb3xG\xdf-f\x131\xeb#\xbd\"=\xfb\xfbØ \xa8!\xdaX\xc8#\x85\xaf{\xac{\x06\xc9\xe9`\x9b)BR2~\x1bE\xd2\xf1ln\xc6FX\xbb\x91;\xa4\xe7\x1eӶ\x06`ce\xcf)\x80'F\xef訄mU;\xb9E\xa72\x8bE\x82.\xa1\xb83C\xad\xdd\x0e\xf7\xf7r3\x9f\xb4}4\x03\x1f=$\x8b(Vř|\x9b\xa9O\xa1\x9c\xb0\xaa%\xc1o\xef\xa7B#=\x96\x8aAAA00AAAAA0006AAA000A00AAA000AAAAa") From 384b1d040f24a82bc67da60ae03392aa58ed8751 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 01:48:52 +0000 Subject: [PATCH 021/119] java4shell: parity asserts where each version came from; musl and build boundary cases Review finding 16. Parity rows now include version_from, so a verdict taken from the release file instead of the VM library fails. New cases: Temurin 21.0.13 on Alpine (musl), a musl library under a forged release file, and a synthetic build-boundary case (SapMachine 21.0.13.1+2 rewritten to +1). 39/39 match. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- parity/JAVA4SHELL-RESULTS.md | 79 +++++---- parity/java4shell.py | 9 +- parity/java4shell/build1-boundary.Dockerfile | 10 ++ parity/java4shell/cases.json | 174 ++++++++++++++----- parity/java4shell/musl-forged.Dockerfile | 5 + 6 files changed, 194 insertions(+), 85 deletions(-) create mode 100644 parity/java4shell/build1-boundary.Dockerfile create mode 100644 parity/java4shell/musl-forged.Dockerfile diff --git a/README.md b/README.md index 5fb84a0..418e7c9 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ Every port must give exactly the verdicts of the scanner it came from before it - `parity/brotli.py` has no standalone scanner to compare with, so it checks every decoder in 38 images against the vendor's own fix status: Node.js, .NET, Bun, Envoy and curl images before and after their October 2026 releases, distribution packages pinned to their exact unfixed and backported builds, and the Python wheels ([BROTLI-RESULTS.md](parity/BROTLI-RESULTS.md)). - `parity/brotli_files.py` checks 73 release binaries and packages, unpacked and never run: Node.js, .NET and Bun for Windows and macOS, seven Electron releases, Envoy and Istio, and the packages that bundle the decoder ([BROTLI-FILES-RESULTS.md](parity/BROTLI-FILES-RESULTS.md)). A WebAssembly build of the decoder is the one case it cannot settle: it is reported as unknown. - `parity/sshole.py` builds ten images from `parity/sshole/` (Alpine with the unfixed and the fixed package, password logins off, UsePAM on, root with PermitRootLogin, a Match on address, the current Alpine release, Debian, an entrypoint that turns password logins on at start, and `sshd -o` in the image command) and checks each verdict against the expected one ([SSHOLE-RESULTS.md](parity/SSHOLE-RESULTS.md)). The expected verdicts come from the upstream fix, musl's crypt and shadow code, and the Alpine package that shipped it. -- `parity/java4shell.py` checks 36 cases against verdicts taken from [FACTS.md](detectors/java4shell/FACTS.md): Temurin 8, 11, 17.0.5, 17.0.6, 17.0.21 (Alpine), 18, 20, 21 (also arm64, all platforms of the image, UBI 9), 25 and 27, Corretto (an Amazon Linux rpm and Alpine, before and after Amazon republished their tags with the fix), Zulu, Liberica, SapMachine, Semeru, Elasticsearch's bundled JDK, the fixed SapMachine 21.0.13.1, a jlink image, bundled product runtimes with and without `setenv.sh`, Alpine, Debian and Ubuntu packages, environment, Tomcat CATALINA_OPTS and setenv.sh mitigations and one that is undone, hostile release files and symlink loops, a filesystem scan and an offline source tree ([JAVA4SHELL-RESULTS.md](parity/JAVA4SHELL-RESULTS.md)). +- `parity/java4shell.py` checks 39 cases against verdicts taken from [FACTS.md](detectors/java4shell/FACTS.md), and that each version came from the VM library (not the release file): Temurin 8, 11, 17.0.5, 17.0.6, 17.0.21 and 21.0.13 on Alpine (musl), a musl library under a forged release file, a fixed release rewritten to the build before the fix (synthetic), 18, 20, 21 (also arm64, all platforms of the image, UBI 9), 25 and 27, Corretto (an Amazon Linux rpm and Alpine, before and after Amazon republished their tags with the fix), Zulu, Liberica, SapMachine, Semeru, Elasticsearch's bundled JDK, the fixed SapMachine 21.0.13.1, a jlink image, bundled product runtimes with and without `setenv.sh`, Alpine, Debian and Ubuntu packages, environment, Tomcat CATALINA_OPTS and setenv.sh mitigations and one that is undone, hostile release files and symlink loops, a filesystem scan and an offline source tree ([JAVA4SHELL-RESULTS.md](parity/JAVA4SHELL-RESULTS.md)). - `parity/php.py` runs php2shell-scan, this repo's php2shell-scan and Early Light over php2shell-scan's validation matrix: official images, distribution packages, source builds and hostile images. Each finding's complete record is compared field by field. It also covers filesystem scans at and below a system root, repository scans, `fix --dry-run`, and every detector at once ([PHP-RESULTS.md](parity/PHP-RESULTS.md)). ## Adding a detector diff --git a/parity/JAVA4SHELL-RESULTS.md b/parity/JAVA4SHELL-RESULTS.md index 824b4c3..f3e6d6c 100644 --- a/parity/JAVA4SHELL-RESULTS.md +++ b/parity/JAVA4SHELL-RESULTS.md @@ -2,43 +2,46 @@ Generated by `parity/java4shell.py`. Each row's expected findings come from [FACTS.md](../detectors/java4shell/FACTS.md). Registry images are scanned by tag; the digest scanned is listed. -| Case | What | Result | Findings (platform, path, kind, verdict, status) | +| Case | What | Result | Findings (platform, path, kind, verdict, status, version from) | | --- | --- | --- | --- | -| temurin-8 | Temurin 8: no Base64 decode intrinsic
`eclipse-temurin:8u512-b09-jre`
linux/amd64 sha256:9b84aee27144e52f023cb1895b9579519806890f7fc989f89c4e735f51287745 | pass | linux/amd64 /opt/java/openjdk runtime fixed not-affected | -| temurin-11 | Temurin 11: no Base64 decode intrinsic
`eclipse-temurin:11.0.33_10-jre`
linux/amd64 sha256:81296a4bedf616c682869254cd55e4a3bff824498d318fcef224e76237e5f69b | pass | linux/amd64 /opt/java/openjdk runtime fixed not-affected | -| temurin-17.0.5 | Temurin 17.0.5, the last 17 update before the decoder (8268276 came in 17.0.6)
`eclipse-temurin:17.0.5_8-jre`
linux/amd64 sha256:402c656f078bc116a6db1e2e23b08c6f4a78920a2c804ea4c2d3e197f1d6b47c | pass | linux/amd64 /opt/java/openjdk runtime fixed not-affected | -| temurin-17.0.6 | Temurin 17.0.6, the first 17 update with the decoder
`eclipse-temurin:17.0.6_10-jre`
linux/amd64 sha256:7dacdab7c335d90cf4e110f5744ca27d5a3ed87901a7c08022c8c12055438bd2 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | -| temurin-17.0.21-alpine | Temurin 17.0.21 on Alpine (musl), before 17.0.21.1
`eclipse-temurin:17.0.21_9-jre-alpine`
linux/amd64 sha256:df2fcd61a7987cfd3514756f2cb6c6e940fdd8076bdfd4e362121850e6893a3f | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | -| temurin-18 | Temurin 18.0.2.1: end of life, no fix
`eclipse-temurin:18.0.2.1_1-jre`
linux/amd64 sha256:0d503e979d1b0c61d122a26985e23e42e87741198fd967c0c1efeefbd240ff95 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | -| temurin-20 | Temurin 20.0.2: end of life, no fix
`eclipse-temurin:20.0.2_9-jre`
linux/amd64 sha256:db32cb29a978fa782ef97bf3a39f4955295712ebff305839c3faaf64f5c5b22b | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | -| temurin-21 | Temurin 21.0.13, before 21.0.13.1
`eclipse-temurin:21.0.13_9-jre`
linux/amd64 sha256:15ed0883abf7550992a343740223a8bab2292e7db126986cde97c0be58aeb06f | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | -| temurin-21-arm64 | Temurin 21.0.13 for linux/arm64: only x86-64 has the decoder
`eclipse-temurin:21.0.13_9-jre`
linux/arm64/v8 sha256:4a541e56af0ae9a1ff20cdbf43e400864542116b0e7804b37f51be4c574f2057 | pass | linux/arm64/v8 /opt/java/openjdk runtime fixed not-affected | -| temurin-21-all | Temurin 21.0.13, every platform of the multi-arch image (Linux and the two Windows Server images, whose layers name C:\ as /Files)
`eclipse-temurin:21.0.13_9-jre`
linux/amd64 sha256:15ed0883abf7550992a343740223a8bab2292e7db126986cde97c0be58aeb06f
linux/arm64/v8 sha256:4a541e56af0ae9a1ff20cdbf43e400864542116b0e7804b37f51be4c574f2057
linux/ppc64le sha256:189a1d03c2789f872b201886a783632fb7c3e8d503110efa19fb08c47b45f05f
linux/s390x sha256:e1542725522c2fe226e7915012cf0aad5751fb29540528776ce77982cbd1785b
windows/amd64 sha256:47e645496b5244c0fe56534299fbd826cfc4b5626635db8076ea445f8d0a80e2
windows/amd64 sha256:85cc6d636a02ce992461587b5d27d00dd511859ecaaed1e1e0e1f93b44ccb0ab | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable
linux/arm64/v8 /opt/java/openjdk runtime fixed not-affected
linux/ppc64le /opt/java/openjdk runtime fixed not-affected
linux/s390x /opt/java/openjdk runtime fixed not-affected
windows/amd64 /Files/openjdk-21 runtime vulnerable vulnerable
windows/amd64 /Files/openjdk-21 runtime vulnerable vulnerable | -| temurin-21-ubi9 | Temurin 21.0.13 on UBI 9 minimal
`eclipse-temurin:21.0.13_9-jre-ubi9-minimal`
linux/amd64 sha256:17e523f3696b36177c5c9a44399f8a4a4634229fdf3f14d4c7582d2597931a1d | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | -| temurin-25 | Temurin 25.0.5, before 25.0.5.1
`eclipse-temurin:25.0.5_8-jre`
linux/amd64 sha256:fa681c5833ecc085202c0923e909f9de888d80d22a7f38d6c51268ae5978c1d7 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | -| temurin-27 | Temurin 27.0.1.0.2, before 27.0.1.1
`eclipse-temurin:27.0.1.0-jre`
linux/amd64 sha256:2719c23ca6855fed092edd3f47fbea2e6870bfd00fa4e10b2077126d551bca28 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | -| corretto-21-al2023-unfixed | Amazon Corretto 21.0.13.0.11, an rpm on Amazon Linux 2023 (the amazoncorretto:21.0.13-al2023-headless image of 2026-11-17, pinned by digest)
`amazoncorretto@sha256:21a9456bd7fee7045c545bf089e63ffc69ceb7d594b3c5bfb25bace199d3f566`
linux/amd64 sha256:21a9456bd7fee7045c545bf089e63ffc69ceb7d594b3c5bfb25bace199d3f566 | pass | linux/amd64 /usr/lib/jvm/java-21-amazon-corretto.x86_64 runtime vulnerable vulnerable | -| corretto-21-al2023 | amazoncorretto:21.0.13-al2023-headless as republished on 2026-11-18 with Corretto 21.0.13.1.2 (the tag 21.0.13 moves to the out-of-band release)
`amazoncorretto:21.0.13-al2023-headless`
linux/amd64 sha256:47cbd3767e95fd412adbb9c81ce371574bc8f67eebddc9ef319c25c6d0c0a601 | pass | linux/amd64 /usr/lib/jvm/java-21-amazon-corretto.x86_64 runtime fixed fixed | -| corretto-17-alpine-unfixed | Amazon Corretto 17.0.21 on Alpine (the amazoncorretto:17.0.21-alpine3.22 image of 2026-11-17, pinned by digest)
`amazoncorretto@sha256:92cdff306e26329894ef0fab79f8d120ac0acc08f3b675206b66a7da85316043`
linux/amd64 sha256:92cdff306e26329894ef0fab79f8d120ac0acc08f3b675206b66a7da85316043 | pass | linux/amd64 /usr/lib/jvm/java-17-amazon-corretto runtime vulnerable vulnerable | -| corretto-17-alpine | amazoncorretto:17.0.21-alpine3.22 as republished on 2026-11-18 with Corretto 17.0.21.1.2
`amazoncorretto:17.0.21-alpine3.22`
linux/amd64 sha256:e6d108efd17fd318481c1db6ab6f8a79d0823c77408ae4d4d1fb7c6b9e201a1e | pass | linux/amd64 /usr/lib/jvm/java-17-amazon-corretto runtime fixed fixed | -| zulu-21 | Azul Zulu 21.0.13.0.3 (the October CA-only release)
`azul/zulu-openjdk:21.0.13.0.3-jre`
linux/amd64 sha256:bad3fa28d3265b6912b78f85b71d6774dab86dc83a656287c4a2e46f84ac5b3b | pass | linux/amd64 /usr/lib/jvm/zulu21-ca-amd64 runtime vulnerable vulnerable | -| liberica-21 | BellSoft Liberica 21.0.13.0.3
`bellsoft/liberica-openjre-debian:21.0.13.0.3`
linux/amd64 sha256:c5f59f695bc1ae8a588c88c60aef901ed3fc66a7d4ba1b44d2b83cc007c9cb86 | pass | linux/amd64 /usr/lib/jvm/jre-21.0.13.0.3-bellsoft-x86_64 runtime vulnerable vulnerable | -| sapmachine-21 | SapMachine 21.0.13.0.3, before 21.0.13.1
`sapmachine:21.0.13.0.3-jre-ubuntu-noble`
linux/amd64 sha256:2d8895467d35e0f0c938fc8ba94a02792d1720ce738637969e342193c7dac16f | pass | linux/amd64 /usr/lib/jvm/sapmachine-21 runtime vulnerable vulnerable | -| semeru-21 | IBM Semeru 21 (OpenJ9, not HotSpot)
`ibm-semeru-runtimes:open-21-jre`
linux/amd64 sha256:c60bbee4f364698fcf1361f3adde6b9b5faabe70b8c6cc8c179ba3f551a4616c | pass | linux/amd64 /opt/java/openjdk runtime fixed not-affected | -| elasticsearch | Elasticsearch 9.5.5, which bundles its own JDK
`elasticsearch:9.5.5`
linux/amd64 sha256:4f963521f1ac85a08b27f2ac1c864697c9729ade989ed49d2a143cf5f79c222f | pass | linux/amd64 /usr/share/elasticsearch/jdk bundled-runtime vulnerable vulnerable | -| sapmachine-fixed | SapMachine 21.0.13.1 (fixed), unpacked from its release tarball | pass | linux/amd64 /opt/sapmachine runtime fixed fixed | -| jlink | jlink runtime made from Temurin 21.0.13 | pass | linux/amd64 /app/runtime runtime vulnerable vulnerable | -| bundled | Two products bundling Temurin 17.0.21; Jira's setenv.sh sets -XX:-UseBASE64Intrinsics | pass | linux/amd64 /opt/atlassian/confluence/jre bundled-runtime vulnerable vulnerable
linux/amd64 /opt/atlassian/jira/jre bundled-runtime inactive mitigated | -| alpine-pkg | Alpine 3.23 openjdk21-jre-headless (21.0.13.0.3_p1-r0, no fixed package) | pass | linux/amd64 /usr/lib/jvm/java-21-openjdk runtime vulnerable vulnerable | -| debian-pkg | Debian 12 openjdk-17-jre-headless (17.0.21+9-1~deb12u1, no fixed package) | pass | linux/amd64 /usr/lib/jvm/java-17-openjdk-amd64 runtime vulnerable vulnerable | -| ubuntu-pkg | Ubuntu 24.04 openjdk-25-jre-headless (25.0.5.0.3, no fixed package) | pass | linux/amd64 /usr/lib/jvm/java-25-openjdk-amd64 runtime vulnerable vulnerable | -| mitigated-env | Temurin 21.0.13 with ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics | pass | linux/amd64 /opt/java/openjdk runtime inactive mitigated | -| mitigated-useavx | Temurin 25.0.5 with ENV JDK_JAVA_OPTIONS=-XX:UseAVX=2 | pass | linux/amd64 /opt/java/openjdk runtime inactive mitigated | -| reenabled | JAVA_TOOL_OPTIONS mitigation undone by _JAVA_OPTIONS | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable | -| tomcat | Tomcat 10.1 on Temurin 21 with CATALINA_OPTS=-XX:-UseBASE64Intrinsics (catalina.sh passes it on) | pass | linux/amd64 /opt/java/openjdk runtime inactive mitigated | -| tomcat-setenv | Tomcat 10.1 on Temurin 21 with -XX:-UseBASE64Intrinsics in bin/setenv.sh (catalina.sh starts JAVA_HOME's JVM) | pass | linux/amd64 /opt/java/openjdk runtime inactive mitigated | -| hostile | Forged and 200 KiB release files over an unfixed VM library, a text file named libjvm.so, symlink loops | pass | linux/amd64 /opt/forged runtime vulnerable vulnerable
linux/amd64 /opt/huge runtime vulnerable vulnerable | -| debian-pkg-fs | The debian-pkg image exported and scanned as a filesystem | pass | fs /usr/lib/jvm/java-17-openjdk-amd64 runtime vulnerable vulnerable | -| repo | Source tree, offline: Dockerfiles, Compose, Kubernetes, setup-java, version files, Gradle | pass | .github/workflows/ci.yml:12 java-line vulnerable
.github/workflows/ci.yml:8 java-pin vulnerable
.java-version:1 java-pin vulnerable
.sdkmanrc:1 java-pin vulnerable
Dockerfile.pkg:2 os-package inactive
Dockerfile:1 image-pin vulnerable
build.gradle.kts:3 java-line vulnerable
build.gradle.kts:7 image-pin vulnerable
compose.yaml:13 not-checked unknown
compose.yaml:3 image-pin vulnerable
compose.yaml:5 image-pin inactive
k8s/deployment.yaml:10 image-pin vulnerable | +| temurin-8 | Temurin 8: no Base64 decode intrinsic
`eclipse-temurin:8u512-b09-jre`
linux/amd64 sha256:9b84aee27144e52f023cb1895b9579519806890f7fc989f89c4e735f51287745 | pass | linux/amd64 /opt/java/openjdk runtime fixed not-affected vm-library | +| temurin-11 | Temurin 11: no Base64 decode intrinsic
`eclipse-temurin:11.0.33_10-jre`
linux/amd64 sha256:81296a4bedf616c682869254cd55e4a3bff824498d318fcef224e76237e5f69b | pass | linux/amd64 /opt/java/openjdk runtime fixed not-affected vm-library | +| temurin-17.0.5 | Temurin 17.0.5, the last 17 update before the decoder (8268276 came in 17.0.6)
`eclipse-temurin:17.0.5_8-jre`
linux/amd64 sha256:402c656f078bc116a6db1e2e23b08c6f4a78920a2c804ea4c2d3e197f1d6b47c | pass | linux/amd64 /opt/java/openjdk runtime fixed not-affected vm-library | +| temurin-17.0.6 | Temurin 17.0.6, the first 17 update with the decoder
`eclipse-temurin:17.0.6_10-jre`
linux/amd64 sha256:7dacdab7c335d90cf4e110f5744ca27d5a3ed87901a7c08022c8c12055438bd2 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library | +| temurin-17.0.21-alpine | Temurin 17.0.21 on Alpine (musl), before 17.0.21.1
`eclipse-temurin:17.0.21_9-jre-alpine`
linux/amd64 sha256:df2fcd61a7987cfd3514756f2cb6c6e940fdd8076bdfd4e362121850e6893a3f | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library | +| temurin-21-alpine | Temurin 21.0.13 on Alpine: a musl VM library (linux-amd64-musl)
`eclipse-temurin:21.0.13_9-jre-alpine`
linux/amd64 sha256:b6ea71e690a72ba240b3d1b5c477410014862f9ea2cc73ab40e41ff21b03ba1c | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library | +| temurin-18 | Temurin 18.0.2.1: end of life, no fix
`eclipse-temurin:18.0.2.1_1-jre`
linux/amd64 sha256:0d503e979d1b0c61d122a26985e23e42e87741198fd967c0c1efeefbd240ff95 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library | +| temurin-20 | Temurin 20.0.2: end of life, no fix
`eclipse-temurin:20.0.2_9-jre`
linux/amd64 sha256:db32cb29a978fa782ef97bf3a39f4955295712ebff305839c3faaf64f5c5b22b | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library | +| temurin-21 | Temurin 21.0.13, before 21.0.13.1
`eclipse-temurin:21.0.13_9-jre`
linux/amd64 sha256:15ed0883abf7550992a343740223a8bab2292e7db126986cde97c0be58aeb06f | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library | +| temurin-21-arm64 | Temurin 21.0.13 for linux/arm64: only x86-64 has the decoder
`eclipse-temurin:21.0.13_9-jre`
linux/arm64/v8 sha256:4a541e56af0ae9a1ff20cdbf43e400864542116b0e7804b37f51be4c574f2057 | pass | linux/arm64/v8 /opt/java/openjdk runtime fixed not-affected vm-library | +| temurin-21-all | Temurin 21.0.13, every platform of the multi-arch image (Linux and the two Windows Server images, whose layers name C:\ as /Files)
`eclipse-temurin:21.0.13_9-jre`
linux/amd64 sha256:15ed0883abf7550992a343740223a8bab2292e7db126986cde97c0be58aeb06f
linux/arm64/v8 sha256:4a541e56af0ae9a1ff20cdbf43e400864542116b0e7804b37f51be4c574f2057
linux/ppc64le sha256:189a1d03c2789f872b201886a783632fb7c3e8d503110efa19fb08c47b45f05f
linux/s390x sha256:e1542725522c2fe226e7915012cf0aad5751fb29540528776ce77982cbd1785b
windows/amd64 sha256:47e645496b5244c0fe56534299fbd826cfc4b5626635db8076ea445f8d0a80e2
windows/amd64 sha256:85cc6d636a02ce992461587b5d27d00dd511859ecaaed1e1e0e1f93b44ccb0ab | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library
linux/arm64/v8 /opt/java/openjdk runtime fixed not-affected vm-library
linux/ppc64le /opt/java/openjdk runtime fixed not-affected vm-library
linux/s390x /opt/java/openjdk runtime fixed not-affected vm-library
windows/amd64 /Files/openjdk-21 runtime vulnerable vulnerable vm-library
windows/amd64 /Files/openjdk-21 runtime vulnerable vulnerable vm-library | +| temurin-21-ubi9 | Temurin 21.0.13 on UBI 9 minimal
`eclipse-temurin:21.0.13_9-jre-ubi9-minimal`
linux/amd64 sha256:17e523f3696b36177c5c9a44399f8a4a4634229fdf3f14d4c7582d2597931a1d | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library | +| temurin-25 | Temurin 25.0.5, before 25.0.5.1
`eclipse-temurin:25.0.5_8-jre`
linux/amd64 sha256:fa681c5833ecc085202c0923e909f9de888d80d22a7f38d6c51268ae5978c1d7 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library | +| temurin-27 | Temurin 27.0.1.0.2, before 27.0.1.1
`eclipse-temurin:27.0.1.0-jre`
linux/amd64 sha256:2719c23ca6855fed092edd3f47fbea2e6870bfd00fa4e10b2077126d551bca28 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library | +| corretto-21-al2023-unfixed | Amazon Corretto 21.0.13.0.11, an rpm on Amazon Linux 2023 (the amazoncorretto:21.0.13-al2023-headless image of 2026-11-17, pinned by digest)
`amazoncorretto@sha256:21a9456bd7fee7045c545bf089e63ffc69ceb7d594b3c5bfb25bace199d3f566`
linux/amd64 sha256:21a9456bd7fee7045c545bf089e63ffc69ceb7d594b3c5bfb25bace199d3f566 | pass | linux/amd64 /usr/lib/jvm/java-21-amazon-corretto.x86_64 runtime vulnerable vulnerable vm-library | +| corretto-21-al2023 | amazoncorretto:21.0.13-al2023-headless as republished on 2026-11-18 with Corretto 21.0.13.1.2 (the tag 21.0.13 moves to the out-of-band release)
`amazoncorretto:21.0.13-al2023-headless`
linux/amd64 sha256:47cbd3767e95fd412adbb9c81ce371574bc8f67eebddc9ef319c25c6d0c0a601 | pass | linux/amd64 /usr/lib/jvm/java-21-amazon-corretto.x86_64 runtime fixed fixed vm-library | +| corretto-17-alpine-unfixed | Amazon Corretto 17.0.21 on Alpine (the amazoncorretto:17.0.21-alpine3.22 image of 2026-11-17, pinned by digest)
`amazoncorretto@sha256:92cdff306e26329894ef0fab79f8d120ac0acc08f3b675206b66a7da85316043`
linux/amd64 sha256:92cdff306e26329894ef0fab79f8d120ac0acc08f3b675206b66a7da85316043 | pass | linux/amd64 /usr/lib/jvm/java-17-amazon-corretto runtime vulnerable vulnerable vm-library | +| corretto-17-alpine | amazoncorretto:17.0.21-alpine3.22 as republished on 2026-11-18 with Corretto 17.0.21.1.2
`amazoncorretto:17.0.21-alpine3.22`
linux/amd64 sha256:e6d108efd17fd318481c1db6ab6f8a79d0823c77408ae4d4d1fb7c6b9e201a1e | pass | linux/amd64 /usr/lib/jvm/java-17-amazon-corretto runtime fixed fixed vm-library | +| zulu-21 | Azul Zulu 21.0.13.0.3 (the October CA-only release)
`azul/zulu-openjdk:21.0.13.0.3-jre`
linux/amd64 sha256:bad3fa28d3265b6912b78f85b71d6774dab86dc83a656287c4a2e46f84ac5b3b | pass | linux/amd64 /usr/lib/jvm/zulu21-ca-amd64 runtime vulnerable vulnerable vm-library | +| liberica-21 | BellSoft Liberica 21.0.13.0.3
`bellsoft/liberica-openjre-debian:21.0.13.0.3`
linux/amd64 sha256:c5f59f695bc1ae8a588c88c60aef901ed3fc66a7d4ba1b44d2b83cc007c9cb86 | pass | linux/amd64 /usr/lib/jvm/jre-21.0.13.0.3-bellsoft-x86_64 runtime vulnerable vulnerable vm-library | +| sapmachine-21 | SapMachine 21.0.13.0.3, before 21.0.13.1
`sapmachine:21.0.13.0.3-jre-ubuntu-noble`
linux/amd64 sha256:2d8895467d35e0f0c938fc8ba94a02792d1720ce738637969e342193c7dac16f | pass | linux/amd64 /usr/lib/jvm/sapmachine-21 runtime vulnerable vulnerable vm-library | +| semeru-21 | IBM Semeru 21 (OpenJ9, not HotSpot)
`ibm-semeru-runtimes:open-21-jre`
linux/amd64 sha256:c60bbee4f364698fcf1361f3adde6b9b5faabe70b8c6cc8c179ba3f551a4616c | pass | linux/amd64 /opt/java/openjdk runtime fixed not-affected release-file | +| elasticsearch | Elasticsearch 9.5.5, which bundles its own JDK
`elasticsearch:9.5.5`
linux/amd64 sha256:4f963521f1ac85a08b27f2ac1c864697c9729ade989ed49d2a143cf5f79c222f | pass | linux/amd64 /usr/share/elasticsearch/jdk bundled-runtime vulnerable vulnerable vm-library | +| sapmachine-fixed | SapMachine 21.0.13.1 (fixed), unpacked from its release tarball | pass | linux/amd64 /opt/sapmachine runtime fixed fixed vm-library | +| build1-boundary | SYNTHETIC: SapMachine 21.0.13.1 rewritten to build +1, below the fixed build +2 | pass | linux/amd64 /opt/sapmachine runtime vulnerable vulnerable vm-library | +| jlink | jlink runtime made from Temurin 21.0.13 | pass | linux/amd64 /app/runtime runtime vulnerable vulnerable vm-library | +| bundled | Two products bundling Temurin 17.0.21; Jira's setenv.sh sets -XX:-UseBASE64Intrinsics | pass | linux/amd64 /opt/atlassian/confluence/jre bundled-runtime vulnerable vulnerable vm-library
linux/amd64 /opt/atlassian/jira/jre bundled-runtime vulnerable mitigated vm-library | +| alpine-pkg | Alpine 3.23 openjdk21-jre-headless (21.0.13.0.3_p1-r0, no fixed package) | pass | linux/amd64 /usr/lib/jvm/java-21-openjdk runtime vulnerable vulnerable vm-library | +| debian-pkg | Debian 12 openjdk-17-jre-headless (17.0.21+9-1~deb12u1, no fixed package) | pass | linux/amd64 /usr/lib/jvm/java-17-openjdk-amd64 runtime vulnerable vulnerable vm-library | +| ubuntu-pkg | Ubuntu 24.04 openjdk-25-jre-headless (25.0.5.0.3, no fixed package) | pass | linux/amd64 /usr/lib/jvm/java-25-openjdk-amd64 runtime vulnerable vulnerable vm-library | +| mitigated-env | Temurin 21.0.13 with ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics | pass | linux/amd64 /opt/java/openjdk runtime vulnerable mitigated vm-library | +| mitigated-useavx | Temurin 25.0.5 with ENV JDK_JAVA_OPTIONS=-XX:UseAVX=2 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable mitigated vm-library | +| reenabled | JAVA_TOOL_OPTIONS mitigation undone by _JAVA_OPTIONS | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library | +| tomcat | Tomcat 10.1 on Temurin 21 with CATALINA_OPTS=-XX:-UseBASE64Intrinsics (catalina.sh passes it on) | pass | linux/amd64 /opt/java/openjdk runtime vulnerable mitigated vm-library | +| tomcat-setenv | Tomcat 10.1 on Temurin 21 with -XX:-UseBASE64Intrinsics in bin/setenv.sh (catalina.sh starts JAVA_HOME's JVM) | pass | linux/amd64 /opt/java/openjdk runtime vulnerable mitigated vm-library | +| hostile | Forged and 200 KiB release files over an unfixed VM library, a text file named libjvm.so, symlink loops | pass | linux/amd64 /opt/forged runtime vulnerable vulnerable vm-library
linux/amd64 /opt/huge runtime vulnerable vulnerable vm-library | +| musl-forged | Temurin 21.0.13 on Alpine (musl) under a release file forged to say 21.0.13.1+2 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library | +| debian-pkg-fs | The debian-pkg image exported and scanned as a filesystem | pass | fs /usr/lib/jvm/java-17-openjdk-amd64 runtime vulnerable vulnerable vm-library | +| repo | Source tree, offline: Dockerfiles, Compose, Kubernetes, setup-java, version files, Gradle | pass | .github/workflows/ci.yml:12 java-line vulnerable
.github/workflows/ci.yml:8 java-pin vulnerable
.java-version:1 java-pin vulnerable
.sdkmanrc:1 java-pin vulnerable
Dockerfile.pkg:2 os-package vulnerable
Dockerfile:1 image-pin vulnerable
build.gradle.kts:3 java-line vulnerable
build.gradle.kts:7 image-pin vulnerable
compose.yaml:13 not-checked unknown
compose.yaml:3 image-pin vulnerable
compose.yaml:5 image-pin vulnerable
k8s/deployment.yaml:10 image-pin vulnerable | -36/36 cases match. +39/39 cases match. diff --git a/parity/java4shell.py b/parity/java4shell.py index 716316e..df1e882 100644 --- a/parity/java4shell.py +++ b/parity/java4shell.py @@ -11,7 +11,7 @@ images built from parity/java4shell/*.Dockerfile (scanned from `docker save` archives), one built image exported and scanned as a filesystem, and a source tree scanned offline. Each case's findings are compared with the -expected [platform, path, kind, verdict, status] rows, which come from +expected [platform, path, kind, verdict, status, version_from] rows, which come from FACTS.md (fixed releases, the release that introduced the decoder, OpenJ9, architecture), not from earlier runs. Writes parity/JAVA4SHELL-RESULTS.md. """ @@ -40,14 +40,15 @@ def rows(report, repo=False): got, digests = [], [] for t in report.get("targets", []): if t.get("error"): - got.append(["error", t["error"][:120], "", "", ""]) + got.append(["error", t["error"][:120], "", "", "", ""]) if t.get("digest"): digests.append(t.get("platform", "") + " " + t["digest"]) for f in t.get("findings", []): if repo: got.append([f["path"] + ":" + str(f.get("line", 0)), f["kind"], f["verdict"]]) else: - got.append([t.get("platform", ""), f["path"], f["kind"], f["verdict"], f.get("facts", {}).get("status", "")]) + facts = f.get("facts", {}) + got.append([t.get("platform", ""), f["path"], f["kind"], f["verdict"], facts.get("status", ""), facts.get("version_from", "")]) return got, digests @@ -130,7 +131,7 @@ def main(): with open(path, "w") as f: f.write("# Java4Shell fixture results\n\nGenerated by `parity/java4shell.py`. Each row's expected findings come from " "[FACTS.md](../detectors/java4shell/FACTS.md). Registry images are scanned by tag; the digest scanned is listed.\n\n" - "| Case | What | Result | Findings (platform, path, kind, verdict, status) |\n| --- | --- | --- | --- |\n") + "| Case | What | Result | Findings (platform, path, kind, verdict, status, version from) |\n| --- | --- | --- | --- |\n") for n in order: f.write(lines[n]) f.write(f"\n{passed}/{len(order)} cases match.\n") diff --git a/parity/java4shell/build1-boundary.Dockerfile b/parity/java4shell/build1-boundary.Dockerfile new file mode 100644 index 0000000..37461a0 --- /dev/null +++ b/parity/java4shell/build1-boundary.Dockerfile @@ -0,0 +1,10 @@ +# SYNTHETIC boundary case: the fixed SapMachine 21.0.13.1+2 with the +# version line in its VM library and release file rewritten to build +1, +# which upstream (jdk-21.0.13.1+1) did not have the fix. No +1 binary was +# published; this checks that a build below the fixed build is not +# judged fixed. +FROM debian:12-slim +ADD --checksum=sha256:6cb4df182dc9efd3cd37722517832e402cd1beed4f7e3d4d9b58abeb3e949ae9 \ + https://github.com/SAP/SapMachine/releases/download/sapmachine-21.0.13.1/sapmachine-jre-21.0.13.1_linux-x64_bin.tar.gz /tmp/sap.tgz +RUN mkdir -p /opt/sapmachine && tar xzf /tmp/sap.tgz -C /opt/sapmachine --strip-components=1 && rm /tmp/sap.tgz \ + && sed -i 's/21\.0\.13\.1+2-LTS/21.0.13.1+1-LTS/g' /opt/sapmachine/lib/server/libjvm.so /opt/sapmachine/release diff --git a/parity/java4shell/cases.json b/parity/java4shell/cases.json index b0ecd87..d0551b0 100644 --- a/parity/java4shell/cases.json +++ b/parity/java4shell/cases.json @@ -10,7 +10,8 @@ "/opt/java/openjdk", "runtime", "fixed", - "not-affected" + "not-affected", + "vm-library" ] ] }, @@ -25,7 +26,8 @@ "/opt/java/openjdk", "runtime", "fixed", - "not-affected" + "not-affected", + "vm-library" ] ] }, @@ -40,7 +42,8 @@ "/opt/java/openjdk", "runtime", "fixed", - "not-affected" + "not-affected", + "vm-library" ] ] }, @@ -55,7 +58,8 @@ "/opt/java/openjdk", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -70,7 +74,24 @@ "/opt/java/openjdk", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" + ] + ] + }, + { + "name": "temurin-21-alpine", + "what": "Temurin 21.0.13 on Alpine: a musl VM library (linux-amd64-musl)", + "mode": "registry", + "ref": "eclipse-temurin:21.0.13_9-jre-alpine", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "vulnerable", + "vulnerable", + "vm-library" ] ] }, @@ -85,7 +106,8 @@ "/opt/java/openjdk", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -100,7 +122,8 @@ "/opt/java/openjdk", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -115,7 +138,8 @@ "/opt/java/openjdk", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -130,7 +154,8 @@ "/opt/java/openjdk", "runtime", "fixed", - "not-affected" + "not-affected", + "vm-library" ] ], "platform": "linux/arm64" @@ -146,42 +171,48 @@ "/opt/java/openjdk", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ], [ "linux/arm64/v8", "/opt/java/openjdk", "runtime", "fixed", - "not-affected" + "not-affected", + "vm-library" ], [ "linux/ppc64le", "/opt/java/openjdk", "runtime", "fixed", - "not-affected" + "not-affected", + "vm-library" ], [ "linux/s390x", "/opt/java/openjdk", "runtime", "fixed", - "not-affected" + "not-affected", + "vm-library" ], [ "windows/amd64", "/Files/openjdk-21", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ], [ "windows/amd64", "/Files/openjdk-21", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ], "platform": "all" @@ -197,7 +228,8 @@ "/opt/java/openjdk", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -212,7 +244,8 @@ "/opt/java/openjdk", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -227,7 +260,8 @@ "/opt/java/openjdk", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -242,7 +276,8 @@ "/usr/lib/jvm/java-21-amazon-corretto.x86_64", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -257,7 +292,8 @@ "/usr/lib/jvm/java-21-amazon-corretto.x86_64", "runtime", "fixed", - "fixed" + "fixed", + "vm-library" ] ] }, @@ -272,7 +308,8 @@ "/usr/lib/jvm/java-17-amazon-corretto", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -287,7 +324,8 @@ "/usr/lib/jvm/java-17-amazon-corretto", "runtime", "fixed", - "fixed" + "fixed", + "vm-library" ] ] }, @@ -302,7 +340,8 @@ "/usr/lib/jvm/zulu21-ca-amd64", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -317,7 +356,8 @@ "/usr/lib/jvm/jre-21.0.13.0.3-bellsoft-x86_64", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -332,7 +372,8 @@ "/usr/lib/jvm/sapmachine-21", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -347,7 +388,8 @@ "/opt/java/openjdk", "runtime", "fixed", - "not-affected" + "not-affected", + "release-file" ] ] }, @@ -362,7 +404,8 @@ "/usr/share/elasticsearch/jdk", "bundled-runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -377,7 +420,24 @@ "/opt/sapmachine", "runtime", "fixed", - "fixed" + "fixed", + "vm-library" + ] + ] + }, + { + "name": "build1-boundary", + "what": "SYNTHETIC: SapMachine 21.0.13.1 rewritten to build +1, below the fixed build +2", + "mode": "build", + "dockerfile": "build1-boundary.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/opt/sapmachine", + "runtime", + "vulnerable", + "vulnerable", + "vm-library" ] ] }, @@ -392,7 +452,8 @@ "/app/runtime", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -407,14 +468,16 @@ "/opt/atlassian/jira/jre", "bundled-runtime", "vulnerable", - "mitigated" + "mitigated", + "vm-library" ], [ "linux/amd64", "/opt/atlassian/confluence/jre", "bundled-runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -429,7 +492,8 @@ "/usr/lib/jvm/java-21-openjdk", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -444,7 +508,8 @@ "/usr/lib/jvm/java-17-openjdk-amd64", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -459,7 +524,8 @@ "/usr/lib/jvm/java-25-openjdk-amd64", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -474,7 +540,8 @@ "/opt/java/openjdk", "runtime", "vulnerable", - "mitigated" + "mitigated", + "vm-library" ] ] }, @@ -489,7 +556,8 @@ "/opt/java/openjdk", "runtime", "vulnerable", - "mitigated" + "mitigated", + "vm-library" ] ] }, @@ -504,7 +572,8 @@ "/opt/java/openjdk", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, @@ -519,7 +588,8 @@ "/opt/java/openjdk", "runtime", "vulnerable", - "mitigated" + "mitigated", + "vm-library" ] ] }, @@ -534,7 +604,8 @@ "/opt/java/openjdk", "runtime", "vulnerable", - "mitigated" + "mitigated", + "vm-library" ] ] }, @@ -549,14 +620,32 @@ "/opt/forged", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ], [ "linux/amd64", "/opt/huge", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" + ] + ] + }, + { + "name": "musl-forged", + "what": "Temurin 21.0.13 on Alpine (musl) under a release file forged to say 21.0.13.1+2", + "mode": "build", + "dockerfile": "musl-forged.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "vulnerable", + "vulnerable", + "vm-library" ] ] }, @@ -571,7 +660,8 @@ "/usr/lib/jvm/java-17-openjdk-amd64", "runtime", "vulnerable", - "vulnerable" + "vulnerable", + "vm-library" ] ] }, diff --git a/parity/java4shell/musl-forged.Dockerfile b/parity/java4shell/musl-forged.Dockerfile new file mode 100644 index 0000000..0314877 --- /dev/null +++ b/parity/java4shell/musl-forged.Dockerfile @@ -0,0 +1,5 @@ +# Temurin 21.0.13 on Alpine (musl: its VM library names linux-amd64-musl) +# under a release file forged to claim the fixed 21.0.13.1: the VM +# library's own version decides. +FROM eclipse-temurin:21.0.13_9-jre-alpine +RUN sed -i 's/^JAVA_VERSION=.*/JAVA_VERSION="21.0.13.1"/; s/^JAVA_RUNTIME_VERSION=.*/JAVA_RUNTIME_VERSION="21.0.13.1+2-LTS"/' /opt/java/openjdk/release From 611e73f43cf337b3f8b28a14c7fe44a1fa045792 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 02:01:34 +0000 Subject: [PATCH 022/119] java4shell: OpenJ9 only from an OpenJ9 VM library Round-2 finding 1. A release file's JVM_VARIANT=Openj9 no longer decides OpenJ9 on its own: only an OpenJ9 library (libj9vm*, or the redirector without a HotSpot version line or decoder stubs) does, and any HotSpot version line or decoder stubs next to OpenJ9 evidence give unknown. A HotSpot library with the decoder whose version line is not parsed, under a release file naming OpenJ9, was not affected; it is now unknown. Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/assess/assess.go | 13 +++++++-- .../internal/assess/review2_test.go | 29 +++++++++++++++++++ 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index 18af1b3..0dbd277 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -156,11 +156,18 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi if p, ok := owner(in, root, lib); ok { f.Package = &p } - openj9 := hasRel && rel.OpenJ9() + // OpenJ9 only from an OpenJ9 library (by name, or the redirector with + // no HotSpot version line and no decoder stubs): the release file's + // JVM_VARIANT alone does not decide it. + relJ9 := hasRel && rel.OpenJ9() + openj9, stubs := false, false for _, l := range libs { if l.OpenJ9 { openj9 = true } + if l.VBMIStubs { + stubs = true + } } // The version: the VM library's own, the release file's otherwise. @@ -193,8 +200,8 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi } } switch { - case openj9 && hotspot: - return f.set(Unknown, "the runtime's files contradict each other: a HotSpot VM library was read, but the release file or another VM library names OpenJ9", + case (openj9 || relJ9) && (hotspot || stubs): + return f.set(Unknown, "the runtime's files contradict each other: a VM library carries HotSpot's version line or decoder stubs, but the release file or another VM library names OpenJ9", what+": HotSpot and OpenJ9 evidence disagree") case openj9: return f.set(NotAffected, "an OpenJ9 VM: the vulnerable decoder is HotSpot code that OpenJ9 does not contain", diff --git a/detectors/java4shell/internal/assess/review2_test.go b/detectors/java4shell/internal/assess/review2_test.go index e26af24..67ebcd1 100644 --- a/detectors/java4shell/internal/assess/review2_test.go +++ b/detectors/java4shell/internal/assess/review2_test.go @@ -83,3 +83,32 @@ func TestBatchFileWindowsOnly(t *testing.T) { t.Errorf("setenv.bat on Windows: %s", f.Status) } } + +// Round-2 finding 1: OpenJ9 only from an OpenJ9 library, never from the +// release file alone, and never when the HotSpot decoder stubs are there. +func TestOpenJ9NeedsLibrary(t *testing.T) { + fastdebug := lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{VBMI: true, Extra: "\x00OpenJDK 64-Bit Server VM (fastdebug 21.0.13+9) for linux-amd64 JRE (21.0.13+9)\x00"}) + in := Input{Libraries: []*jvm.Library{fastdebug}, Releases: map[string]jvm.Release{temurin: rel(t, "JAVA_VERSION", "21.0.13", "JVM_VARIANT", "Openj9")}} + if f := one(t, in); f.Status != Unknown { + t.Errorf("release-only OpenJ9 over a library with the decoder: %s (%s)", f.Status, f.Reason) + } + // A library without stubs and without a version line, release says + // OpenJ9, no OpenJ9 library: not cleared either. + plain := lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{}) + in = Input{Libraries: []*jvm.Library{plain}, Releases: map[string]jvm.Release{temurin: rel(t, "JAVA_VERSION", "21.0.13", "JVM_VARIANT", "Openj9")}} + if f := one(t, in); f.Status == NotAffected { + t.Errorf("release-only OpenJ9: %s (%s)", f.Status, f.Reason) + } + // An OpenJ9 VM library next to a redirector carrying HotSpot stubs: unknown. + j9 := lib(t, temurin+"/lib/default/libj9vm29.so", testlib.Lib{}) + in = Input{Libraries: []*jvm.Library{fastdebug, j9}} + if f := one(t, in); f.Status != Unknown { + t.Errorf("OpenJ9 library next to HotSpot stubs: %s", f.Status) + } + // Real Semeru layout: redirector + libj9vm29, release says OpenJ9. + redir := lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{Extra: "OPENJ9_JAVA_OPTIONS"}) + in = Input{Libraries: []*jvm.Library{redir, j9}, Releases: map[string]jvm.Release{temurin: rel(t, "JAVA_VERSION", "21.0.13.0.3", "JVM_VARIANT", "Openj9")}} + if f := one(t, in); f.Status != NotAffected { + t.Errorf("Semeru: %s (%s)", f.Status, f.Reason) + } +} From c3895409ff65ddc26d37cea9bd76d7e7546d6a1b Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 02:02:30 +0000 Subject: [PATCH 023/119] java4shell: self-built JDKs are unknown at a build boundary; -LTS is not pre-release Round-2 finding 3. A self-built JDK (-internal, adhoc) has no release build number, so at the update the decoder came with (17.0.6) or the release the fix landed in (17.0.21.1...) it is unknown instead of judged by its build; a self-build of an older update is still vulnerable. A -LTS suffix or an rpm release (21.0.13.1.2-1.el9) after the version is no longer read as a pre-release. Co-Authored-By: Claude Opus 5.5 --- .../internal/knowledge/knowledge.go | 24 ++++++++++++++--- .../internal/knowledge/review2_test.go | 27 ++++++++++++++++++- 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/detectors/java4shell/internal/knowledge/knowledge.go b/detectors/java4shell/internal/knowledge/knowledge.go index d7bc41e..829425b 100644 --- a/detectors/java4shell/internal/knowledge/knowledge.go +++ b/detectors/java4shell/internal/knowledge/knowledge.go @@ -44,7 +44,11 @@ type Version struct { Nums []int Build int // -1 when absent EA bool // a pre-release or self-built JDK: -ea, -beta, -internal, adhoc - Raw string + // SelfBuilt is a JDK built from source (-internal, adhoc): its build + // number is not the release's, so it cannot place it before or after a + // build boundary. + SelfBuilt bool + Raw string } // Feature is the major release (8, 11, 17...). @@ -128,8 +132,15 @@ func Parse(s string) (Version, bool) { if i := strings.IndexByte(r, '+'); i >= 0 { pre, rest = r[:i], r[i:] } - // Any pre-release identifier: ea, beta, internal, a build date. - v.EA = pre != "" + switch { + case pre == "", strings.EqualFold(pre, "LTS"), pre[0] >= '0' && pre[0] <= '9': + // A vendor suffix (21.0.13.1-LTS) or an rpm release + // (21.0.13.1.2-1.el9), not a pre-release. + case strings.HasPrefix(pre, "internal"): + v.EA, v.SelfBuilt = true, true + default: + v.EA = true // ea, beta, rc, a build date + } } if r, ok := strings.CutPrefix(rest, "+"); ok { if b, _ := leadingInt(r); b >= 0 { @@ -137,7 +148,7 @@ func Parse(s string) (Version, bool) { } // A self-built JDK ("+0-adhoc.root.jdk17u") is not a release. if strings.Contains(r, "adhoc") { - v.EA = true + v.EA, v.SelfBuilt = true, true } } return v, true @@ -295,6 +306,9 @@ func Judge(v Version) (Status, string) { } if l.Introduced != nil { c := Compare(v.Nums, l.Introduced) + if c == 0 && v.SelfBuilt { + return Unknown, fmt.Sprintf("Java %s is a self-built JDK of %s, the update the decoder came in with (build %d): its build number does not show whether it has it", ver, join(l.Introduced), l.IntroducedBuild) + } if c < 0 || c == 0 && v.EA && v.Build >= 0 && v.Build < l.IntroducedBuild { return NotAffected, fmt.Sprintf("Java %s predates %s, the first %d update with the AVX-512 VBMI Base64 decoder (8268276)", ver, join(l.Introduced), f) } @@ -322,6 +336,8 @@ func Judge(v Version) (Status, string) { switch c := Compare(v.Nums, l.Fixed); { case c < 0: return Vulnerable, fmt.Sprintf("Java %s is older than %s, the first %d release with the fix (%s)", ver, join(l.Fixed), f, BugRef) + case c == 0 && v.SelfBuilt: + return Unknown, fmt.Sprintf("Java %s is a self-built JDK of %s, the release the fix reached in build %d: its build number does not show whether its source had the fix (%s)", ver, join(l.Fixed), l.FixedBuild, BugRef) case c == 0 && v.Build >= 0 && v.Build < l.FixedBuild: return Vulnerable, fmt.Sprintf("Java %s build %d predates the fix: it reached %s in build %d (%s)", ver, v.Build, join(l.Fixed), l.FixedBuild, BugRef) } diff --git a/detectors/java4shell/internal/knowledge/review2_test.go b/detectors/java4shell/internal/knowledge/review2_test.go index 29be026..a5d9cab 100644 --- a/detectors/java4shell/internal/knowledge/review2_test.go +++ b/detectors/java4shell/internal/knowledge/review2_test.go @@ -24,7 +24,7 @@ func TestReviewBuilds(t *testing.T) { // Pre-release builds are not judged fixed. {"21.0.13.1-beta+1-202611100000", Vulnerable}, {"21.0.13.1-beta+2-202611150000", Unknown}, - {"17.0.21.1-internal+0-adhoc.root.jdk17u", Vulnerable}, + {"17.0.21.1-internal+0-adhoc.root.jdk17u", Unknown}, // self-built: the build number says nothing (round 2) {"17.0.21.1-internal+2-adhoc.root.jdk17u", Unknown}, {"17.0.21.1+2-adhoc.builder.jdk", Unknown}, // Older than the fix whatever the fourth number means. @@ -42,3 +42,28 @@ func TestReviewBuilds(t *testing.T) { } } } + +// Round-2 finding 3: self-built JDKs have no meaningful build number, and +// -LTS or an rpm release suffix is not a pre-release. +func TestReviewSelfBuilt(t *testing.T) { + for _, c := range []struct { + v string + want Status + }{ + {"17.0.6-internal+0-adhoc.root.jdk17u", Unknown}, + {"17.0.21.1-internal+0-adhoc.root.jdk17u", Unknown}, + {"21.0.2-internal+0-adhoc.root.jdk21u", Vulnerable}, // the source predates the fix + {"24.0.2-internal+0-adhoc.root.jdk24u", Vulnerable}, // the line has no fix + {"21.0.13.1-LTS", Fixed}, + {"21.0.13.1.2-1.el9", Fixed}, + {"21.0.13-LTS", Vulnerable}, + } { + v, ok := Parse(c.v) + if !ok { + t.Fatalf("Parse(%q)", c.v) + } + if got, why := Judge(v); got != c.want { + t.Errorf("Judge(%s) = %s (%s), want %s", c.v, got, why, c.want) + } + } +} From fc57271b07aac7f655331e1eeacfdcdf43b5d40b Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 02:04:59 +0000 Subject: [PATCH 024/119] java4shell: a closer model of setenv.sh Round-2 finding 2. Keywords count only in command position (so "echo done" no longer closes a block); function bodies and "&& { }" groups are conditional; heredoc text is skipped; commands on one line are read in order and unset clears a variable; the JVM's own variables count only when exported; only the launcher's variables count (catalina.sh: JAVA_OPTS, CATALINA_OPTS; JVM_SUPPORT_RECOMMENDED_ARGS only for Atlassian products), applied in the order the JVM sees them (JAVA_TOOL_OPTIONS, JDK_JAVA_OPTIONS, JAVA_OPTS, CATALINA_OPTS, _JAVA_OPTIONS). Multi-line values, helper variables and sourced files are still not modelled; they are not counted, which leaves the runtime vulnerable. Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/jvm/review2_test.go | 41 +++ detectors/java4shell/internal/jvm/settings.go | 301 ++++++++++++++---- 2 files changed, 275 insertions(+), 67 deletions(-) diff --git a/detectors/java4shell/internal/jvm/review2_test.go b/detectors/java4shell/internal/jvm/review2_test.go index f18b364..cd09218 100644 --- a/detectors/java4shell/internal/jvm/review2_test.go +++ b/detectors/java4shell/internal/jvm/review2_test.go @@ -85,3 +85,44 @@ func FuzzParseRelease(f *testing.F) { _ = r.JLinked() }) } + +// Round-2 finding 2: what the setenv.sh model still accepted. +func TestSetenvModelRound2(t *testing.T) { + jira := "/opt/atlassian/jira/bin/setenv.sh" + tomcat := "/opt/tomcat/bin/setenv.sh" + for _, c := range []struct { + file, text string + want bool + }{ + {jira, "never_called() {\n JVM_SUPPORT_RECOMMENDED_ARGS=\"-XX:-UseBASE64Intrinsics\"\n}\n", false}, + {jira, "function f {\n CATALINA_OPTS=\"-XX:-UseBASE64Intrinsics\"\n}\n", false}, + {jira, "[ \"$X\" = 1 ] && {\n JVM_SUPPORT_RECOMMENDED_ARGS=\"-XX:-UseBASE64Intrinsics\"\n}\n", false}, + {jira, "if [ -n \"$Y\" ]; then\n echo done\n JVM_SUPPORT_RECOMMENDED_ARGS=\"-XX:-UseBASE64Intrinsics\"\nfi\n", false}, + {jira, "cat < 0 - for _, w := range words { - w = strings.TrimSuffix(w, ";") - if shellControl[w] { - cond = true - } - switch w { + // Leading keywords that start a block or a branch. A function + // header ("function f {", "f() {") opens one block, whose "{" + // may be on the same line. + fn := false + for len(words) > 0 { + switch words[0] { + case "function": + depth++ + fn = true + words = words[1:] + if len(words) > 0 { + words = words[1:] // the name + } + continue + case "{": + if !fn { + depth++ + } + fn = false + words = words[1:] + continue case "if", "case", "for", "while", "until": depth++ - case "fi", "esac", "done": + words = words[1:] + continue + case "then", "else", "elif", "do", "!": + words = words[1:] + continue + case "fi", "esac", "done", "}": if depth > 0 { depth-- } + words = words[1:] + continue } + break } - m := assignRE.FindStringSubmatch(line) - if m == nil { - if cond { - for _, n := range append(append([]string{}, EnvVars...), ScriptVars...) { - if strings.Contains(line, n+"=") { - uncertain = true - } - } + if len(words) > 0 && strings.HasSuffix(words[0], "()") { + depth++ // name() { ...: a function body + fn = true + words = words[1:] + } + if n := len(words); n > 0 && words[n-1] == "{" { + // "&& {" opens a group whose end is a "}" line; a function + // header's "{" belongs to the block it already opened. + if !fn { + depth++ } + words = words[:n-1] + } + if fn && len(words) == 1 && words[0] == "{" { + words = nil + } + if len(words) == 0 { continue } - if cond { - if launcherVar(m[1]) { - uncertain = true + cond := c.cond || depth > 0 + touches := func(n string) bool { return wanted[n] } + switch words[0] { + case "unset", "export", "readonly", "declare", "local": + for _, w := range words[1:] { + name, value, assign := strings.Cut(w, "=") + if !touches(name) { + continue + } + if cond { + return nil, false + } + switch { + case words[0] == "unset": + delete(vals, name) + delete(exported, name) + case assign: + vals[name] = expand(value, vals) + exported[name] = words[0] == "export" || exported[name] + default: + exported[name] = exported[name] || words[0] == "export" + } } continue } - name = m[1] - value = strings.Join(Words(m[2]), " ") - value = shVarRE.ReplaceAllStringFunc(value, func(v string) string { - return vals[strings.Trim(v, "${}")] - }) - } - if !launcherVar(name) { - continue - } - if _, seen := vals[name]; !seen { - order = append(order, name) + m := assignRE.FindStringSubmatch(words[0]) + if m == nil || !touches(m[1]) { + continue + } + if cond || len(words) > 1 { + // Under a condition, or a prefix assignment for one command + // (NAME=value cmd), which does not persist. + if !cond && len(words) > 1 { + continue + } + return nil, false + } + vals[m[1]] = expand(m[2], vals) } - vals[name] = value - } - if uncertain { - return } - for _, n := range order { - for _, w := range xxRE.FindAllString(vals[n], -1) { - s.lines = append(s.lines, optLine{0, 0, w}) + for n := range vals { + if jvmEnvVar(n) && !exported[n] { + delete(vals, n) // not exported: java does not see it } } + return vals, true +} + +// expand substitutes $NAME and ${NAME} with the values set so far. +func expand(v string, vals map[string]string) string { + return shVarRE.ReplaceAllStringFunc(v, func(x string) string { return vals[strings.Trim(x, "${}")] }) } From d11059805d7c791a68f89d1f21ab2348041edbf1 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 02:07:27 +0000 Subject: [PATCH 025/119] java4shell: runtime downloads recorded by name; plain units do not count toward the cap Round-2 findings 4 and 5. The engine gets an optional HeadVisitor: a scan that implements it sees the first bytes of every file the walk meets, read or not. java4shell uses it to record Java runtime downloads (names anchored to how vendors publish them: OpenJDK21U-jre_..., amazon-corretto-21-..., zulu21...-ca- jdk21..., jdk-21_linux-x64_bin...) as the annotation java4shell_runtime_archives, without reading them and without counting them as files not scanned. Other archives are not recorded. Only settings files that set a JVM option count toward the settings cap; systemd units without one are kept as small records under their own cap, since an /etc override without options still replaces the unit it overrides. dpkg lists are filtered without splitting them. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/internal/jvm/settings.go | 7 ++ detectors/java4shell/java4shell.go | 78 ++++++++++++++----- detectors/java4shell/review2_test.go | 57 ++++++++++++-- internal/engine/engine.go | 8 ++ internal/engine/engine_test.go | 21 +++++ internal/engine/run.go | 25 +++++- 6 files changed, 168 insertions(+), 28 deletions(-) diff --git a/detectors/java4shell/internal/jvm/settings.go b/detectors/java4shell/internal/jvm/settings.go index 94cf9ac..651e141 100644 --- a/detectors/java4shell/internal/jvm/settings.go +++ b/detectors/java4shell/internal/jvm/settings.go @@ -48,6 +48,13 @@ func (s Setting) Options(feature int) Options { return o } +// SetsOptions reports whether the file sets anything this detector +// reads: a JVM option, or for a systemd unit a JVM option variable (a +// drop-in that resets JAVA_TOOL_OPTIONS matters too). +func (s Setting) SetsOptions() bool { + return len(s.lines) > 0 || len(s.ExecOpts) > 0 || len(s.Env) > 0 +} + // ApplyTo applies the file's options, in order, on top of o. For a // systemd unit the order is HotSpot's: JAVA_TOOL_OPTIONS, JDK_JAVA_OPTIONS, // the command line, then _JAVA_OPTIONS. diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 2bcfe89..0d8096f 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -106,18 +106,31 @@ func (d *Detector) Wants(p string, head []byte, _ bool) bool { return archive.IsExecutable(head) case base == "release", keep(p), jvm.SettingKind(p) != "", hsErr.MatchString(base): return true - case jdkArchive.MatchString(base) && archive.IsArchive(head): - return true } return isScript(head) } var hsErr = regexp.MustCompile(`^hs_err_pid\d{1,10}\.log$`) -// jdkArchive names a Java runtime download (OpenJDK21U-jre_x64_linux_..., -// amazon-corretto-21-x64-linux-jdk.tar.gz, jdk-21_linux-x64_bin.tar.gz): -// a runtime that is not installed, which this detector does not unpack. -var jdkArchive = regexp.MustCompile(`(?i)(jdk|jre|corretto|zulu|temurin|liberica|sapmachine|semeru).*\.(tar\.gz|tgz|zip|tar\.xz|tar)$`) +// jdkArchive names a Java runtime download as vendors publish it: +// OpenJDK21U-jre_x64_linux_hotspot_21.0.13_9.tar.gz (Temurin), +// amazon-corretto-21-x64-linux-jdk.tar.gz, zulu21.42.19-ca-jdk21.0.13-linux_x64.tar.gz, +// jdk-21_linux-x64_bin.tar.gz (Oracle), bellsoft-jre21.0.13+11-linux-amd64.tar.gz, +// sapmachine-jre-21.0.13.1_linux-x64_bin.tar.gz, microsoft-jdk-21.0.13-linux-x64.tar.gz, +// ibm-semeru-open-jre_x64_linux_21.0.13_11_openj9-0.53.0.tar.gz, openjdk-21.0.2_linux-x64_bin.tar.gz. +var jdkArchive = regexp.MustCompile(`(?i)^(?:OpenJDK\d{1,2}U-(?:jdk|jre)_|amazon-corretto-\d{1,2}[.\w-]*-(?:jdk|jre)|zulu\d[\w.]*-ca-(?:jdk|jre|fx-jdk|fx-jre)\d|jdk-\d{1,2}[\w.]*_(?:linux|windows|macos|osx)-|bellsoft-(?:jdk|jre)\d|sapmachine-(?:jdk|jre)-\d|microsoft-jdk-\d|ibm-semeru-open-(?:jdk|jre)_|openjdk-\d{1,2}[\w.]*_(?:linux|windows|macos|osx)-|graalvm-(?:community-)?jdk-\d)[^/]*\.(?:tar\.gz|tgz|zip|tar\.xz|tar)$`) + +// maxArchivesNoted bounds the runtime downloads recorded per target. +const maxArchivesNoted = 256 + +// VisitHead records runtime downloads by name and first bytes, without +// reading them: the detector does not unpack archives, and a runtime that +// is not installed is context, not a file left unscanned. +func (s *scan) VisitHead(p string, head []byte) { + if len(s.archives) < maxArchivesNoted && jdkArchive.MatchString(path.Base(p)) && archive.IsArchive(head) { + s.archives = append(s.archives, p) + } +} func isScript(head []byte) bool { return len(head) > 2 && head[0] == '#' && head[1] == '!' } @@ -140,11 +153,13 @@ const ( maxSetting = 1 << 20 // Caps on what one target can make the detector keep: an image layer // of many small files compresses to almost nothing. - maxReleases = 4096 - maxSettings = 4096 - maxLists = 512 - maxScripts = 8192 - maxKeptTotal = 128 << 20 + maxReleases = 4096 + maxSettings = 4096 + // Plain systemd units are small records; a host has thousands. + maxPlainUnits = 1 << 16 + maxLists = 512 + maxScripts = 8192 + maxKeptTotal = 128 << 20 ) // NewScan starts a filesystem or image scan. @@ -165,6 +180,9 @@ type scan struct { crashes []crash dropped int keptBytes int + archives []string // runtime downloads seen by name, not read + optionFiles int // settings files that set JVM options + plainUnits int // systemd units that set none // limits records the caps this target reached; a capped scan clears // nothing. limits []string @@ -207,8 +225,6 @@ func (s *scan) Visit(f engine.File) []engine.Skip { } } return nil - case jdkArchive.MatchString(base) && archive.IsArchive(f.Data): - return []engine.Skip{{Path: f.Path, Reason: "a Java runtime archive, not installed: java4shell does not unpack it; check the runtime it holds before installing it"}} case hsErr.MatchString(base): if len(s.crashes) < maxHsErrs && len(f.Data) <= maxHsErr { s.crashes = append(s.crashes, readCrash(f.Path, f.Data)) @@ -216,17 +232,38 @@ func (s *scan) Visit(f engine.File) []engine.Skip { return nil } if k := jvm.SettingKind(f.Path); k != "" && len(f.Data) <= maxSetting { - if len(s.settings) >= maxSettings { - s.limit(fmt.Sprintf("more than %d files that set JVM options", maxSettings)) - } else if st, ok := jvm.ReadSetting(f.Path, f.Data); ok { - s.settings = append(s.settings, st) + // Only files that set a JVM option (or, for systemd, a JVM + // option variable) are kept and counted: a host has thousands of + // plain units. + if st, ok := jvm.ReadSetting(f.Path, f.Data); ok { + switch { + case st.SetsOptions() && s.optionFiles >= maxSettings: + s.limit(fmt.Sprintf("more than %d files that set JVM options", maxSettings)) + case st.SetsOptions(): + s.settings = append(s.settings, st) + s.optionFiles++ + case st.Kind == "systemd" && s.plainUnits >= maxPlainUnits: + s.limit(fmt.Sprintf("more than %d systemd units", maxPlainUnits)) + case st.Kind == "systemd": + // A unit without JVM options still replaces or extends + // another file of the same unit: keep it, uncounted. + s.settings = append(s.settings, st) + s.plainUnits++ + } } } if keep(f.Path) && len(f.Data) <= maxKept { if assess.IsDpkgList(f.Path) { - // Only the lines owners are looked up by. + // Only the lines owners are looked up by, without splitting + // the whole list. var b []byte - for _, l := range bytes.Split(f.Data, []byte("\n")) { + for rest := f.Data; len(rest) > 0; { + l := rest + if i := bytes.IndexByte(rest, '\n'); i >= 0 { + l, rest = rest[:i], rest[i+1:] + } else { + rest = nil + } if bytes.HasSuffix(l, []byte("/libjvm.so")) || bytes.HasSuffix(l, []byte("/release")) { b = append(append(b, l...), '\n') } @@ -274,6 +311,9 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { if len(s.crashes) > 0 { ctx.Annotate("java4shell_crash_logs", s.crashes) } + if len(s.archives) > 0 { + ctx.Annotate("java4shell_runtime_archives", s.archives) + } if osr := osRelease(s.kept["/etc/os-release"], s.kept["/usr/lib/os-release"]); osr != "" { ctx.Annotate("java4shell_os", osr) } diff --git a/detectors/java4shell/review2_test.go b/detectors/java4shell/review2_test.go index a94f896..9de9a8e 100644 --- a/detectors/java4shell/review2_test.go +++ b/detectors/java4shell/review2_test.go @@ -1,13 +1,13 @@ package java4shell_test import ( - "bytes" + "encoding/json" "fmt" "strings" "testing" + "github.com/DefectDojo/earlylight/detectors/java4shell" "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" - "github.com/DefectDojo/earlylight/internal/cli" "github.com/DefectDojo/earlylight/internal/engine" ) @@ -39,14 +39,55 @@ func TestKeptCaps(t *testing.T) { } } -// Review finding 14: a JDK archive in the target is recorded as not -// scanned, not passed over in silence. +// Review findings 14 and round-2 5: a JDK download in the target is +// recorded by name as context, without reading it and without counting it +// as a file not scanned; other archives are not. func TestJDKArchiveRecorded(t *testing.T) { root := t.TempDir() + zipHead := []byte("PK\x03\x04") write(t, root, "opt/OpenJDK21U-jre_x64_linux_hotspot_21.0.13_9.tar.gz", []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03")) - var out, errb bytes.Buffer - cli.Run(cfg, []string{"scan", "fs", "--format", "json", "--detector", "java4shell", "--show-skipped", "--as-root", root}, &out, &errb) - if !strings.Contains(out.String(), "OpenJDK21U-jre_x64_linux_hotspot_21.0.13_9.tar.gz") { - t.Errorf("JDK archive not recorded: %s", out.String()) + write(t, root, "opt/amazon-corretto-21-x64-linux-jdk.tar.gz", []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03")) + write(t, root, "docs/openjdk-migration-notes.zip", zipHead) + write(t, root, "docs/majreport-2026.zip", zipHead) + r, code := run(t, "scan", "fs", "--fail-on-skip", "--as-root", root) + got, _ := json.Marshal(r.Targets[0].Annotations["java4shell_runtime_archives"]) + if !strings.Contains(string(got), "OpenJDK21U-jre_x64_linux_hotspot_21.0.13_9.tar.gz") || !strings.Contains(string(got), "amazon-corretto-21-x64-linux-jdk.tar.gz") { + t.Errorf("runtime downloads not recorded: %s", got) + } + if strings.Contains(string(got), "migration") || strings.Contains(string(got), "majreport") { + t.Errorf("other archives recorded: %s", got) + } + if code != 0 { + t.Errorf("exit %d: a recorded download counted as a file not scanned", code) + } + if (&java4shell.Detector{}).Wants("/opt/OpenJDK21U-jre_x64_linux_hotspot_21.0.13_9.tar.gz", []byte("\x1f\x8b\x08"), false) { + t.Error("a runtime download is read in full") + } +} + +// Round-2 finding 4: units that set no JVM option do not count toward the +// cap. +func TestPlainUnitsUncapped(t *testing.T) { + root := t.TempDir() + write(t, root, "opt/fixed/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "21.0.13.1+2-LTS", VBMI: true})) + for i := 0; i < 4100; i++ { + write(t, root, fmt.Sprintf("etc/systemd/system/s%d.service", i), []byte("[Service]\nExecStart=/usr/bin/true\n")) + } + r, code := run(t, "scan", "fs", "--as-root", root) + if f := byPath(r)["/opt/fixed"]; f.Verdict != engine.Fixed || code != 0 { + t.Errorf("plain units capped the scan: %s (%s) exit %d", f.Verdict, f.Reason, code) + } +} + +// A full /etc override without JVM options still replaces the /usr/lib +// unit that set them. +func TestEtcOverrideKept(t *testing.T) { + root := t.TempDir() + write(t, root, "opt/acme/jre/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true})) + write(t, root, "usr/lib/systemd/system/acme.service", []byte("[Service]\nEnvironment=JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics\nExecStart=/opt/acme/bin/run.sh\n")) + write(t, root, "etc/systemd/system/acme.service", []byte("[Service]\nExecStart=/opt/acme/bin/run.sh\n")) + r, _ := run(t, "scan", "fs", "--as-root", root) + if f := byPath(r)["/opt/acme/jre"]; f.Facts["status"] == "mitigated" { + t.Errorf("the /usr/lib unit's mitigation counted over the /etc override: %+v", f.Facts) } } diff --git a/internal/engine/engine.go b/internal/engine/engine.go index c05a48b..5dd488f 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -186,6 +186,14 @@ type Reader interface { Wants(path string, head []byte, executable bool) bool } +// HeadVisitor is implemented by a Scan that wants to see the first bytes +// of every file the walk meets, read in full or not: a record of files +// it does not need to read (a runtime download inside an image) without +// the cost of reading them. +type HeadVisitor interface { + VisitHead(path string, head []byte) +} + // ErrNotApplicable is what a Prober returns when the address does not run // the service it checks (no SSH server where a TLS check was asked for). The // host scan skips that detector, and fails only when every detector did. diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go index c5264c3..7bd4601 100644 --- a/internal/engine/engine_test.go +++ b/internal/engine/engine_test.go @@ -226,3 +226,24 @@ func (p *panicky) Visit(f File) []Skip { } return p.fake.Visit(f) } + +// headFake is a scan that also sees every file's head. +type headFake struct { + *fake + heads *[]string +} + +func (h headFake) NewScan(TargetKind) Scan { return h } +func (h headFake) VisitHead(p string, _ []byte) { *h.heads = append(*h.heads, p) } +func (h headFake) Wants(p string, _ []byte, _ bool) bool { return h.wants(p) } + +func TestHeadVisitorSeesUnreadFiles(t *testing.T) { + root := tree(t, map[string][]byte{"etc/a.conf": []byte("a"), "opt/jdk.tar.gz": []byte("\x1f\x8b")}) + var heads []string + h := headFake{&fake{id: "t-head", wants: func(p string) bool { return strings.HasSuffix(p, ".conf") }, seen: &[]string{}}, &heads} + ScanFS([]Detector{h}, root, Options{AsRoot: true}) + sort.Strings(heads) + if strings.Join(heads, ",") != "/etc/a.conf,/opt/jdk.tar.gz" || strings.Join(*h.seen, ",") != "/etc/a.conf" { + t.Errorf("heads %v, read %v", heads, *h.seen) + } +} diff --git a/internal/engine/run.go b/internal/engine/run.go index 02d6e3b..bf4ea53 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -237,15 +237,38 @@ func (w *walker) sourceOptions(opts Options) source.Options { Symlink: func(p, t string) { w.ctx.symlinks[w.abs(p)] = t }, Hardlink: func(p, t string) { w.ctx.hardlinks[w.abs(p)] = w.abs(t) }, } + var heads []HeadVisitor + for _, s := range w.scans { + if h, ok := s.(HeadVisitor); ok { + heads = append(heads, h) + } + } + visitHead := func(p string, head []byte) { + for _, h := range heads { + h.VisitHead(w.abs(p), head) + } + } var readers []Reader + all := false for _, d := range w.dets { r, ok := d.(Reader) if !ok { - return so // this detector wants everything + all = true // this detector wants everything + break } readers = append(readers, r) } + if all { + if len(heads) > 0 { + so.Read = func(p string, head []byte, _ bool) bool { + visitHead(p, head) + return true + } + } + return so + } so.Read = func(p string, head []byte, exe bool) bool { + visitHead(p, head) for _, r := range readers { if r.Wants(w.abs(p), head, exe) { return true From 5fcfc22e4ded1416c1dc49f1274299654f88f4a5 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 02:08:36 +0000 Subject: [PATCH 026/119] java4shell: package names only as install arguments Round-2 finding 6. A RUN line is split into commands, and only the arguments of an install command ( [flags] install|add) are matched, whole, against the Java package patterns: flags and their values, paths and URLs are not packages. A Temurin tarball moved to /opt/temurin-17 or a Zulu download URL on the same line is no longer reported as an installed package. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/internal/jvm/settings.go | 10 ++ detectors/java4shell/internal/repo/repo.go | 96 +++++++++++++++---- .../java4shell/internal/repo/review3_test.go | 18 ++++ 3 files changed, 107 insertions(+), 17 deletions(-) diff --git a/detectors/java4shell/internal/jvm/settings.go b/detectors/java4shell/internal/jvm/settings.go index 651e141..36b8bce 100644 --- a/detectors/java4shell/internal/jvm/settings.go +++ b/detectors/java4shell/internal/jvm/settings.go @@ -442,6 +442,16 @@ type shellCmd struct { cond bool } +// SplitCommands returns the simple commands of a shell line (split on +// ; && || | & outside quotes). +func SplitCommands(line string) []string { + var out []string + for _, c := range splitCommands(line) { + out = append(out, c.text) + } + return out +} + // splitCommands splits a line on ; && || | & outside quotes. func splitCommands(line string) []shellCmd { var out []shellCmd diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 3ba2bda..14cd144 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -834,30 +834,92 @@ func (s *scanner) packages(rel string, line int, run string) { return } var hits []pkgHit - for _, m := range aptJava.FindAllStringSubmatch(run, -1) { - hits = append(hits, pkgHit{name: m[1], feature: atoi(m[2]), op: opOf(m[3]), ver: m[4], mgr: "apt", vendor: "distribution"}) - } - for _, m := range apkJava.FindAllStringSubmatch(run, -1) { - hits = append(hits, pkgHit{name: m[1], feature: atoi(m[2]), op: m[3], ver: m[4], mgr: "apk", vendor: "distribution"}) - } - for _, m := range rpmJava.FindAllStringSubmatch(run, -1) { - v := "distribution" - if m[3] == "amazon-corretto" { - v = "corretto" + for _, arg := range installArgs(run) { + switch { + case aptArg.MatchString(arg): + m := aptArg.FindStringSubmatch(arg) + hits = append(hits, pkgHit{name: m[1], feature: atoi(m[2]), op: opOf(m[3]), ver: m[4], mgr: "apt", vendor: "distribution"}) + case apkArg.MatchString(arg): + m := apkArg.FindStringSubmatch(arg) + hits = append(hits, pkgHit{name: m[1], feature: atoi(m[2]), op: m[3], ver: m[4], mgr: "apk", vendor: "distribution"}) + case rpmArg.MatchString(arg): + m := rpmArg.FindStringSubmatch(arg) + v := "distribution" + if m[3] == "amazon-corretto" { + v = "corretto" + } + hits = append(hits, pkgHit{name: m[1], feature: atoi(m[2]), ver: m[4], mgr: "rpm", vendor: v}) + case vendorArg.MatchString(arg): + m := vendorArg.FindStringSubmatch(arg) + hits = append(hits, pkgHit{name: m[1], feature: atoi(m[3]), op: opOf(m[4]), ver: m[5], mgr: "package", vendor: m[2]}) + case defaultArg.MatchString(arg): + hits = append(hits, pkgHit{name: arg, mgr: "apt", vendor: "distribution"}) } - hits = append(hits, pkgHit{name: m[1], feature: atoi(m[2]), ver: m[4], mgr: "rpm", vendor: v}) - } - for _, m := range vendorJava.FindAllStringSubmatch(run, -1) { - hits = append(hits, pkgHit{name: m[1], feature: atoi(m[3]), op: opOf(m[4]), ver: m[5], mgr: "package", vendor: m[2]}) - } - for _, m := range defaultJava.FindAllStringSubmatch(run, -1) { - hits = append(hits, pkgHit{name: m[1], mgr: "apt", vendor: "distribution"}) } for _, h := range hits { s.judgePackage(rel, line, h) } } +// anchored matches the whole of one argument. +func anchored(re *regexp.Regexp) *regexp.Regexp { + return regexp.MustCompile(`^(?:` + strings.TrimPrefix(re.String(), `\b`) + `)$`) +} + +var ( + aptArg = anchored(aptJava) + apkArg = anchored(apkJava) + rpmArg = anchored(rpmJava) + vendorArg = anchored(vendorJava) + defaultArg = anchored(defaultJava) +) + +var ( + pkgTools = map[string]bool{"apt-get": true, "apt": true, "apk": true, "dnf": true, "yum": true, "microdnf": true, "tdnf": true, "zypper": true} + pkgVerbs = map[string]bool{"install": true, "add": true, "in": true, "reinstall": true} + // pkgValueFlags are package-manager options followed by a separate value. + pkgValueFlags = map[string]bool{"-t": true, "-o": true, "-X": true, "--repository": true, "--virtual": true, "-c": true, "--root": true, + "-p": true, "--target-release": true, "--option": true, "--repo": true, "--setopt": true, "--enablerepo": true, "--disablerepo": true} +) + +// installArgs returns the package arguments of the install commands on a +// RUN line: the words after " [flags] install|add", without flags, +// their values, paths and URLs. +func installArgs(run string) []string { + var out []string + for _, cmd := range jvm.SplitCommands(run) { + words := jvm.Words(cmd) + i := 0 + for i < len(words) && !pkgTools[path.Base(words[i])] { + i++ + } + if i == len(words) { + continue + } + i++ + for i < len(words) && strings.HasPrefix(words[i], "-") { + if pkgValueFlags[words[i]] { + i++ + } + i++ + } + if i >= len(words) || !pkgVerbs[words[i]] { + continue + } + for j := i + 1; j < len(words); j++ { + w := words[j] + switch { + case pkgValueFlags[w]: + j++ + case strings.HasPrefix(w, "-"), strings.ContainsAny(w, "/$"), strings.Contains(w, "://"): + default: + out = append(out, w) + } + } + } + return out +} + // pkgHit is one Java package an install names. type pkgHit struct { name, op, ver, mgr string diff --git a/detectors/java4shell/internal/repo/review3_test.go b/detectors/java4shell/internal/repo/review3_test.go index b96958d..042671f 100644 --- a/detectors/java4shell/internal/repo/review3_test.go +++ b/detectors/java4shell/internal/repo/review3_test.go @@ -66,3 +66,21 @@ func TestReviewVersionNames(t *testing.T) { t.Errorf("an arm64 stage reported: %+v", f) } } + +// Round-2 finding 6: package names count only as install arguments. +func TestPackageArgsOnly(t *testing.T) { + root := tree(t, map[string]string{ + "a/Dockerfile": "FROM debian:12\nRUN apt-get install -y curl && curl -fsSL https://example.invalid/OpenJDK17U-jre_x64_linux_hotspot_17.0.5_8.tar.gz | tar xz && mv jdk-17.0.5+8-jre /opt/temurin-17\n", + "b/Dockerfile": "FROM debian:12\nRUN apt-get install -y curl && curl -fsSL https://cdn.azul.com/zulu/bin/zulu21.42.19-ca-jdk21.0.13-linux_x64.tar.gz -o /tmp/zulu21.tar.gz\n", + "c/Dockerfile": "FROM debian:12\nRUN apt-get update && apt-get install -y --no-install-recommends curl temurin-21-jdk && rm -rf /var/lib/apt/lists/*\n", + }) + res := scan(t, root) + for _, f := range res.Findings { + if f.File == "a/Dockerfile" || f.File == "b/Dockerfile" { + t.Errorf("a path or URL read as a package: %s:%d %s", f.File, f.Line, f.Message) + } + } + if f, ok := find(res, "c/Dockerfile", 2); !ok || f.Props["package"] != "temurin-21-jdk" { + t.Errorf("install argument missed: %+v", f) + } +} From be4c798fd2081d10ae084cb7f363ebe7e5947b1a Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 02:09:25 +0000 Subject: [PATCH 027/119] java4shell: compare the base OS on every image move, by distribution and major version Round-2 finding 7. The verifier now compares the current and the new image's os-release for every move, also when the variant names the distribution (an -alpine or -noble tag can move to the next release), on ID and major version, so a minor update (Oracle Linux 9.5 to 9.6, Alpine 3.21 to 3.22) is accepted and Ubuntu 24.04 to 26.04 is not. The current image is read with a probe that reads only os-release, not a second full scan. A current tag that is gone is tolerated when the new tag names its OS. os-release values are cut to 32 plain characters and decline reasons go through the usual clean-up. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/internal/repo/plan.go | 20 ++++++--- .../java4shell/internal/repo/review4_test.go | 21 +++++++++ detectors/java4shell/java4shell.go | 45 ++++++++++++++++++- .../java4shell/registry_internal_test.go | 31 +++++++++++++ detectors/java4shell/repo.go | 18 ++++---- 5 files changed, 120 insertions(+), 15 deletions(-) diff --git a/detectors/java4shell/internal/repo/plan.go b/detectors/java4shell/internal/repo/plan.go index 8327ab8..efb3335 100644 --- a/detectors/java4shell/internal/repo/plan.go +++ b/detectors/java4shell/internal/repo/plan.go @@ -342,15 +342,23 @@ func NamesBaseOS(variant string) bool { return false } -// SameBase compares the base OS (ID and VERSION_ID of os-release) of the -// current image and its replacement, for tags whose variant does not name -// it: moving a deployment to another distribution is not this fix's call. +// SameBase compares the base OS of the current image and its +// replacement ("ID VERSION_ID" of os-release) on the distribution and its +// major version: moving a deployment to another distribution or major +// release (Ubuntu 24.04 to 26.04, Debian 12 to 13) is not this fix's call, +// while a minor update (Oracle Linux 9.5 to 9.6, Alpine 3.21 to 3.22) is +// what a rebuilt tag brings anyway. func SameBase(current, target string) error { + major := func(s string) string { + id, ver, _ := strings.Cut(s, " ") + ver, _, _ = strings.Cut(ver, ".") + return id + " " + ver + } switch { case current == "" || target == "": - return &Declined{Reason: "the base OS of the current or the new image could not be read, and the tag does not name it; change it by hand"} - case current != target: - return &Declined{Reason: fmt.Sprintf("the new image is on %s, the current one on %s; change it by hand", target, current)} + return declined("the base OS of the current or the new image could not be read; change it by hand") + case major(current) != major(target): + return declined("the new image is on %s, the current one on %s; change it by hand", refs.CleanText(target, 80), refs.CleanText(current, 80)) } return nil } diff --git a/detectors/java4shell/internal/repo/review4_test.go b/detectors/java4shell/internal/repo/review4_test.go index 769b244..d710aad 100644 --- a/detectors/java4shell/internal/repo/review4_test.go +++ b/detectors/java4shell/internal/repo/review4_test.go @@ -59,3 +59,24 @@ func TestSameBase(t *testing.T) { t.Error("unknown base accepted") } } + +// Round-2 finding 7: the base OS is compared on ID and major version. +func TestSameBaseMajor(t *testing.T) { + for _, c := range []struct { + cur, tgt string + ok bool + }{ + {"ol 9.5", "ol 9.6", true}, + {"alpine 3.21.4", "alpine 3.22.1", true}, + {"ubuntu 24.04", "ubuntu 26.04", false}, + {"debian 12", "debian 13", false}, + {"ubuntu 24.04", "debian 12", false}, + } { + if err := SameBase(c.cur, c.tgt); (err == nil) != c.ok { + t.Errorf("SameBase(%q, %q) = %v", c.cur, c.tgt, err) + } + } + if err := SameBase(strings.Repeat("x", 5000)+" 1", "ubuntu 24.04"); err == nil || len(err.Error()) > 400 { + t.Errorf("unbounded reason: %d bytes", len(err.Error())) + } +} diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 0d8096f..81838d3 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -501,7 +501,7 @@ func osRelease(files ...[]byte) string { if !ok { continue } - v = strings.Trim(v, "\"'") + v = osToken(strings.Trim(v, "\"'")) switch k { case "ID": id = v @@ -515,3 +515,46 @@ func osRelease(files ...[]byte) string { } return "" } + +// osToken keeps an os-release value short and plain: an image's files +// are not trusted. +func osToken(v string) string { + var b strings.Builder + for _, r := range strings.ToLower(v) { + if b.Len() >= 32 { + break + } + if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '.' || r == '-' || r == '_' { + b.WriteRune(r) + } + } + return b.String() +} + +// osProbe reads only an image's os-release: a light second read of the +// image a move starts from. +type osProbe struct{} + +func (osProbe) Manifest() engine.Manifest { + return engine.Manifest{ID: "java4shell-osprobe", Targets: []engine.TargetKind{engine.Image}} +} +func (osProbe) Load() error { return nil } +func (osProbe) Wants(p string, _ []byte, _ bool) bool { + return p == "/etc/os-release" || p == "/usr/lib/os-release" +} +func (osProbe) NewScan(engine.TargetKind) engine.Scan { return &osScan{files: map[string][]byte{}} } + +type osScan struct{ files map[string][]byte } + +func (s *osScan) Visit(f engine.File) []engine.Skip { + if len(f.Data) <= 64<<10 { + s.files[f.Path] = f.Data + } + return nil +} +func (s *osScan) Finish(ctx engine.TargetContext) []engine.Finding { + if v := osRelease(s.files["/etc/os-release"], s.files["/usr/lib/os-release"]); v != "" { + ctx.Annotate("java4shell_os", v) + } + return nil +} diff --git a/detectors/java4shell/registry_internal_test.go b/detectors/java4shell/registry_internal_test.go index 554dd37..b5b0077 100644 --- a/detectors/java4shell/registry_internal_test.go +++ b/detectors/java4shell/registry_internal_test.go @@ -122,3 +122,34 @@ func errorsAs(err error, d **repo.Declined) bool { } return ok } + +// Round-2 finding 7: the verifier compares the base OS for every move, +// and the os-release strings it reads are bounded. +func TestVerifierBaseOS(t *testing.T) { + host := testRegistry(t) + cur := host + "/acme/java:21.0.13_9-jre-noble" + same := host + "/acme/java:21.0.13.1_2-jre-noble" + other := host + "/acme/java:21.0.13.1_3-jre-noble" + files := func(v, osr string) map[string][]byte { + m := runtimeFiles(v) + m["/etc/os-release"] = []byte(osr) + return m + } + pushImage(t, cur, files("21.0.13+9-LTS", "ID=ubuntu\nVERSION_ID=\"24.04\"\n")) + pushImage(t, same, files("21.0.13.1+2-LTS", "ID=ubuntu\nVERSION_ID=\"24.04\"\n")) + pushImage(t, other, files("21.0.13.1+3-LTS", "ID=ubuntu\nVERSION_ID=\"26.04\"\n")) + v := (&Detector{}).verifier(engine.Options{}) + if _, err := v(context.Background(), cur, same); err != nil { + t.Errorf("same base declined: %v", err) + } + if _, err := v(context.Background(), cur, other); err == nil { + t.Error("a move from Ubuntu 24.04 to 26.04 accepted under a variant that names the OS") + } + // A deleted current tag that names its OS is tolerated. + if _, err := v(context.Background(), host+"/acme/java:21.0.12_7-jre-noble", same); err != nil { + t.Errorf("deleted current tag: %v", err) + } + if got := osRelease([]byte("ID=" + strings.Repeat("a", 60000) + "\nVERSION_ID=1\n")); len(got) > 80 { + t.Errorf("unbounded os-release: %d bytes", len(got)) + } +} diff --git a/detectors/java4shell/repo.go b/detectors/java4shell/repo.go index f616bd8..f4569de 100644 --- a/detectors/java4shell/repo.go +++ b/detectors/java4shell/repo.go @@ -370,14 +370,16 @@ func (d *Detector) verifier(o engine.Options) func(ctx context.Context, current, if t.Error != "" { return "", fmt.Errorf("reading %s: %s", target, t.Error) } - // A tag whose variant does not name its base OS ("-jre") may move - // to another distribution between releases: compare them. - if fam, tag, ok := repo.FamilyOf(target); ok { - if tv, ok := fam.ParseTag(tag); !ok || !repo.NamesBaseOS(tv.Variant) { - c := engine.ScanImage([]engine.Detector{d}, current, engine.Options{Platform: "linux/amd64", MaxFileSize: o.MaxFileSize, Guarded: true, PublicOnly: o.PublicOnly}) - if err := repo.SameBase(annotation(c, "java4shell_os"), annotation(t, "java4shell_os")); err != nil { - return "", err - } + // The base OS: distribution and major version must stay (a tag + // whose variant does not name it, "-jre", can move to another + // distribution; one that does can move to its next release). The + // current image is read for its os-release only. A current tag that + // is gone is tolerated when the new tag names its OS. + c := engine.ScanImage([]engine.Detector{osProbe{}}, current, engine.Options{Platform: "linux/amd64", Guarded: true, PublicOnly: o.PublicOnly}) + _, tag, _ := strings.Cut(target[strings.LastIndex(target, "/")+1:], ":") + if c.Error == "" || !repo.NamesBaseOS(tag) { + if err := repo.SameBase(annotation(c, "java4shell_os"), annotation(t, "java4shell_os")); err != nil { + return "", err } } if t.Incomplete != "" || t.Gaps() > 0 || len(t.Problems) > 0 { From 416c81d0de93b736f2e65e2b90f04f072d45f88f Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 02:10:22 +0000 Subject: [PATCH 028/119] java4shell: dates from the knowledge package; wording nits Round-2 nits. Every date in the detector's text comes from the knowledge package: the data date (Checked, now in an AsOf() phrase for "had not published" statements) and the facts it rests on (Disclosed, FixReleased, MainlineFixed, VendorFixPublished); a test keeps date literals out of the other files. The vendor-build reason no longer reads "whether JDK-8393212, inferred to be this CVE's fix is in". The README states what a contradicting release file does (only OpenJ9 evidence makes it unknown; a version mismatch is noted), how runtime downloads are recorded, and that self-built JDKs at a build boundary are unknown. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- .../java4shell/internal/assess/assess.go | 2 +- .../java4shell/internal/assess/packages.go | 5 ++-- .../internal/knowledge/knowledge.go | 24 ++++++++++++++++--- .../internal/knowledge/review2_test.go | 12 +++++++++- detectors/java4shell/internal/repo/repo.go | 4 ++-- detectors/java4shell/java4shell.go | 2 +- detectors/java4shell/review2_test.go | 21 ++++++++++++++++ 8 files changed, 61 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 418e7c9..678c19e 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ One engine for DefectDojo's emerging-vulnerability scanners. Each new vulnerabil | `php2shell` | PHP runtimes vulnerable to CVE-2026-109618 and CVE-2026-109619 ("PHP2Shell"), fixed in PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12 ([GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w), [GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp)). A packaged PHP is judged by its vendor's backport data, never by the version it reports. Also checks the images a source tree builds on and deploys, and can rewrite them to fixed images | `fs`, `image`, `repo`, `fix` | | `brotli` | Brotli decoders vulnerable to CVE-2026-111497 ("Node2Shell", "Broccoli2Shell"), Brotli 1.0.3 through 1.2.0, fixed in 1.0.10, 1.1.1 and 1.2.1 ([GHSA-9v8h-qqgm-4m35](https://github.com/advisories/GHSA-9v8h-qqgm-4m35)): system `libbrotlidec` and every copy bundled into other software (Node.js, .NET, Bun, Electron, Envoy and Istio, Python wheels such as Pillow, pyarrow, duckdb, pycurl and PyMuPDF, brotli4j, and more), on Linux, Windows and macOS. A decoder is judged first by the error code the fix added, so vendor backports are recognised without distribution data; a build that strips it by its own version stamp or by its code, which returns that error code only once fixed. In a source tree it finds the Node.js, .NET and Bun releases and the bundling packages a project pins, and `fix` moves each to the fixed release | `fs`, `image`, `repo`, `fix` | | `sshole` | \*sshole, the OpenSSH password authentication bypass on musl libc fixed in OpenSSH 10.6p2 and in Alpine's openssh packages of November 5, 2026 ([release notes](https://www.openssh.org/releasenotes.html#10.6p2), [writeup](https://sshhole.com)). On musl, sshd from 7.3p1 to 10.6p1 compares an account's password field of `*` with the `*` that crypt returns when it fails, so a crafted password logs in to that account. It judges each installed sshd by its C library, its release and the apk database (Alpine backports keep the release number), then checks what the target's `sshd_config` (Include, Match, PasswordAuthentication, AuthenticationMethods, PermitRootLogin, AllowUsers and the rest) and account files make reachable, and reports the accounts. In an image it also reads the command (`sshd -o` and `-f`) and the startup scripts it runs (entrypoints, s6, cont-init.d), and reports a server as exposed when a startup script turns password logins on, sets a `*` field or sets passwords. OpenWrt's opkg database and its backports (23.05, 24.10, 25.12) count like Alpine's. PAM-checked builds (`UsePAM yes`) are not affected. On a live server it reads the banner and the offered methods and never sends a password. In a source tree it finds Dockerfiles that install an OpenSSH server on Alpine without the fix (package lists in `ARG` and `ENV` too), Ansible apk tasks, Buildroot, OpenWrt and Yocto configurations that build one on musl, and anything that sets a password field to `*`. It also pulls the images the tree references (through the guarded transport, with the command a Compose service or Kubernetes container sets) and judges them like `scan image`. `fix` adds the fixed release floor (in the variable when the list is one), moves an end-of-life Alpine base to a tag on the nearest fixed Alpine release (`alpine:3.14` to `3.16`, `python:3.9-alpine3.14` to `3.9-alpine3.16` after checking that image) as a labelled upgrade, adds upstream commit 4353fdc43 as a patch scoped to the OpenSSH versions it applies to (Buildroot `BR2_GLOBAL_PATCH_DIR`, a version-specific Yocto bbappend), sets Ansible tasks to `state: latest`, and changes `*` to `*NP*` | `fs`, `image`, `host`, `repo`, `fix` | -| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64, fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 on November 15, 2026 by JDK-8393212 ([commit](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b); that this change is the CVE's fix is inferred from the public descriptions, since the OpenJDK advisory could not be read: see the [knowledge table](detectors/java4shell/FACTS.md)). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel server CPUs from Ice Lake on and some client CPUs, not Alder Lake or Raptor Lake; AMD Zen 4 and later); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds Java runtimes by their VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others); a JDK download packed in an archive is recorded as not scanned, not unpacked. Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; each platform of a multi-arch image is judged on its own with `--platform all`), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness: when the library's version line can be read, the library decides, a release file that contradicts it makes the verdict unknown, and a release file alone does not clear a runtime. No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version and build (the first fixed build of each release, such as 21.0.13.1+2; pre-release and self-built JDKs are not judged fixed). OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is recorded as a mitigation on a finding that stays vulnerable (status `mitigated`, counted in the exit status): the options can be overridden where the runtime is deployed, and the runtime still needs the update; `_JAVA_OPTIONS` turning the intrinsic back on undoes it. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context; neither clears a runtime. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft and Oracle images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | +| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64, fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 on November 15, 2026 by JDK-8393212 ([commit](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b); that this change is the CVE's fix is inferred from the public descriptions, since the OpenJDK advisory could not be read: see the [knowledge table](detectors/java4shell/FACTS.md)). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel server CPUs from Ice Lake on and some client CPUs, not Alder Lake or Raptor Lake; AMD Zen 4 and later); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds Java runtimes by their VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others); a JDK download sitting in the target (OpenJDK21U-jre_…tar.gz and the like) is recorded by name as context, not read or unpacked. Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; each platform of a multi-arch image is judged on its own with `--platform all`), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness: when the library's version line can be read, the library decides and a different release-file version is only noted; a release file naming OpenJ9 next to HotSpot evidence makes the verdict unknown; and a release file alone does not clear a runtime (OpenJ9 is recognised from its own VM library, not from the release file). No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version and build (the first fixed build of each release, such as 21.0.13.1+2; pre-release builds are not judged fixed, and a self-built JDK at a build boundary is unknown). OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is recorded as a mitigation on a finding that stays vulnerable (status `mitigated`, counted in the exit status): the options can be overridden where the runtime is deployed, and the runtime still needs the update; `_JAVA_OPTIONS` turning the intrinsic back on undoes it. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context; neither clears a runtime. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft and Oracle images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | The detectors ported from standalone scanners also build as standalone binaries under the names people search for: `emudhra-scan` and `php2shell-scan`. They keep their original commands, flags and exit status rules. `brotli`, `sshole` and `java4shell` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`, `--detector java4shell`). diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index 0dbd277..8788525 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -533,5 +533,5 @@ func fixText(f Finding, v knowledge.Version, ok bool) string { case f.JLinked: return fmt.Sprintf("Rebuild this jlink image from a JDK at %s.%s", target, interim) } - return fmt.Sprintf("Update this runtime to %s (Amazon Corretto and SapMachine published theirs on 2026-11-17; check your vendor).%s", target, interim) + return fmt.Sprintf("Update this runtime to %s (Amazon Corretto and SapMachine published theirs on %s; others had not %s: check your vendor).%s", target, knowledge.VendorFixPublished, knowledge.AsOf(), interim) } diff --git a/detectors/java4shell/internal/assess/packages.go b/detectors/java4shell/internal/assess/packages.go index e34daa2..11bd221 100644 --- a/detectors/java4shell/internal/assess/packages.go +++ b/detectors/java4shell/internal/assess/packages.go @@ -1,6 +1,7 @@ package assess import ( + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" "path" "regexp" "strings" @@ -125,9 +126,9 @@ func upgradeLine(p Package) string { func distroStatus(p Package) string { switch p.Manager { case "apk": - return "Alpine had published no fixed package as of 2026-11-17" + return "Alpine had published no fixed package " + knowledge.AsOf() case "dpkg": - return "Debian and Ubuntu had published no fixed package as of 2026-11-17" + return "Debian and Ubuntu had published no fixed package " + knowledge.AsOf() case "rpm": return "the distribution's fix status was not checked" } diff --git a/detectors/java4shell/internal/knowledge/knowledge.go b/detectors/java4shell/internal/knowledge/knowledge.go index 829425b..81fa877 100644 --- a/detectors/java4shell/internal/knowledge/knowledge.go +++ b/detectors/java4shell/internal/knowledge/knowledge.go @@ -20,9 +20,27 @@ const Bug = "JDK-8393212" // BugRef is how reasons name the fix. const BugRef = "JDK-8393212, inferred to be this CVE's fix" -// Checked is the date the release data was last checked. +// Checked is the date the release data was last checked: every "as of" +// statement (a vendor or distribution had not published a fix) is as of +// this date. const Checked = "2026-11-17" +// Dates the release data rests on. +const ( + // Disclosed is when the CVE and the fixed releases were published. + Disclosed = "2026-11-17" + // FixReleased is the date of the OpenJDK update releases with the fix. + FixReleased = "2026-11-15" + // MainlineFixed is when the fix reached OpenJDK mainline. + MainlineFixed = "2026-11-16" + // VendorFixPublished is when Amazon Corretto and SapMachine published + // their fixed releases. + VendorFixPublished = "2026-11-17" +) + +// AsOf says a status statement's date. +func AsOf() string { return "as of " + Checked + ", the date of this detector's release data" } + // Status is what the release data says about a version. type Status string @@ -296,7 +314,7 @@ func Judge(v Version) (Status, string) { if v.Build >= 0 && v.Build <= EALastUnfixed { return Vulnerable, fmt.Sprintf("JDK %d build %d: the fix reached mainline after jdk-28+%d", f, v.Build, EALastUnfixed) } - return Unknown, fmt.Sprintf("JDK %d build %s: the fix reached mainline on 2026-11-16, after jdk-28+%d; check that this build includes %s", f, buildText(v), EALastUnfixed, BugRef) + return Unknown, fmt.Sprintf("JDK %d build %s: the fix reached mainline on %s, after jdk-28+%d; check that this build includes %s", f, buildText(v), MainlineFixed, EALastUnfixed, BugRef) case f > newestFeature: return Unknown, fmt.Sprintf("Java %s is newer than this detector's release data (%s)", ver, Checked) } @@ -331,7 +349,7 @@ func Judge(v Version) (Status, string) { // OpenJDK patch numbers are small (17.0.8.1, 21.0.13.1); a larger // fourth number is a vendor's build number (Amazon Corretto's // 21.0.13.11), which says nothing about the patch. - return Unknown, fmt.Sprintf("Java %s: the fourth number looks like a vendor build number, not an OpenJDK patch release, so the version does not show whether %s is in", ver, BugRef) + return Unknown, fmt.Sprintf("Java %s: the fourth number looks like a vendor build number, not an OpenJDK patch release, so the version does not show whether it has the fix (%s)", ver, BugRef) } switch c := Compare(v.Nums, l.Fixed); { case c < 0: diff --git a/detectors/java4shell/internal/knowledge/review2_test.go b/detectors/java4shell/internal/knowledge/review2_test.go index a5d9cab..d10ff42 100644 --- a/detectors/java4shell/internal/knowledge/review2_test.go +++ b/detectors/java4shell/internal/knowledge/review2_test.go @@ -1,6 +1,9 @@ package knowledge -import "testing" +import ( + "strings" + "testing" +) // Review findings 2, 12 and 13. func TestReviewBuilds(t *testing.T) { @@ -67,3 +70,10 @@ func TestReviewSelfBuilt(t *testing.T) { } } } + +func TestReasonWording(t *testing.T) { + v, _ := Parse("21.0.13.11") + if _, why := Judge(v); strings.Contains(why, "fix is in") { + t.Errorf("reason: %s", why) + } +} diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 14cd144..2072ee7 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -368,7 +368,7 @@ func (s *scanner) judgeVersion(rel string, line, col int, verText, source, vendo func pinFix(feature int, source string) string { if fx := knowledge.FixedVersion(feature); fx != "" { - return fmt.Sprintf("Select Java %s or later of the same update in %s once your vendor publishes it (Amazon Corretto and SapMachine did on 2026-11-17; Temurin, Debian, Ubuntu and Alpine had not), and reinstall.", fx, source) + return fmt.Sprintf("Select Java %s or later of the same update in %s once your vendor publishes it (Amazon Corretto and SapMachine did on %s; Temurin, Debian, Ubuntu and Alpine had not %s), and reinstall.", fx, source, knowledge.VendorFixPublished, knowledge.AsOf()) } return fmt.Sprintf("Java %d received no fix: move %s to a supported release with the fix, such as %s.", feature, source, knowledge.Upgrade(feature)) } @@ -1011,7 +1011,7 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { switch h.vendor { case "corretto", "sapmachine": s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: props, - Reason: fmt.Sprintf("%s published Java %s on 2026-11-17: an image built after that gets it, one built or cached before does not", who, fx), + Reason: fmt.Sprintf("%s published Java %s on %s: an image built after that gets it, one built or cached before does not", who, fx, knowledge.VendorFixPublished), Message: fmt.Sprintf("installs %s %s: whether the image has the Java4Shell fix depends on when it was built", h.name, what), Fix: fmt.Sprintf("Rebuild without the layer cache, or pin %s to Java %s or later.", h.name, fx)}) case "zulu", "msopenjdk": diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 81838d3..3caecca 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -72,7 +72,7 @@ func (d *Detector) Manifest() engine.Manifest { "https://semgrep.dev/blog/2026/java4shell-openjdk-base64-vulnerability", "https://github.com/corretto/corretto-21/blob/21.0.13.1.2/CHANGELOG.md", }, - Disclosed: "2026-11-17", + Disclosed: knowledge.Disclosed, Targets: []engine.TargetKind{engine.Filesystem, engine.Image, engine.Repository}, Kinds: append([]engine.Kind{ {ID: KindRuntime, Title: "Java runtime vulnerable to Java4Shell", Level: "error", SecuritySeverity: "9.2", CWEs: cwe, diff --git a/detectors/java4shell/review2_test.go b/detectors/java4shell/review2_test.go index 9de9a8e..c706df8 100644 --- a/detectors/java4shell/review2_test.go +++ b/detectors/java4shell/review2_test.go @@ -3,6 +3,9 @@ package java4shell_test import ( "encoding/json" "fmt" + "os" + "path/filepath" + "regexp" "strings" "testing" @@ -91,3 +94,21 @@ func TestEtcOverrideKept(t *testing.T) { t.Errorf("the /usr/lib unit's mitigation counted over the /etc override: %+v", f.Facts) } } + +// Round-2 nits: dates live in the knowledge package (the data date is +// knowledge.Checked), and reasons read cleanly. +func TestDatesInOnePlace(t *testing.T) { + err := filepath.WalkDir(".", func(p string, d os.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") || strings.HasSuffix(p, "knowledge.go") || strings.Contains(p, "testlib") { + return err + } + b, _ := os.ReadFile(p) + if regexp.MustCompile(`"[^"\n]*2026-\d\d-\d\d`).Match(b) { + t.Errorf("%s writes a date in a string; take it from the knowledge package", p) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} From 7427e276d77ff9ed41ebd2dd98102c1e09555264 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 02:24:18 +0000 Subject: [PATCH 029/119] java4shell: install forms the argument parser dropped Round-3 finding 1 (a regression from the round-2 argument parser). The package tool is looked for only outside flags, so RUN --mount=..., target=/var/cache/apt no longer hides it; a trailing rpm .arch, Debian :arch or /target-release is stripped before matching; and a pin to a variable (=${JDK_PKG}) is reported as a pin of unknown version. Parity's source-tree case gets the same forms. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/internal/repo/repo.go | 42 +++++++++++++++++-- .../java4shell/internal/repo/review3_test.go | 19 +++++++++ parity/JAVA4SHELL-RESULTS.md | 2 +- parity/java4shell/cases.json | 27 +++++++++++- parity/java4shell/repo/Dockerfile.forms | 6 +++ 5 files changed, 90 insertions(+), 6 deletions(-) create mode 100644 parity/java4shell/repo/Dockerfile.forms diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 2072ee7..e20a594 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -882,6 +882,30 @@ var ( "-p": true, "--target-release": true, "--option": true, "--repo": true, "--setopt": true, "--enablerepo": true, "--disablerepo": true} ) +var ( + rpmArchRE = regexp.MustCompile(`\.(?:x86_64|aarch64|noarch|i686|i386|ppc64le|s390x)$`) + debArchRE = regexp.MustCompile(`:(?:amd64|arm64|i386|armhf|ppc64el|s390x|all|any|native)$`) +) + +// packageName strips what a package argument adds to the name: an rpm +// .arch, a Debian :arch or /target-release (openjdk-17-jdk/bookworm-backports), +// keeping a "=version" pin. It returns "" for something that is not a +// package argument (a path). +func packageName(w string) string { + name, ver, pinned := strings.Cut(w, "=") + if i := strings.IndexByte(name, '/'); i >= 0 { + if strings.Count(name, "/") > 1 || i == 0 { + return "" // a path + } + name = name[:i] + } + name = debArchRE.ReplaceAllString(name, "") + if pinned { + return name + "=" + ver + } + return rpmArchRE.ReplaceAllString(name, "") +} + // installArgs returns the package arguments of the install commands on a // RUN line: the words after " [flags] install|add", without flags, // their values, paths and URLs. @@ -889,8 +913,9 @@ func installArgs(run string) []string { var out []string for _, cmd := range jvm.SplitCommands(run) { words := jvm.Words(cmd) + // The tool: not a flag's value (RUN --mount=...,target=/var/cache/apt). i := 0 - for i < len(words) && !pkgTools[path.Base(words[i])] { + for i < len(words) && (strings.HasPrefix(words[i], "-") || !pkgTools[path.Base(words[i])]) { i++ } if i == len(words) { @@ -911,9 +936,11 @@ func installArgs(run string) []string { switch { case pkgValueFlags[w]: j++ - case strings.HasPrefix(w, "-"), strings.ContainsAny(w, "/$"), strings.Contains(w, "://"): + case strings.HasPrefix(w, "-"), strings.Contains(w, "://"), strings.HasPrefix(w, "/"), strings.HasPrefix(w, "$"): default: - out = append(out, w) + if a := packageName(w); a != "" { + out = append(out, a) + } } } } @@ -946,7 +973,7 @@ var vendorNames = map[string]string{"distribution": "the distribution", "corrett // pinnedVersion is the Java version a package pin fixes, or "" for a pin // that matches several releases (17.*, ~17, 17). func pinnedVersion(h pkgHit) string { - if h.ver == "" || strings.Contains(h.ver, "*") || strings.Contains(h.op, "~") || strings.ContainsAny(h.op, "<>") { + if h.ver == "" || strings.Contains(h.ver, "$") || strings.Contains(h.ver, "*") || strings.Contains(h.op, "~") || strings.ContainsAny(h.op, "<>") { return "" } up := h.ver @@ -1004,6 +1031,13 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { if h.ver != "" { props["current"] = h.ver } + if strings.Contains(h.ver, "$") { + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: props, + Reason: "the version comes from a variable set outside this line", + Message: fmt.Sprintf("installs %s pinned to %s, a version this scan cannot read: not checked for the Java4Shell fix", h.name, refs.CleanText(h.ver, 60)), + Fix: fmt.Sprintf("Check that the version the variable gives is Java %s or later.", fx)}) + return + } what := "without a version" if h.ver != "" { what = "with a version range (" + h.op + h.ver + ")" diff --git a/detectors/java4shell/internal/repo/review3_test.go b/detectors/java4shell/internal/repo/review3_test.go index 042671f..1f4cf05 100644 --- a/detectors/java4shell/internal/repo/review3_test.go +++ b/detectors/java4shell/internal/repo/review3_test.go @@ -84,3 +84,22 @@ func TestPackageArgsOnly(t *testing.T) { t.Errorf("install argument missed: %+v", f) } } + +// Round-3 finding 1: install forms the argument parser dropped. +func TestInstallFormsRound3(t *testing.T) { + for i, run := range []string{ + "RUN --mount=type=cache,target=/var/cache/apt apt-get install -y openjdk-17-jre-headless", + "RUN --mount=type=cache,target=/var/cache/apk apk add openjdk21", + "RUN --mount=type=cache,target=/var/cache/dnf dnf install -y java-21-openjdk-headless", + "RUN apt-get install -y openjdk-17-jre-headless=${JDK_PKG}", + "RUN dnf install -y java-17-openjdk-headless.x86_64", + "RUN apt-get install -y openjdk-17-jre-headless:amd64", + "RUN apt-get install -y openjdk-17-jdk/bookworm-backports", + } { + root := tree(t, map[string]string{"Dockerfile": "FROM debian:12\n" + run + "\n"}) + f, ok := find(scan(t, root), "Dockerfile", 2) + if !ok || f.Rule != RulePackage { + t.Errorf("%d %q: %+v (found %v)", i, run, f, ok) + } + } +} diff --git a/parity/JAVA4SHELL-RESULTS.md b/parity/JAVA4SHELL-RESULTS.md index f3e6d6c..335feaa 100644 --- a/parity/JAVA4SHELL-RESULTS.md +++ b/parity/JAVA4SHELL-RESULTS.md @@ -42,6 +42,6 @@ Generated by `parity/java4shell.py`. Each row's expected findings come from [FAC | hostile | Forged and 200 KiB release files over an unfixed VM library, a text file named libjvm.so, symlink loops | pass | linux/amd64 /opt/forged runtime vulnerable vulnerable vm-library
linux/amd64 /opt/huge runtime vulnerable vulnerable vm-library | | musl-forged | Temurin 21.0.13 on Alpine (musl) under a release file forged to say 21.0.13.1+2 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library | | debian-pkg-fs | The debian-pkg image exported and scanned as a filesystem | pass | fs /usr/lib/jvm/java-17-openjdk-amd64 runtime vulnerable vulnerable vm-library | -| repo | Source tree, offline: Dockerfiles, Compose, Kubernetes, setup-java, version files, Gradle | pass | .github/workflows/ci.yml:12 java-line vulnerable
.github/workflows/ci.yml:8 java-pin vulnerable
.java-version:1 java-pin vulnerable
.sdkmanrc:1 java-pin vulnerable
Dockerfile.pkg:2 os-package vulnerable
Dockerfile:1 image-pin vulnerable
build.gradle.kts:3 java-line vulnerable
build.gradle.kts:7 image-pin vulnerable
compose.yaml:13 not-checked unknown
compose.yaml:3 image-pin vulnerable
compose.yaml:5 image-pin vulnerable
k8s/deployment.yaml:10 image-pin vulnerable | +| repo | Source tree, offline: Dockerfiles (with install forms: --mount, :arch, .arch, /release, =${VAR}), Compose, Kubernetes, setup-java, version files, Gradle | pass | .github/workflows/ci.yml:12 java-line vulnerable
.github/workflows/ci.yml:8 java-pin vulnerable
.java-version:1 java-pin vulnerable
.sdkmanrc:1 java-pin vulnerable
Dockerfile.forms:2 os-package vulnerable
Dockerfile.forms:3 os-package unknown
Dockerfile.forms:4 os-package vulnerable
Dockerfile.forms:5 os-package vulnerable
Dockerfile.forms:6 os-package vulnerable
Dockerfile.pkg:2 os-package vulnerable
Dockerfile:1 image-pin vulnerable
build.gradle.kts:3 java-line vulnerable
build.gradle.kts:7 image-pin vulnerable
compose.yaml:13 not-checked unknown
compose.yaml:3 image-pin vulnerable
compose.yaml:5 image-pin vulnerable
k8s/deployment.yaml:10 image-pin vulnerable | 39/39 cases match. diff --git a/parity/java4shell/cases.json b/parity/java4shell/cases.json index d0551b0..7c331fa 100644 --- a/parity/java4shell/cases.json +++ b/parity/java4shell/cases.json @@ -667,7 +667,7 @@ }, { "name": "repo", - "what": "Source tree, offline: Dockerfiles, Compose, Kubernetes, setup-java, version files, Gradle", + "what": "Source tree, offline: Dockerfiles (with install forms: --mount, :arch, .arch, /release, =${VAR}), Compose, Kubernetes, setup-java, version files, Gradle", "mode": "repo", "dir": "repo", "expected": [ @@ -730,6 +730,31 @@ "k8s/deployment.yaml:10", "image-pin", "vulnerable" + ], + [ + "Dockerfile.forms:2", + "os-package", + "vulnerable" + ], + [ + "Dockerfile.forms:3", + "os-package", + "unknown" + ], + [ + "Dockerfile.forms:4", + "os-package", + "vulnerable" + ], + [ + "Dockerfile.forms:5", + "os-package", + "vulnerable" + ], + [ + "Dockerfile.forms:6", + "os-package", + "vulnerable" ] ] } diff --git a/parity/java4shell/repo/Dockerfile.forms b/parity/java4shell/repo/Dockerfile.forms new file mode 100644 index 0000000..316cf08 --- /dev/null +++ b/parity/java4shell/repo/Dockerfile.forms @@ -0,0 +1,6 @@ +FROM debian:12 +RUN --mount=type=cache,target=/var/cache/apt apt-get install -y openjdk-17-jre-headless +RUN apt-get install -y openjdk-17-jre-headless=${JDK_PKG} +RUN apt-get install -y openjdk-17-jre-headless:amd64 +RUN apt-get install -y openjdk-17-jdk/bookworm-backports +RUN dnf install -y java-17-openjdk-headless.x86_64 From accee68fbda020c177897eb57a959737185014c2 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 02:24:39 +0000 Subject: [PATCH 030/119] engine: contain a panic in VisitHead like one in Visit Round-3 finding 2. A head visitor that panics on one file loses that file, recorded as not scanned with the detector named, and the scan of the target goes on for every detector. Tests cover that and the branch where another detector wants every file. Co-Authored-By: Claude Opus 5.5 --- internal/engine/engine_test.go | 44 ++++++++++++++++++++++++++++++++++ internal/engine/run.go | 24 +++++++++++++++---- 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go index 7bd4601..b8bf6cc 100644 --- a/internal/engine/engine_test.go +++ b/internal/engine/engine_test.go @@ -247,3 +247,47 @@ func TestHeadVisitorSeesUnreadFiles(t *testing.T) { t.Errorf("heads %v, read %v", heads, *h.seen) } } + +// headPanic panics in VisitHead on one file. +type headPanic struct{ headFake } + +func (h headPanic) NewScan(TargetKind) Scan { return h } +func (h headPanic) VisitHead(p string, b []byte) { + if strings.HasSuffix(p, "bad") { + panic("boom") + } + h.headFake.VisitHead(p, b) +} + +func TestHeadVisitorPanicContained(t *testing.T) { + root := tree(t, map[string][]byte{"etc/a.conf": []byte("a"), "opt/bad": []byte("x")}) + var heads []string + h := headPanic{headFake{&fake{id: "t-headpanic", wants: func(p string) bool { return strings.HasSuffix(p, ".conf") }, seen: &[]string{}}, &heads}} + other := &fake{id: "t-other", wants: func(p string) bool { return true }} + tg := ScanFS([]Detector{h, detector(other)}, root, Options{AsRoot: true}) + if tg.Error != "" || len(*other.seen) != 2 { + t.Fatalf("a VisitHead panic stopped the target: %q, other saw %v", tg.Error, *other.seen) + } + failed := false + for _, s := range tg.Skipped { + if s.Path == "/opt/bad" && s.DetectorFailed { + failed = true + } + } + if !failed { + t.Errorf("the panic was not recorded: %+v", tg.Skipped) + } +} + +// With a detector that wants every file, head visitors still see each one. +func TestHeadVisitorWithAllReader(t *testing.T) { + root := tree(t, map[string][]byte{"etc/a.conf": []byte("a"), "opt/x": []byte("x")}) + var heads []string + h := headFake{&fake{id: "t-head2", wants: func(string) bool { return false }, seen: &[]string{}}, &heads} + all := &fake{id: "t-all2"} + ScanFS([]Detector{h, detector(all)}, root, Options{AsRoot: true}) + sort.Strings(heads) + if strings.Join(heads, ",") != "/etc/a.conf,/opt/x" || len(*all.seen) != 2 { + t.Errorf("heads %v, all saw %v", heads, *all.seen) + } +} diff --git a/internal/engine/run.go b/internal/engine/run.go index bf4ea53..cd6f732 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -237,15 +237,19 @@ func (w *walker) sourceOptions(opts Options) source.Options { Symlink: func(p, t string) { w.ctx.symlinks[w.abs(p)] = t }, Hardlink: func(p, t string) { w.ctx.hardlinks[w.abs(p)] = w.abs(t) }, } - var heads []HeadVisitor - for _, s := range w.scans { + type headScan struct { + id string + h HeadVisitor + } + var heads []headScan + for i, s := range w.scans { if h, ok := s.(HeadVisitor); ok { - heads = append(heads, h) + heads = append(heads, headScan{w.dets[i].Manifest().ID, h}) } } visitHead := func(p string, head []byte) { for _, h := range heads { - h.VisitHead(w.abs(p), head) + w.visitHeadSafely(h.id, h.h, w.abs(p), head) } } var readers []Reader @@ -322,6 +326,18 @@ func (w *walker) visitSafely(i int, s Scan, f File) (skips []Skip) { return s.Visit(f) } +// visitHeadSafely runs one detector's VisitHead on one file. A detector +// that panics on a hostile file loses that file, reported as not scanned, +// and the scan goes on, as with Visit. +func (w *walker) visitHeadSafely(id string, h HeadVisitor, p string, head []byte) { + defer func() { + if r := recover(); r != nil { + w.t.Skipped = append(w.t.Skipped, source.Skip{Path: p, Reason: fmt.Sprintf("detector %s failed on this file (%v); not checked", id, r), DetectorFailed: true}) + } + }() + h.VisitHead(p, head) +} + func (w *walker) finish() { for i, s := range w.scans { fs, err := finishSafely(s, w.ctx) From e03713f56e2002379549f28208f09105bb8f2725 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 02:24:56 +0000 Subject: [PATCH 031/119] java4shell: the os-release probe keeps to --max-file-size Round-3 finding 3. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/registry_internal_test.go | 17 +++++++++++++++++ detectors/java4shell/repo.go | 7 ++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/detectors/java4shell/registry_internal_test.go b/detectors/java4shell/registry_internal_test.go index b5b0077..825df26 100644 --- a/detectors/java4shell/registry_internal_test.go +++ b/detectors/java4shell/registry_internal_test.go @@ -153,3 +153,20 @@ func TestVerifierBaseOS(t *testing.T) { t.Errorf("unbounded os-release: %d bytes", len(got)) } } + +// Round-3 finding 3: the os-release probe keeps to --max-file-size. +func TestOSProbeMaxFileSize(t *testing.T) { + host := testRegistry(t) + ref := host + "/acme/big:1" + pushImage(t, ref, map[string][]byte{"/etc/os-release": append([]byte("ID=ubuntu\n"), bytes.Repeat([]byte("#"), 2<<20)...)}) + tg := osOf(ref, engine.Options{MaxFileSize: 1 << 20}) + skipped := false + for _, s := range tg.Skipped { + if s.Path == "/etc/os-release" { + skipped = true + } + } + if !skipped { + t.Errorf("a 2 MiB os-release was read past a 1 MiB limit: %+v", tg.Skipped) + } +} diff --git a/detectors/java4shell/repo.go b/detectors/java4shell/repo.go index f4569de..9494a26 100644 --- a/detectors/java4shell/repo.go +++ b/detectors/java4shell/repo.go @@ -375,7 +375,7 @@ func (d *Detector) verifier(o engine.Options) func(ctx context.Context, current, // distribution; one that does can move to its next release). The // current image is read for its os-release only. A current tag that // is gone is tolerated when the new tag names its OS. - c := engine.ScanImage([]engine.Detector{osProbe{}}, current, engine.Options{Platform: "linux/amd64", Guarded: true, PublicOnly: o.PublicOnly}) + c := osOf(current, o) _, tag, _ := strings.Cut(target[strings.LastIndex(target, "/")+1:], ":") if c.Error == "" || !repo.NamesBaseOS(tag) { if err := repo.SameBase(annotation(c, "java4shell_os"), annotation(t, "java4shell_os")); err != nil { @@ -416,3 +416,8 @@ func annotation(t *engine.Target, key string) string { v, _ := t.Annotations[key].(string) return v } + +// osOf reads an image for its os-release only. +func osOf(ref string, o engine.Options) *engine.Target { + return engine.ScanImage([]engine.Detector{osProbe{}}, ref, engine.Options{Platform: "linux/amd64", MaxFileSize: o.MaxFileSize, Guarded: true, PublicOnly: o.PublicOnly}) +} From 25ea00907d0b0beb7ddb48ca5f5c1084e43495c7 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 02:25:33 +0000 Subject: [PATCH 032/119] java4shell: setenv.sh stops at return or exit; an exec of java that undoes it voids it Round-3 nit. Assignments after an unconditional return or exit are not read. A java the file starts itself with -XX:+UseBASE64Intrinsics, -XX:UseAVX=3 or higher, or an @argfile, makes the file's mitigation unprovable (a java named by path, $JAVA_HOME/bin/java, counts as java). Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/internal/jvm/options.go | 2 +- .../java4shell/internal/jvm/review2_test.go | 22 +++++++++++++++++++ detectors/java4shell/internal/jvm/settings.go | 12 ++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/detectors/java4shell/internal/jvm/options.go b/detectors/java4shell/internal/jvm/options.go index 4a6e2f8..f3d114b 100644 --- a/detectors/java4shell/internal/jvm/options.go +++ b/detectors/java4shell/internal/jvm/options.go @@ -227,7 +227,7 @@ func Undoes(words []string) (base64, avx, argfile bool) { java := false for _, w := range words { switch { - case baseName(w) == "java": + case baseName(w) == "java" || strings.HasSuffix(w, "/bin/java"): java = true case w == "-XX:+UseBASE64Intrinsics" || w == "-XX:UseBASE64Intrinsics=true": base64 = true diff --git a/detectors/java4shell/internal/jvm/review2_test.go b/detectors/java4shell/internal/jvm/review2_test.go index cd09218..b511c6d 100644 --- a/detectors/java4shell/internal/jvm/review2_test.go +++ b/detectors/java4shell/internal/jvm/review2_test.go @@ -126,3 +126,25 @@ func TestSetenvModelRound2(t *testing.T) { } } } + +// Round-3 nits: unreachable assignments and an exec that turns the +// decoder back on do not count. +func TestSetenvRound3(t *testing.T) { + tomcat := "/opt/tomcat/bin/setenv.sh" + for _, c := range []struct { + text string + want bool + }{ + {"return 0\nCATALINA_OPTS=\"-XX:-UseBASE64Intrinsics\"\n", false}, + {"exit 0\nCATALINA_OPTS=\"-XX:-UseBASE64Intrinsics\"\n", false}, + {"CATALINA_OPTS=\"-XX:-UseBASE64Intrinsics\"\nexec java $CATALINA_OPTS -XX:+UseBASE64Intrinsics -jar /a.jar\n", false}, + {"CATALINA_OPTS=\"-XX:-UseBASE64Intrinsics\"\nexec \"$JAVA_HOME/bin/java\" @/opt/args.txt -jar /a.jar\n", false}, + {"if [ -z \"$X\" ]; then\n return 0\nfi\nCATALINA_OPTS=\"-XX:-UseBASE64Intrinsics\"\n", true}, + {"CATALINA_OPTS=\"-XX:-UseBASE64Intrinsics\"\nexit 0\n", true}, + } { + s, _ := ReadSetting(tomcat, []byte(c.text)) + if m, _ := s.Options(21).Mitigates(); m != c.want { + t.Errorf("%q: %v, want %v", c.text, m, c.want) + } + } +} diff --git a/detectors/java4shell/internal/jvm/settings.go b/detectors/java4shell/internal/jvm/settings.go index 36b8bce..cb83bbf 100644 --- a/detectors/java4shell/internal/jvm/settings.go +++ b/detectors/java4shell/internal/jvm/settings.go @@ -495,6 +495,7 @@ func readShell(text string, wanted map[string]bool) (map[string]string, bool) { exported := map[string]bool{} depth := 0 heredoc, dashed := "", false +lines: for _, raw := range strings.Split(text, "\n") { line := strings.TrimSuffix(raw, "\r") if heredoc != "" { @@ -577,7 +578,18 @@ func readShell(text string, wanted map[string]bool) (map[string]string, bool) { } cond := c.cond || depth > 0 touches := func(n string) bool { return wanted[n] } + // A java the file starts itself (exec java ...) that turns + // the decoder back on, or reads options from an @argfile, + // makes the file's mitigation unprovable. + if b64, avx, argfile := Undoes(words); b64 || avx || argfile { + return nil, false + } switch words[0] { + case "return", "exit": + if !cond { + break lines // nothing after it runs + } + continue case "unset", "export", "readonly", "declare", "local": for _, w := range words[1:] { name, value, assign := strings.Cut(w, "=") From 88646ffbf839c954c33d1ee3a3d0dda482c1c475 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 02:25:33 +0000 Subject: [PATCH 033/119] java4shell: Ubuntu YY.04 and YY.10 are different bases Round-3 nit. SameBase compares Ubuntu on its full VERSION_ID and other distributions on the major version. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/internal/repo/plan.go | 9 +++++++-- detectors/java4shell/internal/repo/review4_test.go | 13 +++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/detectors/java4shell/internal/repo/plan.go b/detectors/java4shell/internal/repo/plan.go index efb3335..675704b 100644 --- a/detectors/java4shell/internal/repo/plan.go +++ b/detectors/java4shell/internal/repo/plan.go @@ -347,11 +347,16 @@ func NamesBaseOS(variant string) bool { // major version: moving a deployment to another distribution or major // release (Ubuntu 24.04 to 26.04, Debian 12 to 13) is not this fix's call, // while a minor update (Oracle Linux 9.5 to 9.6, Alpine 3.21 to 3.22) is -// what a rebuilt tag brings anyway. +// what a rebuilt tag brings anyway. Ubuntu is compared on its full +// VERSION_ID (24.04 and 24.10 are different releases). func SameBase(current, target string) error { major := func(s string) string { id, ver, _ := strings.Cut(s, " ") - ver, _, _ = strings.Cut(ver, ".") + if id != "ubuntu" { + // Ubuntu's YY.04 and YY.10 are different releases; elsewhere + // the first number is the release. + ver, _, _ = strings.Cut(ver, ".") + } return id + " " + ver } switch { diff --git a/detectors/java4shell/internal/repo/review4_test.go b/detectors/java4shell/internal/repo/review4_test.go index d710aad..83f5285 100644 --- a/detectors/java4shell/internal/repo/review4_test.go +++ b/detectors/java4shell/internal/repo/review4_test.go @@ -80,3 +80,16 @@ func TestSameBaseMajor(t *testing.T) { t.Errorf("unbounded reason: %d bytes", len(err.Error())) } } + +// Round-3 nit: Ubuntu's YY.04 and YY.10 are different releases. +func TestSameBaseUbuntu(t *testing.T) { + if err := SameBase("ubuntu 24.04", "ubuntu 24.10"); err == nil { + t.Error("Ubuntu 24.04 to 24.10 accepted") + } + if err := SameBase("ubuntu 24.04", "ubuntu 24.04"); err != nil { + t.Error(err) + } + if err := SameBase("rhel 9.4", "rhel 9.6"); err != nil { + t.Error(err) + } +} From 881f5bebef770b86e699ccb5421ebbe2349f8fae Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 02:41:52 +0000 Subject: [PATCH 034/119] java4shell: apk @repo tags and package names with a variable for the release Round-4 follow-ups. An apk argument with a repository tag (openjdk21-jre-headless@edge) is matched like one with an .arch or :arch suffix. A Java package name with a variable where the release is (openjdk-${V}-jre-headless, java-${V}-openjdk) is reported as not checked, like a pin to a variable version. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/internal/repo/repo.go | 21 ++++++++++++++++ .../java4shell/internal/repo/review3_test.go | 25 ++++++++++++++++++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index e20a594..bffca75 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -854,6 +854,10 @@ func (s *scanner) packages(rel string, line int, run string) { hits = append(hits, pkgHit{name: m[1], feature: atoi(m[3]), op: opOf(m[4]), ver: m[5], mgr: "package", vendor: m[2]}) case defaultArg.MatchString(arg): hits = append(hits, pkgHit{name: arg, mgr: "apt", vendor: "distribution"}) + case varJavaArg.MatchString(arg): + // openjdk-${V}-jre-headless, java-${V}-openjdk: the Java + // release comes from a variable. + hits = append(hits, pkgHit{name: arg, mgr: "package", vendor: "distribution", varName: true}) } } for _, h := range hits { @@ -866,6 +870,10 @@ func anchored(re *regexp.Regexp) *regexp.Regexp { return regexp.MustCompile(`^(?:` + strings.TrimPrefix(re.String(), `\b`) + `)$`) } +// varJavaArg is a Java package name with a variable where the release +// is: openjdk-${V}-jre-headless, openjdk$V, java-${V}-openjdk, temurin-${V}-jdk. +var varJavaArg = regexp.MustCompile(`^(?:openjdk-?|java-|temurin-|zulu|msopenjdk-|sapmachine-)\$\{?[A-Za-z_][A-Za-z0-9_]*\}?(?:-[\w.-]*)?$`) + var ( aptArg = anchored(aptJava) apkArg = anchored(apkJava) @@ -893,6 +901,10 @@ var ( // package argument (a path). func packageName(w string) string { name, ver, pinned := strings.Cut(w, "=") + // An apk repository tag: openjdk21-jre-headless@edge. + if i := strings.IndexByte(name, '@'); i > 0 { + name = name[:i] + } if i := strings.IndexByte(name, '/'); i >= 0 { if strings.Count(name, "/") > 1 || i == 0 { return "" // a path @@ -952,6 +964,7 @@ type pkgHit struct { name, op, ver, mgr string vendor string // distribution, corretto, temurin, zulu, msopenjdk, sapmachine feature int // 0: the distribution's default (default-jre) + varName bool // the name holds a variable where the release is } func opOf(v string) string { @@ -992,6 +1005,14 @@ func pinnedVersion(h pkgHit) string { } func (s *scanner) judgePackage(rel string, line int, h pkgHit) { + if h.varName { + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, + Props: map[string]string{"package": h.name, "manager": h.mgr}, + Reason: "the Java release in the package name comes from a variable set outside this line", + Message: fmt.Sprintf("installs %s, a package whose Java release this scan cannot read: not checked for the Java4Shell fix", refs.CleanText(h.name, 80)), + Fix: "Check which Java release the variable selects: 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update have the fix."}) + return + } if h.feature > 0 && h.feature < 17 { return // Java 8 and 11 packages are not affected } diff --git a/detectors/java4shell/internal/repo/review3_test.go b/detectors/java4shell/internal/repo/review3_test.go index 1f4cf05..a15cb77 100644 --- a/detectors/java4shell/internal/repo/review3_test.go +++ b/detectors/java4shell/internal/repo/review3_test.go @@ -1,6 +1,9 @@ package repo -import "testing" +import ( + "strings" + "testing" +) type want struct { file string @@ -103,3 +106,23 @@ func TestInstallFormsRound3(t *testing.T) { } } } + +// Round-4 follow-ups: an apk @repo tag, and a variable in place of the +// version in a package name. +func TestInstallFormsRound4(t *testing.T) { + root := tree(t, map[string]string{ + "a/Dockerfile": "FROM alpine:3.23\nRUN apk add --no-cache openjdk21-jre-headless@edge\n", + "b/Dockerfile": "FROM debian:12\nRUN apt-get install -y openjdk-${V}-jre-headless\n", + "c/Dockerfile": "FROM rockylinux:9\nRUN dnf install -y java-${V}-openjdk\n", + }) + res := scan(t, root) + if f, ok := find(res, "a/Dockerfile", 2); !ok || f.Rule != RulePackage || f.Props["package"] != "openjdk21-jre-headless" { + t.Errorf("apk @tag: %+v (found %v)", f, ok) + } + for _, file := range []string{"b/Dockerfile", "c/Dockerfile"} { + f, ok := find(res, file, 2) + if !ok || f.Rule != RulePackage || f.Status != StatusUnknown || !strings.Contains(f.Message, "cannot read") { + t.Errorf("%s: %+v (found %v)", file, f, ok) + } + } +} From 11572af6eee47e9b7910fe916430b2c49a946fc4 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Tue, 17 Nov 2026 20:01:14 -0700 Subject: [PATCH 035/119] Build with Go 1.27.4 for GO-2026-6859 (net/http) Co-Authored-By: Claude Opus 5.5 --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 9679fe4..2d34f5a 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/DefectDojo/earlylight -go 1.27.3 +go 1.27.4 require ( github.com/glebarez/go-sqlite v1.23.0 From 62f3d8b70b60054eb543c0e14ee77e6e2c8847c5 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Tue, 17 Nov 2026 20:01:23 -0700 Subject: [PATCH 036/119] Build the image with Go 1.27.4 too Co-Authored-By: Claude Opus 5.5 --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 0c2aa52..43e7971 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.27.3 AS build +FROM golang:1.27.4 AS build WORKDIR /src COPY go.mod go.sum ./ RUN go mod download From f2f83ca31b71fb1c202f0973cd443f88b75540f1 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 03:25:12 +0000 Subject: [PATCH 037/119] engine: a detector's own size limit keeps a larger file from being read A detector that implements engine.Limiter gives a limit of its own for a file, from its path and first bytes. The walk reads a wanted file only as far as the largest limit of the detectors that want it (--max-file-size when one has none), so a file over every limit is never read past its 4 KiB head: it is recorded as skipped, a deliberate exclusion naming the detector, the limit and the size. A file read for another detector is still not shown to a detector whose limit it is over. Detectors without Limiter are read and handed files exactly as before. Co-Authored-By: Claude Opus 5.5 --- internal/engine/engine.go | 14 +++ internal/engine/limit_test.go | 194 +++++++++++++++++++++++++++++++++ internal/engine/run.go | 99 ++++++++++++++--- internal/source/source.go | 83 ++++++++++---- internal/source/source_test.go | 84 +++++++++++++- 5 files changed, 439 insertions(+), 35 deletions(-) create mode 100644 internal/engine/limit_test.go diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 5dd488f..0f62cfb 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -186,6 +186,20 @@ type Reader interface { Wants(path string, head []byte, executable bool) bool } +// Limiter is implemented by detectors that have a size limit of their own +// on some files, below --max-file-size: an os-release, a start script or a +// package database is never hundreds of MiB, and one that is should cost +// nothing. Limit returns the most bytes of the file the detector checks, +// from its path, first bytes and executable flag; 0 or less means no limit +// of its own. A file over its limit is never shown to the detector. It is +// not read past its first bytes unless another detector wants more of it, +// and it is recorded as skipped for that detector: a deliberate exclusion, +// not a coverage gap, since the detector would not check a file that size. +// The limit applies to the files the walk meets, not to archive members. +type Limiter interface { + Limit(path string, head []byte, executable bool) int64 +} + // HeadVisitor is implemented by a Scan that wants to see the first bytes // of every file the walk meets, read in full or not: a record of files // it does not need to read (a runtime download inside an image) without diff --git a/internal/engine/limit_test.go b/internal/engine/limit_test.go new file mode 100644 index 0000000..e7ffa40 --- /dev/null +++ b/internal/engine/limit_test.go @@ -0,0 +1,194 @@ +package engine + +import ( + "archive/tar" + "bytes" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/internal/source" +) + +// limited is a detector that sets its own size limit on some files. +type limited struct { + *fake + max func(p string) int64 +} + +func (l limited) Limit(p string, _ []byte, _ bool) int64 { return l.max(p) } + +// limitedReader is a limited detector that also filters what it reads. +type limitedReader struct { + limited + fakeReader +} + +func (l limitedReader) Manifest() Manifest { return l.limited.Manifest() } +func (l limitedReader) Load() error { return nil } +func (l limitedReader) NewScan(k TargetKind) Scan { return l.limited.NewScan(k) } +func (l limitedReader) Wants(p string, h []byte, e bool) bool { return l.fakeReader.Wants(p, h, e) } + +func capped(id string, wants func(string) bool, max func(string) int64) (*fake, Detector) { + f := &fake{id: id, wants: wants, seen: &[]string{}} + l := limited{f, max} + if wants == nil { + return f, l + } + return f, limitedReader{l, fakeReader{f}} +} + +func osRelease(p string) bool { return p == "/etc/os-release" } + +func limit64K(p string) int64 { + if osRelease(p) { + return 64 << 10 + } + return 0 +} + +func ownSkips(t *Target) []source.Skip { + var out []source.Skip + for _, s := range t.Skipped { + if strings.Contains(s.Reason, "-byte limit of") { + out = append(out, s) + } + } + return out +} + +// A file over a detector's own limit is not read for it: it is recorded as a +// deliberate exclusion naming the detector and the size, and is no coverage gap. +func TestLimiterSkipsAFileOverItsLimit(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 100<<10), "etc/small": []byte("x")}) + f, d := capped("t-cap", func(p string) bool { return strings.HasPrefix(p, "/etc/") }, limit64K) + tg := ScanFS([]Detector{d}, root, Options{AsRoot: true, MaxFileSize: 256 << 20}) + if got := strings.Join(*f.seen, ","); got != "/etc/small" { + t.Errorf("the capped detector saw %q", got) + } + sk := ownSkips(tg) + if len(sk) != 1 || sk[0].Path != "/etc/os-release" || !sk[0].Excluded || + !strings.Contains(sk[0].Reason, "t-cap") || !strings.Contains(sk[0].Reason, "102400 bytes") || !strings.Contains(sk[0].Reason, "65536") { + t.Fatalf("skips %+v", tg.Skipped) + } + if tg.Gaps() != 0 || tg.Read != 1 { + t.Errorf("gaps %d read %d", tg.Gaps(), tg.Read) + } + // At or under the limit it is read as before. + root = tree(t, map[string][]byte{"etc/os-release": make([]byte, 64<<10)}) + f, d = capped("t-cap2", func(p string) bool { return true }, limit64K) + if tg := ScanFS([]Detector{d}, root, Options{AsRoot: true}); len(*f.seen) != 1 || len(tg.Skipped) != 0 { + t.Errorf("a file at the limit: seen %v skipped %+v", *f.seen, tg.Skipped) + } +} + +// The limit holds in an image too, where the size comes from the tar header. +func TestLimiterInAnImage(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "rootfs.tar") + if err := os.WriteFile(p, tarFile(t, map[string][]byte{"etc/os-release": make([]byte, 100<<10), "etc/small": []byte("x")}), 0o600); err != nil { + t.Fatal(err) + } + f, d := capped("t-capimg", func(p string) bool { return true }, limit64K) + tg := ScanImage([]Detector{d}, "rootfs:"+p, Options{MaxFileSize: 256 << 20}) + if tg.Error != "" || strings.Join(*f.seen, ",") != "/etc/small" || len(ownSkips(tg)) != 1 || tg.Gaps() != 0 { + t.Fatalf("error %q seen %v skipped %+v", tg.Error, *f.seen, tg.Skipped) + } +} + +// Another detector that wants the file without a limit still gets it; the +// capped detector does not, and the file is recorded as not checked by it. +func TestLimiterWithAnotherReader(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 100<<10)}) + f, d := capped("t-capu", osRelease, limit64K) + other := &fake{id: "t-uncapped", wants: osRelease} + tg := ScanFS([]Detector{d, detector(other)}, root, Options{AsRoot: true}) + if len(*f.seen) != 0 || len(*other.seen) != 1 { + t.Errorf("capped saw %v, other saw %v", *f.seen, *other.seen) + } + if sk := ownSkips(tg); len(sk) != 1 || !strings.Contains(sk[0].Reason, "t-capu") || strings.Contains(sk[0].Reason, "t-uncapped") || tg.Gaps() != 0 { + t.Errorf("skips %+v", tg.Skipped) + } + + // The largest limit decides how far the file is read; each detector + // still sees only what fits its own. + root = tree(t, map[string][]byte{"etc/os-release": make([]byte, 10<<10)}) + small, ds := capped("t-cap1k", osRelease, func(string) int64 { return 1 << 10 }) + big, db := capped("t-cap64k", osRelease, limit64K) + tg = ScanFS([]Detector{ds, db}, root, Options{AsRoot: true}) + if len(*small.seen) != 0 || len(*big.seen) != 1 || len(ownSkips(tg)) != 1 || !strings.Contains(ownSkips(tg)[0].Reason, "t-cap1k") { + t.Errorf("small saw %v, big saw %v, skipped %+v", *small.seen, *big.seen, tg.Skipped) + } +} + +// With a detector that reads every file, a capped detector is still not +// shown a file over its limit. +func TestLimiterWithAnAllReader(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 100<<10), "etc/x": []byte("x")}) + f, d := capped("t-capall", nil, limit64K) + all := &fake{id: "t-all3"} + tg := ScanFS([]Detector{d, detector(all)}, root, Options{AsRoot: true}) + if strings.Join(*f.seen, ",") != "/etc/x" || len(*all.seen) != 2 || len(ownSkips(tg)) != 1 { + t.Errorf("capped saw %v, all saw %v, skipped %+v", *f.seen, *all.seen, tg.Skipped) + } +} + +// A limit does not apply where the detector sets none, and --max-file-size +// still bounds a file under a detector's limit. +func TestLimiterLeavesOtherFiles(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 100), "bin/big": make([]byte, 200<<10)}) + f, d := capped("t-capo", func(string) bool { return true }, limit64K) + tg := ScanFS([]Detector{d}, root, Options{AsRoot: true, MaxFileSize: 50}) + if len(*f.seen) != 0 || len(tg.Skipped) != 2 || len(ownSkips(tg)) != 0 || tg.Gaps() != 2 { + t.Errorf("seen %v skipped %+v", *f.seen, tg.Skipped) + } + tg = ScanFS([]Detector{d}, root, Options{AsRoot: true}) + if len(*f.seen) != 2 || len(tg.Skipped) != 0 { + t.Errorf("without --max-file-size: seen %v skipped %+v", *f.seen, tg.Skipped) + } +} + +// A file over a detector's limit is never read past its head: scanning a +// huge one allocates about nothing. +func TestLimiterNeverReadsAHugeFile(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "etc"), 0o755); err != nil { + t.Fatal(err) + } + fh, err := os.Create(filepath.Join(root, "etc/os-release")) + if err != nil { + t.Fatal(err) + } + if err := fh.Truncate(128 << 20); err != nil { // sparse: no disk used + t.Fatal(err) + } + fh.Close() + _, d := capped("t-caphuge", osRelease, limit64K) + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + tg := ScanFS([]Detector{d}, root, Options{AsRoot: true, MaxFileSize: 256 << 20}) + runtime.ReadMemStats(&after) + if alloc := after.TotalAlloc - before.TotalAlloc; alloc > 4<<20 { + t.Errorf("scanning a 128 MiB file over a 64 KiB limit allocated %d bytes", alloc) + } + if len(ownSkips(tg)) != 1 { + t.Errorf("skipped %+v", tg.Skipped) + } +} + +func tarFile(t *testing.T, files map[string][]byte) []byte { + t.Helper() + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for name, b := range files { + if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o644, Size: int64(len(b)), Typeflag: tar.TypeReg}); err != nil { + t.Fatal(err) + } + tw.Write(b) + } + tw.Close() + return buf.Bytes() +} diff --git a/internal/engine/run.go b/internal/engine/run.go index cd6f732..fd8a723 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -197,6 +197,17 @@ type walker struct { // when the target is one file, whose path is the prefix itself. prefix string single bool + // limited is the path of the last file read, and limits each scan's own + // limit on it, for handing it out (Limiter). + limited string + limits []fileLimit +} + +// fileLimit is one detector's own limit on one file, and whether it asked +// for the file. +type fileLimit struct { + bytes int64 + wants bool } // abs turns a walked path into its path inside the system root. @@ -252,37 +263,88 @@ func (w *walker) sourceOptions(opts Options) source.Options { w.visitHeadSafely(h.id, h.h, w.abs(p), head) } } - var readers []Reader - all := false - for _, d := range w.dets { - r, ok := d.(Reader) - if !ok { - all = true // this detector wants everything - break + readers := make([]Reader, len(w.dets)) // nil: the detector wants everything + limiters := make([]Limiter, len(w.dets)) + all, limited := false, false + for i, d := range w.dets { + var ok bool + if readers[i], ok = d.(Reader); !ok { + all = true + } + if limiters[i], ok = d.(Limiter); ok { + limited = true + } + } + if limited { + w.limits = make([]fileLimit, len(w.dets)) + so.Read = func(p string, head []byte, exe bool) (bool, source.Limit) { + visitHead(p, head) + return w.limit(w.abs(p), head, exe, readers, limiters) } - readers = append(readers, r) + return so } if all { if len(heads) > 0 { - so.Read = func(p string, head []byte, _ bool) bool { + so.Read = func(p string, head []byte, _ bool) (bool, source.Limit) { visitHead(p, head) - return true + return true, source.Limit{} } } return so } - so.Read = func(p string, head []byte, exe bool) bool { + so.Read = func(p string, head []byte, exe bool) (bool, source.Limit) { visitHead(p, head) for _, r := range readers { if r.Wants(w.abs(p), head, exe) { - return true + return true, source.Limit{} } } - return false + return false, source.Limit{} } return so } +// limit decides whether to read a file when some detector has limits of its +// own: it is read when any detector wants it, as far as the largest limit of +// those that do (--max-file-size when one has none). Each detector's limit +// is kept for handing the file out. +func (w *walker) limit(p string, head []byte, exe bool, readers []Reader, limiters []Limiter) (bool, source.Limit) { + w.limited = p + read, unlimited := false, false + var most int64 + var by []string + for i := range w.dets { + l := fileLimit{wants: readers[i] == nil || readers[i].Wants(p, head, exe)} + if limiters[i] != nil { + l.bytes = limiters[i].Limit(p, head, exe) + } + w.limits[i] = l + switch { + case !l.wants: + case l.bytes <= 0: + read, unlimited = true, true + default: + read = true + most = max(most, l.bytes) + by = append(by, w.dets[i].Manifest().ID) + } + } + if !read || unlimited { + return read, source.Limit{} + } + return true, source.Limit{Bytes: most, By: strings.Join(by, " and ")} +} + +// over reports whether f is over scan i's own limit, which keeps it from +// that detector. +func (w *walker) over(i int, f File) bool { + if f.Member || f.Path != w.limited || w.limits == nil { + return false + } + l := w.limits[i] + return l.bytes > 0 && int64(len(f.Data)) > l.bytes +} + func (w *walker) visit(f source.File) error { f.Path = w.abs(f.Path) w.ctx.seen[f.Path] = true @@ -303,12 +365,21 @@ func (w *walker) visit(f source.File) error { return nil } -// send gives f to every scan, except those skip(i) rules out. +// send gives f to every scan, except those skip(i) rules out and those +// whose own limit it is over: read for another detector, it is recorded +// as not checked by one that asked for it. func (w *walker) send(f File, skip func(int) bool) { for i, s := range w.scans { if skip != nil && skip(i) { continue } + if w.over(i, f) { + if w.limits[i].wants { + w.t.Skipped = append(w.t.Skipped, source.Skip{Path: f.Path, Excluded: true, + Reason: fmt.Sprintf("excluded: larger than the %d-byte limit of %s for this file (%d bytes); not checked by it", w.limits[i].bytes, w.dets[i].Manifest().ID, len(f.Data))}) + } + continue + } for _, sk := range w.visitSafely(i, s, f) { w.t.Skipped = append(w.t.Skipped, source.Skip{Path: sk.Path, Reason: sk.Reason, DetectorFailed: sk.failed}) } diff --git a/internal/source/source.go b/internal/source/source.go index 39b7ce2..d4bbef7 100644 --- a/internal/source/source.go +++ b/internal/source/source.go @@ -4,7 +4,9 @@ // // Every regular file is read in full unless Options.Read narrows it down. The // decision is made from the path and the file's first bytes, so detectors that -// only care about executables or a few named files never pay for the rest. +// only care about executables or a few named files never pay for the rest, +// and a file larger than its readers' own limit is never read past those +// first bytes. package source import ( @@ -50,8 +52,9 @@ type Options struct { // detectors skip and others read. Uncounted []string // Read decides from a file's path, first bytes and executable flag whether - // to read it in full. Nil reads every file. - Read func(abs string, head []byte, executable bool) bool + // to read it in full, and how far its readers want it (Limit). Nil reads + // every file. + Read func(abs string, head []byte, executable bool) (bool, Limit) // IsExecutable decides from a file's first bytes whether it is an executable. IsExecutable func(head []byte) bool // Symlink receives every symbolic link (absolute path, target as written). @@ -70,6 +73,38 @@ var DefaultExcludes = []string{"/proc/", "/sys/", "/dev/"} // uses. Scan the images themselves instead. var ContainerStorage = []string{"/var/lib/docker/", "/var/lib/containerd/", "/var/lib/containers/", "/var/snap/docker/common/var-lib-docker/"} +// Limit is the readers' own bound on one file, below MaxFileSize: what +// they look for is never that large. A file over it is recorded as a +// deliberate exclusion and not read past its first bytes. +type Limit struct { + // Bytes is the most read of the file; 0 or less means MaxFileSize. + Bytes int64 + // By names who set it, for the record ("java4shell"). + By string +} + +// bound is the most read of a file: the reader's own limit when it is below +// MaxFileSize, and whether that limit is the one that applies. +func (o Options) bound(l Limit) (int64, bool) { + if l.Bytes > 0 && (o.MaxFileSize <= 0 || l.Bytes < o.MaxFileSize) { + return l.Bytes, true + } + return o.MaxFileSize, false +} + +// tooLarge is the record of a file over the limit that applies to it. +func tooLarge(abs string, size, most int64, own bool, by string, reading bool) Skip { + switch { + case own && reading: + return Skip{Path: abs, Reason: fmt.Sprintf("excluded: larger than the %d-byte limit of %s for this file, found while reading", most, by), Excluded: true} + case own: + return Skip{Path: abs, Reason: fmt.Sprintf("excluded: larger than the %d-byte limit of %s for this file (%d bytes)", most, by, size), Excluded: true} + case reading: + return Skip{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes) while reading", most)} + } + return Skip{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes)", size)} +} + // Visitor receives each file read. Returning an error stops the walk. type Visitor func(File) error @@ -181,18 +216,23 @@ func readOne(osPath, abs string, fi fs.FileInfo, opts Options, visit Visitor, sk } head = head[:k] exe := opts.IsExecutable != nil && opts.IsExecutable(head) - if opts.Read != nil && !opts.Read(abs, head, exe) { - return nil + var lim Limit + if opts.Read != nil { + var read bool + if read, lim = opts.Read(abs, head, exe); !read { + return nil + } } - if opts.MaxFileSize > 0 && fi.Size() > opts.MaxFileSize { - *skips = append(*skips, Skip{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes)", fi.Size())}) + most, own := opts.bound(lim) + if most > 0 && fi.Size() > most { + *skips = append(*skips, tooLarge(abs, fi.Size(), most, own, lim.By, false)) return nil } // Enforce the limit while reading: some files (FUSE mounts) report size 0 // and are much larger, or endless. var r io.Reader = f - if opts.MaxFileSize > 0 { - r = io.LimitReader(f, opts.MaxFileSize+1-int64(k)) + if most > 0 { + r = io.LimitReader(f, most+1-int64(k)) } rest, err := io.ReadAll(r) if err != nil { @@ -200,8 +240,8 @@ func readOne(osPath, abs string, fi fs.FileInfo, opts Options, visit Visitor, sk return nil } data := append(head, rest...) - if opts.MaxFileSize > 0 && int64(len(data)) > opts.MaxFileSize { - *skips = append(*skips, Skip{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes) while reading", opts.MaxFileSize)}) + if most > 0 && int64(len(data)) > most { + *skips = append(*skips, tooLarge(abs, 0, most, own, lim.By, true)) return nil } return visit(File{Path: abs, Data: data, Executable: exe}) @@ -251,24 +291,29 @@ func Tar(r io.Reader, opts Options, visit Visitor) ([]Skip, int, error) { } head = head[:k] exe := opts.IsExecutable != nil && opts.IsExecutable(head) - if opts.Read != nil && !opts.Read(abs, head, exe) { - continue + var lim Limit + if opts.Read != nil { + var read bool + if read, lim = opts.Read(abs, head, exe); !read { + continue + } } - if opts.MaxFileSize > 0 && h.Size > opts.MaxFileSize { - skips = append(skips, Skip{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes)", h.Size)}) + most, own := opts.bound(lim) + if most > 0 && h.Size > most { + skips = append(skips, tooLarge(abs, h.Size, most, own, lim.By, false)) continue } var rr io.Reader = tr - if opts.MaxFileSize > 0 { - rr = io.LimitReader(tr, opts.MaxFileSize+1-int64(k)) + if most > 0 { + rr = io.LimitReader(tr, most+1-int64(k)) } rest, err := io.ReadAll(rr) if err != nil { return skips, n, fmt.Errorf("reading %s: %w", abs, err) } data := append(head, rest...) - if opts.MaxFileSize > 0 && int64(len(data)) > opts.MaxFileSize { - skips = append(skips, Skip{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes) while reading", opts.MaxFileSize)}) + if most > 0 && int64(len(data)) > most { + skips = append(skips, tooLarge(abs, 0, most, own, lim.By, true)) continue } if err := visit(File{Path: abs, Data: data, Executable: exe}); err != nil { diff --git a/internal/source/source_test.go b/internal/source/source_test.go index f596585..cec4a00 100644 --- a/internal/source/source_test.go +++ b/internal/source/source_test.go @@ -3,6 +3,10 @@ package source import ( "archive/tar" "bytes" + "io" + "os" + "path/filepath" + "runtime" "testing" ) @@ -24,8 +28,10 @@ func TestTarReadFilterAndLinks(t *testing.T) { var read []string links := map[string]string{} opts := Options{ - MaxFileSize: 5, - Read: func(p string, head []byte, exe bool) bool { return p != "/etc/a.conf" || len(head) == 1 }, + MaxFileSize: 5, + Read: func(p string, head []byte, exe bool) (bool, Limit) { + return p != "/etc/a.conf" || len(head) == 1, Limit{} + }, IsExecutable: func(h []byte) bool { return bytes.HasPrefix(h, []byte("\x7fELF")) }, Symlink: func(p, to string) { links[p] = to }, Hardlink: func(p, to string) { links[p] = to }, @@ -59,3 +65,77 @@ func FuzzTar(f *testing.F) { Tar(bytes.NewReader(data), Options{MaxFileSize: 1 << 20}, func(File) error { return nil }) }) } + +// A reader's own limit below MaxFileSize skips a larger file as a deliberate +// exclusion naming who set it; MaxFileSize still applies under it. +func TestTarOwnLimit(t *testing.T) { + data := tarOf(t, map[string]string{"etc/os-release": "0123456789", "etc/small": "01", "big": "0123456789abcdef"}) + var read []string + opts := Options{ + MaxFileSize: 12, + Read: func(p string, _ []byte, _ bool) (bool, Limit) { + if p == "/big" { + return true, Limit{Bytes: 100, By: "t"} // above MaxFileSize: MaxFileSize applies + } + return true, Limit{Bytes: 4, By: "java4shell"} + }, + } + skips, _, err := Tar(bytes.NewReader(data), opts, func(f File) error { read = append(read, f.Path); return nil }) + if err != nil || len(read) != 1 || read[0] != "/etc/small" { + t.Fatalf("read %v err %v", read, err) + } + got := map[string]Skip{} + for _, s := range skips { + got[s.Path] = s + } + if s := got["/etc/os-release"]; !s.Excluded || s.Reason != "excluded: larger than the 4-byte limit of java4shell for this file (10 bytes)" { + t.Errorf("own limit: %+v", s) + } + if s := got["/big"]; s.Excluded || s.Reason != "larger than --max-file-size (16 bytes)" { + t.Errorf("max file size: %+v", s) + } +} + +func TestDirOwnLimit(t *testing.T) { + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "os-release"), make([]byte, 5000), 0o600); err != nil { + t.Fatal(err) + } + var read []string + skips, n, err := Dir(root, Options{Read: func(string, []byte, bool) (bool, Limit) { return true, Limit{Bytes: 4096, By: "t"} }}, + func(f File) error { read = append(read, f.Path); return nil }) + if err != nil || n != 1 || len(read) != 0 || len(skips) != 1 || !skips[0].Excluded || + skips[0].Reason != "excluded: larger than the 4096-byte limit of t for this file (5000 bytes)" { + t.Fatalf("n %d read %v skips %+v err %v", n, read, skips, err) + } +} + +// A tar member over a reader's own limit is passed over, not read: a 128 MiB +// one costs about nothing. +func TestTarOwnLimitNeverReads(t *testing.T) { + const size = 128 << 20 + pr, pw := io.Pipe() + go func() { + tw := tar.NewWriter(pw) + tw.WriteHeader(&tar.Header{Name: "etc/os-release", Mode: 0o644, Size: size, Typeflag: tar.TypeReg}) + io.CopyN(tw, zeros{}, size) + tw.Close() + pw.Close() + }() + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + skips, _, err := Tar(pr, Options{MaxFileSize: 256 << 20, Read: func(string, []byte, bool) (bool, Limit) { return true, Limit{Bytes: 64 << 10, By: "t"} }}, + func(File) error { t.Error("visited"); return nil }) + runtime.ReadMemStats(&after) + if err != nil || len(skips) != 1 || !skips[0].Excluded { + t.Fatalf("skips %+v err %v", skips, err) + } + if alloc := after.TotalAlloc - before.TotalAlloc; alloc > 4<<20 { + t.Errorf("passing over a 128 MiB member allocated %d bytes", alloc) + } +} + +type zeros struct{} + +func (zeros) Read(b []byte) (int, error) { clear(b); return len(b), nil } From 04f572b4dabf12894c5479f0b9653996a4ab42de Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 03:26:36 +0000 Subject: [PATCH 038/119] java4shell: a size limit for each file kept, so a larger one is never read os-release (64 KiB), package databases (16 MiB), start scripts (256 KiB), settings files (1 MiB) and crash logs (4 MiB) are kept only up to a size, which Visit checked after the engine had read the file to --max-file-size. The detector now gives the engine those limits (engine.Limiter), and so does the os-release probe of a move's current image: a hostile 256 MiB /etc/os-release is recorded as excluded and never read past its head. VM libraries and release files keep no limit of their own. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/java4shell.go | 53 ++++++-- detectors/java4shell/limit_internal_test.go | 143 ++++++++++++++++++++ 2 files changed, 187 insertions(+), 9 deletions(-) create mode 100644 detectors/java4shell/limit_internal_test.go diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 3caecca..09d7329 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -110,6 +110,31 @@ func (d *Detector) Wants(p string, head []byte, _ bool) bool { return isScript(head) } +// Limit is the size Visit keeps a file to, so the engine never reads a +// larger one: an os-release, a package database, a start script, a +// settings file or a crash log is never hundreds of MiB. VM libraries are +// read whole, and a release file's size is itself a fact (badReleases). +func (d *Detector) Limit(p string, head []byte, _ bool) int64 { + base := path.Base(p) + switch { + case jvm.IsLibraryName(base), base == "release": + return 0 + case hsErr.MatchString(base): + return maxHsErr + } + var most int64 + if jvm.SettingKind(p) != "" { + most = maxSetting + } + if keep(p) { + most = max(most, keptLimit(p)) + } + if isScript(head) { + most = max(most, maxScript) + } + return most +} + var hsErr = regexp.MustCompile(`^hs_err_pid\d{1,10}\.log$`) // jdkArchive names a Java runtime download as vendors publish it: @@ -143,14 +168,23 @@ func keep(p string) bool { return assess.IsDpkgList(p) } +// keptLimit is the largest package database or os-release kept. +func keptLimit(p string) int64 { + if p == "/etc/os-release" || p == "/usr/lib/os-release" { + return maxOSRelease + } + return maxKept +} + // Limits on what one target keeps. const ( - maxKept = 16 << 20 // a package database - maxScript = 256 << 10 - maxHsErr = 4 << 20 - maxHsErrs = 64 - maxLibs = 4096 - maxSetting = 1 << 20 + maxKept = 16 << 20 // a package database + maxOSRelease = 64 << 10 + maxScript = 256 << 10 + maxHsErr = 4 << 20 + maxHsErrs = 64 + maxLibs = 4096 + maxSetting = 1 << 20 // Caps on what one target can make the detector keep: an image layer // of many small files compresses to almost nothing. maxReleases = 4096 @@ -252,7 +286,7 @@ func (s *scan) Visit(f engine.File) []engine.Skip { } } } - if keep(f.Path) && len(f.Data) <= maxKept { + if keep(f.Path) && int64(len(f.Data)) <= keptLimit(f.Path) { if assess.IsDpkgList(f.Path) { // Only the lines owners are looked up by, without splitting // the whole list. @@ -492,7 +526,7 @@ func (r resolver) resolve(p string) string { // of two images. func osRelease(files ...[]byte) string { for _, b := range files { - if len(b) == 0 || len(b) > 64<<10 { + if len(b) == 0 || len(b) > maxOSRelease { continue } var id, ver string @@ -542,12 +576,13 @@ func (osProbe) Load() error { return nil } func (osProbe) Wants(p string, _ []byte, _ bool) bool { return p == "/etc/os-release" || p == "/usr/lib/os-release" } +func (osProbe) Limit(string, []byte, bool) int64 { return maxOSRelease } func (osProbe) NewScan(engine.TargetKind) engine.Scan { return &osScan{files: map[string][]byte{}} } type osScan struct{ files map[string][]byte } func (s *osScan) Visit(f engine.File) []engine.Skip { - if len(f.Data) <= 64<<10 { + if len(f.Data) <= maxOSRelease { s.files[f.Path] = f.Data } return nil diff --git a/detectors/java4shell/limit_internal_test.go b/detectors/java4shell/limit_internal_test.go new file mode 100644 index 0000000..af10543 --- /dev/null +++ b/detectors/java4shell/limit_internal_test.go @@ -0,0 +1,143 @@ +package java4shell + +import ( + "archive/tar" + "bytes" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/internal/engine" +) + +// allocated returns the bytes f allocates. +func allocated(f func()) uint64 { + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + f() + runtime.ReadMemStats(&after) + return after.TotalAlloc - before.TotalAlloc +} + +func excludedFor(tg *engine.Target, p string) bool { + for _, s := range tg.Skipped { + if s.Path == p && s.Excluded && strings.Contains(s.Reason, "limit of "+ID) { + return true + } + } + return false +} + +// Sensei review: a hostile os-release as large as --max-file-size is not +// read into memory. The detector ignores one over 64 KiB, so the engine +// never reads it past its head. +func TestOSReleaseBounded(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "etc"), 0o755); err != nil { + t.Fatal(err) + } + f, err := os.Create(filepath.Join(root, "etc/os-release")) + if err != nil { + t.Fatal(err) + } + f.WriteString("ID=ubuntu\nVERSION_ID=24.04\n") + if err := f.Truncate(128 << 20); err != nil { // sparse + t.Fatal(err) + } + f.Close() + var tg *engine.Target + if a := allocated(func() { + tg = engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true, MaxFileSize: 256 << 20}) + }); a > 8<<20 { + t.Errorf("a 128 MiB os-release cost %d bytes", a) + } + if !excludedFor(tg, "/etc/os-release") || tg.Gaps() != 0 { + t.Errorf("skipped %+v", tg.Skipped) + } +} + +// The os-release probe of a move's current image does not read a large +// os-release either. +func TestOSProbeBounded(t *testing.T) { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + body := append([]byte("ID=ubuntu\nVERSION_ID=24.04\n"), make([]byte, 16<<20)...) + tw.WriteHeader(&tar.Header{Name: "etc/os-release", Mode: 0o644, Size: int64(len(body)), Typeflag: tar.TypeReg}) + tw.Write(body) + small := []byte("ID=alpine\nVERSION_ID=3.22.1\n") + tw.WriteHeader(&tar.Header{Name: "usr/lib/os-release", Mode: 0o644, Size: int64(len(small)), Typeflag: tar.TypeReg}) + tw.Write(small) + tw.Close() + p := filepath.Join(t.TempDir(), "rootfs.tar") + if err := os.WriteFile(p, buf.Bytes(), 0o600); err != nil { + t.Fatal(err) + } + body, buf = nil, bytes.Buffer{} + var tg *engine.Target + if a := allocated(func() { + tg = engine.ScanImage([]engine.Detector{osProbe{}}, "rootfs:"+p, engine.Options{MaxFileSize: 256 << 20}) + }); a > 4<<20 { + t.Errorf("a 16 MiB os-release cost %d bytes", a) + } + if tg.Error != "" || tg.Annotations["java4shell_os"] != "alpine 3.22.1" || len(tg.Skipped) != 1 || !tg.Skipped[0].Excluded { + t.Errorf("error %q annotations %v skipped %+v", tg.Error, tg.Annotations, tg.Skipped) + } +} + +// Each limit is the one Visit applies after reading, so the detector sees +// every file it would have kept. +func TestLimits(t *testing.T) { + elf := []byte("\x7fELF\x02\x01\x01") + script := []byte("#!/bin/sh\n") + d := &Detector{} + for _, c := range []struct { + path string + head []byte + want int64 + }{ + {"/etc/os-release", []byte("ID=x"), maxOSRelease}, + {"/usr/lib/os-release", script, maxScript}, // a script is kept up to its own limit + {"/var/lib/dpkg/status", []byte("Package: x"), maxKept}, + {"/lib/apk/db/installed", script, maxKept}, + {"/var/lib/dpkg/info/openjdk-21-jre-headless:amd64.list", []byte("/."), maxKept}, + {"/opt/app/bin/start.sh", script, maxScript}, + {"/opt/app/hs_err_pid42.log", []byte("#"), maxHsErr}, + {"/opt/app/hs_err_pid42.log", script, maxHsErr}, + {"/etc/systemd/system/app.service", []byte("[Service]"), maxSetting}, + {"/usr/lib/jvm/java-21/lib/server/libjvm.so", elf, 0}, + {"/usr/lib/jvm/java-21/release", []byte("JAVA_VERSION="), 0}, // its size is part of the verdict + {"/usr/bin/ls", elf, 0}, + {"/etc/passwd", []byte("root:x:0:0"), 0}, + } { + if got := d.Limit(c.path, c.head, false); got != c.want { + t.Errorf("%s %q: limit %d, want %d", c.path, c.head, got, c.want) + } + } + if osProbe.Limit(osProbe{}, "/etc/os-release", nil, false) != maxOSRelease { + t.Error("the os-release probe has no limit") + } +} + +// At its limit an os-release is still read and used. +func TestOSReleaseAtLimit(t *testing.T) { + root := t.TempDir() + body := []byte("ID=debian\nVERSION_ID=\"12\"\n") + body = append(body, bytes.Repeat([]byte("#"), maxOSRelease-len(body))...) + if err := os.MkdirAll(filepath.Join(root, "etc"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "etc/os-release"), body, 0o600); err != nil { + t.Fatal(err) + } + s := (&Detector{}).NewScan(engine.Image).(*scan) + s.Visit(engine.File{Path: "/etc/os-release", Data: body}) + if osRelease(s.kept["/etc/os-release"]) != "debian 12" { + t.Errorf("a %d-byte os-release was not used", len(body)) + } + if tg := engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true}); len(tg.Skipped) != 0 { + t.Errorf("skipped %+v", tg.Skipped) + } +} From 60f76ec583aac63d5dbd2e7bed638d1b1b231896 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 03:27:10 +0000 Subject: [PATCH 039/119] sshole: a size limit for start scripts and kept files, so a larger one is never read Start scripts (256 KiB) and the account, package and configuration files the verdict reads (4 MiB) were checked against those limits only after the engine had read them to --max-file-size. The detector now gives the engine the same limits (engine.Limiter); executables keep none. Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/limit_internal_test.go | 63 +++++++++++++++++++++++++ detectors/sshole/sshole.go | 18 +++++++ 2 files changed, 81 insertions(+) create mode 100644 detectors/sshole/limit_internal_test.go diff --git a/detectors/sshole/limit_internal_test.go b/detectors/sshole/limit_internal_test.go new file mode 100644 index 0000000..0d92d4b --- /dev/null +++ b/detectors/sshole/limit_internal_test.go @@ -0,0 +1,63 @@ +package sshole + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/internal/engine" +) + +// A hostile account file as large as --max-file-size is not read into +// memory: the detector keeps one only up to 4 MiB. +func TestKeptFileBounded(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "etc"), 0o755); err != nil { + t.Fatal(err) + } + f, err := os.Create(filepath.Join(root, "etc/shadow")) + if err != nil { + t.Fatal(err) + } + f.WriteString("root:*:19000:0:99999:7:::\n") + if err := f.Truncate(128 << 20); err != nil { // sparse + t.Fatal(err) + } + f.Close() + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + tg := engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true, MaxFileSize: 256 << 20}) + runtime.ReadMemStats(&after) + if a := after.TotalAlloc - before.TotalAlloc; a > 8<<20 { + t.Errorf("a 128 MiB /etc/shadow cost %d bytes", a) + } + if len(tg.Skipped) != 1 || !tg.Skipped[0].Excluded || !strings.Contains(tg.Skipped[0].Reason, "limit of sshole") || tg.Gaps() != 0 { + t.Errorf("skipped %+v", tg.Skipped) + } +} + +// Each limit is the one Visit applies after reading. +func TestLimits(t *testing.T) { + elf := []byte("\x7fELF\x02\x01\x01") + script := []byte("#!/bin/sh\n") + d := &Detector{} + for _, c := range []struct { + path string + head []byte + want int64 + }{ + {"/etc/shadow", []byte("root:"), maxKept}, + {"/etc/ssh/sshd_config", script, maxKept}, + {"/docker-entrypoint.sh", script, maxScript}, + {"/usr/sbin/sshd", elf, 0}, + {"/etc/ssh/sshd_config", elf, 0}, // an executable is inspected whole + {"/usr/share/doc/x", []byte("text"), 0}, + } { + if got := d.Limit(c.path, c.head, false); got != c.want { + t.Errorf("%s %q: limit %d, want %d", c.path, c.head, got, c.want) + } + } +} diff --git a/detectors/sshole/sshole.go b/detectors/sshole/sshole.go index d91286e..11bfbba 100644 --- a/detectors/sshole/sshole.go +++ b/detectors/sshole/sshole.go @@ -83,6 +83,24 @@ func (d *Detector) Wants(p string, head []byte, _ bool) bool { return archive.IsExecutable(head) || keep(p) || isScript(head) } +// Limit is the size Visit keeps a file to, so the engine never reads a +// larger one: a start script or an account, package or configuration file +// is never hundreds of MiB. Executables (possible sshd binaries) are read +// whole. +func (d *Detector) Limit(p string, head []byte, _ bool) int64 { + if archive.IsExecutable(head) { + return 0 + } + var most int64 + if isScript(head) { + most = maxScript + } + if keep(p) { + most = max(most, maxKept) + } + return most +} + // isScript reports a "#!" script: a container's entrypoint or startup step. func isScript(head []byte) bool { return len(head) > 2 && head[0] == '#' && head[1] == '!' } From 21206aae7481a6ba651ab8b918445bfd056c1e8f Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 03:32:48 +0000 Subject: [PATCH 040/119] source: fuzz Tar with a reader's own limit Co-Authored-By: Claude Opus 5.5 --- internal/source/source_test.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/internal/source/source_test.go b/internal/source/source_test.go index cec4a00..c9db2a3 100644 --- a/internal/source/source_test.go +++ b/internal/source/source_test.go @@ -63,6 +63,14 @@ func FuzzTar(f *testing.F) { f.Add([]byte{}) f.Fuzz(func(t *testing.T, data []byte) { Tar(bytes.NewReader(data), Options{MaxFileSize: 1 << 20}, func(File) error { return nil }) + // With a reader's own limit, nothing larger is ever handed out. + limited := Options{MaxFileSize: 1 << 20, Read: func(string, []byte, bool) (bool, Limit) { return true, Limit{Bytes: 100, By: "t"} }} + Tar(bytes.NewReader(data), limited, func(f File) error { + if len(f.Data) > 100 { + t.Errorf("%s: %d bytes over a 100-byte limit", f.Path, len(f.Data)) + } + return nil + }) }) } From aef1de93a3a8e54f08456c945e5f8944294681e4 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 03:44:52 +0000 Subject: [PATCH 041/119] engine: name each detector's limit in the record; detector IDs looked up once A file over the limits of two detectors was recorded with the larger limit only; the record now names each detector's limit. The walker keeps the detectors' IDs instead of building each Manifest for every file. Co-Authored-By: Claude Opus 5.5 --- internal/engine/limit_test.go | 14 +++++++++++++- internal/engine/run.go | 22 +++++++++++++++++----- internal/source/source.go | 19 ++++++++++--------- internal/source/source_test.go | 12 +++++++----- 4 files changed, 47 insertions(+), 20 deletions(-) diff --git a/internal/engine/limit_test.go b/internal/engine/limit_test.go index e7ffa40..85d1a5e 100644 --- a/internal/engine/limit_test.go +++ b/internal/engine/limit_test.go @@ -52,7 +52,7 @@ func limit64K(p string) int64 { func ownSkips(t *Target) []source.Skip { var out []source.Skip for _, s := range t.Skipped { - if strings.Contains(s.Reason, "-byte limit of") { + if strings.Contains(s.Reason, "-byte limit of") || strings.Contains(s.Reason, "limits of") { out = append(out, s) } } @@ -123,6 +123,18 @@ func TestLimiterWithAnotherReader(t *testing.T) { } } +// A file over the limits of two detectors names both. +func TestLimiterTwoLimits(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 100<<10)}) + _, ds := capped("t-two1k", osRelease, func(string) int64 { return 1 << 10 }) + _, db := capped("t-two64k", osRelease, limit64K) + tg := ScanFS([]Detector{ds, db}, root, Options{AsRoot: true}) + want := "excluded: larger than the limits of t-two1k (1024 bytes) and t-two64k (65536 bytes) for this file (102400 bytes)" + if len(tg.Skipped) != 1 || tg.Skipped[0].Reason != want { + t.Errorf("skipped %+v", tg.Skipped) + } +} + // With a detector that reads every file, a capped detector is still not // shown a file over its limit. func TestLimiterWithAnAllReader(t *testing.T) { diff --git a/internal/engine/run.go b/internal/engine/run.go index fd8a723..37ab7b9 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -187,6 +187,7 @@ func (c *targetCtx) Aliases(p string) []string { // walker hands one target's files to every scan. type walker struct { dets []Detector + ids []string // each detector's ID scans []Scan ctx *targetCtx lim archive.Limits @@ -231,6 +232,7 @@ func newWalker(dets []Detector, kind TargetKind, t *Target, opts Options) *walke continue } w.dets = append(w.dets, d) + w.ids = append(w.ids, d.Manifest().ID) w.scans = append(w.scans, d.NewScan(kind)) if d.Manifest().Archives { w.members = true @@ -312,7 +314,7 @@ func (w *walker) limit(p string, head []byte, exe bool, readers []Reader, limite w.limited = p read, unlimited := false, false var most int64 - var by []string + var capped []int // the detectors that want it, each with a limit for i := range w.dets { l := fileLimit{wants: readers[i] == nil || readers[i].Wants(p, head, exe)} if limiters[i] != nil { @@ -326,15 +328,25 @@ func (w *walker) limit(p string, head []byte, exe bool, readers []Reader, limite default: read = true most = max(most, l.bytes) - by = append(by, w.dets[i].Manifest().ID) + capped = append(capped, i) } } - if !read || unlimited { + switch { + case !read || unlimited: return read, source.Limit{} + case len(capped) == 1: + return true, source.Limit{Bytes: most, Name: ownLimit(most, w.ids[capped[0]])} + } + by := make([]string, len(capped)) + for k, i := range capped { + by[k] = fmt.Sprintf("%s (%d bytes)", w.ids[i], w.limits[i].bytes) } - return true, source.Limit{Bytes: most, By: strings.Join(by, " and ")} + return true, source.Limit{Bytes: most, Name: "the limits of " + strings.Join(by, " and ")} } +// ownLimit names one detector's limit, for the record. +func ownLimit(n int64, id string) string { return fmt.Sprintf("the %d-byte limit of %s", n, id) } + // over reports whether f is over scan i's own limit, which keeps it from // that detector. func (w *walker) over(i int, f File) bool { @@ -376,7 +388,7 @@ func (w *walker) send(f File, skip func(int) bool) { if w.over(i, f) { if w.limits[i].wants { w.t.Skipped = append(w.t.Skipped, source.Skip{Path: f.Path, Excluded: true, - Reason: fmt.Sprintf("excluded: larger than the %d-byte limit of %s for this file (%d bytes); not checked by it", w.limits[i].bytes, w.dets[i].Manifest().ID, len(f.Data))}) + Reason: fmt.Sprintf("excluded: larger than %s for this file (%d bytes); not checked by it", ownLimit(w.limits[i].bytes, w.ids[i]), len(f.Data))}) } continue } diff --git a/internal/source/source.go b/internal/source/source.go index d4bbef7..8a62904 100644 --- a/internal/source/source.go +++ b/internal/source/source.go @@ -79,8 +79,9 @@ var ContainerStorage = []string{"/var/lib/docker/", "/var/lib/containerd/", "/va type Limit struct { // Bytes is the most read of the file; 0 or less means MaxFileSize. Bytes int64 - // By names who set it, for the record ("java4shell"). - By string + // Name says whose limit it is, for the record: "the 65536-byte limit + // of java4shell". + Name string } // bound is the most read of a file: the reader's own limit when it is below @@ -93,12 +94,12 @@ func (o Options) bound(l Limit) (int64, bool) { } // tooLarge is the record of a file over the limit that applies to it. -func tooLarge(abs string, size, most int64, own bool, by string, reading bool) Skip { +func tooLarge(abs string, size, most int64, own bool, name string, reading bool) Skip { switch { case own && reading: - return Skip{Path: abs, Reason: fmt.Sprintf("excluded: larger than the %d-byte limit of %s for this file, found while reading", most, by), Excluded: true} + return Skip{Path: abs, Reason: fmt.Sprintf("excluded: larger than %s for this file, found while reading", name), Excluded: true} case own: - return Skip{Path: abs, Reason: fmt.Sprintf("excluded: larger than the %d-byte limit of %s for this file (%d bytes)", most, by, size), Excluded: true} + return Skip{Path: abs, Reason: fmt.Sprintf("excluded: larger than %s for this file (%d bytes)", name, size), Excluded: true} case reading: return Skip{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes) while reading", most)} } @@ -225,7 +226,7 @@ func readOne(osPath, abs string, fi fs.FileInfo, opts Options, visit Visitor, sk } most, own := opts.bound(lim) if most > 0 && fi.Size() > most { - *skips = append(*skips, tooLarge(abs, fi.Size(), most, own, lim.By, false)) + *skips = append(*skips, tooLarge(abs, fi.Size(), most, own, lim.Name, false)) return nil } // Enforce the limit while reading: some files (FUSE mounts) report size 0 @@ -241,7 +242,7 @@ func readOne(osPath, abs string, fi fs.FileInfo, opts Options, visit Visitor, sk } data := append(head, rest...) if most > 0 && int64(len(data)) > most { - *skips = append(*skips, tooLarge(abs, 0, most, own, lim.By, true)) + *skips = append(*skips, tooLarge(abs, 0, most, own, lim.Name, true)) return nil } return visit(File{Path: abs, Data: data, Executable: exe}) @@ -300,7 +301,7 @@ func Tar(r io.Reader, opts Options, visit Visitor) ([]Skip, int, error) { } most, own := opts.bound(lim) if most > 0 && h.Size > most { - skips = append(skips, tooLarge(abs, h.Size, most, own, lim.By, false)) + skips = append(skips, tooLarge(abs, h.Size, most, own, lim.Name, false)) continue } var rr io.Reader = tr @@ -313,7 +314,7 @@ func Tar(r io.Reader, opts Options, visit Visitor) ([]Skip, int, error) { } data := append(head, rest...) if most > 0 && int64(len(data)) > most { - skips = append(skips, tooLarge(abs, 0, most, own, lim.By, true)) + skips = append(skips, tooLarge(abs, 0, most, own, lim.Name, true)) continue } if err := visit(File{Path: abs, Data: data, Executable: exe}); err != nil { diff --git a/internal/source/source_test.go b/internal/source/source_test.go index c9db2a3..a923944 100644 --- a/internal/source/source_test.go +++ b/internal/source/source_test.go @@ -64,7 +64,7 @@ func FuzzTar(f *testing.F) { f.Fuzz(func(t *testing.T, data []byte) { Tar(bytes.NewReader(data), Options{MaxFileSize: 1 << 20}, func(File) error { return nil }) // With a reader's own limit, nothing larger is ever handed out. - limited := Options{MaxFileSize: 1 << 20, Read: func(string, []byte, bool) (bool, Limit) { return true, Limit{Bytes: 100, By: "t"} }} + limited := Options{MaxFileSize: 1 << 20, Read: func(string, []byte, bool) (bool, Limit) { return true, Limit{Bytes: 100, Name: "t"} }} Tar(bytes.NewReader(data), limited, func(f File) error { if len(f.Data) > 100 { t.Errorf("%s: %d bytes over a 100-byte limit", f.Path, len(f.Data)) @@ -83,9 +83,9 @@ func TestTarOwnLimit(t *testing.T) { MaxFileSize: 12, Read: func(p string, _ []byte, _ bool) (bool, Limit) { if p == "/big" { - return true, Limit{Bytes: 100, By: "t"} // above MaxFileSize: MaxFileSize applies + return true, Limit{Bytes: 100, Name: "t"} // above MaxFileSize: MaxFileSize applies } - return true, Limit{Bytes: 4, By: "java4shell"} + return true, Limit{Bytes: 4, Name: "the 4-byte limit of java4shell"} }, } skips, _, err := Tar(bytes.NewReader(data), opts, func(f File) error { read = append(read, f.Path); return nil }) @@ -110,7 +110,9 @@ func TestDirOwnLimit(t *testing.T) { t.Fatal(err) } var read []string - skips, n, err := Dir(root, Options{Read: func(string, []byte, bool) (bool, Limit) { return true, Limit{Bytes: 4096, By: "t"} }}, + skips, n, err := Dir(root, Options{Read: func(string, []byte, bool) (bool, Limit) { + return true, Limit{Bytes: 4096, Name: "the 4096-byte limit of t"} + }}, func(f File) error { read = append(read, f.Path); return nil }) if err != nil || n != 1 || len(read) != 0 || len(skips) != 1 || !skips[0].Excluded || skips[0].Reason != "excluded: larger than the 4096-byte limit of t for this file (5000 bytes)" { @@ -133,7 +135,7 @@ func TestTarOwnLimitNeverReads(t *testing.T) { var before, after runtime.MemStats runtime.GC() runtime.ReadMemStats(&before) - skips, _, err := Tar(pr, Options{MaxFileSize: 256 << 20, Read: func(string, []byte, bool) (bool, Limit) { return true, Limit{Bytes: 64 << 10, By: "t"} }}, + skips, _, err := Tar(pr, Options{MaxFileSize: 256 << 20, Read: func(string, []byte, bool) (bool, Limit) { return true, Limit{Bytes: 64 << 10, Name: "t"} }}, func(File) error { t.Error("visited"); return nil }) runtime.ReadMemStats(&after) if err != nil || len(skips) != 1 || !skips[0].Excluded { From e6b1ea2b295dbc5a29eaa2e983a4b2d6b429adfc Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 04:16:39 +0000 Subject: [PATCH 042/119] java4shell: test five-part and vendor patch versions on every path The OpenJDK advisory names 17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3 and 27.0.1.0.3 as the last affected releases, and Microsoft (.0.2), Debian sid and Temurin (27.0.1.0.2+1) ship five-part versions of them. They are already judged vulnerable from the VM library, the release file, OS packages, image tags, version files and setup-java; these tests keep it so. Co-Authored-By: Claude Opus 5.5 --- .../internal/assess/coverage_test.go | 68 +++++++++++++++++ .../internal/knowledge/coverage_test.go | 30 ++++++++ .../java4shell/internal/repo/coverage_test.go | 76 +++++++++++++++++++ 3 files changed, 174 insertions(+) create mode 100644 detectors/java4shell/internal/assess/coverage_test.go create mode 100644 detectors/java4shell/internal/knowledge/coverage_test.go create mode 100644 detectors/java4shell/internal/repo/coverage_test.go diff --git a/detectors/java4shell/internal/assess/coverage_test.go b/detectors/java4shell/internal/assess/coverage_test.go new file mode 100644 index 0000000..c7ba68a --- /dev/null +++ b/detectors/java4shell/internal/assess/coverage_test.go @@ -0,0 +1,68 @@ +package assess + +import ( + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" +) + +// fivePart are the last affected releases the OpenJDK advisory names and +// the vendor builds of them (Oracle, Debian sid, Microsoft, Temurin). +var fivePart = []string{ + "17.0.21.0.3+1-LTS", "21.0.13.0.3+1-LTS", "25.0.5.0.3+1-LTS", "27.0.1.0.3+1", + "17.0.21.0.2+1-LTS", "21.0.13.0.2+1-LTS", "25.0.5.0.2+1-LTS", "27.0.1.0.2+1", + "17.0.21.0.3+1-Debian-1", "27.0.1.0.3+1-Debian-1", +} + +func TestFivePartVMLibrary(t *testing.T) { + for _, v := range fivePart { + f := one(t, Input{Libraries: []*jvm.Library{lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{Version: v, VBMI: true})}}) + if f.Status != Vulnerable || f.VersionFrom != "vm-library" { + t.Errorf("%s: %s from %s (%s)", v, f.Status, f.VersionFrom, f.Reason) + } + } +} + +func TestFivePartReleaseFile(t *testing.T) { + for _, v := range fivePart { + // A VM library without a readable version line: the release file + // states the version, and a vulnerable one is reported. + f := one(t, Input{ + Libraries: []*jvm.Library{lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{VBMI: true})}, + Releases: map[string]jvm.Release{temurin: rel(t, "JAVA_VERSION", v[:len(v)-len(v[indexPlus(v):])], "JAVA_RUNTIME_VERSION", v)}, + }) + if f.Status != Vulnerable || f.VersionFrom != "release-file" { + t.Errorf("%s: %s from %s (%s)", v, f.Status, f.VersionFrom, f.Reason) + } + } +} + +func indexPlus(s string) int { + for i := range s { + if s[i] == '+' { + return i + } + } + return len(s) +} + +func TestFivePartPackages(t *testing.T) { + // The package that owns the runtime is named in the fix text; the + // verdict comes from the VM library whatever the package version says. + for _, c := range []struct { + root, lib string + owners map[string]Package + }{ + {"/usr/lib/jvm/java-17-openjdk-amd64", "17.0.21.0.3+1-Debian-1", map[string]Package{ + "/usr/lib/jvm/java-17-openjdk-amd64/lib/server/libjvm.so": {Manager: "dpkg", Name: "openjdk-17-jre-headless", Version: "17.0.21.0.3+1-1"}}}, + {"/usr/lib/jvm/java-21-openjdk", "21.0.13.0.3+1-alpine-r0", map[string]Package{ + "/usr/lib/jvm/java-21-openjdk/lib/server/libjvm.so": {Manager: "apk", Name: "openjdk21-jre-headless", Version: "21.0.13.0.3_p1-r0"}}}, + {"/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-1.el9.x86_64", "17.0.21+9-LTS", nil}, + } { + f := one(t, Input{Libraries: []*jvm.Library{lib(t, c.root+"/lib/server/libjvm.so", testlib.Lib{Version: c.lib, VBMI: true})}, Owners: c.owners}) + if f.Status != Vulnerable || f.Package == nil { + t.Errorf("%s: %s package %v (%s)", c.root, f.Status, f.Package, f.Reason) + } + } +} diff --git a/detectors/java4shell/internal/knowledge/coverage_test.go b/detectors/java4shell/internal/knowledge/coverage_test.go new file mode 100644 index 0000000..9a52285 --- /dev/null +++ b/detectors/java4shell/internal/knowledge/coverage_test.go @@ -0,0 +1,30 @@ +package knowledge + +import "testing" + +// The OpenJDK advisory of 2026-11-17 names 17.0.21.0.3, 21.0.13.0.3, +// 25.0.5.0.3 and 27.0.1.0.3 as the last affected releases; vendors ship +// five-part versions of them (Oracle, Debian sid, Microsoft's .0.2, +// Temurin's 27.0.1.0.2+1). Every one is vulnerable, however it is written. +func TestFivePartVersionsVulnerable(t *testing.T) { + for _, s := range []string{ + "17.0.21.0.3", "21.0.13.0.3", "25.0.5.0.3", "27.0.1.0.3", + "17.0.21.0.3+1-LTS", "21.0.13.0.3+1-LTS", "25.0.5.0.3+1-LTS", "27.0.1.0.3+1", + "17.0.21.0.2", "21.0.13.0.2", "25.0.5.0.2", + "17.0.21.0.2+1-LTS", "21.0.13.0.2+1-LTS", "25.0.5.0.2+1-LTS", + "27.0.1.0.2+1", "27.0.1.0.2+1-LTS", + "17.0.21.0.3+1-Debian-1", "21.0.13.0.3+1-Debian-1", "25.0.5.0.3+1-Debian-3", "27.0.1.0.3+1-Debian-1", + "17.0.21.0.3+1-Ubuntu-1ubuntu124.04.1", "21.0.13.0.3+1-alpine-r0", + // GraalVM's version line: the JDK version, then jvmci. + "17.0.21.0.3+1-LTS-jvmci-23.0-b99", "21.0.13.0.3+1-LTS-jvmci-23.1-b99", + } { + v, ok := Parse(s) + if !ok { + t.Errorf("Parse(%q) failed", s) + continue + } + if st, why := Judge(v); st != Vulnerable { + t.Errorf("Judge(%q) = %s (%s), want vulnerable", s, st, why) + } + } +} diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go new file mode 100644 index 0000000..255b1e9 --- /dev/null +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -0,0 +1,76 @@ +package repo + +import ( + "strings" + "testing" +) + +// The five-part releases the OpenJDK advisory names as the last affected +// (17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3) and the vendor builds +// of them (Microsoft's .0.2, Temurin's 27.0.1.0.2+1) are vulnerable in +// every place a tree can name them. +func TestFivePartRepo(t *testing.T) { + files := map[string]string{ + "Dockerfile.tags": strings.Join([]string{ + "FROM eclipse-temurin:27.0.1.0.2_1-jre", + "FROM eclipse-temurin:27.0.1.0-jre", + "FROM azul/zulu-openjdk:21.0.13.0.3-jre", + "FROM bellsoft/liberica-openjre-debian:21.0.13.0.3", + "FROM sapmachine:21.0.13.0.3-jre-ubuntu-noble", + "FROM mcr.microsoft.com/openjdk/jdk:17.0.21.0.2-ubuntu", + "FROM container-registry.oracle.com/java/jdk:25.0.5.0.3", + "FROM container-registry.oracle.com/java/openjdk:27.0.1.0.3", + }, "\n") + "\n", + "Dockerfile.pkgs": strings.Join([]string{ + "FROM debian:sid", + "RUN apt-get install -y openjdk-17-jre-headless=17.0.21.0.3+1-1", + "RUN apt-get install -y openjdk-25-jre-headless=25.0.5.0.3+1-3", + "RUN apk add openjdk21-jre-headless=21.0.13.0.3_p1-r0", + "RUN apk add openjdk25-jre-headless=25.0.5.0.3_p1-r1", + "RUN dnf install -y java-17-openjdk-headless-17.0.21.0.3-1.el9", + "RUN apt-get install -y msopenjdk-21=21.0.13.0.2-1", + "RUN apt-get install -y temurin-27-jdk=27.0.1.0.2+1", + }, "\n") + "\n", + ".java-version": "27.0.1.0.2\n", + "a/.java-version": "temurin64-27.0.1.0.2\n", + "b/.java-version": "oracle64-17.0.21.0.3\n", + ".sdkmanrc": "java=21.0.13.0.2-ms\n", + "c/.sdkmanrc": "java=25.0.5.0.3-oracle\n", + ".tool-versions": "java temurin-27.0.1.0.2+1\n", + "d/.tool-versions": "java microsoft-17.0.21.0.2\n", + "mise.toml": "[tools]\njava = \"oracle-25.0.5.0.3\"\n", + ".github/workflows/ci.yml": `on: push +jobs: + b: + runs-on: ubuntu-latest + steps: + - uses: actions/setup-java@v5 + with: + distribution: microsoft + java-version: 21.0.13.0.2 + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 27.0.1.0.2+1 +`, + } + res := scan(t, tree(t, files)) + want := map[string]int{"Dockerfile.tags": 8, "Dockerfile.pkgs": 7, ".java-version": 1, "a/.java-version": 1, "b/.java-version": 1, + ".sdkmanrc": 1, "c/.sdkmanrc": 1, ".tool-versions": 1, "d/.tool-versions": 1, "mise.toml": 1, ".github/workflows/ci.yml": 2} + got := map[string]int{} + for _, f := range res.Findings { + if f.Status != StatusVulnerable { + t.Errorf("%s:%d %s %s: %s", f.File, f.Line, f.Rule, f.Status, f.Reason) + continue + } + got[f.File]++ + } + for file, n := range want { + if got[file] != n { + t.Errorf("%s: %d vulnerable findings, want %d", file, got[file], n) + } + } + for _, s := range res.Skips { + t.Logf("skip %+v", s) + } +} From d919f43c8651938b5c226f27fed2ff3faefff69c Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 04:16:47 +0000 Subject: [PATCH 043/119] java4shell: gofmt the five-part tests Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/assess/coverage_test.go | 2 +- .../java4shell/internal/repo/coverage_test.go | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/detectors/java4shell/internal/assess/coverage_test.go b/detectors/java4shell/internal/assess/coverage_test.go index c7ba68a..e463cf0 100644 --- a/detectors/java4shell/internal/assess/coverage_test.go +++ b/detectors/java4shell/internal/assess/coverage_test.go @@ -52,7 +52,7 @@ func TestFivePartPackages(t *testing.T) { // verdict comes from the VM library whatever the package version says. for _, c := range []struct { root, lib string - owners map[string]Package + owners map[string]Package }{ {"/usr/lib/jvm/java-17-openjdk-amd64", "17.0.21.0.3+1-Debian-1", map[string]Package{ "/usr/lib/jvm/java-17-openjdk-amd64/lib/server/libjvm.so": {Manager: "dpkg", Name: "openjdk-17-jre-headless", Version: "17.0.21.0.3+1-1"}}}, diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index 255b1e9..503da39 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -31,14 +31,14 @@ func TestFivePartRepo(t *testing.T) { "RUN apt-get install -y msopenjdk-21=21.0.13.0.2-1", "RUN apt-get install -y temurin-27-jdk=27.0.1.0.2+1", }, "\n") + "\n", - ".java-version": "27.0.1.0.2\n", - "a/.java-version": "temurin64-27.0.1.0.2\n", - "b/.java-version": "oracle64-17.0.21.0.3\n", - ".sdkmanrc": "java=21.0.13.0.2-ms\n", - "c/.sdkmanrc": "java=25.0.5.0.3-oracle\n", - ".tool-versions": "java temurin-27.0.1.0.2+1\n", + ".java-version": "27.0.1.0.2\n", + "a/.java-version": "temurin64-27.0.1.0.2\n", + "b/.java-version": "oracle64-17.0.21.0.3\n", + ".sdkmanrc": "java=21.0.13.0.2-ms\n", + "c/.sdkmanrc": "java=25.0.5.0.3-oracle\n", + ".tool-versions": "java temurin-27.0.1.0.2+1\n", "d/.tool-versions": "java microsoft-17.0.21.0.2\n", - "mise.toml": "[tools]\njava = \"oracle-25.0.5.0.3\"\n", + "mise.toml": "[tools]\njava = \"oracle-25.0.5.0.3\"\n", ".github/workflows/ci.yml": `on: push jobs: b: From 2e9c7faa5291b6cde149fc4e46e07051536103af Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 04:20:54 +0000 Subject: [PATCH 044/119] java4shell: judge GraalVM as GraalVM Oracle's November 2026 CSPU names Oracle GraalVM for JDK 17.0.21.0.3 and 21.0.13.0.3 and GraalVM Enterprise Edition 21.3.20.0.3 as affected. A GraalVM JDK is HotSpot with JVMCI: its version line is the JDK's with -jvmci- (read from GraalVM CE images: 22.3.0/Java 17 is 17.0.5 without the decoder stubs, 22.3.1/Java 17 is 17.0.6 with them, 22.3.1/Java 11 has none, 23.1.2/Java 21 is 21.0.2 with them). - knowledge: JudgeGraalVM is vulnerable wherever the OpenJDK release is, and fixed only at a build listed in GraalVMFixed, which is empty: no fixed GraalVM build was known. A GraalVM Java 8 or 11 VM library that carries the decoder is vulnerable (GraalVM EE 21.3 is listed). JudgeGraalVMRelease judges GraalVM's own numbers with the Java line. - assess: a jvmci version line or a release file with GRAALVM_VERSION marks the runtime as GraalVM; the fix text and facts say so, and fixed_in (OpenJDK's) is not given for it. - repo: sdkman 22.3.1.r17-grl, asdf graalvm-22.3.1+java17 and mandrel names are judged (22.3.0 for 17, and 8/11, not affected; 22.3.1 and later for 17, and any GraalVM for 18 and later, vulnerable; 22.3.r17 stays not checked). JDK-numbered GraalVM names and the Oracle GraalVM and GraalVM Community images are vulnerable where the JDK is and not checked (pulled) otherwise, with no tag edit. - The release data date moves to 2026-11-18, when vendor status was rechecked. Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/assess/assess.go | 17 ++- .../internal/assess/coverage_test.go | 37 +++++ .../internal/knowledge/coverage_test.go | 66 +++++++++ .../java4shell/internal/knowledge/graalvm.go | 115 +++++++++++++++ .../internal/knowledge/knowledge.go | 2 +- .../java4shell/internal/repo/coverage_test.go | 62 ++++++++ detectors/java4shell/internal/repo/graalvm.go | 132 ++++++++++++++++++ detectors/java4shell/internal/repo/images.go | 11 ++ detectors/java4shell/internal/repo/refscan.go | 14 ++ detectors/java4shell/internal/repo/repo.go | 19 ++- detectors/java4shell/java4shell.go | 5 +- 11 files changed, 474 insertions(+), 6 deletions(-) create mode 100644 detectors/java4shell/internal/knowledge/graalvm.go create mode 100644 detectors/java4shell/internal/repo/graalvm.go diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index 8788525..664382b 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -58,6 +58,9 @@ type Finding struct { Mitigation string `json:"mitigation,omitempty"` MitigatedFor []string `json:"mitigated_for,omitempty"` // partial mitigations (one service) Release knowledge.Status `json:"release_status,omitempty"` + // GraalVM is a GraalVM JDK (HotSpot with JVMCI): fixed only at a + // published fixed GraalVM build. + GraalVM bool `json:"graalvm,omitempty"` } // Input is everything one target gives. @@ -188,6 +191,8 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi } } f.VM = lib.VMName + f.GraalVM = knowledge.IsGraalVM(lib.JREVersion) || knowledge.IsGraalVM(lib.VMVersion) || + hasRel && (rel["GRAALVM_VERSION"] != "" || knowledge.IsGraalVM(rel.Version())) if openj9 { f.VM = "OpenJ9" } @@ -218,7 +223,11 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi } return f.set(Unknown, why, what+": Java version unknown") } - ks, kwhy := knowledge.Judge(v) + judgeVersion, judgeBackport := knowledge.Judge, knowledge.JudgeBackport + if f.GraalVM { + judgeVersion, judgeBackport = knowledge.JudgeGraalVM, knowledge.JudgeBackportGraalVM + } + ks, kwhy := judgeVersion(v) f.Release = ks read := lib.HotSpot() // the stub names are only meaningful in a HotSpot library that was read if !read && ks != knowledge.Vulnerable { @@ -233,7 +242,7 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi switch ks { case knowledge.NotAffected: if read && lib.VBMIStubs { - bs, bwhy := knowledge.JudgeBackport(v) + bs, bwhy := judgeBackport(v) f.Release = bs if bs == knowledge.Vulnerable { if ok, how := mitigation(in, env, root, v.Feature(), &f); ok { @@ -515,7 +524,9 @@ func fixText(f Finding, v knowledge.Version, ok bool) string { interim = " The JVM options keep the vulnerable decoder from running until then; keep them until it is updated." } target := "a Java release with the fix (17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later on the same update)" - if ok && v.Feature() < 17 { + if f.GraalVM { + target = fmt.Sprintf("a GraalVM build with the fix once Oracle or the GraalVM project publishes one (none had been as of %s), or a JDK release with the fix (17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1)", knowledge.Checked) + } else if ok && v.Feature() < 17 { // A backported decoder (Oracle's Java 8 Performance Pack). target = fmt.Sprintf("a build of Java %d from the same vendor with the fix (none was known on %s), or one without the backported AVX-512 decoder", v.Feature(), knowledge.Checked) } else if ok { diff --git a/detectors/java4shell/internal/assess/coverage_test.go b/detectors/java4shell/internal/assess/coverage_test.go index e463cf0..74f97b6 100644 --- a/detectors/java4shell/internal/assess/coverage_test.go +++ b/detectors/java4shell/internal/assess/coverage_test.go @@ -1,6 +1,7 @@ package assess import ( + "strings" "testing" "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" @@ -66,3 +67,39 @@ func TestFivePartPackages(t *testing.T) { } } } + +func TestGraalVMRuntime(t *testing.T) { + const home = "/opt/graalvm" + for _, c := range []struct { + name string + lib testlib.Lib + release []string + want Status + }{ + // Version lines read from GraalVM CE images (findepi/graalvm). + {"CE 22.3.0 for Java 17", testlib.Lib{Version: "17.0.5+8-jvmci-22.3-b08"}, nil, NotAffected}, + {"CE 22.3.1 for Java 17", testlib.Lib{Version: "17.0.6+10-jvmci-22.3-b13", VBMI: true}, nil, Vulnerable}, + {"CE 22.3.1 for Java 11", testlib.Lib{Version: "11.0.18+10-jvmci-22.3-b13"}, nil, NotAffected}, + {"CE for JDK 21 (23.1.2)", testlib.Lib{Version: "21.0.2+13-jvmci-23.1-b30", VBMI: true}, nil, Vulnerable}, + {"Oracle GraalVM for JDK 17.0.21.0.3", testlib.Lib{VMName: "Java HotSpot(TM) 64-Bit Server VM", Version: "17.0.21.0.3+1-LTS-jvmci-23.0-b99", VBMI: true}, nil, Vulnerable}, + {"Oracle GraalVM for JDK 21.0.13.0.3", testlib.Lib{VMName: "Java HotSpot(TM) 64-Bit Server VM", Version: "21.0.13.0.3+1-LTS-jvmci-23.1-b99", VBMI: true}, nil, Vulnerable}, + {"GraalVM EE 21.3 for Java 11 carrying the decoder", testlib.Lib{VMName: "Java HotSpot(TM) 64-Bit Server VM", Version: "11.0.33+8-LTS-jvmci-21.3-b99", VBMI: true}, nil, Vulnerable}, + {"GraalVM EE 21.3 for Java 17", testlib.Lib{VMName: "Java HotSpot(TM) 64-Bit Server VM", Version: "17.0.21+8-LTS-jvmci-21.3-b99", VBMI: true}, nil, Vulnerable}, + // Past the OpenJDK fix, but no fixed GraalVM build is known. + {"GraalVM at the OpenJDK fixed release", testlib.Lib{Version: "21.0.13.1+2-jvmci-23.1-b99", VBMI: true}, nil, Unknown}, + {"GraalVM named by its release file only", testlib.Lib{Version: "25.0.5.1+2-LTS", VBMI: true}, []string{"JAVA_VERSION", "25.0.5.1", "GRAALVM_VERSION", "25.0.5.1", "IMPLEMENTOR", "GraalVM Community"}, Unknown}, + } { + in := Input{Libraries: []*jvm.Library{lib(t, home+"/lib/server/libjvm.so", c.lib)}} + if c.release != nil { + in.Releases = map[string]jvm.Release{home: rel(t, c.release...)} + } + f := one(t, in) + if f.Status != c.want || !f.GraalVM { + t.Errorf("%s: %s graalvm %v (%s)", c.name, f.Status, f.GraalVM, f.Reason) + continue + } + if c.want != NotAffected && (!strings.Contains(f.Reason, "GraalVM") || !strings.Contains(f.Fix, "GraalVM")) { + t.Errorf("%s: reason or fix does not name GraalVM:\n%s\n%s", c.name, f.Reason, f.Fix) + } + } +} diff --git a/detectors/java4shell/internal/knowledge/coverage_test.go b/detectors/java4shell/internal/knowledge/coverage_test.go index 9a52285..ec01126 100644 --- a/detectors/java4shell/internal/knowledge/coverage_test.go +++ b/detectors/java4shell/internal/knowledge/coverage_test.go @@ -28,3 +28,69 @@ func TestFivePartVersionsVulnerable(t *testing.T) { } } } + +func TestGraalVM(t *testing.T) { + if !IsGraalVM("17.0.6+10-jvmci-22.3-b13") || IsGraalVM("21.0.13+9-LTS") { + t.Fatal("IsGraalVM") + } + for _, c := range []struct { + v string + want Status + }{ + {"17.0.5+8-jvmci-22.3-b08", NotAffected}, // GraalVM CE 22.3.0 + {"17.0.6+10-jvmci-22.3-b13", Vulnerable}, // GraalVM CE 22.3.1 + {"21.0.2+13-jvmci-23.1-b30", Vulnerable}, // GraalVM CE for JDK 21 (23.1.2) + {"17.0.21.0.3+1-LTS-jvmci-23.0-b99", Vulnerable}, + {"21.0.13.0.3+1-LTS-jvmci-23.1-b99", Vulnerable}, + // At or past the OpenJDK fix, but no fixed GraalVM build is known. + {"21.0.13.1+2-LTS-jvmci-23.1-b99", Unknown}, + {"25.0.5.1+2-LTS-jvmci-b01", Unknown}, + {"11.0.33+8-LTS-jvmci-21.3-b99", NotAffected}, + } { + v, _ := Parse(c.v) + if st, why := JudgeGraalVM(v); st != c.want || why == "" { + t.Errorf("JudgeGraalVM(%s) = %s (%s), want %s", c.v, st, why, c.want) + } + } + // A published fixed GraalVM build, once listed, clears later builds. + saved := GraalVMFixed + t.Cleanup(func() { GraalVMFixed = saved }) + GraalVMFixed = map[int]Build{21: {Version: []int{21, 0, 13, 1}, Build: 2}} + for v, want := range map[string]Status{"21.0.13.1+2-LTS-jvmci-23.1-b99": Fixed, "21.0.13.1+1-LTS-jvmci-23.1-b99": Vulnerable, "21.0.13.0.3+1-LTS-jvmci-23.1-b99": Vulnerable} { + p, _ := Parse(v) + if st, why := JudgeGraalVM(p); st != want { + t.Errorf("with a fixed build listed, JudgeGraalVM(%s) = %s (%s), want %s", v, st, why, want) + } + } + // A GraalVM build of Java 11 whose VM library carries the decoder: + // Oracle names GraalVM Enterprise 21.3.20.0.3 as affected. + v, _ := Parse("11.0.33+8-LTS-jvmci-21.3-b99") + if st, why := JudgeBackportGraalVM(v); st != Vulnerable { + t.Errorf("GraalVM 11 backport: %s (%s)", st, why) + } +} + +func TestGraalVMRelease(t *testing.T) { + for _, c := range []struct { + graal string + java int + want Status + }{ + {"22.3.0", 17, NotAffected}, // built on 17.0.5 + {"22.3.1", 17, Vulnerable}, // built on 17.0.6 + {"22.3.3", 17, Vulnerable}, + {"23.0.1", 17, Vulnerable}, + {"22.3", 17, Unknown}, // 22.3.0 or a later patch + {"21.3.5", 17, Unknown}, + {"22.3.1", 11, NotAffected}, + {"21.3.0", 8, NotAffected}, + {"22.3.1", 19, Vulnerable}, + {"23.1.2", 21, Vulnerable}, + {"22.3.1", 16, NotAffected}, + {"22.3.1", 30, Unknown}, + } { + if st, why := JudgeGraalVMRelease(c.graal, c.java); st != c.want || why == "" { + t.Errorf("JudgeGraalVMRelease(%s, %d) = %s (%s), want %s", c.graal, c.java, st, why, c.want) + } + } +} diff --git a/detectors/java4shell/internal/knowledge/graalvm.go b/detectors/java4shell/internal/knowledge/graalvm.go new file mode 100644 index 0000000..96b0e10 --- /dev/null +++ b/detectors/java4shell/internal/knowledge/graalvm.go @@ -0,0 +1,115 @@ +package knowledge + +import ( + "fmt" + "strings" +) + +// GraalVM: Oracle's Critical Security Patch Update of November 2026 names +// Oracle GraalVM for JDK 17.0.21.0.3 and 21.0.13.0.3 and GraalVM Enterprise +// Edition 21.3.20.0.3 as affected. A GraalVM JDK is HotSpot with JVMCI, so +// its VM library has the same decoder; its version line is the JDK's with +// "-jvmci-" in it (17.0.6+10-jvmci-22.3-b13). Oracle's and the GraalVM +// project's fixed builds are numbered their own way, so a GraalVM build is +// judged fixed only at a fixed GraalVM build listed here. FACTS.md gives +// the sources. + +// Build is a release and the first build of it that has the fix. +type Build struct { + Version []int + Build int // -1: every build of Version +} + +// GraalVMFixed is, per Java line, the first GraalVM build with the fix. +// Empty: no fixed GraalVM build had been published as of Checked. +var GraalVMFixed = map[int]Build{} + +// graalVMAffected names what Oracle lists, for reasons. +const graalVMAffected = "Oracle names GraalVM for JDK 17.0.21.0.3 and 21.0.13.0.3 and GraalVM Enterprise Edition 21.3.20.0.3 as affected" + +// IsGraalVM reports a GraalVM version string: the JDK version with JVMCI +// ("17.0.6+10-jvmci-22.3-b13", "21.0.5+9-LTS-jvmci-23.1-b48"). +func IsGraalVM(version string) bool { return strings.Contains(version, "-jvmci-") } + +// JudgeGraalVM judges a GraalVM build by its JDK version. It is vulnerable +// wherever the OpenJDK release would be; it is fixed only at or past a +// fixed GraalVM build listed in GraalVMFixed. +func JudgeGraalVM(v Version) (Status, string) { + st, why := Judge(v) + switch st { + case NotAffected: + return st, why + case Vulnerable: + return st, "GraalVM: " + why + "; " + graalVMAffected + } + fx, ok := GraalVMFixed[v.Feature()] + if ok && !v.EA { + c := Compare(v.Nums, fx.Version) + // A version without its build is taken as the GA build, as for OpenJDK. + if c < 0 || c == 0 && fx.Build >= 0 && v.Build >= 0 && v.Build < fx.Build { + return Vulnerable, fmt.Sprintf("GraalVM build of Java %s, older than the first fixed GraalVM build (%s)", v, buildName(fx)) + } + return Fixed, fmt.Sprintf("GraalVM build of Java %s, at or past the first fixed GraalVM build (%s)", v, buildName(fx)) + } + return Unknown, fmt.Sprintf("GraalVM build of Java %s: %s, and no fixed GraalVM build had been published as of %s, so its OpenJDK version does not show whether it has the fix (%s)", v, graalVMAffected, Checked, BugRef) +} + +func buildName(b Build) string { + if b.Build < 0 { + return join(b.Version) + } + return fmt.Sprintf("%s+%d", join(b.Version), b.Build) +} + +// JudgeBackportGraalVM judges a GraalVM build of a line without the +// decoder (Java 8 or 11) whose VM library carries it anyway. +func JudgeBackportGraalVM(v Version) (Status, string) { + return Vulnerable, fmt.Sprintf("GraalVM build of Java %s whose VM library carries the AVX-512 VBMI Base64 decoder: %s, and no fixed GraalVM build had been published as of %s", v, graalVMAffected, Checked) +} + +// GraalVM releases numbered the GraalVM way (22.3.1 for Java 17), as +// version managers name them (sdkman 22.3.1.r17-grl, asdf +// graalvm-22.3.1+java17): which JDK update they are built on, read from +// the releases themselves (FACTS.md). +var ( + // graalVM17Without is the last GraalVM release for Java 17 built on an + // update without the decoder (22.3.0: 17.0.5); graalVM17With the first + // built on one with it (22.3.1: 17.0.6). Later GraalVM releases are + // built on later updates. + graalVM17Without = []int{22, 3, 0} + graalVM17With = []int{22, 3, 1} +) + +// JudgeGraalVMRelease judges a GraalVM release named by GraalVM's own +// number and the Java line it is built for. +func JudgeGraalVMRelease(graal string, java int) (Status, string) { + g, ok := Parse(graal) + nums := g.Nums + if !ok { + nums = nil + for _, p := range strings.Split(graal, ".") { + n, r := leadingInt(p) + if n < 0 || r != "" { + return Unknown, fmt.Sprintf("GraalVM %s for Java %d: the GraalVM version could not be read", graal, java) + } + nums = append(nums, n) + } + } + name := fmt.Sprintf("GraalVM %s for Java %d", graal, java) + switch { + case java < firstVBMIDecode: + return NotAffected, fmt.Sprintf("%s is built on OpenJDK %d, which has no x86-64 Base64 decode intrinsic (the Java 11 build of GraalVM 22.3.1 carries no decoder stubs)", name, java) + case java >= newestFeature: + return Unknown, fmt.Sprintf("%s: Java %d is newer than this detector's release data (%s)", name, java, Checked) + case java > firstVBMIDecode: + // Every release of Java 18 and later has the decoder. + return Vulnerable, fmt.Sprintf("%s: every Java %d release has the AVX-512 VBMI Base64 decoder; %s, and no fixed GraalVM build had been published as of %s", name, java, graalVMAffected, Checked) + } + if len(nums) >= 3 && Compare(nums, graalVM17Without) == 0 { + return NotAffected, fmt.Sprintf("%s is built on Java 17.0.5, which predates the AVX-512 VBMI Base64 decoder (17.0.6)", name) + } + if len(nums) >= 3 && Compare(nums, graalVM17With) >= 0 || len(nums) >= 2 && Compare(nums[:2], []int{22, 3}) > 0 { + return Vulnerable, fmt.Sprintf("%s is built on Java 17.0.6 or later (GraalVM 22.3.1 is 17.0.6), which has the AVX-512 VBMI Base64 decoder; %s, and no fixed GraalVM build had been published as of %s", name, graalVMAffected, Checked) + } + return Unknown, fmt.Sprintf("%s: GraalVM 22.3.0 is built on Java 17.0.5 (before the decoder) and 22.3.1 and later on 17.0.6 and later (with it); which Java 17 update this release is built on is not known", name) +} diff --git a/detectors/java4shell/internal/knowledge/knowledge.go b/detectors/java4shell/internal/knowledge/knowledge.go index 81fa877..53315d8 100644 --- a/detectors/java4shell/internal/knowledge/knowledge.go +++ b/detectors/java4shell/internal/knowledge/knowledge.go @@ -23,7 +23,7 @@ const BugRef = "JDK-8393212, inferred to be this CVE's fix" // Checked is the date the release data was last checked: every "as of" // statement (a vendor or distribution had not published a fix) is as of // this date. -const Checked = "2026-11-17" +const Checked = "2026-11-18" // Dates the release data rests on. const ( diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index 503da39..6afff65 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -74,3 +74,65 @@ jobs: t.Logf("skip %+v", s) } } + +func TestGraalVMRepo(t *testing.T) { + root := tree(t, map[string]string{ + "a/.sdkmanrc": "java=22.3.1.r17-grl\n", + "b/.sdkmanrc": "java=22.3.0.r17-grl\n", + "c/.sdkmanrc": "java=22.3.r17-grl\n", + "d/.sdkmanrc": "java=22.3.1.r19-grl\n", + "e/.sdkmanrc": "java=22.3.1.r11-grl\n", + "f/.sdkmanrc": "java=21.0.13.1-graal\n", + "g/.sdkmanrc": "java=21.0.13-graal\n", + "h/.sdkmanrc": "java=21.0.2-graalce\n", + "i/.sdkmanrc": "java=23.1.5.r21-mandrel\n", + "j/.sdkmanrc": "java=25.0.5.1-graalce\n", + "a/.tool-versions": "java graalvm-22.3.1+java17\n", + "b/.tool-versions": "java oracle-graalvm-21.0.13.1\n", + "c/.tool-versions": "java graalvm-community-17.0.9\n", + "d/.tool-versions": "java graalvm-22.3.0+java11\n", + "Dockerfile": strings.Join([]string{ + "FROM container-registry.oracle.com/graalvm/jdk:21.0.13", + "FROM container-registry.oracle.com/graalvm/jdk:21.0.13.1", + "FROM container-registry.oracle.com/graalvm/jdk:21", + "FROM ghcr.io/graalvm/jdk-community:21.0.2", + "FROM ghcr.io/graalvm/native-image-community:17.0.9-ol9", + "FROM container-registry.oracle.com/graalvm/native-image:17.0.21.0.3", + "FROM ghcr.io/graalvm/graalvm-ce:22.3.3", + }, "\n") + "\n", + }) + res := scan(t, root) + checkAll(t, res, []want{ + {"a/.sdkmanrc", 1, RuleJavaPin, StatusVulnerable}, + {"c/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {"d/.sdkmanrc", 1, RuleLine, StatusVulnerable}, + {"f/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {"g/.sdkmanrc", 1, RuleJavaPin, StatusVulnerable}, + {"h/.sdkmanrc", 1, RuleJavaPin, StatusVulnerable}, + {"i/.sdkmanrc", 1, RuleJavaPin, StatusVulnerable}, + {"j/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {"a/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"b/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"c/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"Dockerfile", 1, RuleImagePin, StatusVulnerable}, + {"Dockerfile", 2, RuleNotChecked, StatusUnknown}, + {"Dockerfile", 3, RuleNotChecked, StatusUnknown}, + {"Dockerfile", 4, RuleImagePin, StatusVulnerable}, + {"Dockerfile", 5, RuleImagePin, StatusVulnerable}, + {"Dockerfile", 6, RuleImagePin, StatusVulnerable}, + {"Dockerfile", 7, RuleNotChecked, StatusUnknown}, + }) + for _, file := range []string{"b/.sdkmanrc", "e/.sdkmanrc", "d/.tool-versions"} { + if f, ok := find(res, file, 1); ok { + t.Errorf("%s: GraalVM for a release without the decoder reported: %+v", file, f) + } + } + for _, f := range res.Findings { + if f.Status == StatusVulnerable && (!strings.Contains(f.Reason+f.Fix, "GraalVM") || f.Fixable) { + t.Errorf("%s:%d: a GraalVM finding must name GraalVM and not offer an edit: %+v", f.File, f.Line, f) + } + if f.Rule == RuleNotChecked && f.File == "Dockerfile" && f.Pull == "" { + t.Errorf("Dockerfile:%d: an unknown image is not pulled", f.Line) + } + } +} diff --git a/detectors/java4shell/internal/repo/graalvm.go b/detectors/java4shell/internal/repo/graalvm.go new file mode 100644 index 0000000..87d4f57 --- /dev/null +++ b/detectors/java4shell/internal/repo/graalvm.go @@ -0,0 +1,132 @@ +package repo + +import ( + "fmt" + "regexp" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" + "github.com/DefectDojo/earlylight/internal/refs" +) + +// graalVendors are the version-manager names of GraalVM distributions: +// GraalVM itself and the native-image kits built on it (Liberica NIK, +// Mandrel), whose JDK is HotSpot with the same decoder. +var graalVendors = map[string]bool{"grl": true, "graal": true, "graalce": true, "nik": true, "mandrel": true, + "graalvm": true, "graalvm-community": true, "oracle-graalvm": true, + "GraalVM CE": true, "Oracle GraalVM": true, "Liberica NIK": true, "Mandrel": true} + +func isGraal(vendor string) bool { return graalVendors[vendor] } + +// graalRelease is a GraalVM release in GraalVM's own numbers with the Java +// line it is for: sdkman 22.3.1.r17, asdf graalvm-22.3.1+java17, mandrel +// 22.3.1.0-Final+java17. +var ( + sdkmanGraal = regexp.MustCompile(`^(\d{1,3}(?:\.\d{1,9}){1,4})\.r(\d{1,2})$`) + javaLine = regexp.MustCompile(`java(\d{1,2})\b`) + graalNums = regexp.MustCompile(`\d{1,3}(?:\.\d{1,9}){1,4}`) +) + +// graalTag judges a GraalVM image tag: vulnerable where the OpenJDK +// release would be, and otherwise unknown until a fixed GraalVM build is +// known (the image has to be read). +func graalTag(tv TagVersion, st knowledge.Status, why string) (knowledge.Status, string) { + switch st { + case knowledge.Vulnerable: + return st, "GraalVM: " + why + case knowledge.NotAffected: + return st, why + } + if tv.Exact || len(tv.Nums) >= 3 { + // No fixed GraalVM build is known, so the newest release a tag + // such as 21.0.13 names is not fixed either. + gs, gwhy := knowledge.JudgeGraalVM(knowledge.Version{Nums: tv.Nums, Build: tv.OpenJDKBuild}) + return gs, "the tag names Java " + tv.Text + ": " + gwhy + } + return knowledge.Unknown, why +} + +// graalFix is what to do about a GraalVM release without the fix that +// where (a version file; "" for an image) selects. +func graalFix(feature int, where string) string { + alt := "use a JDK release with the fix (17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1) from a vendor that has published one" + if l, ok := knowledge.LineOf(feature); ok && l.Fixed == nil { + alt = fmt.Sprintf("move to a supported Java release with the fix, such as %s (Java %d received none)", knowledge.Upgrade(feature), feature) + } + what := "Select a GraalVM release with the fix in " + where + if where == "" { + what = "Move to a GraalVM image with the fix" + } + return fmt.Sprintf("%s once Oracle or the GraalVM project publishes one (none had been as of %s), or %s. Until then run Java with -XX:-UseBASE64Intrinsics (for example JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics).", what, knowledge.Checked, alt) +} + +// graalOwn judges a GraalVM release written in GraalVM's own numbers; +// value is the text as written. +func (s *scanner) graalOwn(rel string, line int, graal string, java int, value, source string) { + st, why := knowledge.JudgeGraalVMRelease(graal, java) + props := map[string]string{"source": source, "current": refs.CleanText(value, 80), "graalvm": graal} + switch st { + case knowledge.NotAffected: + return + case knowledge.Vulnerable: + rule, level := RuleJavaPin, "warning" + msg := fmt.Sprintf("%s selects %s (GraalVM %s for Java %d), without the Java4Shell fix", source, refs.CleanText(value, 80), graal, java) + if l, ok := knowledge.LineOf(java); ok && l.Fixed == nil { + rule, level = RuleLine, "error" + msg = fmt.Sprintf("%s selects %s (GraalVM %s for Java %d), a line that received no Java4Shell fix", source, refs.CleanText(value, 80), graal, java) + } + s.add(Finding{Rule: rule, File: rel, Line: line, Level: level, Status: StatusVulnerable, Reason: why, Message: msg, + Fix: graalFix(java, source), Props: props}) + return + } + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, Reason: why, + Message: fmt.Sprintf("%s selects %s, written in GraalVM's own version numbers: not checked for the Java4Shell fix", source, refs.CleanText(value, 80)), + Fix: "Check which Java update this GraalVM release is built on; no fixed GraalVM build had been published as of " + knowledge.Checked + ".", + Props: props}) +} + +// graalVersion handles a GraalVM release named by its JDK version +// (sdkman 21.0.5-graal, asdf oracle-graalvm-21.0.5) once judgeVersion has +// judged it as a JDK: a fixed or unknown verdict becomes not checked, since +// no fixed GraalVM build is known; a vulnerable one names GraalVM. +func (s *scanner) graalVersion(rel string, line int, tv TagVersion, st knowledge.Status, why, source string, props map[string]string) { + verText := tv.Text + switch st { + case knowledge.NotAffected: + return + case knowledge.Vulnerable: + rule, level := RuleJavaPin, "warning" + msg := fmt.Sprintf("%s selects GraalVM for Java %s, without the Java4Shell fix", source, verText) + if l, ok := knowledge.LineOf(tv.Nums[0]); ok && l.Fixed == nil && tv.Nums[0] > 17 { + rule, level = RuleLine, "error" + msg = fmt.Sprintf("%s selects GraalVM for Java %s, a line that received no Java4Shell fix", source, verText) + } + s.add(Finding{Rule: rule, File: rel, Line: line, Level: level, Status: StatusVulnerable, Reason: "GraalVM: " + why, Message: msg, + Fix: graalFix(tv.Nums[0], source), Props: props}) + return + } + gwhy := why + "; no fixed GraalVM build had been published as of " + knowledge.Checked + if tv.Exact { + _, gwhy = knowledge.JudgeGraalVM(knowledge.Version{Nums: tv.Nums, Build: -1}) + } + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, Reason: gwhy, + Message: fmt.Sprintf("%s selects GraalVM for Java %s: not checked for the Java4Shell fix", source, verText), + Fix: "Check that this GraalVM release includes the fix; no fixed GraalVM build had been published as of " + knowledge.Checked + ".", + Props: props}) +} + +// graalNamed reads a GraalVM release in its own numbers from a version +// manager's name, with the Java line: ok is false when it names none. +func graalNamed(value string) (graal string, java int, ok bool) { + if m := sdkmanGraal.FindStringSubmatch(value); m != nil { + return m[1], atoi(m[2]), true + } + j := javaLine.FindStringSubmatchIndex(value) + if j == nil { + return "", 0, false + } + g := graalNums.FindString(value[:j[0]] + " " + value[j[1]:]) + if g == "" { + return "", 0, false + } + return g, atoi(value[j[2]:j[3]]), true +} diff --git a/detectors/java4shell/internal/repo/images.go b/detectors/java4shell/internal/repo/images.go index 5f310db..002b002 100644 --- a/detectors/java4shell/internal/repo/images.go +++ b/detectors/java4shell/internal/repo/images.go @@ -21,6 +21,9 @@ type Family struct { // OpenJDKBuild is true when the build in the tag is OpenJDK's build // number (Temurin's "_9"); other vendors' tag builds are their own. OpenJDKBuild bool + // GraalVM images hold a GraalVM JDK: fixed only at a published fixed + // GraalVM build, and never edited to another tag. + GraalVM bool // exact reports whether the text after the version pins one release // (Temurin's "_9", Liberica's "-10", Zulu's "-21.52"), so the version // has no further numbers. @@ -53,6 +56,14 @@ var Families = []Family{ {Repo: "mcr.microsoft.com/openjdk/jdk", Vendor: "Microsoft Build of OpenJDK"}, {Repo: "container-registry.oracle.com/java/openjdk", Vendor: "Oracle OpenJDK"}, {Repo: "container-registry.oracle.com/java/jdk", Vendor: "Oracle JDK"}, + // GraalVM images whose tags are the JDK version (21, 21.0.5, 21.0.5-ol9). + // ghcr.io/graalvm/jdk and graalvm-ce are left out: their tags have + // been GraalVM's own numbers (22.3.3). + {Repo: "container-registry.oracle.com/graalvm/jdk", Vendor: "Oracle GraalVM", GraalVM: true}, + {Repo: "container-registry.oracle.com/graalvm/native-image", Vendor: "Oracle GraalVM", GraalVM: true}, + {Repo: "ghcr.io/graalvm/jdk-community", Vendor: "GraalVM Community", GraalVM: true}, + {Repo: "ghcr.io/graalvm/native-image-community", Vendor: "GraalVM Community", GraalVM: true}, + {Repo: "ghcr.io/graalvm/graalvm-community", Vendor: "GraalVM Community", GraalVM: true}, {Repo: "ibm-semeru-runtimes", Vendor: "IBM Semeru", OpenJ9: true, Prefix: "open-"}, {Repo: "ibmjava", Vendor: "IBM Java", OpenJ9: true}, {Repo: "icr.io/appcafe/ibm-semeru-runtimes", Vendor: "IBM Semeru", OpenJ9: true, Prefix: "open-"}, diff --git a/detectors/java4shell/internal/repo/refscan.go b/detectors/java4shell/internal/repo/refscan.go index ca665ed..351d6cb 100644 --- a/detectors/java4shell/internal/repo/refscan.go +++ b/detectors/java4shell/internal/repo/refscan.go @@ -78,6 +78,9 @@ func (s *scanner) judgeRef(r refs.Ref, opts Options) { } props["current"] = tv.Text st, why := JudgeTag(tv) + if fam.GraalVM { + st, why = graalTag(tv, st, why) + } switch st { case knowledge.Unknown: s.add(Finding{Rule: RuleNotChecked, File: r.File, Line: r.Line, Level: "note", Status: StatusUnknown, Pull: img, ref: &r, @@ -88,6 +91,17 @@ func (s *scanner) judgeRef(r refs.Ref, opts Options) { return } feature := tv.Nums[0] + if fam.GraalVM { + f := Finding{Rule: RuleImagePin, File: r.File, Line: r.Line, Level: "error", Status: StatusVulnerable, Reason: why, ref: &r, Props: props, + Message: fmt.Sprintf("image %s holds %s for Java %s, without the Java4Shell fix", img, fam.Vendor, tv.Text), + Fix: graalFix(feature, "")} + if mit != "" { + f.Status, f.Reason = StatusMitigated, why+"; "+mit + f.Message += ", mitigated by its JVM options until it is updated" + } + s.add(f) + return + } f := Finding{Rule: RuleImagePin, File: r.File, Line: r.Line, Level: "error", Status: StatusVulnerable, Reason: why, ref: &r, Props: props, Message: fmt.Sprintf("image %s holds %s Java %s, without the Java4Shell fix", img, fam.Vendor, tv.Text)} if fx := knowledge.FixedVersion(feature); fx != "" { diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index bffca75..84091f5 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -338,6 +338,10 @@ func (s *scanner) judgeVersion(rel string, line, col int, verText, source, vendo if vendor != "" { props["vendor"] = vendor } + if isGraal(vendor) { + s.graalVersion(rel, line, tv, st, why, source, props) + return + } if fx := knowledge.FixedVersion(tv.Nums[0]); fx != "" { props["fixed_in"] = fx } @@ -421,7 +425,13 @@ func (s *scanner) sdkmanrc(rel, text string) { if vendor == "" { vendor = m[2] } - if strings.Contains(m[1], ".r") || m[2] == "grl" || (m[2] == "graalce" || m[2] == "graal" || m[2] == "nik" || m[2] == "mandrel") && strings.Count(m[1], ".") < 2 { + if isGraal(m[2]) { + if g, java, ok := graalNamed(m[1]); ok { + s.graalOwn(rel, i+1, g, java, strings.TrimSpace(strings.SplitN(l, "=", 2)[1]), ".sdkmanrc") + continue + } + } + if strings.Contains(m[1], ".r") || m[2] == "grl" || isGraal(m[2]) && strings.Count(m[1], ".") < 2 { // GraalVM 22.3.r17 and the like: GraalVM's numbers. s.ownNumbers(rel, i+1, strings.TrimSpace(strings.SplitN(l, "=", 2)[1]), ".sdkmanrc") continue @@ -441,6 +451,13 @@ func (s *scanner) asdfValue(rel string, line int, value, source string) { return } switch m[1] { + case "graalvm", "mandrel": + if g, java, ok := graalNamed(value); ok { + s.graalOwn(rel, line, g, java, value, source) + return + } + } + switch m[1] { case "zulu", "graalvm", "mandrel", "jetbrains": s.ownNumbers(rel, line, value, source) // their own version numbers return diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 3caecca..b098863 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -423,7 +423,10 @@ func finding(x assess.Finding) engine.Finding { sort.Strings(x.MitigatedFor) facts["mitigated_only_for"] = strings.Join(x.MitigatedFor, ",") } - if fx := fixedFor(x.Version); fx != "" { + if x.GraalVM { + // GraalVM's fixed builds are numbered its own way: none was known. + facts["graalvm"] = "yes" + } else if fx := fixedFor(x.Version); fx != "" { facts["fixed_in"] = fx } method := "vm-library" From 03c6dabed9378971ae759ed22bb43da47e5f078c Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 04:25:15 +0000 Subject: [PATCH 045/119] java4shell: Red Hat backport table, RHEL layout and UBI images Red Hat's CVE page (read by the lead on 2026-11-18) lists OpenJDK 17.0.6 and later as affected and names no fixed build, erratum or UBI image. Red Hat backports fixes, so a fixed Red Hat build can keep its VM library's upstream version (17.0.21+9) and differ only in the rpm release. - knowledge: RedHatFixed (package, RHEL major, EVR, advisory) is empty, with the reason; JudgeRedHat compares an rpm's EVR with rpmvercmp (CompareRPM; the epoch is left out when either side omits it), and RPMUpstream reads Red Hat's 17.0.21.0.9 as 17.0.21+9. - assess: a runtime its rpm installed (the install path names it) is fixed when the table lists a fixed build at or below its EVR and its VM library is the same update; the fix text gives Red Hat's status. - A RHEL 9 layout test (versioned directory, jre-17 and alternatives symlinks) gives one runtime owned by java-17-openjdk-headless. - repo: registry.access.redhat.com and registry.redhat.io ubiN/openjdk-NN images: 8 and 11 not affected; 21 and later, and 17 at latest, vulnerable while the table has no entry; other 17 tags pulled (could predate 17.0.6); pulled once Red Hat lists a fixed build. dnf/microdnf/yum java-NN-openjdk installs give Red Hat's status; a pinned 17.0.21.1.1 (build 1 of 17.0.21.1) is no longer taken as fixed. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/coverage_test.go | 72 ++++++ .../java4shell/internal/assess/assess.go | 35 ++- .../internal/assess/coverage_test.go | 48 ++++ .../java4shell/internal/assess/packages.go | 10 +- .../java4shell/internal/knowledge/redhat.go | 216 ++++++++++++++++++ .../internal/knowledge/redhat_test.go | 78 +++++++ .../java4shell/internal/repo/coverage_test.go | 74 ++++++ detectors/java4shell/internal/repo/redhat.go | 96 ++++++++ detectors/java4shell/internal/repo/refscan.go | 3 + detectors/java4shell/internal/repo/repo.go | 43 +++- 10 files changed, 666 insertions(+), 9 deletions(-) create mode 100644 detectors/java4shell/coverage_test.go create mode 100644 detectors/java4shell/internal/knowledge/redhat.go create mode 100644 detectors/java4shell/internal/knowledge/redhat_test.go create mode 100644 detectors/java4shell/internal/repo/redhat.go diff --git a/detectors/java4shell/coverage_test.go b/detectors/java4shell/coverage_test.go new file mode 100644 index 0000000..d48307c --- /dev/null +++ b/detectors/java4shell/coverage_test.go @@ -0,0 +1,72 @@ +package java4shell_test + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// A RHEL 9 / UBI 9 layout: the rpm's versioned directory, the jre-17 and +// alternatives symlinks that point into it, and /usr/bin/java through +// /etc/alternatives. One runtime, owned by the rpm its path names. +func TestRedHatLayout(t *testing.T) { + root := t.TempDir() + const dir = "usr/lib/jvm/java-17-openjdk-17.0.21.0.9-1.el9.x86_64" + write(t, root, dir+"/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "17.0.21+9-LTS", VBMI: true})) + write(t, root, dir+"/release", testlib.Release("IMPLEMENTOR", "Red Hat, Inc.", "JAVA_RUNTIME_VERSION", "17.0.21+9-LTS", "JAVA_VERSION", "17.0.21", "JAVA_VERSION_DATE", "2026-10-21")) + write(t, root, dir+"/bin/java", []byte("#!fake\n")) + for link, target := range map[string]string{ + "usr/lib/jvm/jre-17-openjdk": "java-17-openjdk-17.0.21.0.9-1.el9.x86_64", + "usr/lib/jvm/jre-17": "/etc/alternatives/jre_17", + "usr/lib/jvm/jre": "/etc/alternatives/jre", + "etc/alternatives/jre_17": "/" + dir, + "etc/alternatives/jre": "/" + dir, + "etc/alternatives/java": "/" + dir + "/bin/java", + "usr/bin/java": "/etc/alternatives/java", + "usr/lib/jvm/java-17-openjdk-17.0.21.0.9-1.el9.x86_64/lib/server/libjvm-self": "libjvm.so", + } { + p := filepath.Join(root, link) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, p); err != nil { + t.Fatal(err) + } + } + r, _ := run(t, "scan", "fs", "--as-root", root) + if r.Targets[0].Error != "" { + t.Fatal(r.Targets[0].Error) + } + fs := byPath(r) + if len(fs) != 1 { + t.Fatalf("want one runtime, got %d: %+v", len(fs), fs) + } + f := fs["/"+dir] + if f.Verdict != engine.Vulnerable || f.Facts["package"] != "java-17-openjdk-headless 17.0.21.0.9-1.el9" || f.Facts["vendor"] != "Red Hat, Inc." || f.Facts["version_from"] != "vm-library" { + t.Errorf("RHEL runtime: %+v", f) + } + if !strings.Contains(f.Fix, "Red Hat had published no fixed") { + t.Errorf("fix text: %s", f.Fix) + } +} + +// GraalVM CE 22.3.1 for Java 17, as its image lays it out (/graalvm with +// GRAALVM_VERSION in the release file). +func TestGraalVMLayout(t *testing.T) { + root := t.TempDir() + write(t, root, "graalvm/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "17.0.6+10-jvmci-22.3-b13", VBMI: true})) + write(t, root, "graalvm/release", testlib.Release("IMPLEMENTOR", "GraalVM Community", "JAVA_VERSION", "17.0.6", "GRAALVM_VERSION", "22.3.1")) + write(t, root, "opt/graalvm-25/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "25.0.5.1+2-LTS-jvmci-b01", VBMI: true})) + r, _ := run(t, "scan", "fs", "--as-root", root) + fs := byPath(r) + if f := fs["/graalvm"]; f.Verdict != engine.Vulnerable || f.Facts["graalvm"] != "yes" || f.Facts["fixed_in"] != "" { + t.Errorf("GraalVM 22.3.1: %+v", f) + } + if f := fs["/opt/graalvm-25"]; f.Verdict != engine.Unknown || !strings.Contains(f.Reason, "no fixed GraalVM build") { + t.Errorf("GraalVM at the OpenJDK fix: %+v", f) + } +} diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index 664382b..14d2d9f 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -103,10 +103,10 @@ func Run(in Input) []Finding { env := jvm.EnvMap(in.Env) var out []Finding for _, r := range roots { - out = append(out, withFix(judge(in, env, r, byRoot[r]))) + out = append(out, withFix(redHat(judge(in, env, r, byRoot[r])))) } for _, l := range loose { - out = append(out, withFix(judge(in, env, path.Dir(l.Path), []*jvm.Library{l}))) + out = append(out, withFix(redHat(judge(in, env, path.Dir(l.Path), []*jvm.Library{l})))) } return out } @@ -277,6 +277,28 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi return f.set(Vulnerable, kwhy, what+" is vulnerable to Java4Shell") } +// redHat applies Red Hat's backport table to a runtime its rpm installed: +// a fixed Red Hat build keeps the upstream version in its VM library, so +// only the rpm release shows the fix. +func redHat(f Finding) Finding { + if f.Package == nil || f.Package.Manager != "rpm" || f.VersionFrom != "vm-library" || f.Status != Vulnerable && f.Status != Mitigated { + return f + } + st, why, known := knowledge.JudgeRedHat(f.Package.Name, f.Package.Version) + if !known || st != knowledge.Fixed { + return f + } + // The VM library has to be the update the rpm packages. + up, ok := knowledge.Parse(knowledge.RPMUpstream(f.Package.Version)) + v, vok := knowledge.Parse(f.Version) + if !ok || !vok || len(up.Nums) < 3 || len(v.Nums) < 3 || knowledge.Compare(up.Nums[:3], v.Nums[:3]) != 0 { + return f + } + f.Release, f.Mitigation, f.MitigatedFor = knowledge.Fixed, "", nil + return f.set(Fixed, why+"; its VM library reads Java "+f.Version+", the update Red Hat backported the fix into", + describe(f, v, true)+" has Red Hat's backported Java4Shell fix (judged by its rpm release)") +} + func (f Finding) set(s Status, reason, msg string) Finding { f.Status, f.Reason, f.Message = s, reason, msg return f @@ -540,6 +562,15 @@ func fixText(f Finding, v knowledge.Version, ok bool) string { case f.Product != "": return fmt.Sprintf("Upgrade %s to a release that bundles %s; its own runtime is not updated by the operating system's Java packages.%s", f.Product, target, interim) case f.Package != nil: + if pkg, el, ok := knowledge.RedHatPackage(f.Package.Name, f.Package.Version); ok { + if fx, ok := knowledge.RedHatFixFor(pkg, el); ok { + evr := fx.EVR + if i := strings.IndexByte(evr, ':'); i >= 0 { + evr = evr[i+1:] + } + target = fmt.Sprintf("Red Hat's build %s or later (%s)", evr, fx.Advisory) + } + } return fmt.Sprintf("Update the %s package to %s: %s (%s).%s", f.Package.Name, target, upgradeLine(*f.Package), distroStatus(*f.Package), interim) case f.JLinked: return fmt.Sprintf("Rebuild this jlink image from a JDK at %s.%s", target, interim) diff --git a/detectors/java4shell/internal/assess/coverage_test.go b/detectors/java4shell/internal/assess/coverage_test.go index 74f97b6..f00f9b7 100644 --- a/detectors/java4shell/internal/assess/coverage_test.go +++ b/detectors/java4shell/internal/assess/coverage_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" ) @@ -103,3 +104,50 @@ func TestGraalVMRuntime(t *testing.T) { } } } + +// Red Hat's layout: /usr/lib/jvm/java-17-openjdk--., +// the rpm named by its install path; the VM library reads the upstream +// version (17.0.21+9-LTS) whatever Red Hat backports. +func TestRedHatRuntime(t *testing.T) { + const el9 = "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-1.el9.x86_64" + run := func(root, ver string) Finding { + return one(t, Input{ + Libraries: []*jvm.Library{lib(t, root+"/lib/server/libjvm.so", testlib.Lib{Version: ver, VBMI: true})}, + Releases: map[string]jvm.Release{root: rel(t, "JAVA_VERSION", "17.0.21", "JAVA_RUNTIME_VERSION", ver, "IMPLEMENTOR", "Red Hat, Inc.")}, + }) + } + f := run(el9, "17.0.21+9-LTS") + if f.Status != Vulnerable || f.Package == nil || f.Package.Name != "java-17-openjdk-headless" || f.Package.Version != "17.0.21.0.9-1.el9" { + t.Fatalf("RHEL 9 rpm: %s %+v (%s)", f.Status, f.Package, f.Reason) + } + if !strings.Contains(f.Fix, "Red Hat had published no fixed") || !strings.Contains(f.Fix, "dnf upgrade java-17-openjdk-headless") { + t.Errorf("fix text: %s", f.Fix) + } + + saved := knowledge.RedHatFixed + t.Cleanup(func() { knowledge.RedHatFixed = saved }) + knowledge.RedHatFixed = []knowledge.RedHatFix{{Package: "java-17-openjdk", EL: 9, EVR: "1:17.0.21.0.9-2.el9", Advisory: "RHSA-2026:0000"}} + if f := run(el9, "17.0.21+9-LTS"); f.Status != Vulnerable || !strings.Contains(f.Fix, "17.0.21.0.9-2.el9") { + t.Errorf("older than the listed build: %s (%s) fix %s", f.Status, f.Reason, f.Fix) + } + fixed := "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-2.el9.x86_64" + if f := run(fixed, "17.0.21+9-LTS"); f.Status != Fixed || !strings.Contains(f.Reason, "Red Hat") || f.Fix != "" { + t.Errorf("listed build: %s (%s) fix %q", f.Status, f.Reason, f.Fix) + } + if f := run("/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-3.el9_7.x86_64", "17.0.21+9-LTS"); f.Status != Fixed { + t.Errorf("later build: %s (%s)", f.Status, f.Reason) + } + // The VM library must be the update the rpm names: a path that says + // 17.0.21 over a 17.0.13 VM library proves nothing. + if f := run("/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-2.el9.x86_64", "17.0.13+11-LTS"); f.Status != Vulnerable { + t.Errorf("mismatched VM library: %s (%s)", f.Status, f.Reason) + } + // No RHEL 8 entry: judged by the VM library. + if f := run("/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-9.el8.x86_64", "17.0.21+9-LTS"); f.Status != Vulnerable { + t.Errorf("RHEL 8: %s (%s)", f.Status, f.Reason) + } + // Not Red Hat: Fedora is not in the table. + if f := run("/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-9.fc41.x86_64", "17.0.21+9"); f.Status != Vulnerable { + t.Errorf("Fedora: %s (%s)", f.Status, f.Reason) + } +} diff --git a/detectors/java4shell/internal/assess/packages.go b/detectors/java4shell/internal/assess/packages.go index 11bd221..30b6c3d 100644 --- a/detectors/java4shell/internal/assess/packages.go +++ b/detectors/java4shell/internal/assess/packages.go @@ -1,10 +1,12 @@ package assess import ( - "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" + "fmt" "path" "regexp" "strings" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" ) // Package is the OS package that installed a runtime. @@ -130,6 +132,12 @@ func distroStatus(p Package) string { case "dpkg": return "Debian and Ubuntu had published no fixed package " + knowledge.AsOf() case "rpm": + if pkg, el, ok := knowledge.RedHatPackage(p.Name, p.Version); ok { + if fx, ok := knowledge.RedHatFixFor(pkg, el); ok { + return fmt.Sprintf("Red Hat's first fixed RHEL %d build is %s, %s", el, fx.EVR, fx.Advisory) + } + return knowledge.RedHatStatus() + } return "the distribution's fix status was not checked" } return "" diff --git a/detectors/java4shell/internal/knowledge/redhat.go b/detectors/java4shell/internal/knowledge/redhat.go new file mode 100644 index 0000000..46f78e8 --- /dev/null +++ b/detectors/java4shell/internal/knowledge/redhat.go @@ -0,0 +1,216 @@ +package knowledge + +import ( + "fmt" + "regexp" + "strconv" + "strings" +) + +// Red Hat backports security fixes into the OpenJDK update it ships, so a +// fixed Red Hat build can keep the upstream version (its VM library still +// reads 17.0.21+9) and only the rpm release moves. Its fixed builds are +// therefore listed by rpm version-release, per package and RHEL major +// release. FACTS.md gives the sources. + +// RedHatFix is the first Red Hat build of an OpenJDK package with the fix +// on one RHEL major release. +type RedHatFix struct { + Package string // source package: java-17-openjdk + EL int // RHEL major release: 8, 9, 10 + EVR string // [epoch:]version-release: 1:17.0.21.0.9-2.el9_6 + Advisory string // RHSA-... +} + +// RedHatFixed is empty: Red Hat's CVE page, read on Checked, lists the +// OpenJDK packages as affected and names no fixed build, erratum or UBI +// image ("exact upstream fixed version ... not yet confirmed by Oracle"). +// An entry here marks that package's builds from EVR on as fixed, whatever +// their VM library's version line says. +var RedHatFixed = []RedHatFix{} + +// RedHatStatus says what Red Hat had published, for reasons. +func RedHatStatus() string { + if len(RedHatFixed) == 0 { + return "Red Hat had published no fixed OpenJDK build " + AsOf() + " (its CVE page lists none)" + } + var parts []string + for _, f := range RedHatFixed { + parts = append(parts, fmt.Sprintf("%s %s on RHEL %d (%s)", f.Package, f.EVR, f.EL, f.Advisory)) + } + return "Red Hat's fixed builds: " + strings.Join(parts, ", ") +} + +var ( + elRelease = regexp.MustCompile(`\.el(\d{1,2})(?:[._]|$)`) + rhPackage = regexp.MustCompile(`^(java-\d{1,2}-openjdk)(?:-(?:headless|devel|jmods|src|demo|javadoc|javadoc-zip|static-libs|fastdebug|slowdebug)\b.*)?$`) + rpmVersion = regexp.MustCompile(`^(?:(\d+):)?([^-]+)(?:-(.+))?$`) +) + +// RedHatPackage returns the source package and the RHEL major release of +// an rpm of Red Hat's OpenJDK: java-17-openjdk-headless with release +// 1.el9_6 is java-17-openjdk on RHEL 9. ok is false for other packages and +// for releases that are not Red Hat's (.fc41, .amzn2023). +func RedHatPackage(name, evr string) (pkg string, el int, ok bool) { + m := rhPackage.FindStringSubmatch(name) + if m == nil { + return "", 0, false + } + e := elRelease.FindStringSubmatch(evr) + if e == nil { + return "", 0, false + } + n, _ := strconv.Atoi(e[1]) + return m[1], n, true +} + +// RedHatFixFor returns the table's entry for a package on a RHEL release. +func RedHatFixFor(pkg string, el int) (RedHatFix, bool) { + for _, f := range RedHatFixed { + if f.Package == pkg && f.EL == el { + return f, true + } + } + return RedHatFix{}, false +} + +// JudgeRedHat judges an rpm of Red Hat's OpenJDK (name and +// [epoch:]version-release) by the backport table. known is false when the +// table has no entry for its package and RHEL release: then only its +// upstream version can judge it. +func JudgeRedHat(name, evr string) (st Status, why string, known bool) { + pkg, el, ok := RedHatPackage(name, evr) + if !ok { + return Unknown, "", false + } + fx, ok := RedHatFixFor(pkg, el) + if !ok { + return Unknown, "", false + } + a, b := evr, fx.EVR + if !strings.Contains(a, ":") || !strings.Contains(b, ":") { + // An install path or a package argument leaves the epoch out. + a, b = stripEpoch(a), stripEpoch(b) + } + if CompareRPM(a, b) < 0 { + return Vulnerable, fmt.Sprintf("Red Hat build %s-%s is older than %s, the first RHEL %d build with the fix (%s)", pkg, stripEpoch(evr), stripEpoch(fx.EVR), el, fx.Advisory), true + } + return Fixed, fmt.Sprintf("Red Hat build %s-%s is at or past %s, the first RHEL %d build with Red Hat's backport of the fix (%s)", pkg, stripEpoch(evr), stripEpoch(fx.EVR), el, fx.Advisory), true +} + +func stripEpoch(evr string) string { + if i := strings.IndexByte(evr, ':'); i >= 0 { + return evr[i+1:] + } + return evr +} + +// RPMUpstream turns a Red Hat or Fedora OpenJDK rpm version into the Java +// version it packages: they append the build to the update, padding the +// patch with 0 (17.0.21.0.9-1.el9 is 17.0.21+9, 17.0.21.1.1 is 17.0.21.1+1). +// A version with fewer than five numbers is returned without its release. +func RPMUpstream(evr string) string { + m := rpmVersion.FindStringSubmatch(evr) + if m == nil { + return evr + } + ver := m[2] + parts := strings.Split(ver, ".") + if len(parts) != 5 { + return ver + } + return strings.Join(parts[:4], ".") + "+" + parts[4] +} + +// CompareRPM compares two [epoch:]version[-release] strings the way rpm +// does (rpmvercmp on each part; a missing epoch is 0). +func CompareRPM(a, b string) int { + ma, mb := rpmVersion.FindStringSubmatch(a), rpmVersion.FindStringSubmatch(b) + if ma == nil || mb == nil { + return strings.Compare(a, b) + } + ea, _ := strconv.Atoi(ma[1]) + eb, _ := strconv.Atoi(mb[1]) + switch { + case ea < eb: + return -1 + case ea > eb: + return 1 + } + if c := rpmvercmp(ma[2], mb[2]); c != 0 { + return c + } + if ma[3] == "" || mb[3] == "" { + return 0 + } + return rpmvercmp(ma[3], mb[3]) +} + +// rpmvercmp is rpm's comparison of one version or release: alternating +// numeric and alphabetic segments, separators ignored, numbers newer than +// letters, and a tilde sorting before anything. +func rpmvercmp(a, b string) int { + if a == b { + return 0 + } + isAlnum := func(c byte) bool { return c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' } + isDigit := func(c byte) bool { return c >= '0' && c <= '9' } + for { + for a != "" && !isAlnum(a[0]) && a[0] != '~' { + a = a[1:] + } + for b != "" && !isAlnum(b[0]) && b[0] != '~' { + b = b[1:] + } + if a != "" && a[0] == '~' || b != "" && b[0] == '~' { + switch { + case a == "" || a[0] != '~': + return 1 + case b == "" || b[0] != '~': + return -1 + } + a, b = a[1:], b[1:] + continue + } + if a == "" || b == "" { + break + } + num := isDigit(a[0]) + seg := func(s string) (string, string) { + i := 0 + for i < len(s) && (num && isDigit(s[i]) || !num && isAlnum(s[i]) && !isDigit(s[i])) { + i++ + } + return s[:i], s[i:] + } + sa, ra := seg(a) + sb, rb := seg(b) + if sb == "" { + // Different kinds of segment: a number is newer than letters. + if num { + return 1 + } + return -1 + } + if num { + sa, sb = strings.TrimLeft(sa, "0"), strings.TrimLeft(sb, "0") + if len(sa) != len(sb) { + if len(sa) < len(sb) { + return -1 + } + return 1 + } + } + if c := strings.Compare(sa, sb); c != 0 { + return c + } + a, b = ra, rb + } + switch { + case a == "" && b == "": + return 0 + case a == "": + return -1 + } + return 1 +} diff --git a/detectors/java4shell/internal/knowledge/redhat_test.go b/detectors/java4shell/internal/knowledge/redhat_test.go new file mode 100644 index 0000000..cc004ad --- /dev/null +++ b/detectors/java4shell/internal/knowledge/redhat_test.go @@ -0,0 +1,78 @@ +package knowledge + +import "testing" + +func TestCompareRPM(t *testing.T) { + for _, c := range []struct { + a, b string + want int + }{ + {"17.0.21.0.9-1.el9", "17.0.21.0.9-1.el9", 0}, + {"17.0.21.0.9-2.el9", "17.0.21.0.9-1.el9", 1}, + {"17.0.21.0.9-1.el9", "17.0.21.0.10-1.el9", -1}, + {"17.0.21.0.9-1.el9_6", "17.0.21.0.9-1.el9", 1}, + {"1:17.0.21.0.9-1.el9", "17.0.21.0.9-2.el9", 1}, + {"17.0.21.1.2-1.el9", "17.0.21.0.9-9.el9", 1}, + {"1.0~rc1-1", "1.0-1", -1}, + {"1.0a-1", "1.0-1", 1}, + {"1.010-1", "1.9-1", 1}, + {"1.0-1.el9", "1.0-1.el10", -1}, + } { + if got := CompareRPM(c.a, c.b); got != c.want { + t.Errorf("CompareRPM(%s, %s) = %d, want %d", c.a, c.b, got, c.want) + } + if got := CompareRPM(c.b, c.a); got != -c.want { + t.Errorf("CompareRPM(%s, %s) = %d, want %d", c.b, c.a, got, -c.want) + } + } +} + +func TestRedHatTable(t *testing.T) { + // Empty today: Red Hat had published no fixed build. + if len(RedHatFixed) != 0 { + t.Fatalf("RedHatFixed has entries; update this test and FACTS.md: %+v", RedHatFixed) + } + if _, _, known := JudgeRedHat("java-17-openjdk-headless", "17.0.21.0.9-1.el9"); known { + t.Error("a build was judged from an empty table") + } + saved := RedHatFixed + t.Cleanup(func() { RedHatFixed = saved }) + RedHatFixed = []RedHatFix{{Package: "java-17-openjdk", EL: 9, EVR: "1:17.0.21.0.9-2.el9", Advisory: "RHSA-2026:0000"}} + for _, c := range []struct { + name, evr string + want Status + known bool + }{ + {"java-17-openjdk-headless", "17.0.21.0.9-1.el9", Vulnerable, true}, + {"java-17-openjdk-headless", "1:17.0.21.0.9-1.el9", Vulnerable, true}, + {"java-17-openjdk-headless", "1:17.0.21.0.9-2.el9", Fixed, true}, + // An install path or a dnf argument omits the epoch: compared without it. + {"java-17-openjdk-headless", "17.0.21.0.9-2.el9", Fixed, true}, + {"java-17-openjdk", "1:17.0.21.0.9-3.el9_7", Fixed, true}, + {"java-17-openjdk-devel", "1:17.0.21.0.9-2.el9", Fixed, true}, + {"java-17-openjdk-headless", "1:17.0.21.0.9-9.el8", "", false}, // no RHEL 8 entry + {"java-21-openjdk-headless", "1:21.0.13.0.9-1.el9", "", false}, + {"java-17-openjdk-headless", "17.0.21.0.9-1.fc41", "", false}, // not Red Hat + {"java-17-amazon-corretto-headless", "17.0.21.0.9-1.el9", "", false}, + } { + st, why, known := JudgeRedHat(c.name, c.evr) + if known != c.known || known && (st != c.want || why == "") { + t.Errorf("JudgeRedHat(%s, %s) = %s %v (%s), want %s %v", c.name, c.evr, st, known, why, c.want, c.known) + } + } +} + +func TestRPMUpstream(t *testing.T) { + for in, want := range map[string]string{ + "17.0.21.0.9-1.el9": "17.0.21.0+9", + "1:17.0.21.1.1-1.el9": "17.0.21.1+1", + "21.0.13.1.2-1.el9": "21.0.13.1+2", + "17.0.21.0.3-1.el9": "17.0.21.0+3", + "17.0.21-1.el9": "17.0.21", + "17.0.21.1-1": "17.0.21.1", + } { + if got := RPMUpstream(in); got != want { + t.Errorf("RPMUpstream(%s) = %s, want %s", in, got, want) + } + } +} diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index 6afff65..4321a1b 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -3,6 +3,8 @@ package repo import ( "strings" "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" ) // The five-part releases the OpenJDK advisory names as the last affected @@ -136,3 +138,75 @@ func TestGraalVMRepo(t *testing.T) { } } } + +func TestRedHatRepo(t *testing.T) { + files := map[string]string{ + "Dockerfile": strings.Join([]string{ + "FROM registry.access.redhat.com/ubi9/openjdk-17:1.20", + "FROM registry.access.redhat.com/ubi9/openjdk-17:latest", + "FROM registry.access.redhat.com/ubi9/openjdk-21-runtime:1.20-2.1729089285", + "FROM registry.redhat.io/ubi9/openjdk-25", + "FROM registry.access.redhat.com/ubi8/openjdk-11", + "FROM registry.access.redhat.com/ubi8/openjdk-8-runtime:1.20", + "FROM registry.access.redhat.com/ubi9/openjdk-17-runtime@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + }, "\n") + "\n", + "Dockerfile.pkg": strings.Join([]string{ + "FROM registry.access.redhat.com/ubi9/ubi-minimal", + "RUN microdnf install -y java-17-openjdk-headless && microdnf clean all", + "RUN dnf install -y java-21-openjdk-devel", + "RUN dnf install -y java-17-openjdk-headless-17.0.21.0.9-1.el9", + "RUN dnf install -y java-17-openjdk-headless-1:17.0.21.1.1-1.el9.x86_64", + "RUN yum install -y java-11-openjdk-headless", + }, "\n") + "\n", + } + res := scan(t, tree(t, files)) + checkAll(t, res, []want{ + {"Dockerfile", 1, RuleNotChecked, StatusUnknown}, + {"Dockerfile", 2, RuleImagePin, StatusVulnerable}, + {"Dockerfile", 3, RuleImagePin, StatusVulnerable}, + {"Dockerfile", 4, RuleImagePin, StatusVulnerable}, + {"Dockerfile", 7, RuleNotChecked, StatusUnknown}, + {"Dockerfile.pkg", 2, RulePackage, StatusVulnerable}, + {"Dockerfile.pkg", 3, RulePackage, StatusVulnerable}, + {"Dockerfile.pkg", 4, RulePackage, StatusVulnerable}, + {"Dockerfile.pkg", 5, RulePackage, StatusVulnerable}, // 17.0.21.1 build 1 predates the fix (build 2) + }) + for _, l := range []int{5, 6} { + if f, ok := find(res, "Dockerfile", l); ok { + t.Errorf("Dockerfile:%d: Java 8 or 11 image reported: %+v", l, f) + } + } + if f, ok := find(res, "Dockerfile.pkg", 6); ok { + t.Errorf("java-11 package reported: %+v", f) + } + for _, f := range res.Findings { + if !strings.Contains(f.Reason, "Red Hat") { + t.Errorf("%s:%d: the reason does not give Red Hat's status: %s", f.File, f.Line, f.Reason) + } + if f.Rule == RuleNotChecked && f.Pull == "" { + t.Errorf("%s:%d: a UBI image that has to be read is not pulled", f.File, f.Line) + } + if f.Fixable { + t.Errorf("%s:%d: offers an edit", f.File, f.Line) + } + } + + // Once Red Hat lists a fixed build, a moving UBI tag or an unpinned + // install may get it: only the image can tell. + saved := knowledge.RedHatFixed + t.Cleanup(func() { knowledge.RedHatFixed = saved }) + knowledge.RedHatFixed = []knowledge.RedHatFix{{Package: "java-17-openjdk", EL: 9, EVR: "1:17.0.21.0.9-2.el9", Advisory: "RHSA-2026:0000"}, + {Package: "java-21-openjdk", EL: 9, EVR: "1:21.0.13.0.9-2.el9", Advisory: "RHSA-2026:0001"}} + files["Dockerfile.pkg"] += "RUN dnf install -y java-17-openjdk-headless-17.0.21.0.9-2.el9\n" + res = scan(t, tree(t, files)) + checkAll(t, res, []want{ + {"Dockerfile", 2, RuleNotChecked, StatusUnknown}, + {"Dockerfile", 3, RuleNotChecked, StatusUnknown}, + {"Dockerfile", 4, RuleImagePin, StatusVulnerable}, // no java-25 entry + {"Dockerfile.pkg", 2, RulePackage, StatusUnknown}, + {"Dockerfile.pkg", 4, RulePackage, StatusVulnerable}, + }) + if f, ok := find(res, "Dockerfile.pkg", 7); ok { + t.Errorf("the listed fixed build reported: %+v", f) + } +} diff --git a/detectors/java4shell/internal/repo/redhat.go b/detectors/java4shell/internal/repo/redhat.go new file mode 100644 index 0000000..aa8bedb --- /dev/null +++ b/detectors/java4shell/internal/repo/redhat.go @@ -0,0 +1,96 @@ +package repo + +import ( + "fmt" + "regexp" + "strings" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" + "github.com/DefectDojo/earlylight/internal/refs" +) + +// redHatImage is a Red Hat OpenJDK image: registry.access.redhat.com/ubi9/openjdk-21, +// ubi8/openjdk-17-runtime, openjdk/openjdk-11-rhel7, on registry.redhat.io too. +// Its tags name the image's release (1.20, 1.20-2.1729089285), not the +// Java update. +var rhSource = regexp.MustCompile(`^(java-\d{1,2}-openjdk)`) + +var redHatImage = regexp.MustCompile(`^(?:registry\.access\.redhat\.com|registry\.redhat\.io)/(?:ubi(\d{1,2})|openjdk)/openjdk-(\d{1,2})(?:-runtime)?(?:-rhel(\d{1,2}))?$`) + +// redHatRef judges a Red Hat OpenJDK image by the Red Hat backport table. +// ok is false for an image that is not one. +func (s *scanner) redHatRef(r refs.Ref, img string, props map[string]string, mit string) bool { + repo, tag := repoName(img) + m := redHatImage.FindStringSubmatch(repo) + if m == nil { + return false + } + feature, el := atoi(m[2]), atoi(m[1]+m[3]) + if feature < 17 { + return true // Java 8 and 11: no decoder + } + props["vendor"] = "Red Hat" + pkg := fmt.Sprintf("java-%d-openjdk", feature) + pull := func(why string) { + s.add(Finding{Rule: RuleNotChecked, File: r.File, Line: r.Line, Level: "note", Status: StatusUnknown, Pull: img, ref: &r, Props: props, + Reason: why, Message: fmt.Sprintf("image %s: %s", img, why)}) + } + if fx, ok := knowledge.RedHatFixFor(pkg, el); ok { + pull(fmt.Sprintf("Red Hat published %s %s (%s); whether this image has it, only the image can show: its tag names the image's release, not the Java update", pkg, fx.EVR, fx.Advisory)) + return true + } + moving := tag == "" && !strings.Contains(img, "@") || tag == "latest" + if feature == 17 && !moving { + pull(fmt.Sprintf("the tag names the image's release, not the Java update: Java 17 images built before 17.0.6 do not have the decoder, and none has the fix (%s)", knowledge.RedHatStatus())) + return true + } + why := fmt.Sprintf("every Java %d release has the AVX-512 VBMI Base64 decoder, and %s, so every image Red Hat had published lacks the fix", feature, knowledge.RedHatStatus()) + if feature == 17 { + why = fmt.Sprintf("the newest image carries a Java 17 update at or after 17.0.6, which brought the decoder, and %s", knowledge.RedHatStatus()) + } + f := Finding{Rule: RuleImagePin, File: r.File, Line: r.Line, Level: "error", Status: StatusVulnerable, Reason: why, ref: &r, Props: props, + Message: fmt.Sprintf("image %s holds Red Hat's OpenJDK %d, without the Java4Shell fix", img, feature), + Fix: fmt.Sprintf("Rebuild on a %s image with Red Hat's fixed %s once Red Hat publishes it (it had not %s), and redeploy. Until then set JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics for the container.", + repo, pkg, knowledge.AsOf())} + if l, ok := knowledge.LineOf(feature); ok && l.Fixed == nil { + f.Fix = fmt.Sprintf("Java %d received no fix: move to a Red Hat image of a supported release with the fix, such as %s.", feature, knowledge.Upgrade(feature)) + } + if mit != "" { + f.Status, f.Reason = StatusMitigated, why+"; "+mit + f.Message += ", mitigated by its JVM options until it is updated" + } + s.add(f) + return true +} + +// redHatPin judges a pinned rpm of Red Hat's OpenJDK +// (java-17-openjdk-headless-17.0.21.0.9-1.el9) by the backport table. ok is +// false when the table does not decide it. +func redHatPin(h pkgHit) (st knowledge.Status, why string, ok bool) { + if h.mgr != "rpm" || h.vendor != "distribution" || h.ver == "" { + return "", "", false + } + return knowledge.JudgeRedHat(h.name, h.ver) +} + +// redHatPublished reports whether Red Hat had published a fixed build of a +// package on any RHEL release, and names it. +func redHatPublished(name string) (string, bool) { + m := rhSource.FindStringSubmatch(name) + if m == nil { + return "", false + } + var out []string + for _, f := range knowledge.RedHatFixed { + if f.Package == m[1] { + out = append(out, fmt.Sprintf("%s on RHEL %d (%s)", f.EVR, f.EL, f.Advisory)) + } + } + return strings.Join(out, ", "), len(out) > 0 +} + +// rpmFix is what to do about an rpm of OpenJDK without the fix. Red Hat +// backports fixes, so its fixed build may keep the upstream version. +func rpmFix(name string) string { + return fmt.Sprintf("Rebuild once Red Hat (or your rpm distribution) publishes a fixed %s and check the installed build: Red Hat backports fixes, so its fixed build may keep the upstream version and differ only in the rpm release. Until then set ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics in this stage.", name) +} diff --git a/detectors/java4shell/internal/repo/refscan.go b/detectors/java4shell/internal/repo/refscan.go index 351d6cb..4c5cb9b 100644 --- a/detectors/java4shell/internal/repo/refscan.go +++ b/detectors/java4shell/internal/repo/refscan.go @@ -56,6 +56,9 @@ func (s *scanner) judgeRef(r refs.Ref, opts Options) { if mit != "" { props["mitigation"] = mit } + if s.redHatRef(r, img, props, mit) { + return + } fam, tag, ok := FamilyOf(img) if !ok { if Javaish(img) { diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 84091f5..a6546cd 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -1011,8 +1011,12 @@ func pinnedVersion(h pkgHit) string { up = up[i+1:] } up = strings.ReplaceAll(up, "_p", "+") - if h.vendor == "corretto" { + switch { + case h.vendor == "corretto": up = CorrettoJava(up) + case h.mgr == "rpm": + // Red Hat and Fedora append the build: 17.0.21.0.9 is 17.0.21+9. + up = knowledge.RPMUpstream(h.ver) } v, ok := knowledge.Parse(up) if !ok || len(v.Nums) < 3 { @@ -1055,14 +1059,28 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { if fx == "" { fx = "a release with the fix" } + if st, why, ok := redHatPin(h); ok { + props["current"] = h.ver + if st == knowledge.Vulnerable { + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "error", Status: StatusVulnerable, Reason: why, + Message: fmt.Sprintf("pins %s to %s, without the Java4Shell fix", h.name, h.ver), + Fix: rpmFix(h.name), + Props: props}) + } + return + } if up := pinnedVersion(h); up != "" { props["current"] = h.ver v, _ := knowledge.Parse(up) if st, why := knowledge.Judge(v); st == knowledge.Vulnerable { + fix := fmt.Sprintf("Pin %s to a package of Java %s or later once %s publishes it, then rebuild. Until then set ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics in this stage.", h.name, fx, who) + if h.mgr == "rpm" && h.vendor == "distribution" { + why += "; " + knowledge.RedHatStatus() + fix = rpmFix(h.name) + } s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "error", Status: StatusVulnerable, Reason: why, Message: fmt.Sprintf("pins %s to %s, without the Java4Shell fix", h.name, h.ver), - Fix: fmt.Sprintf("Pin %s to a package of Java %s or later once %s publishes it, then rebuild. Until then set ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics in this stage.", h.name, fx, who), - Props: props}) + Fix: fix, Props: props}) } return } @@ -1080,6 +1098,15 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { if h.ver != "" { what = "with a version range (" + h.op + h.ver + ")" } + published, rhFixed := redHatPublished(h.name) + switch { + case h.mgr == "rpm" && h.vendor == "distribution" && rhFixed: + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: props, + Reason: fmt.Sprintf("Red Hat published fixed builds (%s): an image built after that gets one, one built or cached before does not", published), + Message: fmt.Sprintf("installs %s %s: whether the image has the Java4Shell fix depends on when it was built", h.name, what), + Fix: fmt.Sprintf("Rebuild without the layer cache and check that %s is Red Hat's fixed build or later.", h.name)}) + return + } switch h.vendor { case "corretto", "sapmachine": s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: props, @@ -1092,7 +1119,12 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { Message: fmt.Sprintf("installs %s %s: not checked for the Java4Shell fix", h.name, what), Fix: fmt.Sprintf("Check that %s's package is Java %s or later, then rebuild.", who, fx)}) default: - reason := fmt.Sprintf("Debian, Ubuntu and Alpine had published no %s package with the fix as of %s (Red Hat's status was not checked), so a build today installs a release without it", fx, knowledge.Checked) + reason := fmt.Sprintf("Debian, Ubuntu and Alpine had published no %s package with the fix as of %s, so a build today installs a release without it", fx, knowledge.Checked) + fix := fmt.Sprintf("Rebuild once %s publishes Java %s or later and check the installed version; until then set ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics in this stage.", who, fx) + if h.mgr == "rpm" && h.vendor == "distribution" { + reason = fmt.Sprintf("%s, and Debian, Ubuntu and Alpine no %s package with the fix (other rpm distributions such as Fedora and SUSE were not checked), so a build today installs a release without it", knowledge.RedHatStatus(), fx) + fix = rpmFix(h.name) + } msg := fmt.Sprintf("installs %s %s: it gets whatever the distribution has, which had no Java4Shell fix yet", h.name, what) if h.vendor == "temurin" { reason = fmt.Sprintf("Eclipse Temurin had published no %s release as of %s, so a build today installs a release without it", fx, knowledge.Checked) @@ -1101,8 +1133,7 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { if h.feature == 0 { msg = fmt.Sprintf("installs %s, the distribution's default OpenJDK (17 or later on current Debian and Ubuntu releases), which had no Java4Shell fix yet", h.name) } - s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "warning", Status: StatusVulnerable, Reason: reason, Message: msg, Props: props, - Fix: fmt.Sprintf("Rebuild once %s publishes Java %s or later and check the installed version; until then set ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics in this stage.", who, fx)}) + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "warning", Status: StatusVulnerable, Reason: reason, Message: msg, Props: props, Fix: fix}) } } From 9d8d108fa395314e9772226a07f387aaa62d3958 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 04:27:46 +0000 Subject: [PATCH 046/119] java4shell: CVSS 8.1, the advisories, and vendor status of 2026-11-18 - Findings score 8.1, the OpenJDK and Oracle CVSS; FACTS.md records Calif's 9.2 and Red Hat's 9.8. - The manifest links the OpenJDK advisory and Oracle's CSPU, now read (by the lead); the runtime kinds say GraalVM is affected. - Fix texts give the vendor status of 2026-11-18 from one place (knowledge.VendorStatus): Corretto and SapMachine fixed; Temurin, Microsoft, Debian, Ubuntu, Alpine and Red Hat not; Azul and Liberica not checked. Microsoft packages and setup-java distribution microsoft are now vulnerable like Temurin, not unknown. - The CVE to JDK-8393212 mapping stays inferred; FACTS.md records that the advisory confirms the component, the lines and the last affected releases, and adds the advisories, GraalVM and Red Hat sections. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- detectors/java4shell/FACTS.md | 67 ++++++++++++++----- detectors/java4shell/coverage_test.go | 25 +++++++ .../java4shell/internal/assess/assess.go | 2 +- .../internal/assess/coverage_test.go | 9 +++ .../internal/knowledge/knowledge.go | 32 ++++++++- .../java4shell/internal/repo/coverage_test.go | 33 +++++++++ detectors/java4shell/internal/repo/repo.go | 20 +++--- detectors/java4shell/java4shell.go | 9 ++- detectors/java4shell/repo.go | 8 +-- 10 files changed, 171 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 678c19e..6d91977 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ One engine for DefectDojo's emerging-vulnerability scanners. Each new vulnerabil | `php2shell` | PHP runtimes vulnerable to CVE-2026-109618 and CVE-2026-109619 ("PHP2Shell"), fixed in PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12 ([GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w), [GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp)). A packaged PHP is judged by its vendor's backport data, never by the version it reports. Also checks the images a source tree builds on and deploys, and can rewrite them to fixed images | `fs`, `image`, `repo`, `fix` | | `brotli` | Brotli decoders vulnerable to CVE-2026-111497 ("Node2Shell", "Broccoli2Shell"), Brotli 1.0.3 through 1.2.0, fixed in 1.0.10, 1.1.1 and 1.2.1 ([GHSA-9v8h-qqgm-4m35](https://github.com/advisories/GHSA-9v8h-qqgm-4m35)): system `libbrotlidec` and every copy bundled into other software (Node.js, .NET, Bun, Electron, Envoy and Istio, Python wheels such as Pillow, pyarrow, duckdb, pycurl and PyMuPDF, brotli4j, and more), on Linux, Windows and macOS. A decoder is judged first by the error code the fix added, so vendor backports are recognised without distribution data; a build that strips it by its own version stamp or by its code, which returns that error code only once fixed. In a source tree it finds the Node.js, .NET and Bun releases and the bundling packages a project pins, and `fix` moves each to the fixed release | `fs`, `image`, `repo`, `fix` | | `sshole` | \*sshole, the OpenSSH password authentication bypass on musl libc fixed in OpenSSH 10.6p2 and in Alpine's openssh packages of November 5, 2026 ([release notes](https://www.openssh.org/releasenotes.html#10.6p2), [writeup](https://sshhole.com)). On musl, sshd from 7.3p1 to 10.6p1 compares an account's password field of `*` with the `*` that crypt returns when it fails, so a crafted password logs in to that account. It judges each installed sshd by its C library, its release and the apk database (Alpine backports keep the release number), then checks what the target's `sshd_config` (Include, Match, PasswordAuthentication, AuthenticationMethods, PermitRootLogin, AllowUsers and the rest) and account files make reachable, and reports the accounts. In an image it also reads the command (`sshd -o` and `-f`) and the startup scripts it runs (entrypoints, s6, cont-init.d), and reports a server as exposed when a startup script turns password logins on, sets a `*` field or sets passwords. OpenWrt's opkg database and its backports (23.05, 24.10, 25.12) count like Alpine's. PAM-checked builds (`UsePAM yes`) are not affected. On a live server it reads the banner and the offered methods and never sends a password. In a source tree it finds Dockerfiles that install an OpenSSH server on Alpine without the fix (package lists in `ARG` and `ENV` too), Ansible apk tasks, Buildroot, OpenWrt and Yocto configurations that build one on musl, and anything that sets a password field to `*`. It also pulls the images the tree references (through the guarded transport, with the command a Compose service or Kubernetes container sets) and judges them like `scan image`. `fix` adds the fixed release floor (in the variable when the list is one), moves an end-of-life Alpine base to a tag on the nearest fixed Alpine release (`alpine:3.14` to `3.16`, `python:3.9-alpine3.14` to `3.9-alpine3.16` after checking that image) as a labelled upgrade, adds upstream commit 4353fdc43 as a patch scoped to the OpenSSH versions it applies to (Buildroot `BR2_GLOBAL_PATCH_DIR`, a version-specific Yocto bbappend), sets Ansible tasks to `state: latest`, and changes `*` to `*NP*` | `fs`, `image`, `host`, `repo`, `fix` | -| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64, fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 on November 15, 2026 by JDK-8393212 ([commit](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b); that this change is the CVE's fix is inferred from the public descriptions, since the OpenJDK advisory could not be read: see the [knowledge table](detectors/java4shell/FACTS.md)). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel server CPUs from Ice Lake on and some client CPUs, not Alder Lake or Raptor Lake; AMD Zen 4 and later); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds Java runtimes by their VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others); a JDK download sitting in the target (OpenJDK21U-jre_…tar.gz and the like) is recorded by name as context, not read or unpacked. Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; each platform of a multi-arch image is judged on its own with `--platform all`), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness: when the library's version line can be read, the library decides and a different release-file version is only noted; a release file naming OpenJ9 next to HotSpot evidence makes the verdict unknown; and a release file alone does not clear a runtime (OpenJ9 is recognised from its own VM library, not from the release file). No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version and build (the first fixed build of each release, such as 21.0.13.1+2; pre-release builds are not judged fixed, and a self-built JDK at a build boundary is unknown). OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is recorded as a mitigation on a finding that stays vulnerable (status `mitigated`, counted in the exit status): the options can be overridden where the runtime is deployed, and the runtime still needs the update; `_JAVA_OPTIONS` turning the intrinsic back on undoes it. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context; neither clears a runtime. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft and Oracle images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | +| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64, fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 on November 15, 2026 by JDK-8393212 ([commit](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b); that this change is the CVE's fix is inferred: the [OpenJDK advisory](https://openjdk.org/groups/vulnerability/advisories/2026-11-17) confirms the component (hotspot/compiler), the lines (17, 21, 25, 27) and the last affected releases (17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3) but names no JDK bug: see the [knowledge table](detectors/java4shell/FACTS.md)). CVSS 8.1 (OpenJDK and Oracle). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel server CPUs from Ice Lake on and some client CPUs, not Alder Lake or Raptor Lake; AMD Zen 4 and later); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds Java runtimes by their VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others); a JDK download sitting in the target (OpenJDK21U-jre_…tar.gz and the like) is recorded by name as context, not read or unpacked. Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; each platform of a multi-arch image is judged on its own with `--platform all`), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness: when the library's version line can be read, the library decides and a different release-file version is only noted; a release file naming OpenJ9 next to HotSpot evidence makes the verdict unknown; and a release file alone does not clear a runtime (OpenJ9 is recognised from its own VM library, not from the release file). No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version and build (the first fixed build of each release, such as 21.0.13.1+2; pre-release builds are not judged fixed, and a self-built JDK at a build boundary is unknown). A GraalVM JDK (a `-jvmci-` version line; Oracle lists GraalVM for JDK 17 and 21 and GraalVM Enterprise 21.3 as affected) is vulnerable where its OpenJDK version is and fixed only at a published fixed GraalVM build (none yet). A Red Hat rpm build is judged by its VM library unless Red Hat's backport table, keyed on the rpm release, lists a fixed build (it is empty: Red Hat had published none). OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is recorded as a mitigation on a finding that stays vulnerable (status `mitigated`, counted in the exit status): the options can be overridden where the runtime is deployed, and the runtime still needs the update; `_JAVA_OPTIONS` turning the intrinsic back on undoes it. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context; neither clears a runtime. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft, Oracle, GraalVM and Red Hat UBI `openjdk-NN` images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | The detectors ported from standalone scanners also build as standalone binaries under the names people search for: `emudhra-scan` and `php2shell-scan`. They keep their original commands, flags and exit status rules. `brotli`, `sshole` and `java4shell` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`, `--detector java4shell`). diff --git a/detectors/java4shell/FACTS.md b/detectors/java4shell/FACTS.md index 95d0674..5b5bc72 100644 --- a/detectors/java4shell/FACTS.md +++ b/detectors/java4shell/FACTS.md @@ -1,10 +1,20 @@ # Java4Shell (CVE-2026-114938): what is known, and from where -Checked 2026-11-17. Every row names its source. "Not fixed yet" means the +Checked 2026-11-17; the advisories and vendor status rechecked 2026-11-18. Every row names its source. "Not fixed yet" means the source was read on that date and had no fixed release; it is not a guess about the future. Rows marked **inferred** are reasoning from the sources, not something a source states. +## The advisories (read by the lead in a browser, 2026-11-17 and 2026-11-18) + +The research host cannot reach openjdk.org, oracle.com or access.redhat.com; the lead read these pages and relayed them. + +| Fact | Source | +| --- | --- | +| "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" (for the advisory's CVEs as a set). CVE-2026-114938: component **hotspot/compiler**, CVSS 3.1 **8.1**, affects the **17, 21, 25 and 27** lines only (not 8, not 11). Acknowledgements include Quang Luong (Calif). The page names no JDK bug ids. The advisory's other CVEs (CVE-2026-114939 to 114947) are not this detector's. Last updated 2026-11-17 17:44 UTC | [OpenJDK Vulnerability Advisory 2026-11-17](https://openjdk.org/groups/vulnerability/advisories/2026-11-17) | +| CVE-2026-114938 in Oracle Java SE, **Oracle GraalVM for JDK** and **Oracle GraalVM Enterprise Edition**, component Compiler, CVSS 3.1 **8.1** (AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H), remotely exploitable without authentication. Affected: Java SE 8u511b33-perf, 17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3; GraalVM for JDK 17.0.21.0.3, 21.0.13.0.3; GraalVM Enterprise Edition 21.3.20.0.3. Note 1: exploitable by supplying data to APIs in the component without untrusted Web Start applications or applets, for example through a web service. Credit: Albert Yang; Quang Luong of Calif.io | [Oracle Critical Security Patch Update, November 2026](https://www.oracle.com/security-alerts/cspunov2026.html) | +| Scores: OpenJDK and Oracle **8.1** (the detector's score); Calif 9.2; Red Hat 9.8 | the two advisories above; Calif advisory; Red Hat CVE page | + ## The flaw | Fact | Source | @@ -13,7 +23,7 @@ not something a source states. | What the unfixed code does with a 1 to 3 byte tail that ends in `=`: `output_size` is 0, `L_padding` decrements it to -1, `bzhiq(output_mask, -1, output_size)` with an index of 255 keeps all 64 mask bits, and the masked `evmovdqub` stores 64 bytes at `dest + dp`: a write of up to 64 bytes past the output the caller sized. Read from the stub, and observed (next row); no vendor source states the impact in words | same file, lines around `L_finalBit` and `L_padding` | | **Observed** on an AMD EPYC 9B14 (Zen 4, with avx512f, avx512bw, avx512vbmi and bmi2), 2026-11-17: after C2 compiles the decoder, `Base64.getDecoder().decode(src, dst)` of a malformed input that ends in a 1 to 3 character fragment with `=` (for example 64 valid characters then `A=`) writes bytes into `dst` past the decoded output. Seen on Temurin 18.0.2.1, 20.0.2, 17.0.6, 17.0.21, 21.0.2, 21.0.13 and 25.0.5; not seen on Temurin 17.0.5 or on SapMachine 21.0.13.1 (the fixed release); not seen on 21.0.13 started with `-XX:-UseBASE64Intrinsics` or with `-XX:UseAVX=2`. On 17.0.x to 20 the input has to be longer than 128 bytes, on 21 and later longer than 31 bytes: the 17u stub enters the AVX-512 path only above 128 bytes (`cmpl(length, 128)`), the 21u stub above 31. With an output array sized by `decode(byte[])` the write goes past the array into the heap. The test program is not in this repository | local run, `eclipse-temurin` images and the SapMachine 21.0.13.1 tarball (sha256 `6cb4df18…949ae9`, matching the GitHub release asset digest) | | CVE-2026-114938 is listed with CVSS 8.1, component hotspot/compiler, in Amazon Corretto's changelogs of 2026-11-17 | [corretto-17 CHANGELOG 17.0.21.1.2](https://github.com/corretto/corretto-17/blob/17.0.21.1.2/CHANGELOG.md), [corretto-21 21.0.13.1.2](https://github.com/corretto/corretto-21/blob/21.0.13.1.2/CHANGELOG.md), [corretto-25 25.0.5.1.2](https://github.com/corretto/corretto-25/blob/25.0.5.1.2/CHANGELOG.md), [corretto-27 27.0.1.1.4](https://github.com/corretto/corretto-27/blob/27.0.1.1.4/CHANGELOG.md) | -| CVE-2026-114938 is JDK-8393212. The Corretto changelogs list CVEs by component, not by JDK bug, and the OpenJDK advisory that states the mapping could not be read (HTTP 403 for the lead, unreachable here). The public writeups (lead's sources below) describe exactly the code 8393212 changes: the output mask computed from length and padding, `output_len` underflowing on a padding-only tail, `bzhiq(-1, output_len)` giving all ones and `evmovdqub` writing all 64 bytes. **Inferred from that match**, not stated by a source | Corretto changelogs; Calif and Semgrep writeups as relayed by the lead | +| CVE-2026-114938 is JDK-8393212. Neither the Corretto changelogs (CVEs by component) nor the OpenJDK advisory (no JDK bug ids) state the mapping. The advisory does confirm what 8393212 fits: component hotspot/compiler, lines 17, 21, 25 and 27 (the lines with the AVX-512 VBMI decoder), and last affected releases just before the .1 releases that carry 8393212. The public writeups (lead's sources below) describe exactly the code 8393212 changes: the output mask computed from length and padding, `output_len` underflowing on a padding-only tail, `bzhiq(-1, output_len)` giving all ones and `evmovdqub` writing all 64 bytes. **Inferred from that match**, not stated by a source | Corretto changelogs; OpenJDK advisory; Calif and Semgrep writeups as relayed by the lead | | The vulnerable path runs only when the CPU reports AVX-512 VBMI, AVX-512BW and BMI2 and HotSpot keeps them enabled: `if (VM_Version::supports_avx512_vbmi() && VM_Version::supports_avx512bw() && VM_Version::supports_bmi2())`. AVX-512 features need AVX-512F, so the four CPU flags are `avx512f avx512bw avx512vbmi bmi2` | stubGenerator_x86_64.cpp at the fix commit | | MIME decoding (`isMIME`) skips the AVX-512 path; standard and URL-safe decoding use it | same function, `cmpl(isMIME, 0)` | | `-XX:UseAVX=0/1/2` clears every AVX-512 feature, VBMI included, so the path is not generated | `src/hotspot/cpu/x86/vm_version_x86.cpp`, `if (UseAVX < 3)` block (jdk17u-dev and jdk HEAD) | @@ -27,11 +37,11 @@ The lead read these; they could not be fetched from the research host. Facts her | Fact | Source | | --- | --- | -| Named Java4Shell, credited to Calif. CVSS 9.2 (Corretto's changelogs list 8.1; the detector reports 9.2, the discoverer's score) | [Calif advisory](https://calif.io/java4shell/), [Semgrep blog](https://semgrep.dev/blog/2026/java4shell-openjdk-base64-vulnerability) | +| Named Java4Shell, credited to Calif. Calif scores it CVSS 9.2; OpenJDK, Oracle and Corretto 8.1, which the detector reports | [Calif advisory](https://calif.io/java4shell/), [Semgrep blog](https://semgrep.dev/blog/2026/java4shell-openjdk-base64-vulnerability) | | Trigger: 64 `A` then `=` (on 17: 128 `A` then `=`); a 65-byte input decoded into a 50-byte buffer is written 62 bytes past its end. Reached only after the intrinsic is JIT-compiled. Matches what was observed here (65 and 129 byte inputs) | same | | Pre-authentication remote code execution shown on default configurations of Keycloak, Jira, Confluence, JFrog Artifactory, Jenkins and PingFederate; post-authentication on Kafka, Solr, Elasticsearch, Gerrit and Spinnaker; Struts and Spring Boot sample apps; and a client-side variant (a Java client opening TLS to a malicious server). Chain details withheld | same, and posts by Charles Carmakal (Mandiant) and Semgrep | -| Affected: OpenJDK 17.0.6 and later on x86-64 CPUs with avx512f, avx512bw, avx512vbmi and bmi2; ARM64 not affected; every distribution. Oracle Java SE builds named as affected: **8u511b33-perf**, 17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3 (for 8, only the Performance Pack build). The 8u-perf build carries a backport of the decoder; **no fixed 8u-perf version is known**. The detector reports a Java 8 VM library that carries the decoder's stubs as vulnerable up to update 511 and unknown above it | same; Oracle alert cspunov2026 (403 for the lead) | -| Oracle and OpenJDK released fixes on 2026-11-17 (Oracle alert "cspunov2026"); the lead had no fixed versions per line. They are established above from the OpenJDK repositories and vendor releases | lead | +| Affected: OpenJDK 17.0.6 and later on x86-64 CPUs with avx512f, avx512bw, avx512vbmi and bmi2; ARM64 not affected; every distribution. Oracle Java SE builds named as affected: **8u511b33-perf**, 17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3 (for 8, only the Performance Pack build). The 8u-perf build carries a backport of the decoder; **no fixed 8u-perf version is known**. The detector reports a Java 8 VM library that carries the decoder's stubs as vulnerable up to update 511 and unknown above it | same; Oracle CSPU November 2026 (above) | +| Oracle and OpenJDK released fixes on 2026-11-17 (the advisories above); neither page names the fixed versions per line. They are established below from the OpenJDK repositories and vendor releases | lead | | Mitigations: `-XX:-UseBASE64Intrinsics` (preferred, for example through `JAVA_TOOL_OPTIONS`), or `-XX:UseAVX=2` on x86-64 only: **an ARM JVM refuses to start with it** | same | | CPU check: `grep -m1 '^flags' /proc/cpuinfo \| tr ' ' '\n' \| grep -E '^(avx512f\|avx512bw\|avx512vbmi\|bmi2)$'` (all four needed); Kubernetes node label `feature.node.kubernetes.io/cpu-cpuid.AVX512VBMI: "true"` (Node Feature Discovery) | Calif | | Indicators (not proof): `hs_err_pid*.log` crash files and bursts of `IllegalArgumentException` from `java.util.Base64$Decoder`. No network signature or IOCs published | same | @@ -60,7 +70,7 @@ The lead read these; they could not be fetched from the research host. Facts her | 18, 19, 20, 22, 23, 24 | **no fix** (end of life) | n/a | | JDK 28 (early access) | fix pushed to mainline 2026-11-16; `jdk-28+24` does **not** have it; no later build tagged yet | openjdk/jdk tags | | 17.0.22, 21.0.14, 25.0.6 (January 2027 updates) | **not known**: the -dev repositories (HEAD of 2026-11-17, tags up to `+2`) do not have the fix yet. Embargoed fixes usually reach -dev at the next release; that is an expectation, not a fact, so these versions are reported as unknown | openjdk/jdk17u-dev, jdk21u-dev, jdk25u-dev HEAD | -| 17.0.21.0.2 / .0.3, 21.0.13.0.2 / .0.3, 25.0.5.0.2 / .0.3, 27.0.1.0.2 / .0.3 | **not fixed**: these October 2026 out-of-band releases carry CA changes only (8395142, 8395690) | -dev repo tags `jdk-*.0.3+*` | +| 17.0.21.0.2 / .0.3, 21.0.13.0.2 / .0.3, 25.0.5.0.2 / .0.3, 27.0.1.0.2 / .0.3 | **not fixed**: these October 2026 out-of-band releases carry CA changes only (8395142, 8395690); the OpenJDK advisory and Oracle name the .0.3 releases as the last affected. Vendors ship them as five-part versions (Oracle and Debian sid 17.0.21.0.3, Microsoft 17.0.21.0.2 / 21.0.13.0.2 / 25.0.5.0.2, Temurin 27.0.1.0.2+1); the detector judges every one vulnerable, from the VM library, the release file, OS package pins, image tags and version files | -dev repo tags `jdk-*.0.3+*`; OpenJDK advisory; Oracle CSPU | ## Vendors and distributions (2026-11-17, rechecked 2026-11-18) @@ -68,27 +78,50 @@ The lead read these; they could not be fetched from the research host. Facts her | --- | --- | --- | | Amazon Corretto | fixed: 17.0.21.1.2, 21.0.13.1.2, 25.0.5.1.2, 27.0.1.1.4 (all 2026-11-17, each "Import jdk-…1+2/+4", CVE-2026-114938 listed). Corretto 8 and 11: no release after October (not affected). **Docker Hub, 2026-11-18:** Amazon republished the existing `amazoncorretto:21.0.13-*` and `17.0.21-*` tags with the fixed builds (the images report 21.0.13.1+2 and 17.0.21.1+2); there are no `.1` tags. A Corretto tag of the fixed update therefore names whichever build was pushed last, and the detector reads the image | GitHub releases API, CHANGELOG.md of each tag; images scanned by this detector (parity cases corretto-*) | | SapMachine | releases 17.0.21.1, 21.0.13.1, 25.0.5.1, 27.0.1.1 published 2026-11-17 (the release page names no CVE) | GitHub releases API, SAP/SapMachine | -| Eclipse Temurin | **not fixed yet**: no `jdk-17.0.21.1+2`, `jdk-21.0.13.1+2`, `jdk-25.0.5.1+2` or `jdk-27.0.1.1+4` release in adoptium/temurinNN-binaries; Docker Hub `eclipse-temurin` newest tags are 17.0.21_9, 21.0.13_9, 25.0.5_8, 27.0.1.0 | GitHub API, registry-1.docker.io tag list | -| Azul Zulu, BellSoft Liberica, Microsoft, Oracle | **not checked**: their sites could not be reached from the research host. Docker Hub `azul/zulu-openjdk` and `bellsoft/liberica-openjdk-debian` newest tags are 27.0.1.0.3 / 21.0.13.0.3 (not fixed) | registry-1.docker.io tag list | +| Eclipse Temurin | **not fixed** (2026-11-18): newest releases 17.0.21+9, 21.0.13+9-LTS, 25.0.5+8-LTS, 27.0.1.0.2+1; no 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 build on any line. Docker Hub `eclipse-temurin` newest tags 17.0.21_9, 21.0.13_9, 25.0.5_8, 27.0.1.0 | api.adoptium.net (lead, 2026-11-18); GitHub API, registry-1.docker.io tag list (2026-11-17) | +| Microsoft Build of OpenJDK | **not fixed** (2026-11-18): newest releases 17.0.21.0.2, 21.0.13.0.2, 25.0.5.0.2 (download page of 2026-11-04), which predate the fix | learn.microsoft.com/java/openjdk release notes and download page (lead) | +| Oracle Java SE | 8u511b33-perf, 17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3 and earlier affected; the fixed Oracle version numbers were not relayed, so Oracle builds after .0.3 are judged by the OpenJDK fixed releases | Oracle CSPU November 2026 | +| Oracle GraalVM, GraalVM Community | GraalVM for JDK 17.0.21.0.3 and 21.0.13.0.3 and GraalVM Enterprise Edition 21.3.20.0.3 affected; **no fixed GraalVM build known** (2026-11-18). See "GraalVM" below | Oracle CSPU November 2026 | +| Azul Zulu, BellSoft Liberica | **not checked**: their pages could not be read (HTTP 403/404 for the lead; unreachable here). Docker Hub `azul/zulu-openjdk` and `bellsoft/liberica-openjdk-debian` newest tags were 27.0.1.0.3 / 21.0.13.0.3 on 2026-11-17 (not fixed) | registry-1.docker.io tag list | | IBM Semeru | OpenJ9, not HotSpot (see above) | image inspection | -| Debian | **not fixed yet**: newest sources openjdk-17 17.0.21.0.3+1-1, openjdk-21 21.0.13.0.3+1-1, openjdk-25 25.0.5.0.3+1-3; security.debian.org 17.0.21+9-1~deb12u1, 21.0.13+9-1~deb13u2, 25.0.5+8-1~deb13u1. The security tracker has no page for CVE-2026-114938 | deb.debian.org and security.debian.org pools, security-tracker.debian.org | -| Ubuntu | **not fixed yet**: newest sources openjdk-17 17.0.21.0.3+1-1~XX.04.1, openjdk-25 25.0.5.0.3+1-3~XX.04.1 (openjdk-21 listing timed out) | archive.ubuntu.com pool | -| Alpine | **not fixed yet**: community openjdk17 17.0.21.0.3_p1-r0, openjdk21 21.0.13.0.3_p1-r0, openjdk25 25.0.5.0.3_p1-r0/-r1 (3.23, 3.24, edge); 3.21 and 3.22 carry older 17/21 | dl-cdn.alpinelinux.org APKINDEX | -| Red Hat (RHEL, UBI) | **not checked**: access.redhat.com and registry.access.redhat.com unreachable | n/a | +| Debian | **not fixed** (2026-11-18): the tracker lists every package vulnerable and unfixed: openjdk-17 bookworm-security 17.0.21+9-1~deb12u1, sid 17.0.21.0.3+1-1; openjdk-21 trixie-security 21.0.13+9-1~deb13u2, forky/sid 21.0.13.0.3+1-1; openjdk-25 trixie-security 25.0.5+8-1~deb13u1, sid 25.0.5.0.3+1-3; openjdk-27 sid 27.0.1.0.3+1-1 | [security-tracker.debian.org CVE-2026-114938](https://security-tracker.debian.org/tracker/CVE-2026-114938) (lead); deb.debian.org and security.debian.org pools | +| Ubuntu | **not fixed**: newest sources openjdk-17 17.0.21.0.3+1-1~XX.04.1, openjdk-25 25.0.5.0.3+1-3~XX.04.1 (openjdk-21 listing timed out, 2026-11-17). The Ubuntu CVE page could not be read (2026-11-18) | archive.ubuntu.com pool | +| Alpine | **not fixed**: community openjdk17 17.0.21.0.3_p1-r0, openjdk21 21.0.13.0.3_p1-r0, openjdk25 25.0.5.0.3_p1-r0/-r1 (3.23, 3.24, edge); 3.21 and 3.22 carry older 17/21. The edge secdb had no entry for the CVE on 2026-11-18 | dl-cdn.alpinelinux.org APKINDEX; Alpine secdb (lead) | +| Red Hat (RHEL, UBI) | **no fixed build** (2026-11-18): affected "OpenJDK 17.0.6 and later" on x86-64 with AVX-512 VBMI; "exact upstream fixed version ... not yet confirmed by Oracle"; no fixed NVRs, no errata, no UBI tags. Bulletin RHSB-2026-018, Bugzilla 2574227, Red Hat CVSS 9.8. See "Red Hat" below | [access.redhat.com CVE-2026-114938](https://access.redhat.com/security/cve/CVE-2026-114938) (lead) | + +## GraalVM + +| Fact | Source | +| --- | --- | +| A GraalVM JDK is HotSpot with JVMCI: its `lib/server/libjvm.so` has HotSpot's version line with the JDK version and `-jvmci-` (`OpenJDK 64-Bit Server VM (17.0.6+10-jvmci-22.3-b13) for linux-amd64 JRE (17.0.6+10-jvmci-22.3-b13)`) and its release file has `GRAALVM_VERSION` and `IMPLEMENTOR="GraalVM Community"` | GraalVM CE images below | +| **Observed** 2026-11-18: GraalVM CE 22.3.0 for Java 17 is 17.0.5+8 and its libjvm has **no** decoder stubs; 22.3.1 for Java 17 is 17.0.6+10 **with** them; 22.3.1 for Java 11 is 11.0.18+10 without them; GraalVM CE for JDK 21 (GRAALVM_VERSION 23.1.2) is 21.0.2+13 with them | Docker Hub `findepi/graalvm` (a repackaging of the GraalVM CE release archives; registry ghcr.io/graalvm is unreachable here): `22.3.0-java17` sha256:b4460f6857d2…d9b373, `22.3.1-java17` sha256:a953392b9572…ada717, `22.3.1-java11` sha256:983c7f6640ca…66beed, `java21-native` sha256:19937684c9ef…8ed235 | +| GraalVM EE 21.3 ships JDK 11 and JDK 17 builds; which of them Oracle's listing of 21.3.20.0.3 covers is **not stated**. The detector judges a GraalVM JDK 17 build by its version (vulnerable today) and a GraalVM JDK 8 or 11 build vulnerable only when its libjvm carries the decoder stubs | Oracle CSPU; **inferred** | +| No fixed GraalVM build is known, and GraalVM's fixed builds need not follow OpenJDK's numbering, so the detector judges a GraalVM build at or past the OpenJDK fixed release as **unknown**, never fixed, until a fixed GraalVM build is listed in `knowledge.GraalVMFixed` (empty) | lead, 2026-11-18 | +| sdkman and asdf name GraalVM releases in GraalVM's numbers (`22.3.1.r17-grl`, `graalvm-22.3.1+java17`): 22.3.0 for 17 and any release for 8 or 11 are not affected; 22.3.1 and later for 17, and any release for 18 and later, are vulnerable; `22.3.r17` (no patch) and 21.3.x for 17 stay not checked. Liberica NIK and Mandrel follow GraalVM's numbering and are judged the same way (**inferred**: not checked against their releases) | observations above | +| Whether GraalVM Native Image binaries (SubstrateVM, no libjvm) carry a port of the decoder is **not known**; the detector does not look at them | n/a | + +## Red Hat + +| Fact | Source | +| --- | --- | +| Red Hat backports fixes into the update it ships, so a fixed Red Hat build can keep the upstream version in its libjvm and differ only in the rpm release. The detector keeps a backport table, `knowledge.RedHatFixed` (package, RHEL major release, fixed EVR, advisory), that marks rpm builds from that EVR on as fixed when their libjvm is the same update. It is **empty**: Red Hat had published no fixed build on 2026-11-18 | Red Hat CVE page (lead) | +| RHEL 8/9 and UBI install the JDK in `/usr/lib/jvm/java-17-openjdk--.` with `jre-17`, `jre` and `/etc/alternatives` symlinks into it; the rpm version appends the build to the update (17.0.21.0.9 is 17.0.21+9). **Not verified on a real image here**: registry.access.redhat.com and cdn-ubi.redhat.com (dnf in `redhat/ubi9`) are unreachable from the research host; the detector's tests use that layout | Red Hat packaging convention; unverified | +| UBI OpenJDK images (`registry.access.redhat.com/ubi9/openjdk-21`, `-runtime`, also on registry.redhat.io) are tagged by image release (1.20, 1.20-2.1729089285), not by Java update. With the table empty, the repo scan reports 21 and later (every release has the decoder) and 17 at `latest` as vulnerable, other 17 tags (older images could predate 17.0.6) as not checked and pulled, and 8 and 11 as not affected | lead; **inferred** | ## Advisory links -The detector's catalog entry links only pages someone on this work could read: the Calif advisory and the Semgrep post (read by -the lead), the OpenJDK fix commit and Amazon Corretto's changelog. **Not read by anyone (HTTP 403 or unreachable):** the OpenJDK -advisory https://openjdk.org/groups/vulnerability/advisories/2026-11-17 and Oracle's alert -https://www.oracle.com/security-alerts/cspunov2026.html; they are listed here only. +The detector's catalog entry links only pages someone on this work could read: the OpenJDK advisory and Oracle's CSPU (read by the +lead on 2026-11-17/18 after they were unreadable on 2026-11-17), the Calif advisory and the Semgrep post (read by the lead), the +OpenJDK fix commit and Amazon Corretto's changelog. ## How the detector uses this - The version that decides is the one inside the libjvm (` () for - JRE ()`), read from the binary, with the `release` file as a second witness; the CPU architecture comes from the ELF, PE or Mach-O header. - A packaged JDK (apk, dpkg, rpm) is judged by the same upstream version: no distribution has published a fixed package or a backport - statement yet. When one does, its fixed package version goes into the knowledge table. + statement yet. Red Hat's fixed builds, once published, go into the Red Hat backport table, which overrides the libjvm's version. +- A GraalVM JDK is judged by its JDK version, but never fixed until a fixed GraalVM build is listed. +- Findings carry CVSS 8.1, the OpenJDK and Oracle score. - No marker in the binary separates fixed from unfixed code: the stub is generated at run time by C++ code, and the fix only adds a compare and a branch to that generator. The stubs' names (`lookup_lo_base64`, `pack_vec_base64`, `join_0_1_base64`) do show that the AVX-512 decode path is present, which is how a vendor backport into an older line is caught. diff --git a/detectors/java4shell/coverage_test.go b/detectors/java4shell/coverage_test.go index d48307c..76a427c 100644 --- a/detectors/java4shell/coverage_test.go +++ b/detectors/java4shell/coverage_test.go @@ -1,6 +1,7 @@ package java4shell_test import ( + "github.com/DefectDojo/earlylight/detectors/java4shell" "os" "path/filepath" "strings" @@ -70,3 +71,27 @@ func TestGraalVMLayout(t *testing.T) { t.Errorf("GraalVM at the OpenJDK fix: %+v", f) } } + +// CVSS: the OpenJDK advisory and Oracle score CVE-2026-114938 8.1; that is +// the primary score (Calif's 9.2 and Red Hat's 9.8 are in FACTS.md). The +// two advisories are linked now that they have been read. +func TestManifestScoreAndLinks(t *testing.T) { + m := (&java4shell.Detector{}).Manifest() + for _, k := range m.Kinds { + if k.SecuritySeverity == "9.2" || k.SecuritySeverity == "9.8" { + t.Errorf("kind %s scores %s, want the OpenJDK/Oracle 8.1", k.ID, k.SecuritySeverity) + } + if k.Level == "error" && k.SecuritySeverity != "8.1" { + t.Errorf("kind %s scores %q", k.ID, k.SecuritySeverity) + } + } + links := strings.Join(m.Advisories, " ") + for _, u := range []string{"https://openjdk.org/groups/vulnerability/advisories/2026-11-17", "https://www.oracle.com/security-alerts/cspunov2026.html"} { + if !strings.Contains(links, u) { + t.Errorf("advisory %s not linked", u) + } + } + if !strings.Contains(m.Kinds[0].Description, "GraalVM") { + t.Error("the runtime kind does not say GraalVM is affected") + } +} diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index 14d2d9f..dbc0c1a 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -575,5 +575,5 @@ func fixText(f Finding, v knowledge.Version, ok bool) string { case f.JLinked: return fmt.Sprintf("Rebuild this jlink image from a JDK at %s.%s", target, interim) } - return fmt.Sprintf("Update this runtime to %s (Amazon Corretto and SapMachine published theirs on %s; others had not %s: check your vendor).%s", target, knowledge.VendorFixPublished, knowledge.AsOf(), interim) + return fmt.Sprintf("Update this runtime to %s (%s: check your vendor).%s", target, knowledge.VendorStatus(), interim) } diff --git a/detectors/java4shell/internal/assess/coverage_test.go b/detectors/java4shell/internal/assess/coverage_test.go index f00f9b7..754737d 100644 --- a/detectors/java4shell/internal/assess/coverage_test.go +++ b/detectors/java4shell/internal/assess/coverage_test.go @@ -151,3 +151,12 @@ func TestRedHatRuntime(t *testing.T) { t.Errorf("Fedora: %s (%s)", f.Status, f.Reason) } } + +func TestVendorStatusFix(t *testing.T) { + f := one(t, Input{Libraries: []*jvm.Library{lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true})}}) + for _, s := range []string{"Amazon Corretto and SapMachine", "Temurin, Microsoft, Debian, Ubuntu, Alpine and Red Hat had not", "Azul and BellSoft Liberica were not checked"} { + if !strings.Contains(f.Fix, s) { + t.Errorf("fix text does not say %q: %s", s, f.Fix) + } + } +} diff --git a/detectors/java4shell/internal/knowledge/knowledge.go b/detectors/java4shell/internal/knowledge/knowledge.go index 53315d8..b9ad01b 100644 --- a/detectors/java4shell/internal/knowledge/knowledge.go +++ b/detectors/java4shell/internal/knowledge/knowledge.go @@ -12,8 +12,9 @@ import ( // CVE is the vulnerability this detector checks. const CVE = "CVE-2026-114938" -// Bug is the OpenJDK change taken as the fix. The mapping is inferred: -// the OpenJDK advisory that would state it could not be read, and the +// Bug is the OpenJDK change taken as the fix. The mapping is inferred: the +// OpenJDK advisory confirms the component (hotspot/compiler), the lines (17, +// 21, 25, 27) and the last affected releases but names no JDK bug, and the // public descriptions of the CVE match this change (FACTS.md). const Bug = "JDK-8393212" @@ -38,6 +39,33 @@ const ( VendorFixPublished = "2026-11-17" ) +// The advisories that name the affected releases (read by the lead on +// 2026-11-17/18; FACTS.md). +const ( + OpenJDKAdvisory = "https://openjdk.org/groups/vulnerability/advisories/2026-11-17" + OracleAdvisory = "https://www.oracle.com/security-alerts/cspunov2026.html" +) + +// CVSS is the score OpenJDK and Oracle give (CVSS 3.1 +// AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H). Calif scores it 9.2 and Red Hat +// 9.8 (FACTS.md). +const CVSS = "8.1" + +// Vendor status as of Checked, for fix texts. +const ( + // VendorsFixed published fixed releases. + VendorsFixed = "Amazon Corretto and SapMachine" + // VendorsNotFixed had published none. + VendorsNotFixed = "Temurin, Microsoft, Debian, Ubuntu, Alpine and Red Hat" + // VendorsNotChecked could not be checked. + VendorsNotChecked = "Azul and BellSoft Liberica" +) + +// VendorStatus says who had published a fixed release, in words. +func VendorStatus() string { + return VendorsFixed + " published theirs on " + VendorFixPublished + "; " + VendorsNotFixed + " had not " + AsOf() + "; " + VendorsNotChecked + " were not checked" +} + // AsOf says a status statement's date. func AsOf() string { return "as of " + Checked + ", the date of this detector's release data" } diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index 4321a1b..5efcd6c 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -210,3 +210,36 @@ func TestRedHatRepo(t *testing.T) { t.Errorf("the listed fixed build reported: %+v", f) } } + +// Vendor status of 2026-11-18: Temurin, Microsoft, Debian, Ubuntu, Alpine +// had no fixed release and Red Hat no fixed build; Azul and Liberica were +// not checked. +func TestVendorStatus(t *testing.T) { + res := scan(t, tree(t, map[string]string{ + "Dockerfile": "FROM ubuntu:24.04\nRUN apt-get install -y msopenjdk-21\nRUN apt-get install -y zulu21-jdk\n", + ".github/workflows/ci.yml": "jobs:\n a:\n steps:\n - uses: actions/setup-java@v5\n with:\n distribution: microsoft\n java-version: '21'\n", + ".java-version": "21.0.13\n", + })) + checkAll(t, res, []want{ + {"Dockerfile", 2, RulePackage, StatusVulnerable}, + {"Dockerfile", 3, RulePackage, StatusUnknown}, + {".github/workflows/ci.yml", 7, RuleJavaPin, StatusVulnerable}, + {".java-version", 1, RuleJavaPin, StatusVulnerable}, + }) + for _, c := range []struct { + file string + line int + text []string + }{ + {"Dockerfile", 2, []string{"Microsoft", "2026-11-18"}}, + {".github/workflows/ci.yml", 7, []string{"Microsoft", "2026-11-18"}}, + {".java-version", 1, []string{"Temurin, Microsoft, Debian, Ubuntu, Alpine and Red Hat", "Azul and BellSoft Liberica were not checked"}}, + } { + f, _ := find(res, c.file, c.line) + for _, s := range c.text { + if !strings.Contains(f.Reason+" "+f.Fix, s) { + t.Errorf("%s:%d does not say %q: %s / %s", c.file, c.line, s, f.Reason, f.Fix) + } + } + } +} diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index a6546cd..1bc946c 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -372,7 +372,7 @@ func (s *scanner) judgeVersion(rel string, line, col int, verText, source, vendo func pinFix(feature int, source string) string { if fx := knowledge.FixedVersion(feature); fx != "" { - return fmt.Sprintf("Select Java %s or later of the same update in %s once your vendor publishes it (Amazon Corretto and SapMachine did on %s; Temurin, Debian, Ubuntu and Alpine had not %s), and reinstall.", fx, source, knowledge.VendorFixPublished, knowledge.AsOf()) + return fmt.Sprintf("Select Java %s or later of the same update in %s once your vendor publishes it (%s), and reinstall.", fx, source, knowledge.VendorStatus()) } return fmt.Sprintf("Java %d received no fix: move %s to a supported release with the fix, such as %s.", feature, source, knowledge.Upgrade(feature)) } @@ -523,6 +523,10 @@ func vendorWord(s string) string { // moving version ("21") installs a fixed release. var publishedFix = map[string]bool{"corretto": true, "sapmachine": true} +// notFixedYet are the distributions (setup-java names) whose newest release +// of each fixed line did not have the fix when the data was checked. +var notFixedYet = map[string]string{"temurin": "Eclipse Temurin", "adopt": "Eclipse Temurin", "adopt-hotspot": "Eclipse Temurin", "microsoft": "Microsoft"} + func (s *scanner) workflow(rel string, b []byte) { var doc yaml.Node if err := yaml.Unmarshal(b, &doc); err != nil { @@ -622,11 +626,11 @@ func (s *scanner) movingSetupJava(rel string, v *yaml.Node, ver, dist string) { } fx := knowledge.FixedVersion(feature) props := map[string]string{"source": "actions/setup-java", "current": ver, "distribution": dist, "fixed_in": fx} - if dist == "temurin" || dist == "adopt" || dist == "adopt-hotspot" { + if who := notFixedYet[dist]; who != "" { s.add(Finding{Rule: RuleJavaPin, File: rel, Line: v.Line, Level: "warning", Status: StatusVulnerable, Props: props, - Reason: fmt.Sprintf("Eclipse Temurin had published no Java %s as of %s, so the job installs a release without the fix", fx, knowledge.Checked), + Reason: fmt.Sprintf("%s had published no Java %s as of %s, so the job installs a release without the fix", who, fx, knowledge.Checked), Message: fmt.Sprintf("actions/setup-java installs the newest %s Java %d, which had no Java4Shell fix yet", orAny(dist), feature), - Fix: fmt.Sprintf("Rerun once Temurin publishes Java %s, or use distribution corretto or sapmachine, whose newest Java %d has the fix.", fx, feature)}) + Fix: fmt.Sprintf("Rerun once %s publishes Java %s, or use distribution corretto or sapmachine, whose newest Java %d has the fix.", who, fx, feature)}) return } s.add(Finding{Rule: RuleNotChecked, File: rel, Line: v.Line, Level: "note", Status: StatusUnknown, Props: props, @@ -1113,7 +1117,7 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { Reason: fmt.Sprintf("%s published Java %s on %s: an image built after that gets it, one built or cached before does not", who, fx, knowledge.VendorFixPublished), Message: fmt.Sprintf("installs %s %s: whether the image has the Java4Shell fix depends on when it was built", h.name, what), Fix: fmt.Sprintf("Rebuild without the layer cache, or pin %s to Java %s or later.", h.name, fx)}) - case "zulu", "msopenjdk": + case "zulu": s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: props, Reason: fmt.Sprintf("%s's fixed release could not be checked (%s)", who, knowledge.Checked), Message: fmt.Sprintf("installs %s %s: not checked for the Java4Shell fix", h.name, what), @@ -1126,9 +1130,9 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { fix = rpmFix(h.name) } msg := fmt.Sprintf("installs %s %s: it gets whatever the distribution has, which had no Java4Shell fix yet", h.name, what) - if h.vendor == "temurin" { - reason = fmt.Sprintf("Eclipse Temurin had published no %s release as of %s, so a build today installs a release without it", fx, knowledge.Checked) - msg = fmt.Sprintf("installs %s %s: Temurin had no Java4Shell fix yet", h.name, what) + if h.vendor == "temurin" || h.vendor == "msopenjdk" { + reason = fmt.Sprintf("%s had published no %s release as of %s, so a build today installs a release without it", who, fx, knowledge.Checked) + msg = fmt.Sprintf("installs %s %s: %s had no Java4Shell fix yet", h.name, what, who) } if h.feature == 0 { msg = fmt.Sprintf("installs %s, the distribution's default OpenJDK (17 or later on current Debian and Ubuntu releases), which had no Java4Shell fix yet", h.name) diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index b098863..e58b583 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -56,7 +56,8 @@ const about = " HotSpot's AVX-512 VBMI Base64 decoder (x86-64, JDK 18 and later, " with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel server CPUs from Ice Lake on and some client CPUs, not Alder" + " Lake or Raptor Lake; AMD Zen 4 and later; common on cloud instances). Fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1" + " and 27.0.1.1 (by JDK-8393212, the change the public descriptions of the CVE match); Java 18 to 20, 22 to 24" + - " and 26 received no fix. -XX:-UseBASE64Intrinsics (or, on x86-64 only, -XX:UseAVX=2) keeps the decoder from being" + + " and 26 received no fix. Oracle GraalVM for JDK 17 and 21 and GraalVM Enterprise Edition 21.3 are affected too, with no" + + " fixed GraalVM build known yet. -XX:-UseBASE64Intrinsics (or, on x86-64 only, -XX:UseAVX=2) keeps the decoder from being" + " generated until the runtime is updated." // Manifest describes the detector. @@ -67,6 +68,8 @@ func (d *Detector) Manifest() engine.Manifest { Title: "Java4Shell: HotSpot AVX-512 Base64 decoder out-of-bounds write (" + knowledge.CVE + ")", CVEs: []string{knowledge.CVE}, Advisories: []string{ + knowledge.OpenJDKAdvisory, + knowledge.OracleAdvisory, "https://calif.io/java4shell/", "https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b", "https://semgrep.dev/blog/2026/java4shell-openjdk-base64-vulnerability", @@ -75,9 +78,9 @@ func (d *Detector) Manifest() engine.Manifest { Disclosed: knowledge.Disclosed, Targets: []engine.TargetKind{engine.Filesystem, engine.Image, engine.Repository}, Kinds: append([]engine.Kind{ - {ID: KindRuntime, Title: "Java runtime vulnerable to Java4Shell", Level: "error", SecuritySeverity: "9.2", CWEs: cwe, + {ID: KindRuntime, Title: "Java runtime vulnerable to Java4Shell", Level: "error", SecuritySeverity: knowledge.CVSS, CWEs: cwe, Description: "A HotSpot Java runtime for x86-64 with the AVX-512 VBMI Base64 decoder and without the fix: an installed JDK or JRE, a packaged OpenJDK, a jlink image or a runtime in a container image." + about}, - {ID: KindBundled, Title: "Java runtime bundled in a product is vulnerable to Java4Shell", Level: "error", SecuritySeverity: "9.2", CWEs: cwe, + {ID: KindBundled, Title: "Java runtime bundled in a product is vulnerable to Java4Shell", Level: "error", SecuritySeverity: knowledge.CVSS, CWEs: cwe, Description: "A Java runtime that a product ships inside its own install directory (Atlassian Jira and Confluence, Elasticsearch, Artifactory, JetBrains IDEs and others) without the fix. Updating the operating system's Java does not fix it: upgrade the product." + about}, }, repoKinds()...), Tags: []string{"security", "java", "openjdk", "hotspot", "Java4Shell"}, diff --git a/detectors/java4shell/repo.go b/detectors/java4shell/repo.go index 9494a26..dd333ce 100644 --- a/detectors/java4shell/repo.go +++ b/detectors/java4shell/repo.go @@ -32,15 +32,15 @@ const ( func repoKinds() []engine.Kind { cwe := []string{"CWE-787"} return []engine.Kind{ - {ID: KindImagePin, Title: "Source tree uses a Java image without the Java4Shell fix", Level: "error", SecuritySeverity: "9.2", CWEs: cwe, + {ID: KindImagePin, Title: "Source tree uses a Java image without the Java4Shell fix", Level: "error", SecuritySeverity: knowledge.CVSS, CWEs: cwe, Description: "A Dockerfile, Compose, Kubernetes, Helm values, CI or Jib file names a Java runtime image (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine and others) whose tag is a Java release without the fix."}, - {ID: KindImage, Title: "Image the source tree uses holds a Java runtime vulnerable to Java4Shell", Level: "error", SecuritySeverity: "9.2", CWEs: cwe, + {ID: KindImage, Title: "Image the source tree uses holds a Java runtime vulnerable to Java4Shell", Level: "error", SecuritySeverity: knowledge.CVSS, CWEs: cwe, Description: "An image the tree builds on or deploys, read from its registry for linux/amd64 and judged as scan image does: a moving tag, or a product image (Jira, Elasticsearch, Jenkins...) that carries its own runtime."}, {ID: KindJavaPin, Title: "Source tree pins a Java release without the Java4Shell fix", Level: "warning", SecuritySeverity: "6.5", CWEs: cwe, Description: "A version file (.java-version, .sdkmanrc, .tool-versions, mise), a GitHub Actions setup-java step, a buildpack setting or a Maven Enforcer floor that selects or allows a Java release without the fix."}, - {ID: KindLine, Title: "Source tree selects a Java line that received no Java4Shell fix", Level: "error", SecuritySeverity: "9.2", CWEs: cwe, + {ID: KindLine, Title: "Source tree selects a Java line that received no Java4Shell fix", Level: "error", SecuritySeverity: knowledge.CVSS, CWEs: cwe, Description: "A toolchain, version file, CI step, buildpack, image or package of Java 18, 19, 20, 22, 23, 24 or 26: those lines are end of life and received no fix."}, - {ID: KindPackage, Title: "Dockerfile installs a distribution OpenJDK package without the Java4Shell fix", Level: "error", SecuritySeverity: "9.2", CWEs: cwe, + {ID: KindPackage, Title: "Dockerfile installs a distribution OpenJDK package without the Java4Shell fix", Level: "error", SecuritySeverity: knowledge.CVSS, CWEs: cwe, Description: "An apt, apk, dnf, yum or microdnf install of an OpenJDK 17 or later package pinned to a release without the fix, or without a version while the distribution had no fixed package."}, {ID: KindNotChecked, Title: "Java runtime not checked for the Java4Shell fix", Level: "note", Description: "An image whose tag does not name one Java release (a moving tag, a product image) that was not read, a workflow expression, or a file that could not be read. It is not known to be safe."}, From e4a4ec61463ce4c032264249b15b7622061e4bfc Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 04:38:12 +0000 Subject: [PATCH 047/119] java4shell: fuzz the rpm comparison and seed the new repo forms Co-Authored-By: Claude Opus 5.5 --- .../internal/knowledge/redhat_test.go | 24 +++++++++++++++++++ .../java4shell/internal/repo/repo_test.go | 3 +++ 2 files changed, 27 insertions(+) diff --git a/detectors/java4shell/internal/knowledge/redhat_test.go b/detectors/java4shell/internal/knowledge/redhat_test.go index cc004ad..6814ef3 100644 --- a/detectors/java4shell/internal/knowledge/redhat_test.go +++ b/detectors/java4shell/internal/knowledge/redhat_test.go @@ -76,3 +76,27 @@ func TestRPMUpstream(t *testing.T) { } } } + +func FuzzRPM(f *testing.F) { + for _, s := range [][2]string{{"1:17.0.21.0.9-1.el9_6", "17.0.21.0.9-2.el9"}, {"1.0~rc1-1", "1.0a-1"}, {"22.3.1", "17"}} { + f.Add(s[0], s[1]) + } + f.Fuzz(func(t *testing.T, a, b string) { + if len(a) > 256 || len(b) > 256 { + return + } + if c := CompareRPM(a, a); c != 0 { + t.Fatalf("CompareRPM(%q, itself) = %d", a, c) + } + if x, y := CompareRPM(a, b), CompareRPM(b, a); x != -y { + t.Fatalf("CompareRPM(%q, %q) = %d but reversed %d", a, b, x, y) + } + _ = RPMUpstream(a) + if st, why, known := JudgeRedHat("java-17-openjdk-headless", a); known && (st == "" || why == "") { + t.Fatalf("JudgeRedHat(%q) gave no verdict or reason", a) + } + if st, why := JudgeGraalVMRelease(a, len(b)%40); st == "" || why == "" { + t.Fatalf("JudgeGraalVMRelease(%q) gave no verdict or reason", a) + } + }) +} diff --git a/detectors/java4shell/internal/repo/repo_test.go b/detectors/java4shell/internal/repo/repo_test.go index 5df009c..b35aef1 100644 --- a/detectors/java4shell/internal/repo/repo_test.go +++ b/detectors/java4shell/internal/repo/repo_test.go @@ -247,6 +247,9 @@ func FuzzScanText(f *testing.F) { f.Add(".github/workflows/a.yml", "jobs:\n a:\n steps:\n - uses: actions/setup-java@v4\n with:\n java-version: |\n 17\n 21.0.5\n") f.Add("pom.xml", "[17.0.1,)eclipse-temurin:21.0.1_12-jre") f.Add(".tool-versions", "java corretto-21.0.5.11.1\n") + f.Add(".sdkmanrc", "java=22.3.1.r17-grl\njava=21.0.13.1-graal\n") + f.Add(".tool-versions", "java graalvm-22.3.1+java17\n") + f.Add("Dockerfile", "FROM registry.access.redhat.com/ubi9/openjdk-21:1.20\nRUN microdnf install -y java-17-openjdk-headless-1:17.0.21.1.1-1.el9.x86_64\nFROM container-registry.oracle.com/graalvm/jdk:21.0.13\n") f.Add("compose.yaml", "services:\n a:\n image: amazoncorretto:21.0.1\n environment: [\"JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics\"]\n") f.Fuzz(func(t *testing.T, name, text string) { if strings.ContainsAny(name, "/\\\x00") || name == "" || name == "." || name == ".." || len(text) > 1<<16 { From 544c76539c950de1c3d10b85cf0b081448676b29 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 04:47:04 +0000 Subject: [PATCH 048/119] parity: java4shell GraalVM CE images, Debian sid five-part package, Red Hat and GraalVM repo lines New cases: GraalVM CE 22.3.0/Java 17 (17.0.5, not affected), 22.3.1/Java 17 (17.0.6, vulnerable) and for JDK 21 (21.0.2, vulnerable), pinned by digest from findepi/graalvm (ghcr.io is unreachable here); Debian sid openjdk-17-jre-headless 17.0.21.0.3+1-1 (vulnerable). The repo case adds UBI images, a microdnf install, an Oracle GraalVM image and an sdkman GraalVM name. 43/43 match. Co-Authored-By: Claude Opus 5.5 --- parity/JAVA4SHELL-RESULTS.md | 8 +- parity/java4shell/cases.json | 93 ++++++++++++++++++- parity/java4shell/debian-sid-pkg.Dockerfile | 4 + parity/java4shell/repo/Dockerfile.redhat | 5 + parity/java4shell/repo/graalvm/.sdkmanrc | 1 + parity/java4shell/repo/graalvm/.tool-versions | 1 + 6 files changed, 108 insertions(+), 4 deletions(-) create mode 100644 parity/java4shell/debian-sid-pkg.Dockerfile create mode 100644 parity/java4shell/repo/Dockerfile.redhat create mode 100644 parity/java4shell/repo/graalvm/.sdkmanrc create mode 100644 parity/java4shell/repo/graalvm/.tool-versions diff --git a/parity/JAVA4SHELL-RESULTS.md b/parity/JAVA4SHELL-RESULTS.md index 335feaa..acdd8a8 100644 --- a/parity/JAVA4SHELL-RESULTS.md +++ b/parity/JAVA4SHELL-RESULTS.md @@ -26,6 +26,9 @@ Generated by `parity/java4shell.py`. Each row's expected findings come from [FAC | liberica-21 | BellSoft Liberica 21.0.13.0.3
`bellsoft/liberica-openjre-debian:21.0.13.0.3`
linux/amd64 sha256:c5f59f695bc1ae8a588c88c60aef901ed3fc66a7d4ba1b44d2b83cc007c9cb86 | pass | linux/amd64 /usr/lib/jvm/jre-21.0.13.0.3-bellsoft-x86_64 runtime vulnerable vulnerable vm-library | | sapmachine-21 | SapMachine 21.0.13.0.3, before 21.0.13.1
`sapmachine:21.0.13.0.3-jre-ubuntu-noble`
linux/amd64 sha256:2d8895467d35e0f0c938fc8ba94a02792d1720ce738637969e342193c7dac16f | pass | linux/amd64 /usr/lib/jvm/sapmachine-21 runtime vulnerable vulnerable vm-library | | semeru-21 | IBM Semeru 21 (OpenJ9, not HotSpot)
`ibm-semeru-runtimes:open-21-jre`
linux/amd64 sha256:c60bbee4f364698fcf1361f3adde6b9b5faabe70b8c6cc8c179ba3f551a4616c | pass | linux/amd64 /opt/java/openjdk runtime fixed not-affected release-file | +| graalvm-ce-22.3.0-java17 | GraalVM CE 22.3.0 for Java 17: built on 17.0.5, before the decoder (findepi/graalvm repackages the CE release archives; ghcr.io is unreachable here)
`findepi/graalvm@sha256:b4460f6857d29beec43231b7cfbbaaa3e6eaafe2d5f406ff6ffb416751d9b373`
linux/amd64 sha256:b4460f6857d29beec43231b7cfbbaaa3e6eaafe2d5f406ff6ffb416751d9b373 | pass | linux/amd64 /graalvm runtime fixed not-affected vm-library | +| graalvm-ce-22.3.1-java17 | GraalVM CE 22.3.1 for Java 17: 17.0.6+10-jvmci-22.3-b13 with the decoder, no fixed GraalVM build
`findepi/graalvm@sha256:a953392b957211d965012180bd7600ab5929ea6326f9ea49d3aba5db24ada717`
linux/amd64 sha256:a953392b957211d965012180bd7600ab5929ea6326f9ea49d3aba5db24ada717 | pass | linux/amd64 /graalvm runtime vulnerable vulnerable vm-library | +| graalvm-ce-21 | GraalVM CE for JDK 21 (23.1.2): 21.0.2+13-jvmci-23.1-b30
`findepi/graalvm@sha256:19937684c9efd655c5892f83c9c381f139b0b271818303ebe1159cf7968ed235`
linux/amd64 sha256:19937684c9efd655c5892f83c9c381f139b0b271818303ebe1159cf7968ed235 | pass | linux/amd64 /graalvm runtime vulnerable vulnerable vm-library | | elasticsearch | Elasticsearch 9.5.5, which bundles its own JDK
`elasticsearch:9.5.5`
linux/amd64 sha256:4f963521f1ac85a08b27f2ac1c864697c9729ade989ed49d2a143cf5f79c222f | pass | linux/amd64 /usr/share/elasticsearch/jdk bundled-runtime vulnerable vulnerable vm-library | | sapmachine-fixed | SapMachine 21.0.13.1 (fixed), unpacked from its release tarball | pass | linux/amd64 /opt/sapmachine runtime fixed fixed vm-library | | build1-boundary | SYNTHETIC: SapMachine 21.0.13.1 rewritten to build +1, below the fixed build +2 | pass | linux/amd64 /opt/sapmachine runtime vulnerable vulnerable vm-library | @@ -34,6 +37,7 @@ Generated by `parity/java4shell.py`. Each row's expected findings come from [FAC | alpine-pkg | Alpine 3.23 openjdk21-jre-headless (21.0.13.0.3_p1-r0, no fixed package) | pass | linux/amd64 /usr/lib/jvm/java-21-openjdk runtime vulnerable vulnerable vm-library | | debian-pkg | Debian 12 openjdk-17-jre-headless (17.0.21+9-1~deb12u1, no fixed package) | pass | linux/amd64 /usr/lib/jvm/java-17-openjdk-amd64 runtime vulnerable vulnerable vm-library | | ubuntu-pkg | Ubuntu 24.04 openjdk-25-jre-headless (25.0.5.0.3, no fixed package) | pass | linux/amd64 /usr/lib/jvm/java-25-openjdk-amd64 runtime vulnerable vulnerable vm-library | +| debian-sid-pkg | Debian sid openjdk-17-jre-headless (17.0.21.0.3+1-1, the five-part last affected release, no fixed package) | pass | linux/amd64 /usr/lib/jvm/java-17-openjdk-amd64 runtime vulnerable vulnerable vm-library | | mitigated-env | Temurin 21.0.13 with ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics | pass | linux/amd64 /opt/java/openjdk runtime vulnerable mitigated vm-library | | mitigated-useavx | Temurin 25.0.5 with ENV JDK_JAVA_OPTIONS=-XX:UseAVX=2 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable mitigated vm-library | | reenabled | JAVA_TOOL_OPTIONS mitigation undone by _JAVA_OPTIONS | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library | @@ -42,6 +46,6 @@ Generated by `parity/java4shell.py`. Each row's expected findings come from [FAC | hostile | Forged and 200 KiB release files over an unfixed VM library, a text file named libjvm.so, symlink loops | pass | linux/amd64 /opt/forged runtime vulnerable vulnerable vm-library
linux/amd64 /opt/huge runtime vulnerable vulnerable vm-library | | musl-forged | Temurin 21.0.13 on Alpine (musl) under a release file forged to say 21.0.13.1+2 | pass | linux/amd64 /opt/java/openjdk runtime vulnerable vulnerable vm-library | | debian-pkg-fs | The debian-pkg image exported and scanned as a filesystem | pass | fs /usr/lib/jvm/java-17-openjdk-amd64 runtime vulnerable vulnerable vm-library | -| repo | Source tree, offline: Dockerfiles (with install forms: --mount, :arch, .arch, /release, =${VAR}), Compose, Kubernetes, setup-java, version files, Gradle | pass | .github/workflows/ci.yml:12 java-line vulnerable
.github/workflows/ci.yml:8 java-pin vulnerable
.java-version:1 java-pin vulnerable
.sdkmanrc:1 java-pin vulnerable
Dockerfile.forms:2 os-package vulnerable
Dockerfile.forms:3 os-package unknown
Dockerfile.forms:4 os-package vulnerable
Dockerfile.forms:5 os-package vulnerable
Dockerfile.forms:6 os-package vulnerable
Dockerfile.pkg:2 os-package vulnerable
Dockerfile:1 image-pin vulnerable
build.gradle.kts:3 java-line vulnerable
build.gradle.kts:7 image-pin vulnerable
compose.yaml:13 not-checked unknown
compose.yaml:3 image-pin vulnerable
compose.yaml:5 image-pin vulnerable
k8s/deployment.yaml:10 image-pin vulnerable | +| repo | Source tree, offline: Dockerfiles (with install forms: --mount, :arch, .arch, /release, =${VAR}), Compose, Kubernetes, setup-java, version files, Gradle; Red Hat UBI images and a microdnf install, GraalVM in sdkman and asdf names and an Oracle GraalVM image | pass | .github/workflows/ci.yml:12 java-line vulnerable
.github/workflows/ci.yml:8 java-pin vulnerable
.java-version:1 java-pin vulnerable
.sdkmanrc:1 java-pin vulnerable
Dockerfile.forms:2 os-package vulnerable
Dockerfile.forms:3 os-package unknown
Dockerfile.forms:4 os-package vulnerable
Dockerfile.forms:5 os-package vulnerable
Dockerfile.forms:6 os-package vulnerable
Dockerfile.pkg:2 os-package vulnerable
Dockerfile.redhat:1 image-pin vulnerable
Dockerfile.redhat:2 not-checked unknown
Dockerfile.redhat:4 os-package vulnerable
Dockerfile.redhat:5 image-pin vulnerable
Dockerfile:1 image-pin vulnerable
build.gradle.kts:3 java-line vulnerable
build.gradle.kts:7 image-pin vulnerable
compose.yaml:13 not-checked unknown
compose.yaml:3 image-pin vulnerable
compose.yaml:5 image-pin vulnerable
graalvm/.sdkmanrc:1 java-pin vulnerable
k8s/deployment.yaml:10 image-pin vulnerable | -39/39 cases match. +43/43 cases match. diff --git a/parity/java4shell/cases.json b/parity/java4shell/cases.json index 7c331fa..69f72c1 100644 --- a/parity/java4shell/cases.json +++ b/parity/java4shell/cases.json @@ -393,6 +393,54 @@ ] ] }, + { + "name": "graalvm-ce-22.3.0-java17", + "what": "GraalVM CE 22.3.0 for Java 17: built on 17.0.5, before the decoder (findepi/graalvm repackages the CE release archives; ghcr.io is unreachable here)", + "mode": "registry", + "ref": "findepi/graalvm@sha256:b4460f6857d29beec43231b7cfbbaaa3e6eaafe2d5f406ff6ffb416751d9b373", + "expected": [ + [ + "linux/amd64", + "/graalvm", + "runtime", + "fixed", + "not-affected", + "vm-library" + ] + ] + }, + { + "name": "graalvm-ce-22.3.1-java17", + "what": "GraalVM CE 22.3.1 for Java 17: 17.0.6+10-jvmci-22.3-b13 with the decoder, no fixed GraalVM build", + "mode": "registry", + "ref": "findepi/graalvm@sha256:a953392b957211d965012180bd7600ab5929ea6326f9ea49d3aba5db24ada717", + "expected": [ + [ + "linux/amd64", + "/graalvm", + "runtime", + "vulnerable", + "vulnerable", + "vm-library" + ] + ] + }, + { + "name": "graalvm-ce-21", + "what": "GraalVM CE for JDK 21 (23.1.2): 21.0.2+13-jvmci-23.1-b30", + "mode": "registry", + "ref": "findepi/graalvm@sha256:19937684c9efd655c5892f83c9c381f139b0b271818303ebe1159cf7968ed235", + "expected": [ + [ + "linux/amd64", + "/graalvm", + "runtime", + "vulnerable", + "vulnerable", + "vm-library" + ] + ] + }, { "name": "elasticsearch", "what": "Elasticsearch 9.5.5, which bundles its own JDK", @@ -529,6 +577,22 @@ ] ] }, + { + "name": "debian-sid-pkg", + "what": "Debian sid openjdk-17-jre-headless (17.0.21.0.3+1-1, the five-part last affected release, no fixed package)", + "mode": "build", + "dockerfile": "debian-sid-pkg.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/lib/jvm/java-17-openjdk-amd64", + "runtime", + "vulnerable", + "vulnerable", + "vm-library" + ] + ] + }, { "name": "mitigated-env", "what": "Temurin 21.0.13 with ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics", @@ -667,7 +731,7 @@ }, { "name": "repo", - "what": "Source tree, offline: Dockerfiles (with install forms: --mount, :arch, .arch, /release, =${VAR}), Compose, Kubernetes, setup-java, version files, Gradle", + "what": "Source tree, offline: Dockerfiles (with install forms: --mount, :arch, .arch, /release, =${VAR}), Compose, Kubernetes, setup-java, version files, Gradle; Red Hat UBI images and a microdnf install, GraalVM in sdkman and asdf names and an Oracle GraalVM image", "mode": "repo", "dir": "repo", "expected": [ @@ -755,7 +819,32 @@ "Dockerfile.forms:6", "os-package", "vulnerable" + ], + [ + "Dockerfile.redhat:1", + "image-pin", + "vulnerable" + ], + [ + "Dockerfile.redhat:2", + "not-checked", + "unknown" + ], + [ + "Dockerfile.redhat:4", + "os-package", + "vulnerable" + ], + [ + "Dockerfile.redhat:5", + "image-pin", + "vulnerable" + ], + [ + "graalvm/.sdkmanrc:1", + "java-pin", + "vulnerable" ] ] } -] \ No newline at end of file +] diff --git a/parity/java4shell/debian-sid-pkg.Dockerfile b/parity/java4shell/debian-sid-pkg.Dockerfile new file mode 100644 index 0000000..1eda3c5 --- /dev/null +++ b/parity/java4shell/debian-sid-pkg.Dockerfile @@ -0,0 +1,4 @@ +# Debian sid's openjdk-17 package: the five-part 17.0.21.0.3+1-1 (the +# release the OpenJDK advisory names as the last affected; no fix yet). +FROM debian:sid-slim +RUN apt-get update && apt-get install -y --no-install-recommends openjdk-17-jre-headless && rm -rf /var/lib/apt/lists/* diff --git a/parity/java4shell/repo/Dockerfile.redhat b/parity/java4shell/repo/Dockerfile.redhat new file mode 100644 index 0000000..f379222 --- /dev/null +++ b/parity/java4shell/repo/Dockerfile.redhat @@ -0,0 +1,5 @@ +FROM registry.access.redhat.com/ubi9/openjdk-21-runtime:1.20 +FROM registry.access.redhat.com/ubi9/openjdk-17:1.20 +FROM registry.access.redhat.com/ubi8/openjdk-11 +RUN microdnf install -y java-17-openjdk-headless && microdnf clean all +FROM container-registry.oracle.com/graalvm/jdk:21.0.13 diff --git a/parity/java4shell/repo/graalvm/.sdkmanrc b/parity/java4shell/repo/graalvm/.sdkmanrc new file mode 100644 index 0000000..f91ce43 --- /dev/null +++ b/parity/java4shell/repo/graalvm/.sdkmanrc @@ -0,0 +1 @@ +java=22.3.1.r17-grl diff --git a/parity/java4shell/repo/graalvm/.tool-versions b/parity/java4shell/repo/graalvm/.tool-versions new file mode 100644 index 0000000..01256fe --- /dev/null +++ b/parity/java4shell/repo/graalvm/.tool-versions @@ -0,0 +1 @@ +java graalvm-22.3.0+java17 From 0fefb5ee2e51264e47bb3acb32b5b6de42af97ce Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 06:31:34 +0000 Subject: [PATCH 049/119] engine: over-limit files recorded per detector; LimitVisitor; Exists for every file met From the independent review of the Limiter branch: - engine.LimitVisitor lets a Limiter's scan say that a file it asked for and did not get, over its limit, is a coverage gap: VisitOverLimit is called instead of Visit and its skips are recorded as gaps. Without it, the file stays a deliberate exclusion. The record is now per detector, whether the file was left unread or read for another detector. - Exists is set when the read decision is made, for every regular file the walk meets: a file over a detector's limit (or --max-file-size, or wanted by no detector) exists, so verdicts no longer depend on which other detectors ran. - source.Options.Read returns the readers' limit as a plain size, and Over records a file over it. - Tests: a property fuzz test of the read, hand-out and record decisions against a model (catches > for >=), LimitVisitor gaps, Exists with limits, the own-limit 'found while reading' branch, FuzzTar seeds and limits at the boundaries. Co-Authored-By: Claude Opus 5.5 --- internal/engine/engine.go | 24 +++-- internal/engine/limit_test.go | 165 ++++++++++++++++++++++++++++++++- internal/engine/run.go | 107 +++++++++++++-------- internal/source/source.go | 63 ++++++------- internal/source/source_test.go | 89 ++++++++++++++---- 5 files changed, 349 insertions(+), 99 deletions(-) diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 0f62cfb..b4dca01 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -138,7 +138,8 @@ type Skip struct { // it decides verdicts. type TargetContext interface { Kind() TargetKind - // Exists reports whether a regular file at that absolute path was scanned. + // Exists reports whether the walk met a regular file at that absolute + // path, read or not: it does not depend on which detectors ran. Exists(path string) bool // Env is the image configuration's environment ("KEY=value"), nil otherwise. Env() []string @@ -191,15 +192,26 @@ type Reader interface { // package database is never hundreds of MiB, and one that is should cost // nothing. Limit returns the most bytes of the file the detector checks, // from its path, first bytes and executable flag; 0 or less means no limit -// of its own. A file over its limit is never shown to the detector. It is -// not read past its first bytes unless another detector wants more of it, -// and it is recorded as skipped for that detector: a deliberate exclusion, -// not a coverage gap, since the detector would not check a file that size. -// The limit applies to the files the walk meets, not to archive members. +// of its own. A file over its limit is never shown to the detector, and is +// not read past its first bytes unless another detector wants more of it. +// It is recorded as not checked by each detector that asked for it: a +// deliberate exclusion, not a coverage gap, unless the detector's scan says +// otherwise (LimitVisitor). The limit applies to the files the walk meets, +// not to archive members. type Limiter interface { Limit(path string, head []byte, executable bool) int64 } +// LimitVisitor is implemented by a Limiter's Scan when a file it asked for +// and did not get, over its limit, can change a verdict: an sshd_config +// include that may turn PAM off must not let the scan clear a server. +// VisitOverLimit is called instead of Visit, with the file's size (-1 when +// it was found larger while reading). The skips it returns are recorded as +// coverage gaps; when it returns none, the file is a deliberate exclusion. +type LimitVisitor interface { + VisitOverLimit(path string, size int64) []Skip +} + // HeadVisitor is implemented by a Scan that wants to see the first bytes // of every file the walk meets, read in full or not: a record of files // it does not need to read (a runtime download inside an image) without diff --git a/internal/engine/limit_test.go b/internal/engine/limit_test.go index 85d1a5e..56f435b 100644 --- a/internal/engine/limit_test.go +++ b/internal/engine/limit_test.go @@ -3,9 +3,11 @@ package engine import ( "archive/tar" "bytes" + "fmt" "os" "path/filepath" "runtime" + "strconv" "strings" "testing" @@ -52,7 +54,7 @@ func limit64K(p string) int64 { func ownSkips(t *Target) []source.Skip { var out []source.Skip for _, s := range t.Skipped { - if strings.Contains(s.Reason, "-byte limit of") || strings.Contains(s.Reason, "limits of") { + if strings.Contains(s.Reason, "-byte limit of") { out = append(out, s) } } @@ -123,15 +125,20 @@ func TestLimiterWithAnotherReader(t *testing.T) { } } -// A file over the limits of two detectors names both. +// A file over the limits of two detectors is recorded for each. func TestLimiterTwoLimits(t *testing.T) { root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 100<<10)}) _, ds := capped("t-two1k", osRelease, func(string) int64 { return 1 << 10 }) _, db := capped("t-two64k", osRelease, limit64K) tg := ScanFS([]Detector{ds, db}, root, Options{AsRoot: true}) - want := "excluded: larger than the limits of t-two1k (1024 bytes) and t-two64k (65536 bytes) for this file (102400 bytes)" - if len(tg.Skipped) != 1 || tg.Skipped[0].Reason != want { - t.Errorf("skipped %+v", tg.Skipped) + var got []string + for _, s := range tg.Skipped { + got = append(got, s.Reason) + } + want := "excluded: larger than the 1024-byte limit of t-two1k for this file (102400 bytes)|" + + "excluded: larger than the 65536-byte limit of t-two64k for this file (102400 bytes)" + if strings.Join(got, "|") != want { + t.Errorf("skipped %q", got) } } @@ -204,3 +211,151 @@ func tarFile(t *testing.T, files map[string][]byte) []byte { tw.Close() return buf.Bytes() } + +// gapScan is a capped detector whose scan says an over-limit file is a gap. +type gapScan struct { + limitedReader + gap bool + sizes *[]int64 +} + +func (g gapScan) NewScan(TargetKind) Scan { return g } +func (g gapScan) Visit(f File) []Skip { return g.limited.fake.Visit(f) } +func (g gapScan) Finish(ctx TargetContext) []Finding { + return g.limited.fake.Finish(ctx) +} +func (g gapScan) VisitOverLimit(p string, size int64) []Skip { + *g.sizes = append(*g.sizes, size) + if !g.gap { + return nil + } + return []Skip{{Path: p, Reason: "an include over the limit; not cleared"}} +} + +func gapDetector(id string, gap bool) (*fake, gapScan) { + f := &fake{id: id, wants: osRelease, seen: &[]string{}} + return f, gapScan{limitedReader{limited{f, limit64K}, fakeReader{f}}, gap, &[]int64{}} +} + +// A scan that implements LimitVisitor turns an over-limit file into a +// coverage gap, whether the file was left unread or read for another +// detector; returning nothing leaves it a deliberate exclusion. +func TestLimitVisitor(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 100<<10)}) + f, g := gapDetector("t-gap", true) + tg := ScanFS([]Detector{g}, root, Options{AsRoot: true}) + if len(*f.seen) != 0 || len(tg.Skipped) != 1 || tg.Skipped[0].Excluded || tg.Gaps() != 1 || strings.Join(fmtSizes(*g.sizes), ",") != "102400" { + t.Errorf("unread: seen %v skipped %+v sizes %v", *f.seen, tg.Skipped, *g.sizes) + } + f, g = gapDetector("t-gap2", true) + other := &fake{id: "t-reads", wants: osRelease} + tg = ScanFS([]Detector{g, detector(other)}, root, Options{AsRoot: true}) + if len(*f.seen) != 0 || len(*other.seen) != 1 || len(tg.Skipped) != 1 || tg.Gaps() != 1 { + t.Errorf("read for another: seen %v skipped %+v", *f.seen, tg.Skipped) + } + f, g = gapDetector("t-nogap", false) + tg = ScanFS([]Detector{g}, root, Options{AsRoot: true}) + if len(tg.Skipped) != 1 || !tg.Skipped[0].Excluded || tg.Gaps() != 0 || len(*g.sizes) != 1 { + t.Errorf("no gap: skipped %+v sizes %v", tg.Skipped, *g.sizes) + } +} + +func fmtSizes(s []int64) []string { + var out []string + for _, n := range s { + out = append(out, strconv.FormatInt(n, 10)) + } + return out +} + +// Exists is true for every regular file the walk met: one over a +// detector's limit, one over --max-file-size and one no detector wants. +// It does not depend on which detectors ran. +func TestExistsWithLimits(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 100<<10), "bin/big": make([]byte, 2000), "etc/x": []byte("x")}) + for _, extra := range [][]Detector{nil, {detector(&fake{id: "t-ex-all"})}} { + var got []bool + f := &fake{id: "t-ex", wants: osRelease, seen: &[]string{}, finish: func(ctx TargetContext) []Finding { + got = []bool{ctx.Exists("/etc/os-release"), ctx.Exists("/bin/big"), ctx.Exists("/etc/x"), ctx.Exists("/etc/none")} + return nil + }} + d := limitedReader{limited{f, limit64K}, fakeReader{f}} + ScanFS(append([]Detector{d}, extra...), root, Options{AsRoot: true, MaxFileSize: 1000}) + if fmt.Sprint(got) != "[true true true false]" { + t.Errorf("with %d other detectors: exists %v", len(extra), got) + } + } +} + +// The limit decision, checked against a model for any file size, limits and +// wants: who sees the file, what is recorded, and that Exists holds. +func FuzzLimits(f *testing.F) { + for _, s := range [][5]uint16{{100, 100, 0, 3, 0}, {101, 100, 0, 3, 0}, {4096, 4096, 4097, 3, 1}, {4097, 4096, 0, 1, 2}, {5000, 4096, 5000, 2, 3}, {0, 1, 1, 3, 3}, {1, 0, 0, 0, 0}} { + f.Add(s[0], s[1], s[2], uint8(s[3]), uint8(s[4])) + } + f.Fuzz(func(t *testing.T, size, limA, limB uint16, wants, maxSel uint8) { + size %= 9000 + maxSize := []int64{0, 4096, 5000, 100}[maxSel%4] + lims := []int64{int64(limA % 9000), int64(limB % 9000)} + want := []bool{wants&1 != 0, wants&2 != 0} + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, size)}) + var fakes []*fake + var dets []Detector + for i := range lims { + i := i + fk := &fake{id: fmt.Sprintf("t-fz%d", i), wants: func(string) bool { return want[i] }, seen: &[]string{}} + fakes = append(fakes, fk) + dets = append(dets, limitedReader{limited{fk, func(string) int64 { return lims[i] }}, fakeReader{fk}}) + } + var exists bool + fakes[0].finish = func(ctx TargetContext) []Finding { exists = ctx.Exists("/etc/os-release"); return nil } + tg := ScanFS(dets, root, Options{AsRoot: true, MaxFileSize: maxSize}) + + over := func(i int) bool { return lims[i] > 0 && int64(size) > lims[i] } + // The read limit: the largest limit of those who want it, or + // --max-file-size when one of them has none; a limit at or above + // --max-file-size is --max-file-size. + read := false + var bound int64 + unlimited := false + for i := range lims { + if !want[i] { + continue + } + read = true + if lims[i] <= 0 { + unlimited = true + } + bound = max(bound, lims[i]) + } + if unlimited || maxSize > 0 && bound >= maxSize { + bound = maxSize + } + readIt := read && (bound <= 0 || int64(size) <= bound) + ownSkip := read && !unlimited && bound != maxSize && int64(size) > bound + for i := range lims { + sees := readIt && !over(i) + if (len(*fakes[i].seen) == 1) != sees { + t.Fatalf("size %d lims %v want %v max %d: detector %d saw %v, want %v (skipped %+v)", size, lims, want, maxSize, i, *fakes[i].seen, sees, tg.Skipped) + } + } + recorded := 0 + for _, s := range tg.Skipped { + if s.Excluded { + recorded++ + } + } + wantRecords := 0 + for i := range lims { + if want[i] && over(i) && (readIt || ownSkip) { + wantRecords++ + } + } + if recorded != wantRecords { + t.Fatalf("size %d lims %v want %v max %d: %d own-limit records, want %d: %+v", size, lims, want, maxSize, recorded, wantRecords, tg.Skipped) + } + if !exists { + t.Fatalf("Exists false for a file the walk met") + } + }) +} diff --git a/internal/engine/run.go b/internal/engine/run.go index 37ab7b9..f155a73 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -277,31 +277,33 @@ func (w *walker) sourceOptions(opts Options) source.Options { limited = true } } - if limited { + var decide func(p string, head []byte, exe bool) (bool, int64) + switch { + case limited: w.limits = make([]fileLimit, len(w.dets)) - so.Read = func(p string, head []byte, exe bool) (bool, source.Limit) { - visitHead(p, head) - return w.limit(w.abs(p), head, exe, readers, limiters) - } - return so - } - if all { - if len(heads) > 0 { - so.Read = func(p string, head []byte, _ bool) (bool, source.Limit) { - visitHead(p, head) - return true, source.Limit{} + decide = func(p string, head []byte, exe bool) (bool, int64) { + return w.limit(p, head, exe, readers, limiters) + } + so.Over = func(p string, size int64) []source.Skip { return w.tooLarge(w.abs(p), size) } + case all: + decide = func(string, []byte, bool) (bool, int64) { return true, 0 } + default: + decide = func(p string, head []byte, exe bool) (bool, int64) { + for _, r := range readers { + if r.Wants(p, head, exe) { + return true, 0 + } } + return false, 0 } - return so } - so.Read = func(p string, head []byte, exe bool) (bool, source.Limit) { + so.Read = func(p string, head []byte, exe bool) (bool, int64) { + abs := w.abs(p) + // The file exists whether or not any detector reads it, so Exists + // does not depend on which detectors ran. + w.ctx.seen[abs] = true visitHead(p, head) - for _, r := range readers { - if r.Wants(w.abs(p), head, exe) { - return true, source.Limit{} - } - } - return false, source.Limit{} + return decide(abs, head, exe) } return so } @@ -310,11 +312,10 @@ func (w *walker) sourceOptions(opts Options) source.Options { // own: it is read when any detector wants it, as far as the largest limit of // those that do (--max-file-size when one has none). Each detector's limit // is kept for handing the file out. -func (w *walker) limit(p string, head []byte, exe bool, readers []Reader, limiters []Limiter) (bool, source.Limit) { +func (w *walker) limit(p string, head []byte, exe bool, readers []Reader, limiters []Limiter) (bool, int64) { w.limited = p read, unlimited := false, false var most int64 - var capped []int // the detectors that want it, each with a limit for i := range w.dets { l := fileLimit{wants: readers[i] == nil || readers[i].Wants(p, head, exe)} if limiters[i] != nil { @@ -328,24 +329,57 @@ func (w *walker) limit(p string, head []byte, exe bool, readers []Reader, limite default: read = true most = max(most, l.bytes) - capped = append(capped, i) } } - switch { - case !read || unlimited: - return read, source.Limit{} - case len(capped) == 1: - return true, source.Limit{Bytes: most, Name: ownLimit(most, w.ids[capped[0]])} + if unlimited { + return read, 0 } - by := make([]string, len(capped)) - for k, i := range capped { - by[k] = fmt.Sprintf("%s (%d bytes)", w.ids[i], w.limits[i].bytes) + return read, most +} + +// tooLarge records a file that was not read because it is over the limit +// of every detector that wants it (size -1 when found while reading). +func (w *walker) tooLarge(p string, size int64) []source.Skip { + var out []source.Skip + for i, l := range w.limits { + if l.wants && l.bytes > 0 && (size < 0 || size > l.bytes) { + out = append(out, w.overLimit(i, p, size)...) + } } - return true, source.Limit{Bytes: most, Name: "the limits of " + strings.Join(by, " and ")} + return out } -// ownLimit names one detector's limit, for the record. -func ownLimit(n int64, id string) string { return fmt.Sprintf("the %d-byte limit of %s", n, id) } +// overLimit records that scan i did not check p, which is over its limit: +// what its VisitOverLimit returns (coverage gaps), or else a deliberate +// exclusion. +func (w *walker) overLimit(i int, p string, size int64) []source.Skip { + if lv, ok := w.scans[i].(LimitVisitor); ok { + if skips := w.visitOverLimitSafely(i, lv, p, size); len(skips) > 0 { + out := make([]source.Skip, len(skips)) + for k, sk := range skips { + out[k] = source.Skip{Path: sk.Path, Reason: sk.Reason, DetectorFailed: sk.failed} + } + return out + } + } + what := fmt.Sprintf("(%d bytes)", size) + if size < 0 { + what = "(found while reading)" + } + return []source.Skip{{Path: p, Excluded: true, + Reason: fmt.Sprintf("excluded: larger than the %d-byte limit of %s for this file %s", w.limits[i].bytes, w.ids[i], what)}} +} + +// visitOverLimitSafely runs one detector's VisitOverLimit, containing a +// panic as Visit does. +func (w *walker) visitOverLimitSafely(i int, lv LimitVisitor, p string, size int64) (skips []Skip) { + defer func() { + if r := recover(); r != nil { + skips = []Skip{{Path: p, Reason: fmt.Sprintf("detector %s failed on this file (%v); not checked", w.ids[i], r), failed: true}} + } + }() + return lv.VisitOverLimit(p, size) +} // over reports whether f is over scan i's own limit, which keeps it from // that detector. @@ -379,7 +413,7 @@ func (w *walker) visit(f source.File) error { // send gives f to every scan, except those skip(i) rules out and those // whose own limit it is over: read for another detector, it is recorded -// as not checked by one that asked for it. +// as not checked by each one that asked for it. func (w *walker) send(f File, skip func(int) bool) { for i, s := range w.scans { if skip != nil && skip(i) { @@ -387,8 +421,7 @@ func (w *walker) send(f File, skip func(int) bool) { } if w.over(i, f) { if w.limits[i].wants { - w.t.Skipped = append(w.t.Skipped, source.Skip{Path: f.Path, Excluded: true, - Reason: fmt.Sprintf("excluded: larger than %s for this file (%d bytes); not checked by it", ownLimit(w.limits[i].bytes, w.ids[i]), len(f.Data))}) + w.t.Skipped = append(w.t.Skipped, w.overLimit(i, f.Path, int64(len(f.Data)))...) } continue } diff --git a/internal/source/source.go b/internal/source/source.go index 8a62904..a24c279 100644 --- a/internal/source/source.go +++ b/internal/source/source.go @@ -52,9 +52,14 @@ type Options struct { // detectors skip and others read. Uncounted []string // Read decides from a file's path, first bytes and executable flag whether - // to read it in full, and how far its readers want it (Limit). Nil reads - // every file. - Read func(abs string, head []byte, executable bool) (bool, Limit) + // to read it in full, and the readers' own limit on it: what they look + // for is never larger (0 or less: MaxFileSize). A file over a limit + // below MaxFileSize is not read past its first bytes. Nil reads every + // file. + Read func(abs string, head []byte, executable bool) (read bool, limit int64) + // Over records a file over the limit Read set (size -1 when it was found + // larger while reading). Nil records it as a deliberate exclusion. + Over func(abs string, size int64) []Skip // IsExecutable decides from a file's first bytes whether it is an executable. IsExecutable func(head []byte) bool // Symlink receives every symbolic link (absolute path, target as written). @@ -73,37 +78,29 @@ var DefaultExcludes = []string{"/proc/", "/sys/", "/dev/"} // uses. Scan the images themselves instead. var ContainerStorage = []string{"/var/lib/docker/", "/var/lib/containerd/", "/var/lib/containers/", "/var/snap/docker/common/var-lib-docker/"} -// Limit is the readers' own bound on one file, below MaxFileSize: what -// they look for is never that large. A file over it is recorded as a -// deliberate exclusion and not read past its first bytes. -type Limit struct { - // Bytes is the most read of the file; 0 or less means MaxFileSize. - Bytes int64 - // Name says whose limit it is, for the record: "the 65536-byte limit - // of java4shell". - Name string -} - -// bound is the most read of a file: the reader's own limit when it is below -// MaxFileSize, and whether that limit is the one that applies. -func (o Options) bound(l Limit) (int64, bool) { - if l.Bytes > 0 && (o.MaxFileSize <= 0 || l.Bytes < o.MaxFileSize) { - return l.Bytes, true +// bound is the most read of a file: the readers' own limit when it is +// below MaxFileSize, and whether that limit is the one that applies. +func (o Options) bound(limit int64) (int64, bool) { + if limit > 0 && (o.MaxFileSize <= 0 || limit < o.MaxFileSize) { + return limit, true } return o.MaxFileSize, false } -// tooLarge is the record of a file over the limit that applies to it. -func tooLarge(abs string, size, most int64, own bool, name string, reading bool) Skip { +// tooLarge records a file over the limit that applies to it; size is -1 +// when it was found larger while reading. +func (o Options) tooLarge(abs string, size, most int64, own bool) []Skip { switch { - case own && reading: - return Skip{Path: abs, Reason: fmt.Sprintf("excluded: larger than %s for this file, found while reading", name), Excluded: true} + case own && o.Over != nil: + return o.Over(abs, size) + case own && size < 0: + return []Skip{{Path: abs, Reason: fmt.Sprintf("excluded: larger than the %d-byte limit set for this file, found while reading", most), Excluded: true}} case own: - return Skip{Path: abs, Reason: fmt.Sprintf("excluded: larger than %s for this file (%d bytes)", name, size), Excluded: true} - case reading: - return Skip{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes) while reading", most)} + return []Skip{{Path: abs, Reason: fmt.Sprintf("excluded: larger than the %d-byte limit set for this file (%d bytes)", most, size), Excluded: true}} + case size < 0: + return []Skip{{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes) while reading", most)}} } - return Skip{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes)", size)} + return []Skip{{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes)", size)}} } // Visitor receives each file read. Returning an error stops the walk. @@ -217,7 +214,7 @@ func readOne(osPath, abs string, fi fs.FileInfo, opts Options, visit Visitor, sk } head = head[:k] exe := opts.IsExecutable != nil && opts.IsExecutable(head) - var lim Limit + var lim int64 if opts.Read != nil { var read bool if read, lim = opts.Read(abs, head, exe); !read { @@ -226,7 +223,7 @@ func readOne(osPath, abs string, fi fs.FileInfo, opts Options, visit Visitor, sk } most, own := opts.bound(lim) if most > 0 && fi.Size() > most { - *skips = append(*skips, tooLarge(abs, fi.Size(), most, own, lim.Name, false)) + *skips = append(*skips, opts.tooLarge(abs, fi.Size(), most, own)...) return nil } // Enforce the limit while reading: some files (FUSE mounts) report size 0 @@ -242,7 +239,7 @@ func readOne(osPath, abs string, fi fs.FileInfo, opts Options, visit Visitor, sk } data := append(head, rest...) if most > 0 && int64(len(data)) > most { - *skips = append(*skips, tooLarge(abs, 0, most, own, lim.Name, true)) + *skips = append(*skips, opts.tooLarge(abs, -1, most, own)...) return nil } return visit(File{Path: abs, Data: data, Executable: exe}) @@ -292,7 +289,7 @@ func Tar(r io.Reader, opts Options, visit Visitor) ([]Skip, int, error) { } head = head[:k] exe := opts.IsExecutable != nil && opts.IsExecutable(head) - var lim Limit + var lim int64 if opts.Read != nil { var read bool if read, lim = opts.Read(abs, head, exe); !read { @@ -301,7 +298,7 @@ func Tar(r io.Reader, opts Options, visit Visitor) ([]Skip, int, error) { } most, own := opts.bound(lim) if most > 0 && h.Size > most { - skips = append(skips, tooLarge(abs, h.Size, most, own, lim.Name, false)) + skips = append(skips, opts.tooLarge(abs, h.Size, most, own)...) continue } var rr io.Reader = tr @@ -314,7 +311,7 @@ func Tar(r io.Reader, opts Options, visit Visitor) ([]Skip, int, error) { } data := append(head, rest...) if most > 0 && int64(len(data)) > most { - skips = append(skips, tooLarge(abs, 0, most, own, lim.Name, true)) + skips = append(skips, opts.tooLarge(abs, -1, most, own)...) continue } if err := visit(File{Path: abs, Data: data, Executable: exe}); err != nil { diff --git a/internal/source/source_test.go b/internal/source/source_test.go index a923944..92d782b 100644 --- a/internal/source/source_test.go +++ b/internal/source/source_test.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "runtime" + "strings" "testing" ) @@ -29,8 +30,8 @@ func TestTarReadFilterAndLinks(t *testing.T) { links := map[string]string{} opts := Options{ MaxFileSize: 5, - Read: func(p string, head []byte, exe bool) (bool, Limit) { - return p != "/etc/a.conf" || len(head) == 1, Limit{} + Read: func(p string, head []byte, exe bool) (bool, int64) { + return p != "/etc/a.conf" || len(head) == 1, 0 }, IsExecutable: func(h []byte) bool { return bytes.HasPrefix(h, []byte("\x7fELF")) }, Symlink: func(p, to string) { links[p] = to }, @@ -61,19 +62,71 @@ func TestTarReadFilterAndLinks(t *testing.T) { func FuzzTar(f *testing.F) { f.Add(tarOf(f, map[string]string{"a": "b"})) f.Add([]byte{}) + // Members at and around the limits the fuzz body sets. + for _, n := range []int{100, 101, 4096, 4097, 5000} { + f.Add(tarOf(f, map[string]string{"etc/os-release": strings.Repeat("x", n), "small": "x"})) + } f.Fuzz(func(t *testing.T, data []byte) { Tar(bytes.NewReader(data), Options{MaxFileSize: 1 << 20}, func(File) error { return nil }) - // With a reader's own limit, nothing larger is ever handed out. - limited := Options{MaxFileSize: 1 << 20, Read: func(string, []byte, bool) (bool, Limit) { return true, Limit{Bytes: 100, Name: "t"} }} - Tar(bytes.NewReader(data), limited, func(f File) error { - if len(f.Data) > 100 { - t.Errorf("%s: %d bytes over a 100-byte limit", f.Path, len(f.Data)) - } - return nil - }) + // With a reader's own limit, nothing larger is ever handed out, + // and nothing at or under it is recorded as over it. + for _, limit := range []int64{100, 4096} { + var over []Skip + limited := Options{MaxFileSize: 1 << 20, + Read: func(string, []byte, bool) (bool, int64) { return true, limit }, + Over: func(p string, size int64) []Skip { + if size >= 0 && size <= limit { + t.Errorf("%s: %d bytes recorded as over a %d-byte limit", p, size, limit) + } + over = append(over, Skip{Path: p}) + return nil + }} + Tar(bytes.NewReader(data), limited, func(f File) error { + if int64(len(f.Data)) > limit { + t.Errorf("%s: %d bytes over a %d-byte limit", f.Path, len(f.Data), limit) + } + return nil + }) + } }) } +// A file found larger than its readers' limit only while reading (it grew, +// or its size was misreported) is recorded through Over with size -1. +func TestDirOwnLimitWhileReading(t *testing.T) { + root := t.TempDir() + p := filepath.Join(root, "os-release") + if err := os.WriteFile(p, []byte("ID=x\n"), 0o600); err != nil { + t.Fatal(err) + } + var sizes []int64 + opts := Options{MaxFileSize: 1 << 20, + Read: func(string, []byte, bool) (bool, int64) { + // The walk has its size; the file grows before it is read. + if err := os.WriteFile(p, make([]byte, 8000), 0o600); err != nil { + t.Fatal(err) + } + return true, 4096 + }, + Over: func(_ string, size int64) []Skip { + sizes = append(sizes, size) + return []Skip{{Path: "/os-release", Reason: "over"}} + }} + skips, _, err := Dir(root, opts, func(f File) error { t.Errorf("read %d bytes", len(f.Data)); return nil }) + if err != nil || len(sizes) != 1 || sizes[0] != -1 || len(skips) != 1 || skips[0].Reason != "over" { + t.Fatalf("sizes %v skips %+v err %v", sizes, skips, err) + } + // Without Over, the default record says so. + if err := os.WriteFile(p, []byte("ID=x\n"), 0o600); err != nil { + t.Fatal(err) + } + opts.Over = nil + skips, _, _ = Dir(root, opts, func(File) error { return nil }) + if len(skips) != 1 || !skips[0].Excluded || skips[0].Reason != "excluded: larger than the 4096-byte limit set for this file, found while reading" { + t.Fatalf("skips %+v", skips) + } +} + // A reader's own limit below MaxFileSize skips a larger file as a deliberate // exclusion naming who set it; MaxFileSize still applies under it. func TestTarOwnLimit(t *testing.T) { @@ -81,11 +134,11 @@ func TestTarOwnLimit(t *testing.T) { var read []string opts := Options{ MaxFileSize: 12, - Read: func(p string, _ []byte, _ bool) (bool, Limit) { + Read: func(p string, _ []byte, _ bool) (bool, int64) { if p == "/big" { - return true, Limit{Bytes: 100, Name: "t"} // above MaxFileSize: MaxFileSize applies + return true, 100 // above MaxFileSize: MaxFileSize applies } - return true, Limit{Bytes: 4, Name: "the 4-byte limit of java4shell"} + return true, 4 }, } skips, _, err := Tar(bytes.NewReader(data), opts, func(f File) error { read = append(read, f.Path); return nil }) @@ -96,7 +149,7 @@ func TestTarOwnLimit(t *testing.T) { for _, s := range skips { got[s.Path] = s } - if s := got["/etc/os-release"]; !s.Excluded || s.Reason != "excluded: larger than the 4-byte limit of java4shell for this file (10 bytes)" { + if s := got["/etc/os-release"]; !s.Excluded || s.Reason != "excluded: larger than the 4-byte limit set for this file (10 bytes)" { t.Errorf("own limit: %+v", s) } if s := got["/big"]; s.Excluded || s.Reason != "larger than --max-file-size (16 bytes)" { @@ -110,12 +163,12 @@ func TestDirOwnLimit(t *testing.T) { t.Fatal(err) } var read []string - skips, n, err := Dir(root, Options{Read: func(string, []byte, bool) (bool, Limit) { - return true, Limit{Bytes: 4096, Name: "the 4096-byte limit of t"} + skips, n, err := Dir(root, Options{Read: func(string, []byte, bool) (bool, int64) { + return true, 4096 }}, func(f File) error { read = append(read, f.Path); return nil }) if err != nil || n != 1 || len(read) != 0 || len(skips) != 1 || !skips[0].Excluded || - skips[0].Reason != "excluded: larger than the 4096-byte limit of t for this file (5000 bytes)" { + skips[0].Reason != "excluded: larger than the 4096-byte limit set for this file (5000 bytes)" { t.Fatalf("n %d read %v skips %+v err %v", n, read, skips, err) } } @@ -135,7 +188,7 @@ func TestTarOwnLimitNeverReads(t *testing.T) { var before, after runtime.MemStats runtime.GC() runtime.ReadMemStats(&before) - skips, _, err := Tar(pr, Options{MaxFileSize: 256 << 20, Read: func(string, []byte, bool) (bool, Limit) { return true, Limit{Bytes: 64 << 10, Name: "t"} }}, + skips, _, err := Tar(pr, Options{MaxFileSize: 256 << 20, Read: func(string, []byte, bool) (bool, int64) { return true, 64 << 10 }}, func(File) error { t.Error("visited"); return nil }) runtime.ReadMemStats(&after) if err != nil || len(skips) != 1 || !skips[0].Excluded { From afd68cec9afd00c1c7058dcf019d8e7151f00dc0 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 06:34:06 +0000 Subject: [PATCH 050/119] sshole: a file the verdict reads over the limit is a gap and never clears a server From the independent review of the Limiter branch: an sshd_config include over the 4 MiB limit that sets UsePAM no was dropped, so a PAM build with UsePAM yes in what was read was cleared (inactive), and the branch recorded the file as a deliberate exclusion, so --fail-on-skip passed. The same false clear happened before the branch whenever the file was read and then dropped. - The scan implements engine.LimitVisitor: an account file, the package database, an sshd_config or a file one includes over the limit is a coverage gap. A start script over it stays an exclusion. - Such a file is still found by an Include glob (as is one too large on disk under a system root), and the parser lists it, and anything past its own include and directive limits, in Config.Unread. - UsePAM yes with anything unread is unknown, not inactive. - Tests: the reviewer's repro (PAM build, Include then UsePAM yes, a 4,194,305-byte UsePAM no include: unknown and exit 3 with --fail-on-skip, alone and with a detector that reads every file), a 300 KiB login shell gives the same verdict as a small one, and --fail-on-skip with an over-limit script (exit 0) and /etc/shadow (exit 3). Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/internal/assess/assess.go | 8 + detectors/sshole/internal/assess/config.go | 9 ++ .../sshole/internal/assess/unread_test.go | 43 ++++++ detectors/sshole/limit_internal_test.go | 6 +- detectors/sshole/limit_test.go | 142 ++++++++++++++++++ detectors/sshole/sshole.go | 58 +++++-- 6 files changed, 253 insertions(+), 13 deletions(-) create mode 100644 detectors/sshole/internal/assess/unread_test.go create mode 100644 detectors/sshole/limit_test.go diff --git a/detectors/sshole/internal/assess/assess.go b/detectors/sshole/internal/assess/assess.go index 1be61e5..c9d65a6 100644 --- a/detectors/sshole/internal/assess/assess.go +++ b/detectors/sshole/internal/assess/assess.go @@ -235,6 +235,14 @@ func assessUnit(in Input, u []*Binary) (Finding, bool) { return f, true } f.UsePAM = strings.ToLower(cfg.Global("usepam", "no")) + if f.PAM && f.UsePAM == "yes" && len(cfg.Unread) > 0 { + // A part of the configuration that was not read can turn PAM off: + // never clear on what was not read. + f.Status = Undecided + f.Reason = fmt.Sprintf("this build uses PAM and UsePAM is yes in what was read, but %s was not read and can set UsePAM no", strings.Join(cfg.Unread, ", ")) + f.Message = fmt.Sprintf("OpenSSH %s server on musl without the *sshole fix; whether PAM checks passwords is unknown", main.Release) + return f, true + } if f.PAM && f.UsePAM == "yes" { f.Status = Inactive f.Reason = "this build uses PAM (UsePAM yes), and PAM checks passwords without crypt's failure result" diff --git a/detectors/sshole/internal/assess/config.go b/detectors/sshole/internal/assess/config.go index 368290f..39fec1a 100644 --- a/detectors/sshole/internal/assess/config.go +++ b/detectors/sshole/internal/assess/config.go @@ -14,6 +14,11 @@ type Config struct { // Missing lists Include patterns that matched no file, and files that // could not be read. Missing []string `json:"missing,omitempty"` + // Unread lists what is in the configuration but was not read: an + // included file that could not be read (larger than the scan reads), + // or the rest of a file past a parser limit. A setting in it is + // unknown, so it can never clear a server. + Unread []string `json:"unread,omitempty"` } // Directive is one keyword line. @@ -73,6 +78,7 @@ func ParseConfig(files Files, p string) Config { case "include": if depth >= 16 { c.Missing = append(c.Missing, file+": Include nested too deeply") + c.Unread = append(c.Unread, file+": Include nested too deeply") continue } for _, pat := range args[1:] { @@ -90,6 +96,7 @@ func ParseConfig(files Files, p string) Config { } if filesRead >= maxIncludes { c.Missing = append(c.Missing, g+": more than 256 included files; the rest are not read") + c.Unread = append(c.Unread, g+": more than 256 included files") break } filesRead++ @@ -97,6 +104,7 @@ func ParseConfig(files Files, p string) Config { walk(g, b, cur, depth+1) } else { c.Missing = append(c.Missing, g) + c.Unread = append(c.Unread, g) } } } @@ -104,6 +112,7 @@ func ParseConfig(files Files, p string) Config { } if len(c.Directives) >= maxDirectives { c.Missing = append(c.Missing, file+": more than 100000 directives; the rest are not read") + c.Unread = append(c.Unread, file+": more than 100000 directives") return } c.Directives = append(c.Directives, Directive{Key: key, Args: args[1:], File: file, Line: i + 1, Match: cur, Block: curBlock}) diff --git a/detectors/sshole/internal/assess/unread_test.go b/detectors/sshole/internal/assess/unread_test.go new file mode 100644 index 0000000..cdc344c --- /dev/null +++ b/detectors/sshole/internal/assess/unread_test.go @@ -0,0 +1,43 @@ +package assess + +import ( + "fmt" + "strings" + "testing" +) + +// unreadFiles lists some files that Read cannot give (over the limit). +type unreadFiles struct { + memFiles + unread []string +} + +func (u unreadFiles) Glob(pattern string) []string { + out := u.memFiles.Glob(pattern) + for _, p := range u.unread { + if strings.HasPrefix(p, strings.TrimSuffix(pattern, "*.conf")) { + out = append(out, p) + } + } + return out +} + +// What the configuration names but was not read is listed as unread: an +// included file Read cannot give, and anything past the parser's limits. +func TestConfigUnread(t *testing.T) { + fs := unreadFiles{memFiles{"/etc/ssh/sshd_config": "Include /etc/ssh/sshd_config.d/*.conf\nUsePAM yes\n"}, []string{"/etc/ssh/sshd_config.d/50-site.conf"}} + c := ParseConfig(fs, "/etc/ssh/sshd_config") + if strings.Join(c.Unread, ",") != "/etc/ssh/sshd_config.d/50-site.conf" || c.Global("usepam", "no") != "yes" { + t.Errorf("unread %v", c.Unread) + } + m := memFiles{"/etc/ssh/sshd_config": "Include /etc/ssh/sshd_config.d/*.conf\n"} + for i := 0; i <= maxIncludes; i++ { + m[fmt.Sprintf("/etc/ssh/sshd_config.d/%03d.conf", i)] = "Port 22\n" + } + if c := ParseConfig(m, "/etc/ssh/sshd_config"); len(c.Unread) != 1 || !strings.Contains(c.Unread[0], "more than 256") { + t.Errorf("past the include limit: unread %v", c.Unread) + } + if c := ParseConfig(memFiles{"/etc/ssh/sshd_config": "UsePAM yes\n"}, "/etc/ssh/sshd_config"); len(c.Unread) != 0 { + t.Errorf("all read: unread %v", c.Unread) + } +} diff --git a/detectors/sshole/limit_internal_test.go b/detectors/sshole/limit_internal_test.go index 0d92d4b..3945cad 100644 --- a/detectors/sshole/limit_internal_test.go +++ b/detectors/sshole/limit_internal_test.go @@ -11,7 +11,8 @@ import ( ) // A hostile account file as large as --max-file-size is not read into -// memory: the detector keeps one only up to 4 MiB. +// memory: the detector keeps one only up to 4 MiB, and one over that is a +// coverage gap. func TestKeptFileBounded(t *testing.T) { root := t.TempDir() if err := os.MkdirAll(filepath.Join(root, "etc"), 0o755); err != nil { @@ -34,7 +35,8 @@ func TestKeptFileBounded(t *testing.T) { if a := after.TotalAlloc - before.TotalAlloc; a > 8<<20 { t.Errorf("a 128 MiB /etc/shadow cost %d bytes", a) } - if len(tg.Skipped) != 1 || !tg.Skipped[0].Excluded || !strings.Contains(tg.Skipped[0].Reason, "limit of sshole") || tg.Gaps() != 0 { + // The verdict reads it: a coverage gap, not an exclusion. + if len(tg.Skipped) != 1 || tg.Skipped[0].Excluded || !strings.Contains(tg.Skipped[0].Reason, "sshole reads") || tg.Gaps() != 1 { t.Errorf("skipped %+v", tg.Skipped) } } diff --git a/detectors/sshole/limit_test.go b/detectors/sshole/limit_test.go new file mode 100644 index 0000000..a58165c --- /dev/null +++ b/detectors/sshole/limit_test.go @@ -0,0 +1,142 @@ +package sshole_test + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + _ "github.com/DefectDojo/earlylight/detectors/emudhra" // a detector that reads every file + "github.com/DefectDojo/earlylight/detectors/sshole/internal/testelf" + "github.com/DefectDojo/earlylight/internal/cli" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// maxKept is the most sshole reads of a file its verdict depends on. +const maxKept = 4 << 20 + +// padded writes data followed by zeros up to size bytes (sparse). +func padded(t *testing.T, root, rel string, data []byte, size int64) { + t.Helper() + write(t, root, rel, data, 0o644) + if err := os.Truncate(filepath.Join(root, rel), size); err != nil { + t.Fatal(err) + } +} + +// scanExit runs a JSON scan and returns its findings, skips and exit status. +func scanExit(t *testing.T, args ...string) ([]engine.Finding, []struct { + Path string `json:"path"` + Excluded bool `json:"excluded"` +}, int) { + t.Helper() + var out, errb bytes.Buffer + code := cli.Run(cfg, append([]string{"scan", "fs", "--format", "json"}, args...), &out, &errb) + var r struct { + Targets []struct { + Findings []engine.Finding `json:"findings"` + Skipped []struct { + Path string `json:"path"` + Excluded bool `json:"excluded"` + } `json:"skipped"` + } `json:"targets"` + } + if err := json.Unmarshal(out.Bytes(), &r); err != nil || len(r.Targets) != 1 { + t.Fatalf("%v\n%s\n%s", err, out.String(), errb.String()) + } + return r.Targets[0].Findings, r.Targets[0].Skipped, code +} + +// pamRoot is alpineRoot with sshd built with PAM and UsePAM yes after an +// Include of sshd_config.d. +func pamRoot(t *testing.T) string { + root := alpineRoot(t, "10.0_p1-r10") + write(t, root, "usr/sbin/sshd", testelf.ELF("/lib/ld-musl-x86_64.so.1", []string{"libc.musl-x86_64.so.1", "libpam.so.0"}, + testelf.SSHDStrings("10.0p2", "/usr/lib/ssh/sshd-session", "/usr/lib/ssh/sshd-auth")...), 0o755) + write(t, root, "etc/ssh/sshd_config", []byte("Include /etc/ssh/sshd_config.d/*.conf\nUsePAM yes\n"), 0o644) + return root +} + +// Review finding 1: an included file over the limit that may turn PAM off +// keeps the server from being cleared, and is a coverage gap. +func TestIncludeOverLimitNeverClears(t *testing.T) { + root := pamRoot(t) + fs, _, _ := scanExit(t, "--detector", "sshole", "--as-root", root) + if len(fs) != 1 || fs[0].Verdict != engine.Inactive { + t.Fatalf("PAM on, nothing included: %+v", fs) + } + write(t, root, "etc/ssh/sshd_config.d/50-site.conf", []byte("UsePAM no\n"), 0o644) + fs, _, _ = scanExit(t, "--detector", "sshole", "--as-root", root) + if len(fs) != 1 || fs[0].Verdict != engine.Vulnerable || fs[0].Severity != "critical" { + t.Fatalf("a small include turning PAM off: %+v", fs) + } + padded(t, root, "etc/ssh/sshd_config.d/50-site.conf", []byte("UsePAM no\n"), maxKept+1) + for _, extra := range [][]string{nil, {"--detector", "emudhra"}} { + args := append(append([]string{"--detector", "sshole"}, extra...), "--as-root", "--fail-on-skip", root) + fs, skipped, code := scanExit(t, args...) + var got []engine.Finding + for _, f := range fs { + if f.Detector == "sshole" { + got = append(got, f) + } + } + if len(got) != 1 || got[0].Verdict.Cleared() || got[0].Verdict != engine.Unknown || !strings.Contains(got[0].Reason, "50-site.conf") { + t.Errorf("with %v, an include over the limit: %+v", extra, got) + } + gap := false + for _, s := range skipped { + gap = gap || s.Path == "/etc/ssh/sshd_config.d/50-site.conf" && !s.Excluded + } + if !gap || code != 3 { + t.Errorf("with %v: exit %d, skipped %+v", extra, code, skipped) + } + } +} + +// Review finding 2: a login shell over the script limit still exists, so +// the verdict is the same as for a small one, with or without other +// detectors. +func TestShellOverLimitExists(t *testing.T) { + verdict := func(script []byte, size int64, extra ...string) string { + root := alpineRoot(t, "10.0_p1-r10") + write(t, root, "etc/passwd", []byte("root:x:0:0:root:/root:/bin/sh\nalice:x:1000:1000::/home/alice:/bin/sh\nbob:x:1001:1001::/home/bob:/usr/local/bin/menu\n"), 0o644) + padded(t, root, "usr/local/bin/menu", script, size) + fs, _, _ := scanExit(t, append(append([]string{"--detector", "sshole"}, extra...), "--as-root", root)...) + for _, f := range fs { + if f.Detector == "sshole" { + return string(f.Verdict) + "/" + f.Severity + } + } + return "none" + } + script := []byte("#!/bin/sh\nexec /bin/sh\n") + small := verdict(script, int64(len(script))) + if small != "vulnerable/critical" { + t.Fatalf("small shell: %s", small) + } + if big := verdict(script, 300<<10); big != small { + t.Errorf("a 300 KiB shell: %s, a small one: %s", big, small) + } + if big := verdict(script, 300<<10, "--detector", "emudhra"); big != small { + t.Errorf("a 300 KiB shell with emudhra: %s, a small one: %s", big, small) + } +} + +// --fail-on-skip: a start script over the limit is a deliberate exclusion +// (the startup analysis never clears a server), an account file over it a +// gap. +func TestFailOnSkipWithLimits(t *testing.T) { + root := alpineRoot(t, "10.0_p1-r11") // fixed: exit 0 when nothing is a gap + padded(t, root, "opt/install.sh", []byte("#!/bin/sh\n"), 300<<10) + _, skipped, code := scanExit(t, "--detector", "sshole", "--as-root", "--fail-on-skip", root) + if code != 0 || len(skipped) != 1 || !skipped[0].Excluded { + t.Errorf("a large script: exit %d skipped %+v", code, skipped) + } + padded(t, root, "etc/shadow", []byte("root:*::0:::::\n"), maxKept+1) + _, skipped, code = scanExit(t, "--detector", "sshole", "--as-root", "--fail-on-skip", root) + if code != 3 || len(skipped) != 2 { + t.Errorf("a large /etc/shadow: exit %d skipped %+v", code, skipped) + } +} diff --git a/detectors/sshole/sshole.go b/detectors/sshole/sshole.go index 11bfbba..98f6131 100644 --- a/detectors/sshole/sshole.go +++ b/detectors/sshole/sshole.go @@ -15,6 +15,7 @@ package sshole import ( + "fmt" "os" "path" "path/filepath" @@ -134,7 +135,7 @@ const maxKept = 4 << 20 // NewScan starts a filesystem or image scan. func (d *Detector) NewScan(kind engine.TargetKind) engine.Scan { - return &scan{kind: kind, files: map[string][]byte{}, scripts: map[string][]byte{}} + return &scan{kind: kind, files: map[string][]byte{}, scripts: map[string][]byte{}, over: map[string]bool{}} } type scan struct { @@ -143,6 +144,22 @@ type scan struct { files map[string][]byte scripts map[string][]byte scriptBytes int + // over holds the files a verdict reads that were over the limit: + // present, but their content is unknown. + over map[string]bool +} + +// VisitOverLimit records a file the verdict reads (an account file, the +// package database, an sshd_config or a file one includes) that is over +// the limit: it is a coverage gap, and a configuration that includes it is +// never taken as turning PAM on. A start script over the limit is only an +// exclusion: the startup analysis never clears a server. +func (s *scan) VisitOverLimit(p string, size int64) []engine.Skip { + if !keep(p) { + return nil + } + s.over[p] = true + return []engine.Skip{{Path: p, Reason: fmt.Sprintf("larger than the %d bytes sshole reads of a file its verdict depends on; not checked", maxKept)}} } func (s *scan) Visit(f engine.File) []engine.Skip { @@ -167,7 +184,7 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { if len(s.binaries) == 0 { return nil } - fs := &files{kept: s.files, root: ctx.SystemRoot()} + fs := &files{kept: s.files, over: s.over, root: ctx.SystemRoot()} links, _ := ctx.Links() res := resolver{links: links, exists: func(p string) bool { if ctx.Exists(p) { @@ -278,6 +295,7 @@ func yes(b bool) string { // root's own files from disk. type files struct { kept map[string][]byte + over map[string]bool // present but larger than maxKept: Read is nil root string } @@ -285,7 +303,7 @@ func (f *files) Read(p string) []byte { if b, ok := f.kept[p]; ok { return b } - if f.root == "" { + if f.root == "" || f.over[p] { return nil } return f.disk(p) @@ -324,12 +342,13 @@ func (f *files) diskRegular(p string) bool { return err == nil && fi.Mode().IsRegular() } -// disk reads a regular file below the system root, never through a -// symbolic link in any component of its path. -func (f *files) disk(p string) []byte { +// diskFile returns the OS path of a regular file below the system root, +// reached through no symbolic link in any component of its path. A file +// too large to read is still found: Glob lists it, Read gives nil. +func (f *files) diskFile(p string) (string, bool) { full, ok := f.diskPath(p) if !ok { - return nil + return "", false } rel, _ := filepath.Rel(f.root, full) cur := f.root @@ -337,11 +356,22 @@ func (f *files) disk(p string) []byte { cur = filepath.Join(cur, part) fi, err := os.Lstat(cur) if err != nil || fi.Mode()&os.ModeSymlink != 0 { - return nil + return "", false } } fi, err := os.Lstat(full) - if err != nil || !fi.Mode().IsRegular() || fi.Size() > maxKept { + return full, err == nil && fi.Mode().IsRegular() +} + +// disk reads a regular file below the system root, never through a +// symbolic link in any component of its path. +func (f *files) disk(p string) []byte { + full, ok := f.diskFile(p) + if !ok { + return nil + } + fi, err := os.Lstat(full) + if err != nil || fi.Size() > maxKept { return nil } b, err := os.ReadFile(full) @@ -354,12 +384,18 @@ func (f *files) disk(p string) []byte { func (f *files) Glob(pattern string) []string { seen := map[string]bool{} var out []string - for p := range f.kept { + match := func(p string) { if ok, _ := path.Match(pattern, p); ok && !seen[p] { seen[p] = true out = append(out, p) } } + for p := range f.kept { + match(p) + } + for p := range f.over { + match(p) + } if f.root != "" { if full, ok := f.diskPath(pattern); ok { ms, _ := filepath.Glob(full) @@ -369,7 +405,7 @@ func (f *files) Glob(pattern string) []string { continue } p := "/" + filepath.ToSlash(rel) - if !seen[p] && f.disk(p) != nil { + if _, ok := f.diskFile(p); !seen[p] && ok { seen[p] = true out = append(out, p) } From 3cdfdb0c731d65c48995f00c85e808bfd0ea1edf Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 06:35:23 +0000 Subject: [PATCH 051/119] java4shell: a JVM settings file over the limit is a coverage gap An option in a settings file over 1 MiB can undo a mitigation the scan would report, so the file is a gap (engine.LimitVisitor). The other files with a limit stay deliberate exclusions: java4shell clears a runtime only on its VM library and release file, which have no limit of their own. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/java4shell.go | 13 +++++++ detectors/java4shell/limit_internal_test.go | 41 +++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 09d7329..d829a84 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -135,6 +135,19 @@ func (d *Detector) Limit(p string, head []byte, _ bool) int64 { return most } +// VisitOverLimit records a JVM settings file over the limit as a coverage +// gap: an option in it can undo a mitigation the scan would report. The +// other files with a limit are deliberate exclusions: no verdict is cleared +// on them (a runtime is cleared only by its VM library and release file), +// and an os-release, package database, start script or crash log that +// large is not a real one. +func (s *scan) VisitOverLimit(p string, _ int64) []engine.Skip { + if jvm.SettingKind(p) == "" { + return nil + } + return []engine.Skip{{Path: p, Reason: fmt.Sprintf("larger than the %d MiB java4shell reads of a JVM settings file; its options are not checked", maxSetting>>20)}} +} + var hsErr = regexp.MustCompile(`^hs_err_pid\d{1,10}\.log$`) // jdkArchive names a Java runtime download as vendors publish it: diff --git a/detectors/java4shell/limit_internal_test.go b/detectors/java4shell/limit_internal_test.go index af10543..7bff66d 100644 --- a/detectors/java4shell/limit_internal_test.go +++ b/detectors/java4shell/limit_internal_test.go @@ -141,3 +141,44 @@ func TestOSReleaseAtLimit(t *testing.T) { t.Errorf("skipped %+v", tg.Skipped) } } + +// A JVM settings file over the limit is a coverage gap; the other files +// with a limit are deliberate exclusions. +func TestOverLimitGaps(t *testing.T) { + root := t.TempDir() + for rel, size := range map[string]int64{ + "opt/atlassian/confluence/bin/setenv.sh": maxSetting + 1, + "etc/os-release": maxOSRelease + 1, + "opt/install.sh": maxScript + 1, + "var/lib/dpkg/status": maxKept + 1, + } { + p := filepath.Join(root, rel) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + head := []byte("X=1\n") + if strings.HasSuffix(rel, ".sh") { + head = []byte("#!/bin/sh\n") + } + if err := os.WriteFile(p, head, 0o644); err != nil { + t.Fatal(err) + } + if err := os.Truncate(p, size); err != nil { + t.Fatal(err) + } + } + tg := engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true}) + got := map[string]bool{} + for _, s := range tg.Skipped { + got[s.Path] = s.Excluded + } + want := map[string]bool{"/opt/atlassian/confluence/bin/setenv.sh": false, "/etc/os-release": true, "/opt/install.sh": true, "/var/lib/dpkg/status": true} + if len(got) != len(want) || tg.Gaps() != 1 { + t.Fatalf("skipped %+v", tg.Skipped) + } + for p, ex := range want { + if got[p] != ex { + t.Errorf("%s: excluded %v, want %v", p, got[p], ex) + } + } +} From b4caaa159b4dcc717df876e0f385193acfeedb97 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 06:57:08 +0000 Subject: [PATCH 052/119] java4shell: Red Hat rows clear only a confirmed build of their own stream (review F1, F2) F1: the install path alone cleared a runtime. With a row, another vendor's 17.0.21+9 under a later Red Hat release, a 17.0.21+5, 17.0.21.0.3, -ea, self-built or GraalVM library under the fixed path, and 17.0.21.1.1 (build 1 of 17.0.21.1) all read fixed. Now a row clears a runtime only when its VM library is a released, non-GraalVM HotSpot of exactly the update and build the rpm packages and its release file names Red Hat, Inc. as the implementor; otherwise the path's claim makes the verdict unknown. A row also speaks only to its own upstream update and build, so a later update (17.0.21.1.1) is judged by its upstream version, in images and in Dockerfile pins. F2: rows were keyed by RHEL major and matched any .elN release. Rows now name the dist tag (el9_6) and match only releases of that stream whose release is a number and that tag, so Oracle Linux (2.0.1.el9), AlmaLinux (.alma) and other streams are not judged by them. UBI images: only 17, 21 and 25 are judged by name, 8 and 11 skipped by name; any other ubiN/openjdk-NN is not checked and pulled. Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/assess/assess.go | 37 +++++++-- .../internal/assess/coverage_test.go | 79 +++++++++++++------ .../java4shell/internal/assess/packages.go | 2 +- .../java4shell/internal/knowledge/redhat.go | 67 ++++++++++------ .../internal/knowledge/redhat_test.go | 29 ++++--- .../java4shell/internal/repo/coverage_test.go | 22 +++++- detectors/java4shell/internal/repo/redhat.go | 35 ++++++-- 7 files changed, 196 insertions(+), 75 deletions(-) diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index dbc0c1a..243c253 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -277,25 +277,48 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi return f.set(Vulnerable, kwhy, what+" is vulnerable to Java4Shell") } +// redHatVendor is what Red Hat's release files name as IMPLEMENTOR. +const redHatVendor = "Red Hat, Inc." + // redHat applies Red Hat's backport table to a runtime its rpm installed: // a fixed Red Hat build keeps the upstream version in its VM library, so -// only the rpm release shows the fix. +// only the rpm release shows the fix. The rpm is named by the install path +// alone (the rpm database is not read), so the table clears a runtime only +// when the runtime confirms it: its VM library is a released HotSpot (not +// GraalVM, not a pre-release or self-built JDK) of exactly the upstream +// update and build the rpm packages, and its release file names Red Hat as +// the implementor. Otherwise the verdict is unknown: the path says fixed, +// the runtime does not show it. func redHat(f Finding) Finding { - if f.Package == nil || f.Package.Manager != "rpm" || f.VersionFrom != "vm-library" || f.Status != Vulnerable && f.Status != Mitigated { + if f.Package == nil || f.Package.Manager != "rpm" || f.Status != Vulnerable && f.Status != Mitigated { return f } st, why, known := knowledge.JudgeRedHat(f.Package.Name, f.Package.Version) if !known || st != knowledge.Fixed { return f } - // The VM library has to be the update the rpm packages. - up, ok := knowledge.Parse(knowledge.RPMUpstream(f.Package.Version)) + up, uok := knowledge.Parse(knowledge.RPMUpstream(f.Package.Version)) v, vok := knowledge.Parse(f.Version) - if !ok || !vok || len(up.Nums) < 3 || len(v.Nums) < 3 || knowledge.Compare(up.Nums[:3], v.Nums[:3]) != 0 { - return f + var doubt string + switch { + case f.VersionFrom != "vm-library" || !vok: + doubt = "its VM library's version line could not be read" + case f.GraalVM: + doubt = "its VM library is a GraalVM build, not Red Hat's" + case v.EA || v.SelfBuilt: + doubt = "its VM library is a pre-release or self-built JDK (" + f.Version + ")" + case !uok || up.Build < 0 || v.Build != up.Build || knowledge.Compare(v.Nums, up.Nums) != 0: + doubt = "its VM library is Java " + f.Version + ", not the update and build the rpm packages" + case f.Vendor != redHatVendor: + doubt = "its release file does not name Red Hat as the implementor" + } + if doubt != "" { + f.Release = knowledge.Unknown + return f.set(Unknown, why+", by its install path; but "+doubt+", so the runtime does not show that it is that build", + describe(f, v, vok)+": the install path names Red Hat's fixed build, the runtime does not confirm it") } f.Release, f.Mitigation, f.MitigatedFor = knowledge.Fixed, "", nil - return f.set(Fixed, why+"; its VM library reads Java "+f.Version+", the update Red Hat backported the fix into", + return f.set(Fixed, why+"; its VM library reads Java "+f.Version+", the update and build Red Hat backported the fix into, and its release file names Red Hat", describe(f, v, true)+" has Red Hat's backported Java4Shell fix (judged by its rpm release)") } diff --git a/detectors/java4shell/internal/assess/coverage_test.go b/detectors/java4shell/internal/assess/coverage_test.go index 754737d..3cc5bd4 100644 --- a/detectors/java4shell/internal/assess/coverage_test.go +++ b/detectors/java4shell/internal/assess/coverage_test.go @@ -109,15 +109,31 @@ func TestGraalVMRuntime(t *testing.T) { // the rpm named by its install path; the VM library reads the upstream // version (17.0.21+9-LTS) whatever Red Hat backports. func TestRedHatRuntime(t *testing.T) { - const el9 = "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-1.el9.x86_64" - run := func(root, ver string) Finding { - return one(t, Input{ - Libraries: []*jvm.Library{lib(t, root+"/lib/server/libjvm.so", testlib.Lib{Version: ver, VBMI: true})}, - Releases: map[string]jvm.Release{root: rel(t, "JAVA_VERSION", "17.0.21", "JAVA_RUNTIME_VERSION", ver, "IMPLEMENTOR", "Red Hat, Inc.")}, - }) + const el96 = "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-1.el9_6.x86_64" + type rt struct { + root, lib, vendor string + noVersionLine bool + env []string + } + run := func(c rt) Finding { + l := testlib.Lib{Version: c.lib, VBMI: true} + if c.noVersionLine { + l.Version = "" + } + kv := []string{"JAVA_VERSION", "17.0.21", "JAVA_RUNTIME_VERSION", c.lib} + if c.vendor != "" { + kv = append(kv, "IMPLEMENTOR", c.vendor) + } + in := Input{ + Libraries: []*jvm.Library{lib(t, c.root+"/lib/server/libjvm.so", l)}, + Releases: map[string]jvm.Release{c.root: rel(t, kv...)}, + Env: c.env, + } + return one(t, in) } - f := run(el9, "17.0.21+9-LTS") - if f.Status != Vulnerable || f.Package == nil || f.Package.Name != "java-17-openjdk-headless" || f.Package.Version != "17.0.21.0.9-1.el9" { + const rh = "Red Hat, Inc." + f := run(rt{el96, "17.0.21+9-LTS", rh, false, nil}) + if f.Status != Vulnerable || f.Package == nil || f.Package.Name != "java-17-openjdk-headless" || f.Package.Version != "17.0.21.0.9-1.el9_6" { t.Fatalf("RHEL 9 rpm: %s %+v (%s)", f.Status, f.Package, f.Reason) } if !strings.Contains(f.Fix, "Red Hat had published no fixed") || !strings.Contains(f.Fix, "dnf upgrade java-17-openjdk-headless") { @@ -126,29 +142,44 @@ func TestRedHatRuntime(t *testing.T) { saved := knowledge.RedHatFixed t.Cleanup(func() { knowledge.RedHatFixed = saved }) - knowledge.RedHatFixed = []knowledge.RedHatFix{{Package: "java-17-openjdk", EL: 9, EVR: "1:17.0.21.0.9-2.el9", Advisory: "RHSA-2026:0000"}} - if f := run(el9, "17.0.21+9-LTS"); f.Status != Vulnerable || !strings.Contains(f.Fix, "17.0.21.0.9-2.el9") { + knowledge.RedHatFixed = []knowledge.RedHatFix{{Package: "java-17-openjdk", Dist: "el9_6", EVR: "1:17.0.21.0.9-2.el9_6", Advisory: "RHSA-2026:0000"}} + if f := run(rt{el96, "17.0.21+9-LTS", rh, false, nil}); f.Status != Vulnerable || !strings.Contains(f.Fix, "17.0.21.0.9-2.el9_6") { t.Errorf("older than the listed build: %s (%s) fix %s", f.Status, f.Reason, f.Fix) } - fixed := "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-2.el9.x86_64" - if f := run(fixed, "17.0.21+9-LTS"); f.Status != Fixed || !strings.Contains(f.Reason, "Red Hat") || f.Fix != "" { + fixed := "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-2.el9_6.x86_64" + if f := run(rt{fixed, "17.0.21+9-LTS", rh, false, nil}); f.Status != Fixed || !strings.Contains(f.Reason, "Red Hat") || f.Fix != "" { t.Errorf("listed build: %s (%s) fix %q", f.Status, f.Reason, f.Fix) } - if f := run("/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-3.el9_7.x86_64", "17.0.21+9-LTS"); f.Status != Fixed { + if f := run(rt{"/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-3.el9_6.x86_64", "17.0.21+9-LTS", rh, false, nil}); f.Status != Fixed { t.Errorf("later build: %s (%s)", f.Status, f.Reason) } - // The VM library must be the update the rpm names: a path that says - // 17.0.21 over a 17.0.13 VM library proves nothing. - if f := run("/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-2.el9.x86_64", "17.0.13+11-LTS"); f.Status != Vulnerable { - t.Errorf("mismatched VM library: %s (%s)", f.Status, f.Reason) + // A mitigated runtime of the fixed build is fixed too. + if f := run(rt{fixed, "17.0.21+9-LTS", rh, false, []string{"JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics"}}); f.Status != Fixed || f.Mitigation != "" { + t.Errorf("mitigated fixed build: %s (%s)", f.Status, f.Reason) } - // No RHEL 8 entry: judged by the VM library. - if f := run("/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-9.el8.x86_64", "17.0.21+9-LTS"); f.Status != Vulnerable { - t.Errorf("RHEL 8: %s (%s)", f.Status, f.Reason) - } - // Not Red Hat: Fedora is not in the table. - if f := run("/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-9.fc41.x86_64", "17.0.21+9"); f.Status != Vulnerable { - t.Errorf("Fedora: %s (%s)", f.Status, f.Reason) + // What the install path alone must not clear: the path names the fixed + // build, but the VM library or the release file does not confirm it. + for _, c := range []struct { + name string + rt rt + }{ + {"another vendor's library under a later release", rt{"/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-99.el9_6.x86_64", "17.0.21+9", "Eclipse Adoptium", false, nil}}, + {"no release-file vendor", rt{fixed, "17.0.21+9-LTS", "", false, nil}}, + {"another build", rt{fixed, "17.0.21+5-LTS", rh, false, nil}}, + {"another update", rt{fixed, "17.0.21.0.3+1-LTS", rh, false, nil}}, + {"pre-release", rt{fixed, "17.0.21-ea+9", rh, false, nil}}, + {"self-built", rt{fixed, "17.0.21-internal+0-adhoc.root.src", rh, false, nil}}, + {"GraalVM", rt{fixed, "17.0.21+9-jvmci-23.0-b12", rh, false, nil}}, + {"version from the release file only", rt{fixed, "17.0.21+9-LTS", rh, true, nil}}, + {"a later update the row does not cover", rt{"/usr/lib/jvm/java-17-openjdk-17.0.21.1.1-1.el9_6.x86_64", "17.0.21.1+1-LTS", rh, false, nil}}, + {"another stream", rt{"/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-9.el9_7.x86_64", "17.0.21+9-LTS", rh, false, nil}}, + {"RHEL 8", rt{"/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-9.el8.x86_64", "17.0.21+9-LTS", rh, false, nil}}, + {"Oracle Linux", rt{"/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-2.0.1.el9_6.x86_64", "17.0.21+9-LTS", "Oracle Corporation", false, nil}}, + {"Fedora", rt{"/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-9.fc41.x86_64", "17.0.21+9", rh, false, nil}}, + } { + if f := run(c.rt); f.Status == Fixed || f.Status == NotAffected { + t.Errorf("%s: cleared: %s (%s)", c.name, f.Status, f.Reason) + } } } diff --git a/detectors/java4shell/internal/assess/packages.go b/detectors/java4shell/internal/assess/packages.go index 30b6c3d..fb7b370 100644 --- a/detectors/java4shell/internal/assess/packages.go +++ b/detectors/java4shell/internal/assess/packages.go @@ -134,7 +134,7 @@ func distroStatus(p Package) string { case "rpm": if pkg, el, ok := knowledge.RedHatPackage(p.Name, p.Version); ok { if fx, ok := knowledge.RedHatFixFor(pkg, el); ok { - return fmt.Sprintf("Red Hat's first fixed RHEL %d build is %s, %s", el, fx.EVR, fx.Advisory) + return fmt.Sprintf("Red Hat's first fixed %s build is %s, %s", el, fx.EVR, fx.Advisory) } return knowledge.RedHatStatus() } diff --git a/detectors/java4shell/internal/knowledge/redhat.go b/detectors/java4shell/internal/knowledge/redhat.go index 46f78e8..df0ec95 100644 --- a/detectors/java4shell/internal/knowledge/redhat.go +++ b/detectors/java4shell/internal/knowledge/redhat.go @@ -14,10 +14,13 @@ import ( // release. FACTS.md gives the sources. // RedHatFix is the first Red Hat build of an OpenJDK package with the fix -// on one RHEL major release. +// in one RHEL stream. A row speaks only to builds of the same stream (the +// rpm release's dist tag, el9_6) and the same upstream update and build +// (17.0.21.0.9 is 17.0.21+9): Red Hat's streams are maintained separately, +// and a later update is judged by its upstream version. type RedHatFix struct { Package string // source package: java-17-openjdk - EL int // RHEL major release: 8, 9, 10 + Dist string // the release's dist tag: el9_6, el8_10, el9 EVR string // [epoch:]version-release: 1:17.0.21.0.9-2.el9_6 Advisory string // RHSA-... } @@ -36,55 +39,69 @@ func RedHatStatus() string { } var parts []string for _, f := range RedHatFixed { - parts = append(parts, fmt.Sprintf("%s %s on RHEL %d (%s)", f.Package, f.EVR, f.EL, f.Advisory)) + parts = append(parts, fmt.Sprintf("%s %s for %s (%s)", f.Package, f.EVR, f.Dist, f.Advisory)) } return "Red Hat's fixed builds: " + strings.Join(parts, ", ") } var ( - elRelease = regexp.MustCompile(`\.el(\d{1,2})(?:[._]|$)`) + // A Red Hat release: a number and the dist tag, nothing else (Oracle + // Linux's 2.0.1.el9 and AlmaLinux's 2.el9_6.alma.1 are not Red Hat's + // builds). CentOS Stream's el9 looks the same as RHEL's el9. + rhRelease = regexp.MustCompile(`^\d+\.(el\d{1,2}(?:_\d{1,2})?)$`) rhPackage = regexp.MustCompile(`^(java-\d{1,2}-openjdk)(?:-(?:headless|devel|jmods|src|demo|javadoc|javadoc-zip|static-libs|fastdebug|slowdebug)\b.*)?$`) rpmVersion = regexp.MustCompile(`^(?:(\d+):)?([^-]+)(?:-(.+))?$`) ) -// RedHatPackage returns the source package and the RHEL major release of -// an rpm of Red Hat's OpenJDK: java-17-openjdk-headless with release -// 1.el9_6 is java-17-openjdk on RHEL 9. ok is false for other packages and -// for releases that are not Red Hat's (.fc41, .amzn2023). -func RedHatPackage(name, evr string) (pkg string, el int, ok bool) { +// RedHatPackage returns the source package and the dist tag of an rpm of +// Red Hat's OpenJDK: java-17-openjdk-headless with release 1.el9_6 is +// java-17-openjdk in el9_6. ok is false for other packages and for +// releases that are not Red Hat's (.fc41, .amzn2023, 2.0.1.el9). +func RedHatPackage(name, evr string) (pkg, dist string, ok bool) { m := rhPackage.FindStringSubmatch(name) if m == nil { - return "", 0, false + return "", "", false } - e := elRelease.FindStringSubmatch(evr) - if e == nil { - return "", 0, false + v := rpmVersion.FindStringSubmatch(evr) + if v == nil || v[3] == "" { + return "", "", false } - n, _ := strconv.Atoi(e[1]) - return m[1], n, true + d := rhRelease.FindStringSubmatch(v[3]) + if d == nil { + return "", "", false + } + return m[1], d[1], true } -// RedHatFixFor returns the table's entry for a package on a RHEL release. -func RedHatFixFor(pkg string, el int) (RedHatFix, bool) { +// RedHatFixFor returns the table's row for a package in a RHEL stream. +func RedHatFixFor(pkg, dist string) (RedHatFix, bool) { for _, f := range RedHatFixed { - if f.Package == pkg && f.EL == el { + if f.Package == pkg && f.Dist == dist { return f, true } } return RedHatFix{}, false } +// sameUpstream reports whether two Red Hat rpm versions package the same +// upstream update and build. +func sameUpstream(a, b string) bool { + x, okx := Parse(RPMUpstream(a)) + y, oky := Parse(RPMUpstream(b)) + return okx && oky && x.Build >= 0 && x.Build == y.Build && Compare(x.Nums, y.Nums) == 0 +} + // JudgeRedHat judges an rpm of Red Hat's OpenJDK (name and // [epoch:]version-release) by the backport table. known is false when the -// table has no entry for its package and RHEL release: then only its -// upstream version can judge it. +// table has no row for its package and stream, or the row is for another +// upstream update or build: then only its upstream version can judge it. func JudgeRedHat(name, evr string) (st Status, why string, known bool) { - pkg, el, ok := RedHatPackage(name, evr) + pkg, dist, ok := RedHatPackage(name, evr) if !ok { return Unknown, "", false } - fx, ok := RedHatFixFor(pkg, el) - if !ok { + fx, ok := RedHatFixFor(pkg, dist) + if !ok || !sameUpstream(evr, fx.EVR) { return Unknown, "", false } a, b := evr, fx.EVR @@ -93,9 +110,9 @@ func JudgeRedHat(name, evr string) (st Status, why string, known bool) { a, b = stripEpoch(a), stripEpoch(b) } if CompareRPM(a, b) < 0 { - return Vulnerable, fmt.Sprintf("Red Hat build %s-%s is older than %s, the first RHEL %d build with the fix (%s)", pkg, stripEpoch(evr), stripEpoch(fx.EVR), el, fx.Advisory), true + return Vulnerable, fmt.Sprintf("Red Hat build %s-%s is older than %s, the first %s build with the fix (%s)", pkg, stripEpoch(evr), stripEpoch(fx.EVR), dist, fx.Advisory), true } - return Fixed, fmt.Sprintf("Red Hat build %s-%s is at or past %s, the first RHEL %d build with Red Hat's backport of the fix (%s)", pkg, stripEpoch(evr), stripEpoch(fx.EVR), el, fx.Advisory), true + return Fixed, fmt.Sprintf("Red Hat build %s-%s is at or past %s, the first %s build with Red Hat's backport of the fix (%s)", pkg, stripEpoch(evr), stripEpoch(fx.EVR), dist, fx.Advisory), true } func stripEpoch(evr string) string { diff --git a/detectors/java4shell/internal/knowledge/redhat_test.go b/detectors/java4shell/internal/knowledge/redhat_test.go index 6814ef3..b9a40bc 100644 --- a/detectors/java4shell/internal/knowledge/redhat_test.go +++ b/detectors/java4shell/internal/knowledge/redhat_test.go @@ -37,23 +37,32 @@ func TestRedHatTable(t *testing.T) { } saved := RedHatFixed t.Cleanup(func() { RedHatFixed = saved }) - RedHatFixed = []RedHatFix{{Package: "java-17-openjdk", EL: 9, EVR: "1:17.0.21.0.9-2.el9", Advisory: "RHSA-2026:0000"}} + RedHatFixed = []RedHatFix{{Package: "java-17-openjdk", Dist: "el9_6", EVR: "1:17.0.21.0.9-2.el9_6", Advisory: "RHSA-2026:0000"}} for _, c := range []struct { name, evr string want Status known bool }{ - {"java-17-openjdk-headless", "17.0.21.0.9-1.el9", Vulnerable, true}, - {"java-17-openjdk-headless", "1:17.0.21.0.9-1.el9", Vulnerable, true}, - {"java-17-openjdk-headless", "1:17.0.21.0.9-2.el9", Fixed, true}, + {"java-17-openjdk-headless", "17.0.21.0.9-1.el9_6", Vulnerable, true}, + {"java-17-openjdk-headless", "1:17.0.21.0.9-1.el9_6", Vulnerable, true}, + {"java-17-openjdk-headless", "1:17.0.21.0.9-2.el9_6", Fixed, true}, // An install path or a dnf argument omits the epoch: compared without it. - {"java-17-openjdk-headless", "17.0.21.0.9-2.el9", Fixed, true}, - {"java-17-openjdk", "1:17.0.21.0.9-3.el9_7", Fixed, true}, - {"java-17-openjdk-devel", "1:17.0.21.0.9-2.el9", Fixed, true}, - {"java-17-openjdk-headless", "1:17.0.21.0.9-9.el8", "", false}, // no RHEL 8 entry - {"java-21-openjdk-headless", "1:21.0.13.0.9-1.el9", "", false}, + {"java-17-openjdk-headless", "17.0.21.0.9-2.el9_6", Fixed, true}, + {"java-17-openjdk", "1:17.0.21.0.9-3.el9_6", Fixed, true}, + {"java-17-openjdk-devel", "1:17.0.21.0.9-2.el9_6", Fixed, true}, + // Another stream of RHEL 9 (el9, el9_4, el9_7): the row does not speak to it. + {"java-17-openjdk-headless", "1:17.0.21.0.9-9.el9", "", false}, + {"java-17-openjdk-headless", "1:17.0.21.0.9-9.el9_7", "", false}, + {"java-17-openjdk-headless", "1:17.0.21.0.9-9.el8_10", "", false}, + // Rebuilds that are not Red Hat's: Oracle Linux, AlmaLinux. + {"java-17-openjdk-headless", "1:17.0.21.0.9-2.0.1.el9_6", "", false}, + {"java-17-openjdk-headless", "1:17.0.21.0.9-2.el9_6.alma.1", "", false}, + // Another upstream update or build: the row does not speak to it. + {"java-17-openjdk-headless", "1:17.0.21.1.1-1.el9_6", "", false}, + {"java-17-openjdk-headless", "1:17.0.21.0.10-1.el9_6", "", false}, + {"java-21-openjdk-headless", "1:21.0.13.0.9-1.el9_6", "", false}, {"java-17-openjdk-headless", "17.0.21.0.9-1.fc41", "", false}, // not Red Hat - {"java-17-amazon-corretto-headless", "17.0.21.0.9-1.el9", "", false}, + {"java-17-amazon-corretto-headless", "17.0.21.0.9-2.el9_6", "", false}, } { st, why, known := JudgeRedHat(c.name, c.evr) if known != c.known || known && (st != c.want || why == "") { diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index 5efcd6c..b8b76aa 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -149,6 +149,11 @@ func TestRedHatRepo(t *testing.T) { "FROM registry.access.redhat.com/ubi8/openjdk-11", "FROM registry.access.redhat.com/ubi8/openjdk-8-runtime:1.20", "FROM registry.access.redhat.com/ubi9/openjdk-17-runtime@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + "FROM registry.access.redhat.com/ubi9/openjdk-22", + "FROM registry.access.redhat.com/ubi9/openjdk-28", + "FROM registry.access.redhat.com/ubi9/openjdk-99", + "FROM registry.access.redhat.com/ubi8/openjdk-1", + "FROM registry.access.redhat.com/ubi8/openjdk-16", }, "\n") + "\n", "Dockerfile.pkg": strings.Join([]string{ "FROM registry.access.redhat.com/ubi9/ubi-minimal", @@ -166,6 +171,11 @@ func TestRedHatRepo(t *testing.T) { {"Dockerfile", 3, RuleImagePin, StatusVulnerable}, {"Dockerfile", 4, RuleImagePin, StatusVulnerable}, {"Dockerfile", 7, RuleNotChecked, StatusUnknown}, + {"Dockerfile", 8, RuleNotChecked, StatusUnknown}, + {"Dockerfile", 9, RuleNotChecked, StatusUnknown}, + {"Dockerfile", 10, RuleNotChecked, StatusUnknown}, + {"Dockerfile", 11, RuleNotChecked, StatusUnknown}, + {"Dockerfile", 12, RuleNotChecked, StatusUnknown}, {"Dockerfile.pkg", 2, RulePackage, StatusVulnerable}, {"Dockerfile.pkg", 3, RulePackage, StatusVulnerable}, {"Dockerfile.pkg", 4, RulePackage, StatusVulnerable}, @@ -195,9 +205,13 @@ func TestRedHatRepo(t *testing.T) { // install may get it: only the image can tell. saved := knowledge.RedHatFixed t.Cleanup(func() { knowledge.RedHatFixed = saved }) - knowledge.RedHatFixed = []knowledge.RedHatFix{{Package: "java-17-openjdk", EL: 9, EVR: "1:17.0.21.0.9-2.el9", Advisory: "RHSA-2026:0000"}, - {Package: "java-21-openjdk", EL: 9, EVR: "1:21.0.13.0.9-2.el9", Advisory: "RHSA-2026:0001"}} - files["Dockerfile.pkg"] += "RUN dnf install -y java-17-openjdk-headless-17.0.21.0.9-2.el9\n" + knowledge.RedHatFixed = []knowledge.RedHatFix{{Package: "java-17-openjdk", Dist: "el9", EVR: "1:17.0.21.0.9-2.el9", Advisory: "RHSA-2026:0000"}, + {Package: "java-21-openjdk", Dist: "el9_6", EVR: "1:21.0.13.0.9-2.el9_6", Advisory: "RHSA-2026:0001"}} + files["Dockerfile.pkg"] += "RUN dnf install -y java-17-openjdk-headless-17.0.21.0.9-2.el9\n" + + // The row is for 17.0.21+9: a later update's build 1 and an Oracle + // Linux rebuild are judged by their upstream version. + "RUN dnf install -y java-17-openjdk-headless-17.0.21.1.1-1.el9\n" + + "RUN dnf install -y java-17-openjdk-headless-17.0.21.0.9-2.0.1.el9\n" res = scan(t, tree(t, files)) checkAll(t, res, []want{ {"Dockerfile", 2, RuleNotChecked, StatusUnknown}, @@ -205,6 +219,8 @@ func TestRedHatRepo(t *testing.T) { {"Dockerfile", 4, RuleImagePin, StatusVulnerable}, // no java-25 entry {"Dockerfile.pkg", 2, RulePackage, StatusUnknown}, {"Dockerfile.pkg", 4, RulePackage, StatusVulnerable}, + {"Dockerfile.pkg", 8, RulePackage, StatusVulnerable}, + {"Dockerfile.pkg", 9, RulePackage, StatusVulnerable}, }) if f, ok := find(res, "Dockerfile.pkg", 7); ok { t.Errorf("the listed fixed build reported: %+v", f) diff --git a/detectors/java4shell/internal/repo/redhat.go b/detectors/java4shell/internal/repo/redhat.go index aa8bedb..c1c7f68 100644 --- a/detectors/java4shell/internal/repo/redhat.go +++ b/detectors/java4shell/internal/repo/redhat.go @@ -25,9 +25,11 @@ func (s *scanner) redHatRef(r refs.Ref, img string, props map[string]string, mit if m == nil { return false } - feature, el := atoi(m[2]), atoi(m[1]+m[3]) - if feature < 17 { - return true // Java 8 and 11: no decoder + feature, el := atoi(m[2]), m[1]+m[3] + if feature == 8 || feature == 11 { + // Red Hat's Java 8 and 11 builds: OpenJDK 8 and 11 have no decode + // intrinsic (skipped by name, as eclipse-temurin:11 is; FACTS.md). + return true } props["vendor"] = "Red Hat" pkg := fmt.Sprintf("java-%d-openjdk", feature) @@ -35,7 +37,11 @@ func (s *scanner) redHatRef(r refs.Ref, img string, props map[string]string, mit s.add(Finding{Rule: RuleNotChecked, File: r.File, Line: r.Line, Level: "note", Status: StatusUnknown, Pull: img, ref: &r, Props: props, Reason: why, Message: fmt.Sprintf("image %s: %s", img, why)}) } - if fx, ok := knowledge.RedHatFixFor(pkg, el); ok { + if !redHatLines[feature] { + pull(fmt.Sprintf("Red Hat's OpenJDK %d images are not in this detector's release data: only the image can show which Java it holds", feature)) + return true + } + if fx, ok := redHatRowFor(pkg, el); ok { pull(fmt.Sprintf("Red Hat published %s %s (%s); whether this image has it, only the image can show: its tag names the image's release, not the Java update", pkg, fx.EVR, fx.Advisory)) return true } @@ -63,6 +69,25 @@ func (s *scanner) redHatRef(r refs.Ref, img string, props map[string]string, mit return true } +// redHatLines are the Java lines of Red Hat's OpenJDK images this +// detector judges by name: the lines Red Hat ships with the decoder. +var redHatLines = map[int]bool{17: true, 21: true, 25: true} + +// redHatRowFor returns a table row for a package in any stream of a RHEL +// major release ("9" matches el9, el9_6...); el "" (openjdk/openjdk-11-rhel7 +// has a release) matches any. +func redHatRowFor(pkg, el string) (knowledge.RedHatFix, bool) { + for _, f := range knowledge.RedHatFixed { + if f.Package != pkg { + continue + } + if d := strings.TrimPrefix(f.Dist, "el"); el == "" || d == el || strings.HasPrefix(d, el+"_") { + return f, true + } + } + return knowledge.RedHatFix{}, false +} + // redHatPin judges a pinned rpm of Red Hat's OpenJDK // (java-17-openjdk-headless-17.0.21.0.9-1.el9) by the backport table. ok is // false when the table does not decide it. @@ -83,7 +108,7 @@ func redHatPublished(name string) (string, bool) { var out []string for _, f := range knowledge.RedHatFixed { if f.Package == m[1] { - out = append(out, fmt.Sprintf("%s on RHEL %d (%s)", f.EVR, f.EL, f.Advisory)) + out = append(out, fmt.Sprintf("%s for %s (%s)", f.EVR, f.Dist, f.Advisory)) } } return strings.Join(out, ", "), len(out) > 0 From eae6a1b95ba1918a21778ab11e74b411956fe9c9 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 06:57:13 +0000 Subject: [PATCH 053/119] java4shell: gofmt Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/internal/assess/coverage_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/detectors/java4shell/internal/assess/coverage_test.go b/detectors/java4shell/internal/assess/coverage_test.go index 3cc5bd4..4a612f1 100644 --- a/detectors/java4shell/internal/assess/coverage_test.go +++ b/detectors/java4shell/internal/assess/coverage_test.go @@ -112,8 +112,8 @@ func TestRedHatRuntime(t *testing.T) { const el96 = "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-1.el9_6.x86_64" type rt struct { root, lib, vendor string - noVersionLine bool - env []string + noVersionLine bool + env []string } run := func(c rt) Finding { l := testlib.Lib{Version: c.lib, VBMI: true} From 9c5261b3c272698a97ef4882eda1f6a8f0b84b3f Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 06:59:02 +0000 Subject: [PATCH 054/119] java4shell: GraalVM's own numbers clear only what was checked (review F3, F4) F3: the repo scan cleared GraalVM names that 62f3d8b marked not checked: 22.3.0.r17-nik (NIK's numbering is inferred), Java 1 or 0 (22.3.1.r1-grl, graalvm-22.3.1+java1), 21.3.x for Java 8 and 11 (GraalVM Enterprise 21.3.20.0.3 is listed without its Java line), and malformed numbers (22.3.0-dev, 22.3.00, 22.3.0.0). Now a GraalVM release in its own numbers is not affected only for GraalVM Community names (sdkman grl and graalce, asdf graalvm) with Java 8 to 16 outside 21.3.x, or exactly 22.3.0 for Java 17; the number must be well formed; everything else the data cannot settle is not checked. 22.3.0 for Java 19 stays vulnerable. F4: with a GraalVMFixed row, a version OpenJDK's data judges unknown (17.0.21.9, a vendor build number; 17.0.22, a later update) read fixed. A row now clears only what Judge also judges fixed. GraalVM Community's own release numbers (25.1.3 for JDK 25.0.3, 25.5.5.0.3 for 25.0.5.0.3) are recognised (a second number other than 0) and never judged as Java versions, in version files and image tags. Co-Authored-By: Claude Opus 5.5 --- .../internal/knowledge/coverage_test.go | 79 ++++++++++++++++++- .../java4shell/internal/knowledge/graalvm.go | 58 +++++++++----- .../internal/knowledge/redhat_test.go | 2 +- .../java4shell/internal/repo/coverage_test.go | 43 ++++++++++ detectors/java4shell/internal/repo/graalvm.go | 34 ++++++-- detectors/java4shell/internal/repo/repo.go | 4 +- 6 files changed, 190 insertions(+), 30 deletions(-) diff --git a/detectors/java4shell/internal/knowledge/coverage_test.go b/detectors/java4shell/internal/knowledge/coverage_test.go index ec01126..4b006cd 100644 --- a/detectors/java4shell/internal/knowledge/coverage_test.go +++ b/detectors/java4shell/internal/knowledge/coverage_test.go @@ -83,14 +83,89 @@ func TestGraalVMRelease(t *testing.T) { {"22.3", 17, Unknown}, // 22.3.0 or a later patch {"21.3.5", 17, Unknown}, {"22.3.1", 11, NotAffected}, - {"21.3.0", 8, NotAffected}, + {"21.3.0", 8, Unknown}, // 21.3.x: GraalVM Enterprise 21.3 is listed {"22.3.1", 19, Vulnerable}, {"23.1.2", 21, Vulnerable}, {"22.3.1", 16, NotAffected}, {"22.3.1", 30, Unknown}, } { - if st, why := JudgeGraalVMRelease(c.graal, c.java); st != c.want || why == "" { + if st, why := JudgeGraalVMRelease(c.graal, c.java, true); st != c.want || why == "" { t.Errorf("JudgeGraalVMRelease(%s, %d) = %s (%s), want %s", c.graal, c.java, st, why, c.want) } } } + +// Review F3: GraalVM's own numbers clear a release only for GraalVM +// Community names with Java 8 to 16 (not 21.3.x, whose Enterprise build is +// listed as affected) or exactly 22.3.0 for Java 17; NIK, Mandrel, other +// vendors and malformed numbers stay unknown. +func TestGraalVMReleaseStrict(t *testing.T) { + for _, c := range []struct { + graal string + java int + community bool + want Status + }{ + {"22.3.0", 17, true, NotAffected}, + {"22.3.0", 17, false, Unknown}, // NIK, Mandrel: numbering inferred + {"22.3.1", 17, false, Vulnerable}, + {"22.3.1", 11, true, NotAffected}, + {"22.3.1", 11, false, Unknown}, + {"22.3.1", 1, true, Unknown}, + {"22.3.1", 0, true, Unknown}, + {"22.3.1", 7, true, Unknown}, + {"21.3.20", 11, true, Unknown}, + {"21.3.20", 8, true, Unknown}, + {"22.3.0-dev", 17, true, Unknown}, + {"22.3.00", 17, true, Unknown}, + {"22.3.0.0", 17, true, Unknown}, + {"22.3.0", 19, true, Vulnerable}, // every Java 19 release has the decoder + {"22.3.0", 19, false, Vulnerable}, + } { + if st, why := JudgeGraalVMRelease(c.graal, c.java, c.community); st != c.want || why == "" { + t.Errorf("JudgeGraalVMRelease(%s, %d, community %v) = %s (%s), want %s", c.graal, c.java, c.community, st, why, c.want) + } + } +} + +// Review F4: with a fixed GraalVM row, only a version OpenJDK's data also +// judges fixed is fixed; a vendor build number or a later update stays +// unknown, and pre-release or older builds are not fixed. +func TestGraalVMRow(t *testing.T) { + saved := GraalVMFixed + t.Cleanup(func() { GraalVMFixed = saved }) + GraalVMFixed = map[int]Build{17: {Version: []int{17, 0, 21, 1}, Build: 2}} + for v, want := range map[string]Status{ + "17.0.21.1+2-jvmci-23.0-b99": Fixed, + "17.0.21.1+3-jvmci-23.0-b99": Fixed, + "17.0.21.9+1-jvmci-23.0-b99": Unknown, + "17.0.22+7-jvmci-23.0-b99": Unknown, + "17.0.21.1+1-jvmci-23.0-b99": Vulnerable, + "17.0.21.1-ea+2-jvmci-23.0-b99": Unknown, + "17.0.21.1-ea+1-jvmci-23.0-b99": Vulnerable, + "17.0.21.0.3+1-LTS-jvmci-23.0-b99": Vulnerable, + } { + p, ok := Parse(v) + if !ok { + t.Fatalf("Parse(%s)", v) + } + if st, why := JudgeGraalVM(p); st != want { + t.Errorf("row 17.0.21.1+2: JudgeGraalVM(%s) = %s (%s), want %s", v, st, why, want) + } + } +} + +// GraalVM Community's own release numbers (graal-25.5.5.0.3 is JDK +// 25.0.5.0.3, graal-25.1.3 is JDK 25.0.3) are never Java versions. +func TestGraalVMOwnNumbersNotJava(t *testing.T) { + for _, s := range []string{"25.1.3", "25.5.5.0.3", "23.1.2"} { + if !GraalVMOwnNumber(s) { + t.Errorf("%s not recognised as GraalVM's own number", s) + } + } + for _, s := range []string{"25.0.3", "25.0.5.0.3", "17.0.21.1", "21"} { + if GraalVMOwnNumber(s) { + t.Errorf("%s taken as GraalVM's own number", s) + } + } +} diff --git a/detectors/java4shell/internal/knowledge/graalvm.go b/detectors/java4shell/internal/knowledge/graalvm.go index 96b0e10..f479a32 100644 --- a/detectors/java4shell/internal/knowledge/graalvm.go +++ b/detectors/java4shell/internal/knowledge/graalvm.go @@ -2,6 +2,8 @@ package knowledge import ( "fmt" + "regexp" + "strconv" "strings" ) @@ -42,8 +44,9 @@ func JudgeGraalVM(v Version) (Status, string) { case Vulnerable: return st, "GraalVM: " + why + "; " + graalVMAffected } - fx, ok := GraalVMFixed[v.Feature()] - if ok && !v.EA { + // A row clears only what OpenJDK's data also judges fixed: a vendor + // build number in the fourth place or a later update stays unknown. + if fx, ok := GraalVMFixed[v.Feature()]; ok && st == Fixed { c := Compare(v.Nums, fx.Version) // A version without its build is taken as the GA build, as for OpenJDK. if c < 0 || c == 0 && fx.Build >= 0 && v.Build >= 0 && v.Build < fx.Build { @@ -80,36 +83,53 @@ var ( graalVM17With = []int{22, 3, 1} ) +// GraalVMOwnNumber reports a version in GraalVM's own numbers (22.3.1, +// 23.1.2, GraalVM Community's 25.1.3 for JDK 25.0.3 and 25.5.5.0.3 for JDK +// 25.0.5.0.3) rather than a Java version: Java's second number has been 0 +// since JDK 10. +func GraalVMOwnNumber(s string) bool { + v, ok := Parse(s) + return ok && v.Feature() >= 10 && len(v.Nums) >= 2 && v.Nums[1] != 0 +} + +// graalRelease is a well-formed GraalVM release number: two to four +// numbers without leading zeros. +var graalRelease = regexp.MustCompile(`^(?:0|[1-9]\d?)\.(?:0|[1-9]\d?)(?:\.(?:0|[1-9]\d{0,2})){0,2}$`) + // JudgeGraalVMRelease judges a GraalVM release named by GraalVM's own -// number and the Java line it is built for. -func JudgeGraalVMRelease(graal string, java int) (Status, string) { - g, ok := Parse(graal) - nums := g.Nums - if !ok { - nums = nil - for _, p := range strings.Split(graal, ".") { - n, r := leadingInt(p) - if n < 0 || r != "" { - return Unknown, fmt.Sprintf("GraalVM %s for Java %d: the GraalVM version could not be read", graal, java) - } - nums = append(nums, n) - } - } +// number and the Java line it is built for. community is true for GraalVM +// Community's own names (sdkman grl and graalce, asdf graalvm): only those +// are cleared, since the releases checked are GraalVM Community's; the +// numbering of Liberica NIK, Mandrel and Oracle's builds is not checked. +func JudgeGraalVMRelease(graal string, java int, community bool) (Status, string) { name := fmt.Sprintf("GraalVM %s for Java %d", graal, java) + if !graalRelease.MatchString(graal) { + return Unknown, fmt.Sprintf("%s: the GraalVM version could not be read", name) + } + var nums []int + for _, p := range strings.Split(graal, ".") { + n, _ := strconv.Atoi(p) + nums = append(nums, n) + } + is213 := Compare(nums[:2], []int{21, 3}) == 0 switch { + case java < 8: + return Unknown, fmt.Sprintf("%s: not a Java line GraalVM is built for", name) + case java < firstVBMIDecode && community && !is213: + return NotAffected, fmt.Sprintf("%s is built on OpenJDK %d, which has no x86-64 Base64 decode intrinsic (the Java 11 build of GraalVM Community 22.3.1 carries no decoder stubs)", name, java) case java < firstVBMIDecode: - return NotAffected, fmt.Sprintf("%s is built on OpenJDK %d, which has no x86-64 Base64 decode intrinsic (the Java 11 build of GraalVM 22.3.1 carries no decoder stubs)", name, java) + return Unknown, fmt.Sprintf("%s: OpenJDK %d has no decoder, but whether this build carries one is not known (GraalVM Enterprise Edition 21.3.20.0.3 is listed as affected without its Java line, and other vendors' GraalVM builds were not checked)", name, java) case java >= newestFeature: return Unknown, fmt.Sprintf("%s: Java %d is newer than this detector's release data (%s)", name, java, Checked) case java > firstVBMIDecode: // Every release of Java 18 and later has the decoder. return Vulnerable, fmt.Sprintf("%s: every Java %d release has the AVX-512 VBMI Base64 decoder; %s, and no fixed GraalVM build had been published as of %s", name, java, graalVMAffected, Checked) } - if len(nums) >= 3 && Compare(nums, graalVM17Without) == 0 { + if community && len(nums) == 3 && Compare(nums, graalVM17Without) == 0 { return NotAffected, fmt.Sprintf("%s is built on Java 17.0.5, which predates the AVX-512 VBMI Base64 decoder (17.0.6)", name) } if len(nums) >= 3 && Compare(nums, graalVM17With) >= 0 || len(nums) >= 2 && Compare(nums[:2], []int{22, 3}) > 0 { return Vulnerable, fmt.Sprintf("%s is built on Java 17.0.6 or later (GraalVM 22.3.1 is 17.0.6), which has the AVX-512 VBMI Base64 decoder; %s, and no fixed GraalVM build had been published as of %s", name, graalVMAffected, Checked) } - return Unknown, fmt.Sprintf("%s: GraalVM 22.3.0 is built on Java 17.0.5 (before the decoder) and 22.3.1 and later on 17.0.6 and later (with it); which Java 17 update this release is built on is not known", name) + return Unknown, fmt.Sprintf("%s: GraalVM Community 22.3.0 is built on Java 17.0.5 (before the decoder) and 22.3.1 and later on 17.0.6 and later (with it); which Java 17 update this release is built on is not known", name) } diff --git a/detectors/java4shell/internal/knowledge/redhat_test.go b/detectors/java4shell/internal/knowledge/redhat_test.go index b9a40bc..fe0161d 100644 --- a/detectors/java4shell/internal/knowledge/redhat_test.go +++ b/detectors/java4shell/internal/knowledge/redhat_test.go @@ -104,7 +104,7 @@ func FuzzRPM(f *testing.F) { if st, why, known := JudgeRedHat("java-17-openjdk-headless", a); known && (st == "" || why == "") { t.Fatalf("JudgeRedHat(%q) gave no verdict or reason", a) } - if st, why := JudgeGraalVMRelease(a, len(b)%40); st == "" || why == "" { + if st, why := JudgeGraalVMRelease(a, len(b)%40, len(a)%2 == 0); st == "" || why == "" { t.Fatalf("JudgeGraalVMRelease(%q) gave no verdict or reason", a) } }) diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index b8b76aa..a01befe 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -259,3 +259,46 @@ func TestVendorStatus(t *testing.T) { } } } + +// Review F3: GraalVM names the data cannot settle are not checked, never +// silently cleared; GraalVM Community's own release numbers (25.1.3, +// 25.5.5.0.3) are not Java versions. +func TestGraalVMRepoStrict(t *testing.T) { + root := tree(t, map[string]string{ + "a/.sdkmanrc": "java=22.3.0.r17-nik\n", + "b/.sdkmanrc": "java=22.3.1.r1-grl\n", + "c/.sdkmanrc": "java=21.3.20.r8-grl\n", + "d/.sdkmanrc": "java=22.3.0.r19-grl\n", + "e/.sdkmanrc": "java=25.1.3-graalce\n", + "f/.sdkmanrc": "java=22.3.00.r17-grl\n", + "a/.tool-versions": "java graalvm-22.3.1+java1\n", + "b/.tool-versions": "java graalvm-21.3.20+java11\n", + "c/.tool-versions": "java graalvm-22.3.0-dev+java17\n", + "d/.tool-versions": "java graalvm-22.3.0.0+java17\n", + "e/.tool-versions": "java mandrel-22.3.0.0-Final+java17\n", + "f/.tool-versions": "java graalvm-community-25.5.5.0.3\n", + "Dockerfile": "FROM ghcr.io/graalvm/jdk-community:25.5.5.0.3\nFROM ghcr.io/graalvm/jdk-community:25.1.3-ol9\n", + }) + res := scan(t, root) + checkAll(t, res, []want{ + {"a/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {"b/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {"c/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {"d/.sdkmanrc", 1, RuleLine, StatusVulnerable}, + {"e/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {"f/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {"a/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"b/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"c/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"d/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"e/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"f/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"Dockerfile", 1, RuleNotChecked, StatusUnknown}, + {"Dockerfile", 2, RuleNotChecked, StatusUnknown}, + }) + for _, f := range res.Findings { + if (f.File == "e/.sdkmanrc" || f.File == "f/.tool-versions" || f.File == "Dockerfile") && !strings.Contains(f.Reason, "GraalVM's own") { + t.Errorf("%s:%d: %s", f.File, f.Line, f.Reason) + } + } +} diff --git a/detectors/java4shell/internal/repo/graalvm.go b/detectors/java4shell/internal/repo/graalvm.go index 87d4f57..fe35215 100644 --- a/detectors/java4shell/internal/repo/graalvm.go +++ b/detectors/java4shell/internal/repo/graalvm.go @@ -3,6 +3,7 @@ package repo import ( "fmt" "regexp" + "strings" "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" "github.com/DefectDojo/earlylight/internal/refs" @@ -23,13 +24,15 @@ func isGraal(vendor string) bool { return graalVendors[vendor] } var ( sdkmanGraal = regexp.MustCompile(`^(\d{1,3}(?:\.\d{1,9}){1,4})\.r(\d{1,2})$`) javaLine = regexp.MustCompile(`java(\d{1,2})\b`) - graalNums = regexp.MustCompile(`\d{1,3}(?:\.\d{1,9}){1,4}`) ) // graalTag judges a GraalVM image tag: vulnerable where the OpenJDK // release would be, and otherwise unknown until a fixed GraalVM build is // known (the image has to be read). func graalTag(tv TagVersion, st knowledge.Status, why string) (knowledge.Status, string) { + if knowledge.GraalVMOwnNumber(tv.Text) { + return knowledge.Unknown, ownNumberWhy(tv.Text) + } switch st { case knowledge.Vulnerable: return st, "GraalVM: " + why @@ -45,6 +48,12 @@ func graalTag(tv TagVersion, st knowledge.Status, why string) (knowledge.Status, return knowledge.Unknown, why } +// ownNumberWhy says why a GraalVM release in GraalVM's own numbers is not +// judged as a Java version. +func ownNumberWhy(v string) string { + return fmt.Sprintf("%s is in GraalVM's own version numbers, not a Java version (GraalVM Community 25.1.3 is JDK 25.0.3, 25.5.5.0.3 is JDK 25.0.5.0.3): which Java update it is built on is not read from it", v) +} + // graalFix is what to do about a GraalVM release without the fix that // where (a version file; "" for an image) selects. func graalFix(feature int, where string) string { @@ -61,8 +70,10 @@ func graalFix(feature int, where string) string { // graalOwn judges a GraalVM release written in GraalVM's own numbers; // value is the text as written. -func (s *scanner) graalOwn(rel string, line int, graal string, java int, value, source string) { - st, why := knowledge.JudgeGraalVMRelease(graal, java) +// community is true for GraalVM Community's own names (sdkman grl and +// graalce, asdf graalvm). +func (s *scanner) graalOwn(rel string, line int, graal string, java int, community bool, value, source string) { + st, why := knowledge.JudgeGraalVMRelease(graal, java, community) props := map[string]string{"source": source, "current": refs.CleanText(value, 80), "graalvm": graal} switch st { case knowledge.NotAffected: @@ -90,6 +101,13 @@ func (s *scanner) graalOwn(rel string, line int, graal string, java int, value, // no fixed GraalVM build is known; a vulnerable one names GraalVM. func (s *scanner) graalVersion(rel string, line int, tv TagVersion, st knowledge.Status, why, source string, props map[string]string) { verText := tv.Text + if knowledge.GraalVMOwnNumber(verText) { + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, Reason: ownNumberWhy(verText), + Message: fmt.Sprintf("%s selects GraalVM %s, written in GraalVM's own version numbers: not checked for the Java4Shell fix", source, verText), + Fix: "Check which Java update this GraalVM release is built on; no fixed GraalVM build had been published as of " + knowledge.Checked + ".", + Props: props}) + return + } switch st { case knowledge.NotAffected: return @@ -120,13 +138,17 @@ func graalNamed(value string) (graal string, java int, ok bool) { if m := sdkmanGraal.FindStringSubmatch(value); m != nil { return m[1], atoi(m[2]), true } + // asdf: graalvm-22.3.1+java17, mandrel-22.3.1.0-Final+java17. The + // GraalVM number is everything between the name and the Java line, so + // a malformed one (22.3.0-dev) stays malformed and is not judged. j := javaLine.FindStringSubmatchIndex(value) if j == nil { return "", 0, false } - g := graalNums.FindString(value[:j[0]] + " " + value[j[1]:]) - if g == "" { + before := strings.TrimRight(value[:j[0]], "+-_") + i := strings.IndexAny(before, "0123456789") + if i < 0 { return "", 0, false } - return g, atoi(value[j[2]:j[3]]), true + return strings.TrimSuffix(before[i:], "-Final"), atoi(value[j[2]:j[3]]), true } diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 1bc946c..31fd514 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -427,7 +427,7 @@ func (s *scanner) sdkmanrc(rel, text string) { } if isGraal(m[2]) { if g, java, ok := graalNamed(m[1]); ok { - s.graalOwn(rel, i+1, g, java, strings.TrimSpace(strings.SplitN(l, "=", 2)[1]), ".sdkmanrc") + s.graalOwn(rel, i+1, g, java, m[2] == "grl" || m[2] == "graalce", strings.TrimSpace(strings.SplitN(l, "=", 2)[1]), ".sdkmanrc") continue } } @@ -453,7 +453,7 @@ func (s *scanner) asdfValue(rel string, line int, value, source string) { switch m[1] { case "graalvm", "mandrel": if g, java, ok := graalNamed(value); ok { - s.graalOwn(rel, line, g, java, value, source) + s.graalOwn(rel, line, g, java, m[1] == "graalvm", value, source) return } } From 9ac80cfb5b738074967d784a854e2e105597ea65 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:00:49 +0000 Subject: [PATCH 055/119] java4shell: rpm installs the repo scan dropped or cleared; Microsoft's lines (review F6, F7) F7: java-latest-openjdk, a version pattern (java-17-openjdk-17.0.21*), and rpm -i/-U of a package file (or dnf install of a .rpm path or URL) gave nothing; now the first two are not checked and package files are judged by their name-version-release. A pinned version the release data does not settle (17.0.22.0.7, 17.0.21.9) is now not checked instead of dropped, for every package manager. A four-number rpm version outside Red Hat's five-number scheme (openEuler 17.0.21.2) read fixed: the fourth number may be a build, so it is not checked. rpm queries (-qip) are not installs. F6: Microsoft publishes no Java 27 (or any line but 17, 21, 25 with the decoder): msopenjdk-27 and setup-java microsoft 27 are not checked. Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/repo/coverage_test.go | 48 ++++++++ detectors/java4shell/internal/repo/repo.go | 104 +++++++++++++++--- 2 files changed, 138 insertions(+), 14 deletions(-) diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index a01befe..9627297 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -302,3 +302,51 @@ func TestGraalVMRepoStrict(t *testing.T) { } } } + +// Review F6: Microsoft ships no Java 27, so its status for 27 is not known. +func TestMicrosoftLines(t *testing.T) { + res := scan(t, tree(t, map[string]string{ + "Dockerfile": "FROM ubuntu:24.04\nRUN apt-get install -y msopenjdk-27\nRUN apt-get install -y msopenjdk-25\n", + ".github/workflows/ci.yml": "jobs:\n a:\n steps:\n - uses: actions/setup-java@v5\n with:\n distribution: microsoft\n java-version: '27'\n", + })) + checkAll(t, res, []want{ + {"Dockerfile", 2, RulePackage, StatusUnknown}, + {"Dockerfile", 3, RulePackage, StatusVulnerable}, + {".github/workflows/ci.yml", 7, RuleNotChecked, StatusUnknown}, + }) +} + +// Review F7: rpm installs the scan dropped or cleared. +func TestRPMGaps(t *testing.T) { + res := scan(t, tree(t, map[string]string{ + "Dockerfile": strings.Join([]string{ + "FROM registry.access.redhat.com/ubi9/ubi", + "RUN dnf install -y java-latest-openjdk", + "RUN dnf install -y 'java-17-openjdk-17.0.21*'", + "RUN rpm -ivh https://example.com/java-17-openjdk-headless-17.0.21.0.9-1.el9.x86_64.rpm", + "RUN dnf install -y java-17-openjdk-17.0.22.0.7-1.el9", + "RUN dnf install -y java-17-openjdk-17.0.21.9-1.oe2403", + "RUN dnf install -y java-17-openjdk-17.0.21.2-1.oe2403", + "RUN dnf install -y ./java-21-openjdk-headless-21.0.13.0.9-1.el9.x86_64.rpm", + "RUN apt-get install -y openjdk-21-jre-headless=21.0.14+1-1", + "RUN rpm -Uvh --nodeps /tmp/java-21-openjdk-headless-21.0.13.1.2-1.el9.x86_64.rpm", + "RUN rpm -qip /tmp/java-17-openjdk-headless-17.0.21.0.9-1.el9.x86_64.rpm", + }, "\n") + "\n", + })) + checkAll(t, res, []want{ + {"Dockerfile", 2, RulePackage, StatusUnknown}, + {"Dockerfile", 3, RulePackage, StatusUnknown}, + {"Dockerfile", 4, RulePackage, StatusVulnerable}, + {"Dockerfile", 5, RulePackage, StatusUnknown}, + {"Dockerfile", 6, RulePackage, StatusUnknown}, + {"Dockerfile", 7, RulePackage, StatusUnknown}, // 17.0.21.2: a fourth number may be a build + {"Dockerfile", 8, RulePackage, StatusVulnerable}, + {"Dockerfile", 9, RulePackage, StatusUnknown}, + }) + if f, ok := find(res, "Dockerfile", 10); ok { + t.Errorf("21.0.13.1+2 (fixed upstream) reported: %+v", f) + } + if f, ok := find(res, "Dockerfile", 11); ok { + t.Errorf("an rpm query reported as an install: %+v", f) + } +} diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 31fd514..c372bb8 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -626,7 +626,7 @@ func (s *scanner) movingSetupJava(rel string, v *yaml.Node, ver, dist string) { } fx := knowledge.FixedVersion(feature) props := map[string]string{"source": "actions/setup-java", "current": ver, "distribution": dist, "fixed_in": fx} - if who := notFixedYet[dist]; who != "" { + if who := notFixedYet[dist]; who != "" && (dist != "microsoft" || microsoftLines[feature]) { s.add(Finding{Rule: RuleJavaPin, File: rel, Line: v.Line, Level: "warning", Status: StatusVulnerable, Props: props, Reason: fmt.Sprintf("%s had published no Java %s as of %s, so the job installs a release without the fix", who, fx, knowledge.Checked), Message: fmt.Sprintf("actions/setup-java installs the newest %s Java %d, which had no Java4Shell fix yet", orAny(dist), feature), @@ -776,15 +776,22 @@ func (s *scanner) jibRef(rel string, line, col int, image string) { // ---- Dockerfiles: OS packages and the mitigation a stage sets var ( - installRE = regexp.MustCompile(`\b(?:apt-get|apt|apk|dnf|yum|microdnf|tdnf|zypper)\b(?:\s+-{1,2}[\w=./:-]+)*\s+(?:install|add|in)\b`) - aptJava = regexp.MustCompile(`\b(openjdk-(\d{1,2})-(?:jre|jdk)(?:-headless)?)\b(=([^\s;&|]+))?`) - apkJava = regexp.MustCompile(`\b(openjdk(\d{1,2})(?:-jre|-jdk|-jre-headless|-jmods)?)(?:([=~><]+)([^\s;&|]+))?`) - rpmJava = regexp.MustCompile(`\b(java-(\d{1,2})-(openjdk|amazon-corretto)(?:-headless|-devel|-jdk)?)(?:-(\d[\w.:-]*))?`) - vendorJava = regexp.MustCompile(`\b((temurin|zulu|msopenjdk|sapmachine)-?(\d{1,2})(?:-ca)?(?:-(?:jdk|jre))?(?:-headless)?)\b(=([^\s;&|]+))?`) - defaultJava = regexp.MustCompile(`\b(default-(?:jre|jdk)(?:-headless)?)\b`) - envJTO = regexp.MustCompile(`(?i)^\s*ENV\s+`) - cmdLine = regexp.MustCompile(`(?i)^\s*(?:ENTRYPOINT|CMD)\s+`) - fromLine = regexp.MustCompile(`(?i)^\s*FROM\s`) + installRE = regexp.MustCompile(`\b(?:apt-get|apt|apk|dnf|yum|microdnf|tdnf|zypper)\b(?:\s+-{1,2}[\w=./:-]+)*\s+(?:install|add|in)\b`) + aptJava = regexp.MustCompile(`\b(openjdk-(\d{1,2})-(?:jre|jdk)(?:-headless)?)\b(=([^\s;&|]+))?`) + apkJava = regexp.MustCompile(`\b(openjdk(\d{1,2})(?:-jre|-jdk|-jre-headless|-jmods)?)(?:([=~><]+)([^\s;&|]+))?`) + rpmJava = regexp.MustCompile(`\b(java-(\d{1,2})-(openjdk|amazon-corretto)(?:-headless|-devel|-jdk)?)(?:-(\d[\w.:*?-]*))?`) + // rpmLatest is Fedora's and EPEL's java-latest-openjdk: the newest + // release the distribution carries, named by no release. + rpmLatest = regexp.MustCompile(`^java-latest-openjdk(?:-headless|-devel|-jmods)?(?:-\d[\w.:*?-]*)?$`) + // rpmInstall is an rpm command that installs or upgrades package files. + // A query (-qip) or an erase (-e) is not an install. + rpmInstall = regexp.MustCompile(`\brpm\b(?:\s+-{1,2}[\w=./:-]+)*?\s+(?:-[a-dfh-pr-zA-UW-Z]*[iUF][a-dfh-pr-zA-UW-Z]*|--install|--upgrade|--freshen)(?:\s|$)`) + rpmInstallFlag = regexp.MustCompile(`^(?:-[a-dfh-pr-zA-UW-Z]*[iUF][a-dfh-pr-zA-UW-Z]*|--install|--upgrade|--freshen)$`) + vendorJava = regexp.MustCompile(`\b((temurin|zulu|msopenjdk|sapmachine)-?(\d{1,2})(?:-ca)?(?:-(?:jdk|jre))?(?:-headless)?)\b(=([^\s;&|]+))?`) + defaultJava = regexp.MustCompile(`\b(default-(?:jre|jdk)(?:-headless)?)\b`) + envJTO = regexp.MustCompile(`(?i)^\s*ENV\s+`) + cmdLine = regexp.MustCompile(`(?i)^\s*(?:ENTRYPOINT|CMD)\s+`) + fromLine = regexp.MustCompile(`(?i)^\s*FROM\s`) ) func (s *scanner) dockerfile(rel, text string) { @@ -851,7 +858,7 @@ func (s *scanner) dockerfile(rel, text string) { // packages and the vendors' own (Temurin, Corretto, Zulu, Microsoft, // SapMachine), with or without a version. func (s *scanner) packages(rel string, line int, run string) { - if !installRE.MatchString(run) { + if !installRE.MatchString(run) && !rpmInstall.MatchString(run) { return } var hits []pkgHit @@ -875,6 +882,8 @@ func (s *scanner) packages(rel string, line int, run string) { hits = append(hits, pkgHit{name: m[1], feature: atoi(m[3]), op: opOf(m[4]), ver: m[5], mgr: "package", vendor: m[2]}) case defaultArg.MatchString(arg): hits = append(hits, pkgHit{name: arg, mgr: "apt", vendor: "distribution"}) + case rpmLatest.MatchString(arg): + hits = append(hits, pkgHit{name: arg, mgr: "rpm", vendor: "distribution", latest: true}) case varJavaArg.MatchString(arg): // openjdk-${V}-jre-headless, java-${V}-openjdk: the Java // release comes from a variable. @@ -904,7 +913,7 @@ var ( ) var ( - pkgTools = map[string]bool{"apt-get": true, "apt": true, "apk": true, "dnf": true, "yum": true, "microdnf": true, "tdnf": true, "zypper": true} + pkgTools = map[string]bool{"apt-get": true, "apt": true, "apk": true, "dnf": true, "yum": true, "microdnf": true, "tdnf": true, "zypper": true, "rpm": true} pkgVerbs = map[string]bool{"install": true, "add": true, "in": true, "reinstall": true} // pkgValueFlags are package-manager options followed by a separate value. pkgValueFlags = map[string]bool{"-t": true, "-o": true, "-X": true, "--repository": true, "--virtual": true, "-c": true, "--root": true, @@ -954,19 +963,35 @@ func installArgs(run string) []string { if i == len(words) { continue } + tool := path.Base(words[i]) i++ + installs := false for i < len(words) && strings.HasPrefix(words[i], "-") { + if tool == "rpm" && rpmInstallFlag.MatchString(words[i]) { + installs = true + } if pkgValueFlags[words[i]] { i++ } i++ } - if i >= len(words) || !pkgVerbs[words[i]] { + if tool == "rpm" { + // rpm -ivh file.rpm: the package files follow the flags. + if !installs { + continue + } + i-- + } else if i >= len(words) || !pkgVerbs[words[i]] { continue } for j := i + 1; j < len(words); j++ { w := words[j] switch { + case strings.HasSuffix(w, ".rpm"): + // A package file, local or a URL: its name is + // name-version-release.arch.rpm. + out = append(out, rpmArchRE.ReplaceAllString(strings.TrimSuffix(path.Base(w), ".rpm"), "")) + case tool == "rpm": case pkgValueFlags[w]: j++ case strings.HasPrefix(w, "-"), strings.Contains(w, "://"), strings.HasPrefix(w, "/"), strings.HasPrefix(w, "$"): @@ -986,6 +1011,7 @@ type pkgHit struct { vendor string // distribution, corretto, temurin, zulu, msopenjdk, sapmachine feature int // 0: the distribution's default (default-jre) varName bool // the name holds a variable where the release is + latest bool // java-latest-openjdk: no release in the name } func opOf(v string) string { @@ -1001,6 +1027,19 @@ func atoi(s string) int { return n } +// rpmNumbers counts the numbers of an rpm version, without its epoch and +// release: 17.0.21.0.9-1.el9 has five. +func rpmNumbers(evr string) int { + if i := strings.IndexByte(evr, ':'); i >= 0 { + evr = evr[i+1:] + } + v, _, _ := strings.Cut(evr, "-") + return strings.Count(v, ".") + 1 +} + +// microsoftLines are the Java lines Microsoft publishes with the decoder. +var microsoftLines = map[int]bool{17: true, 21: true, 25: true} + var vendorNames = map[string]string{"distribution": "the distribution", "corretto": "Amazon Corretto", "temurin": "Eclipse Temurin", "zulu": "Azul Zulu", "msopenjdk": "Microsoft", "sapmachine": "SapMachine"} @@ -1038,11 +1077,26 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { Fix: "Check which Java release the variable selects: 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update have the fix."}) return } + if h.latest { + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, + Props: map[string]string{"package": h.name, "manager": h.mgr}, + Reason: "java-latest-openjdk installs the newest OpenJDK the distribution (Fedora, EPEL) carries, named by no release, and those distributions' status was not checked", + Message: fmt.Sprintf("installs %s, whose Java release this scan cannot read: not checked for the Java4Shell fix", refs.CleanText(h.name, 80)), + Fix: "Check the installed release: 25.0.5.1 or 27.0.1.1 and later of the same update have the fix; 26 received none."}) + return + } if h.feature > 0 && h.feature < 17 { return // Java 8 and 11 packages are not affected } props := map[string]string{"package": h.name, "manager": h.mgr} who := vendorNames[h.vendor] + if h.vendor == "msopenjdk" && h.feature > 0 && !microsoftLines[h.feature] { + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: props, + Reason: fmt.Sprintf("Microsoft publishes no Java %d, so its status for it was not checked", h.feature), + Message: fmt.Sprintf("installs %s, a Microsoft package of a Java line Microsoft does not ship: not checked for the Java4Shell fix", h.name), + Fix: "Check which Java release the package installs."}) + return + } if h.feature > 0 { l, ok := knowledge.LineOf(h.feature) switch { @@ -1076,7 +1130,20 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { if up := pinnedVersion(h); up != "" { props["current"] = h.ver v, _ := knowledge.Parse(up) - if st, why := knowledge.Judge(v); st == knowledge.Vulnerable { + st, why := knowledge.Judge(v) + if st == knowledge.Fixed && h.mgr == "rpm" && h.vendor == "distribution" && rpmNumbers(h.ver) == 4 { + // Red Hat and Fedora write five numbers; a fourth number from + // another rpm distribution (openEuler's 17.0.21.2) may be a + // build, not a patch release. + st, why = knowledge.Unknown, fmt.Sprintf("%s has four numbers: outside Red Hat's five-number scheme the fourth may be a build number, not the OpenJDK patch release", h.ver) + } + if st == knowledge.Unknown { + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Reason: why, Props: props, + Message: fmt.Sprintf("pins %s to %s, a version this detector's release data does not settle: not checked for the Java4Shell fix", h.name, h.ver), + Fix: fmt.Sprintf("Check that %s %s includes the fix (Java %s or later of the same update, or the distribution's backport).", h.name, h.ver, fx)}) + return + } + if st == knowledge.Vulnerable { fix := fmt.Sprintf("Pin %s to a package of Java %s or later once %s publishes it, then rebuild. Until then set ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics in this stage.", h.name, fx, who) if h.mgr == "rpm" && h.vendor == "distribution" { why += "; " + knowledge.RedHatStatus() @@ -1091,6 +1158,15 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { if h.ver != "" { props["current"] = h.ver } + if h.mgr == "rpm" && h.vendor == "distribution" && strings.ContainsAny(h.ver, "*?") { + // Red Hat's fixed build can keep the upstream version, so a pattern + // such as 17.0.21* may match fixed and unfixed builds. + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: props, + Reason: "the version is a pattern that can match builds with and without the fix (Red Hat's backports keep the upstream version)", + Message: fmt.Sprintf("installs %s matching %s: not checked for the Java4Shell fix", h.name, refs.CleanText(h.ver, 60)), + Fix: rpmFix(h.name)}) + return + } if strings.Contains(h.ver, "$") { s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: props, Reason: "the version comes from a variable set outside this line", From 54e60ef74516a7bd23449e9d0ebf4c700629ea95 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:01:19 +0000 Subject: [PATCH 056/119] java4shell: test a GraalVM row whose first fixed build follows OpenJDK's (review F8) The mutants F8 names are killed: redHat()'s vm-library and Mitigated conditions, java > 17 in JudgeGraalVMRelease, and JudgeGraalVM's EA and build checks with a row (this test covers the build check, which the OpenJDK build boundary had masked). Co-Authored-By: Claude Opus 5.5 --- .../internal/knowledge/coverage_test.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/detectors/java4shell/internal/knowledge/coverage_test.go b/detectors/java4shell/internal/knowledge/coverage_test.go index 4b006cd..51aaef8 100644 --- a/detectors/java4shell/internal/knowledge/coverage_test.go +++ b/detectors/java4shell/internal/knowledge/coverage_test.go @@ -155,6 +155,23 @@ func TestGraalVMRow(t *testing.T) { } } +// A row whose first fixed GraalVM build comes after OpenJDK's: the builds +// in between are OpenJDK-fixed but not GraalVM-fixed. +func TestGraalVMRowLaterBuild(t *testing.T) { + saved := GraalVMFixed + t.Cleanup(func() { GraalVMFixed = saved }) + GraalVMFixed = map[int]Build{21: {Version: []int{21, 0, 13, 1}, Build: 5}} + for v, want := range map[string]Status{ + "21.0.13.1+3-jvmci-23.1-b99": Vulnerable, + "21.0.13.1+5-jvmci-23.1-b99": Fixed, + } { + p, _ := Parse(v) + if st, why := JudgeGraalVM(p); st != want { + t.Errorf("row 21.0.13.1+5: JudgeGraalVM(%s) = %s (%s), want %s", v, st, why, want) + } + } +} + // GraalVM Community's own release numbers (graal-25.5.5.0.3 is JDK // 25.0.5.0.3, graal-25.1.3 is JDK 25.0.3) are never Java versions. func TestGraalVMOwnNumbersNotJava(t *testing.T) { From 0a5bdf60852709ee3e875eda18364f35c5607c19 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:01:48 +0000 Subject: [PATCH 057/119] java4shell: FACTS.md corrections from the review (F5) Mark GraalVM EE 21.3's Java lines unverified (a Java 8 build may exist) and the GraalVM-numbering generalisation inferred; cite graalvm/graalvm-ce-builds for GraalVM Community (newest release 2026-11-03, before the fix) and its Innovation numbering (graal-25.1.3 is JDK 25.0.3); complete the Ubuntu row (openjdk-21 21.0.13.0.3+1-1) with its date; cite actions/setup-java's Microsoft list; describe the Red Hat table's stream and witness rules and the UBI 8/11 skip as inferred. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/FACTS.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/detectors/java4shell/FACTS.md b/detectors/java4shell/FACTS.md index 5b5bc72..ab27f45 100644 --- a/detectors/java4shell/FACTS.md +++ b/detectors/java4shell/FACTS.md @@ -79,13 +79,13 @@ The lead read these; they could not be fetched from the research host. Facts her | Amazon Corretto | fixed: 17.0.21.1.2, 21.0.13.1.2, 25.0.5.1.2, 27.0.1.1.4 (all 2026-11-17, each "Import jdk-…1+2/+4", CVE-2026-114938 listed). Corretto 8 and 11: no release after October (not affected). **Docker Hub, 2026-11-18:** Amazon republished the existing `amazoncorretto:21.0.13-*` and `17.0.21-*` tags with the fixed builds (the images report 21.0.13.1+2 and 17.0.21.1+2); there are no `.1` tags. A Corretto tag of the fixed update therefore names whichever build was pushed last, and the detector reads the image | GitHub releases API, CHANGELOG.md of each tag; images scanned by this detector (parity cases corretto-*) | | SapMachine | releases 17.0.21.1, 21.0.13.1, 25.0.5.1, 27.0.1.1 published 2026-11-17 (the release page names no CVE) | GitHub releases API, SAP/SapMachine | | Eclipse Temurin | **not fixed** (2026-11-18): newest releases 17.0.21+9, 21.0.13+9-LTS, 25.0.5+8-LTS, 27.0.1.0.2+1; no 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 build on any line. Docker Hub `eclipse-temurin` newest tags 17.0.21_9, 21.0.13_9, 25.0.5_8, 27.0.1.0 | api.adoptium.net (lead, 2026-11-18); GitHub API, registry-1.docker.io tag list (2026-11-17) | -| Microsoft Build of OpenJDK | **not fixed** (2026-11-18): newest releases 17.0.21.0.2, 21.0.13.0.2, 25.0.5.0.2 (download page of 2026-11-04), which predate the fix | learn.microsoft.com/java/openjdk release notes and download page (lead) | +| Microsoft Build of OpenJDK | **not fixed** (2026-11-18): newest releases 17.0.21.0.2, 21.0.13.0.2, 25.0.5.0.2 (download page of 2026-11-04), which predate the fix. actions/setup-java's Microsoft version list (updated 2026-11-14) is older still: newest 17.0.19, 21.0.11, 25.0.5+0.2. Microsoft publishes no Java 27: the detector does not judge Microsoft packages or setup-java versions of lines it does not ship | learn.microsoft.com/java/openjdk release notes and download page (lead); actions/setup-java Microsoft manifest (reviewer, 2026-11-18) | | Oracle Java SE | 8u511b33-perf, 17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3 and earlier affected; the fixed Oracle version numbers were not relayed, so Oracle builds after .0.3 are judged by the OpenJDK fixed releases | Oracle CSPU November 2026 | -| Oracle GraalVM, GraalVM Community | GraalVM for JDK 17.0.21.0.3 and 21.0.13.0.3 and GraalVM Enterprise Edition 21.3.20.0.3 affected; **no fixed GraalVM build known** (2026-11-18). See "GraalVM" below | Oracle CSPU November 2026 | +| Oracle GraalVM, GraalVM Community | GraalVM for JDK 17.0.21.0.3 and 21.0.13.0.3 and GraalVM Enterprise Edition 21.3.20.0.3 affected (Oracle). GraalVM Community: the newest release on graalvm/graalvm-ce-builds was published 2026-11-03, before the fix. **No fixed GraalVM build known** (2026-11-18). See "GraalVM" below | Oracle CSPU November 2026; [graalvm/graalvm-ce-builds releases](https://github.com/graalvm/graalvm-ce-builds/releases) (reviewer, 2026-11-18) | | Azul Zulu, BellSoft Liberica | **not checked**: their pages could not be read (HTTP 403/404 for the lead; unreachable here). Docker Hub `azul/zulu-openjdk` and `bellsoft/liberica-openjdk-debian` newest tags were 27.0.1.0.3 / 21.0.13.0.3 on 2026-11-17 (not fixed) | registry-1.docker.io tag list | | IBM Semeru | OpenJ9, not HotSpot (see above) | image inspection | | Debian | **not fixed** (2026-11-18): the tracker lists every package vulnerable and unfixed: openjdk-17 bookworm-security 17.0.21+9-1~deb12u1, sid 17.0.21.0.3+1-1; openjdk-21 trixie-security 21.0.13+9-1~deb13u2, forky/sid 21.0.13.0.3+1-1; openjdk-25 trixie-security 25.0.5+8-1~deb13u1, sid 25.0.5.0.3+1-3; openjdk-27 sid 27.0.1.0.3+1-1 | [security-tracker.debian.org CVE-2026-114938](https://security-tracker.debian.org/tracker/CVE-2026-114938) (lead); deb.debian.org and security.debian.org pools | -| Ubuntu | **not fixed**: newest sources openjdk-17 17.0.21.0.3+1-1~XX.04.1, openjdk-25 25.0.5.0.3+1-3~XX.04.1 (openjdk-21 listing timed out, 2026-11-17). The Ubuntu CVE page could not be read (2026-11-18) | archive.ubuntu.com pool | +| Ubuntu | **not fixed** (2026-11-18): newest sources openjdk-17 17.0.21.0.3+1-1 (17.0.21.0.3+1-1~XX.04.1 in the stable releases), openjdk-21 21.0.13.0.3+1-1, openjdk-25 25.0.5.0.3+1-3~XX.04.1; none is the fixed update or a backport. The Ubuntu CVE page could not be read | archive.ubuntu.com pool (2026-11-17; openjdk-21 and -17 reread by the reviewer 2026-11-18) | | Alpine | **not fixed**: community openjdk17 17.0.21.0.3_p1-r0, openjdk21 21.0.13.0.3_p1-r0, openjdk25 25.0.5.0.3_p1-r0/-r1 (3.23, 3.24, edge); 3.21 and 3.22 carry older 17/21. The edge secdb had no entry for the CVE on 2026-11-18 | dl-cdn.alpinelinux.org APKINDEX; Alpine secdb (lead) | | Red Hat (RHEL, UBI) | **no fixed build** (2026-11-18): affected "OpenJDK 17.0.6 and later" on x86-64 with AVX-512 VBMI; "exact upstream fixed version ... not yet confirmed by Oracle"; no fixed NVRs, no errata, no UBI tags. Bulletin RHSB-2026-018, Bugzilla 2574227, Red Hat CVSS 9.8. See "Red Hat" below | [access.redhat.com CVE-2026-114938](https://access.redhat.com/security/cve/CVE-2026-114938) (lead) | @@ -95,18 +95,19 @@ The lead read these; they could not be fetched from the research host. Facts her | --- | --- | | A GraalVM JDK is HotSpot with JVMCI: its `lib/server/libjvm.so` has HotSpot's version line with the JDK version and `-jvmci-` (`OpenJDK 64-Bit Server VM (17.0.6+10-jvmci-22.3-b13) for linux-amd64 JRE (17.0.6+10-jvmci-22.3-b13)`) and its release file has `GRAALVM_VERSION` and `IMPLEMENTOR="GraalVM Community"` | GraalVM CE images below | | **Observed** 2026-11-18: GraalVM CE 22.3.0 for Java 17 is 17.0.5+8 and its libjvm has **no** decoder stubs; 22.3.1 for Java 17 is 17.0.6+10 **with** them; 22.3.1 for Java 11 is 11.0.18+10 without them; GraalVM CE for JDK 21 (GRAALVM_VERSION 23.1.2) is 21.0.2+13 with them | Docker Hub `findepi/graalvm` (a repackaging of the GraalVM CE release archives; registry ghcr.io/graalvm is unreachable here): `22.3.0-java17` sha256:b4460f6857d2…d9b373, `22.3.1-java17` sha256:a953392b9572…ada717, `22.3.1-java11` sha256:983c7f6640ca…66beed, `java21-native` sha256:19937684c9ef…8ed235 | -| GraalVM EE 21.3 ships JDK 11 and JDK 17 builds; which of them Oracle's listing of 21.3.20.0.3 covers is **not stated**. The detector judges a GraalVM JDK 17 build by its version (vulnerable today) and a GraalVM JDK 8 or 11 build vulnerable only when its libjvm carries the decoder stubs | Oracle CSPU; **inferred** | -| No fixed GraalVM build is known, and GraalVM's fixed builds need not follow OpenJDK's numbering, so the detector judges a GraalVM build at or past the OpenJDK fixed release as **unknown**, never fixed, until a fixed GraalVM build is listed in `knowledge.GraalVMFixed` (empty) | lead, 2026-11-18 | -| sdkman and asdf name GraalVM releases in GraalVM's numbers (`22.3.1.r17-grl`, `graalvm-22.3.1+java17`): 22.3.0 for 17 and any release for 8 or 11 are not affected; 22.3.1 and later for 17, and any release for 18 and later, are vulnerable; `22.3.r17` (no patch) and 21.3.x for 17 stay not checked. Liberica NIK and Mandrel follow GraalVM's numbering and are judged the same way (**inferred**: not checked against their releases) | observations above | +| GraalVM EE 21.3 builds: which Java lines exist (JDK 11 and 17 at least; a Java 8 build may exist too, and Oracle's Java 8 Performance Pack does carry the decoder) and which of them Oracle's listing of 21.3.20.0.3 covers are **not verified**. The detector judges a GraalVM JDK 17 build by its version (vulnerable today), a GraalVM JDK 8 or 11 runtime vulnerable when its libjvm carries the decoder stubs, and leaves 21.3.x for Java 8 or 11 named in a version file not checked | Oracle CSPU; **unverified** | +| No fixed GraalVM build is known, and GraalVM's fixed builds need not follow OpenJDK's numbering, so the detector judges a GraalVM build at or past the OpenJDK fixed release as **unknown**, never fixed, until a fixed GraalVM build is listed in `knowledge.GraalVMFixed` (empty). A row clears only what OpenJDK's data also judges fixed | lead and reviewer, 2026-11-18; graalvm/graalvm-ce-builds releases | +| sdkman and asdf name GraalVM releases in GraalVM's numbers (`22.3.1.r17-grl`, `graalvm-22.3.1+java17`). From the four images above (**inferred** for the releases not looked at): GraalVM Community 22.3.0 for 17, and Community releases for Java 8 to 16 other than 21.3.x, are not affected; 22.3.1 and later for 17, and any release for 18 and later, are vulnerable. Not checked: `22.3.r17` (no patch), 21.3.x for any line, malformed numbers, Java lines below 8, and Liberica NIK and Mandrel releases that would otherwise be cleared (their numbering is assumed to follow GraalVM's, not checked against their releases) | observations above; **inferred** | +| GraalVM Community's Innovation releases carry their own numbers: graal-25.5.5.0.3 is JDK 25.0.5.0.3, graal-25.1.3 is JDK 25.0.3. A number whose second field is not 0 (Java's has been 0 since JDK 10) is GraalVM's own and is never read as a Java version | [graalvm/graalvm-ce-builds releases](https://github.com/graalvm/graalvm-ce-builds/releases) (reviewer, 2026-11-18) | | Whether GraalVM Native Image binaries (SubstrateVM, no libjvm) carry a port of the decoder is **not known**; the detector does not look at them | n/a | ## Red Hat | Fact | Source | | --- | --- | -| Red Hat backports fixes into the update it ships, so a fixed Red Hat build can keep the upstream version in its libjvm and differ only in the rpm release. The detector keeps a backport table, `knowledge.RedHatFixed` (package, RHEL major release, fixed EVR, advisory), that marks rpm builds from that EVR on as fixed when their libjvm is the same update. It is **empty**: Red Hat had published no fixed build on 2026-11-18 | Red Hat CVE page (lead) | +| Red Hat backports fixes into the update it ships, so a fixed Red Hat build can keep the upstream version in its libjvm and differ only in the rpm release. The detector keeps a backport table, `knowledge.RedHatFixed` (package, dist tag such as el9_6, fixed EVR, advisory). A row speaks only to rpm releases of its own stream (a number and that dist tag: not Oracle Linux's 2.0.1.el9 or AlmaLinux's .alma; CentOS Stream's el9 cannot be told from RHEL's el9) and its own upstream update and build. It clears an installed runtime only when the libjvm is a released, non-GraalVM HotSpot of exactly that update and build and the release file names `Red Hat, Inc.`; the rpm itself is named by the install path, since the rpm database is not read, so a contradicting runtime is reported unknown. It is **empty**: Red Hat had published no fixed build on 2026-11-18 | Red Hat CVE page (lead) | | RHEL 8/9 and UBI install the JDK in `/usr/lib/jvm/java-17-openjdk--.` with `jre-17`, `jre` and `/etc/alternatives` symlinks into it; the rpm version appends the build to the update (17.0.21.0.9 is 17.0.21+9). **Not verified on a real image here**: registry.access.redhat.com and cdn-ubi.redhat.com (dnf in `redhat/ubi9`) are unreachable from the research host; the detector's tests use that layout | Red Hat packaging convention; unverified | -| UBI OpenJDK images (`registry.access.redhat.com/ubi9/openjdk-21`, `-runtime`, also on registry.redhat.io) are tagged by image release (1.20, 1.20-2.1729089285), not by Java update. With the table empty, the repo scan reports 21 and later (every release has the decoder) and 17 at `latest` as vulnerable, other 17 tags (older images could predate 17.0.6) as not checked and pulled, and 8 and 11 as not affected | lead; **inferred** | +| UBI OpenJDK images (`registry.access.redhat.com/ubi9/openjdk-21`, `-runtime`, also on registry.redhat.io) are tagged by image release (1.20, 1.20-2.1729089285), not by Java update. With the table empty, the repo scan reports 21 and 25 (every release has the decoder) and 17 at `latest` as vulnerable, other 17 tags (older images could predate 17.0.6) as not checked and pulled. `openjdk-8` and `openjdk-11` are skipped by name, as `eclipse-temurin:11` is (**inferred**: OpenJDK 8 and 11 have no decode intrinsic; Red Hat's builds were not read). Any other line in the name is not checked and pulled | lead; **inferred** | ## Advisory links From 3e89cbc3b79de87a4d42f2374262ed20244fba03 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:01:55 +0000 Subject: [PATCH 058/119] README: the Red Hat table's stream and witness rules Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6d91977..79dcf72 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ One engine for DefectDojo's emerging-vulnerability scanners. Each new vulnerabil | `php2shell` | PHP runtimes vulnerable to CVE-2026-109618 and CVE-2026-109619 ("PHP2Shell"), fixed in PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12 ([GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w), [GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp)). A packaged PHP is judged by its vendor's backport data, never by the version it reports. Also checks the images a source tree builds on and deploys, and can rewrite them to fixed images | `fs`, `image`, `repo`, `fix` | | `brotli` | Brotli decoders vulnerable to CVE-2026-111497 ("Node2Shell", "Broccoli2Shell"), Brotli 1.0.3 through 1.2.0, fixed in 1.0.10, 1.1.1 and 1.2.1 ([GHSA-9v8h-qqgm-4m35](https://github.com/advisories/GHSA-9v8h-qqgm-4m35)): system `libbrotlidec` and every copy bundled into other software (Node.js, .NET, Bun, Electron, Envoy and Istio, Python wheels such as Pillow, pyarrow, duckdb, pycurl and PyMuPDF, brotli4j, and more), on Linux, Windows and macOS. A decoder is judged first by the error code the fix added, so vendor backports are recognised without distribution data; a build that strips it by its own version stamp or by its code, which returns that error code only once fixed. In a source tree it finds the Node.js, .NET and Bun releases and the bundling packages a project pins, and `fix` moves each to the fixed release | `fs`, `image`, `repo`, `fix` | | `sshole` | \*sshole, the OpenSSH password authentication bypass on musl libc fixed in OpenSSH 10.6p2 and in Alpine's openssh packages of November 5, 2026 ([release notes](https://www.openssh.org/releasenotes.html#10.6p2), [writeup](https://sshhole.com)). On musl, sshd from 7.3p1 to 10.6p1 compares an account's password field of `*` with the `*` that crypt returns when it fails, so a crafted password logs in to that account. It judges each installed sshd by its C library, its release and the apk database (Alpine backports keep the release number), then checks what the target's `sshd_config` (Include, Match, PasswordAuthentication, AuthenticationMethods, PermitRootLogin, AllowUsers and the rest) and account files make reachable, and reports the accounts. In an image it also reads the command (`sshd -o` and `-f`) and the startup scripts it runs (entrypoints, s6, cont-init.d), and reports a server as exposed when a startup script turns password logins on, sets a `*` field or sets passwords. OpenWrt's opkg database and its backports (23.05, 24.10, 25.12) count like Alpine's. PAM-checked builds (`UsePAM yes`) are not affected. On a live server it reads the banner and the offered methods and never sends a password. In a source tree it finds Dockerfiles that install an OpenSSH server on Alpine without the fix (package lists in `ARG` and `ENV` too), Ansible apk tasks, Buildroot, OpenWrt and Yocto configurations that build one on musl, and anything that sets a password field to `*`. It also pulls the images the tree references (through the guarded transport, with the command a Compose service or Kubernetes container sets) and judges them like `scan image`. `fix` adds the fixed release floor (in the variable when the list is one), moves an end-of-life Alpine base to a tag on the nearest fixed Alpine release (`alpine:3.14` to `3.16`, `python:3.9-alpine3.14` to `3.9-alpine3.16` after checking that image) as a labelled upgrade, adds upstream commit 4353fdc43 as a patch scoped to the OpenSSH versions it applies to (Buildroot `BR2_GLOBAL_PATCH_DIR`, a version-specific Yocto bbappend), sets Ansible tasks to `state: latest`, and changes `*` to `*NP*` | `fs`, `image`, `host`, `repo`, `fix` | -| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64, fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 on November 15, 2026 by JDK-8393212 ([commit](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b); that this change is the CVE's fix is inferred: the [OpenJDK advisory](https://openjdk.org/groups/vulnerability/advisories/2026-11-17) confirms the component (hotspot/compiler), the lines (17, 21, 25, 27) and the last affected releases (17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3) but names no JDK bug: see the [knowledge table](detectors/java4shell/FACTS.md)). CVSS 8.1 (OpenJDK and Oracle). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel server CPUs from Ice Lake on and some client CPUs, not Alder Lake or Raptor Lake; AMD Zen 4 and later); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds Java runtimes by their VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others); a JDK download sitting in the target (OpenJDK21U-jre_…tar.gz and the like) is recorded by name as context, not read or unpacked. Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; each platform of a multi-arch image is judged on its own with `--platform all`), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness: when the library's version line can be read, the library decides and a different release-file version is only noted; a release file naming OpenJ9 next to HotSpot evidence makes the verdict unknown; and a release file alone does not clear a runtime (OpenJ9 is recognised from its own VM library, not from the release file). No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version and build (the first fixed build of each release, such as 21.0.13.1+2; pre-release builds are not judged fixed, and a self-built JDK at a build boundary is unknown). A GraalVM JDK (a `-jvmci-` version line; Oracle lists GraalVM for JDK 17 and 21 and GraalVM Enterprise 21.3 as affected) is vulnerable where its OpenJDK version is and fixed only at a published fixed GraalVM build (none yet). A Red Hat rpm build is judged by its VM library unless Red Hat's backport table, keyed on the rpm release, lists a fixed build (it is empty: Red Hat had published none). OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is recorded as a mitigation on a finding that stays vulnerable (status `mitigated`, counted in the exit status): the options can be overridden where the runtime is deployed, and the runtime still needs the update; `_JAVA_OPTIONS` turning the intrinsic back on undoes it. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context; neither clears a runtime. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft, Oracle, GraalVM and Red Hat UBI `openjdk-NN` images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | +| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64, fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 on November 15, 2026 by JDK-8393212 ([commit](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b); that this change is the CVE's fix is inferred: the [OpenJDK advisory](https://openjdk.org/groups/vulnerability/advisories/2026-11-17) confirms the component (hotspot/compiler), the lines (17, 21, 25, 27) and the last affected releases (17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3) but names no JDK bug: see the [knowledge table](detectors/java4shell/FACTS.md)). CVSS 8.1 (OpenJDK and Oracle). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel server CPUs from Ice Lake on and some client CPUs, not Alder Lake or Raptor Lake; AMD Zen 4 and later); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds Java runtimes by their VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others); a JDK download sitting in the target (OpenJDK21U-jre_…tar.gz and the like) is recorded by name as context, not read or unpacked. Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; each platform of a multi-arch image is judged on its own with `--platform all`), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness: when the library's version line can be read, the library decides and a different release-file version is only noted; a release file naming OpenJ9 next to HotSpot evidence makes the verdict unknown; and a release file alone does not clear a runtime (OpenJ9 is recognised from its own VM library, not from the release file). No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version and build (the first fixed build of each release, such as 21.0.13.1+2; pre-release builds are not judged fixed, and a self-built JDK at a build boundary is unknown). A GraalVM JDK (a `-jvmci-` version line; Oracle lists GraalVM for JDK 17 and 21 and GraalVM Enterprise 21.3 as affected) is vulnerable where its OpenJDK version is and fixed only at a published fixed GraalVM build (none yet). A Red Hat rpm build is judged by its VM library unless Red Hat's backport table, keyed on the rpm release's stream (el9_6) and upstream build, lists a fixed build and the runtime confirms it (its VM library is that exact update and build, its release file names Red Hat); the table is empty: Red Hat had published none. OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is recorded as a mitigation on a finding that stays vulnerable (status `mitigated`, counted in the exit status): the options can be overridden where the runtime is deployed, and the runtime still needs the update; `_JAVA_OPTIONS` turning the intrinsic back on undoes it. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context; neither clears a runtime. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft, Oracle, GraalVM and Red Hat UBI `openjdk-NN` images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | The detectors ported from standalone scanners also build as standalone binaries under the names people search for: `emudhra-scan` and `php2shell-scan`. They keep their original commands, flags and exit status rules. `brotli`, `sshole` and `java4shell` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`, `--detector java4shell`). From 18a6b9d634be6f69b9ea025c09811b831fa55913 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:22:04 +0000 Subject: [PATCH 059/119] emudhra: botocore's bundle is cleared only on a certifi bundle that was read From the round-2 review: Exists now holds for every file the walk meets, read or not, so a certifi bundle over --max-file-size let botocore's bundle be cleared (inactive), even when that unread bundle held the bad CA. The rule now asks whether the scan visited the certifi bundle (Context.Scanned). emudhra was the only detector that used Exists to mean 'was read'; sshole uses it for a login shell's existence, which is right. Co-Authored-By: Claude Opus 5.5 --- detectors/emudhra/emudhra.go | 12 +++-- detectors/emudhra/internal/assess/assess.go | 11 +++-- .../emudhra/internal/assess/assess_test.go | 2 +- detectors/emudhra/limit_test.go | 45 +++++++++++++++++++ 4 files changed, 61 insertions(+), 9 deletions(-) create mode 100644 detectors/emudhra/limit_test.go diff --git a/detectors/emudhra/emudhra.go b/detectors/emudhra/emudhra.go index 13a6d46..c2c7a93 100644 --- a/detectors/emudhra/emudhra.go +++ b/detectors/emudhra/emudhra.go @@ -71,7 +71,7 @@ func (d *Detector) Load() error { // NewScan starts a filesystem or image scan. func (d *Detector) NewScan(engine.TargetKind) engine.Scan { - return &scan{det: d.det, files: map[string][]byte{}, dedupe: map[string]bool{}} + return &scan{det: d.det, files: map[string][]byte{}, dedupe: map[string]bool{}, scanned: map[string]bool{}} } // Probe checks the certificate chain a TLS server presents. @@ -92,6 +92,7 @@ type scan struct { findings []detect.Finding files map[string][]byte dedupe map[string]bool + scanned map[string]bool // certifi bundles visited } // keep reports whether the assessment rules need this file's content: the @@ -105,6 +106,9 @@ func (s *scan) Visit(f engine.File) []engine.Skip { if keep(f.Path) { s.files[f.Path] = f.Data // raw path: lookups must never alias another file } + if !f.Member && strings.HasSuffix(f.Path, "/certifi/cacert.pem") { + s.scanned[f.Path] = true // checked here, not only known to exist + } found, skips := s.det.ScanAll(f.Path, f.Data) for _, x := range found { // The same certificate can be seen twice in one file, for example in an @@ -125,9 +129,9 @@ func (s *scan) Visit(f engine.File) []engine.Skip { func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { rs := assess.Assess(s.findings, assess.Context{ - Read: func(p string) []byte { return s.files[p] }, - Exists: ctx.Exists, - Env: ctx.Env(), + Read: func(p string) []byte { return s.files[p] }, + Scanned: func(p string) bool { return s.scanned[p] }, + Env: ctx.Env(), }) out := make([]engine.Finding, 0, len(rs)) for _, r := range rs { diff --git a/detectors/emudhra/internal/assess/assess.go b/detectors/emudhra/internal/assess/assess.go index f626b95..bf6f69b 100644 --- a/detectors/emudhra/internal/assess/assess.go +++ b/detectors/emudhra/internal/assess/assess.go @@ -39,9 +39,12 @@ type Result struct { // Context supplies what the rules need to know about the rest of the scanned root. // Paths are absolute inside the root (for example "/etc/ca-certificates.conf"). type Context struct { - Read func(absPath string) []byte // file content, nil when absent - Exists func(absPath string) bool // whether a regular file was scanned at that path - Env []string // container image Config.Env, "KEY=value" entries + Read func(absPath string) []byte // file content, nil when absent + // Scanned reports whether the file at that path was read and checked: + // a file only known to exist (too large to read) proves nothing about + // what it trusts. + Scanned func(absPath string) bool + Env []string // container image Config.Env, "KEY=value" entries } func (c Context) env(key string) (string, bool) { @@ -186,7 +189,7 @@ func botocoreUsesCertifi(p string, ctx Context) bool { if !strings.HasSuffix(site, "/site-packages") && !strings.HasSuffix(site, "/dist-packages") { continue } - return ctx.Exists != nil && ctx.Exists(site+"/certifi/cacert.pem") + return ctx.Scanned != nil && ctx.Scanned(site+"/certifi/cacert.pem") } return false } diff --git a/detectors/emudhra/internal/assess/assess_test.go b/detectors/emudhra/internal/assess/assess_test.go index b831a63..e61c947 100644 --- a/detectors/emudhra/internal/assess/assess_test.go +++ b/detectors/emudhra/internal/assess/assess_test.go @@ -14,7 +14,7 @@ func ctx(files map[string]string) Context { } return nil }, - Exists: func(p string) bool { _, ok := files[p]; return ok }, + Scanned: func(p string) bool { _, ok := files[p]; return ok }, } } diff --git a/detectors/emudhra/limit_test.go b/detectors/emudhra/limit_test.go new file mode 100644 index 0000000..e3e8edf --- /dev/null +++ b/detectors/emudhra/limit_test.go @@ -0,0 +1,45 @@ +package emudhra_test + +import ( + "bytes" + "os" + "path/filepath" + "testing" + + "github.com/DefectDojo/earlylight/internal/cli" +) + +// Round-2 review finding 1: botocore's bundle is cleared only on a certifi +// bundle that was read and checked, not one too large to read. +func TestBotocoreNotClearedByUnreadCertifi(t *testing.T) { + g3, err := os.ReadFile(filepath.Join(g3Bundle(t), "cacert.pem")) + if err != nil { + t.Fatal(err) + } + site := "usr/lib/python3/site-packages" + for _, c := range []struct { + name string + certifi []byte + want int + }{ + {"read certifi", []byte("# empty bundle\n"), 0}, + {"unread certifi", bytes.Repeat([]byte("#"), 5000), 1}, + {"unread certifi holding the CA", append(g3, bytes.Repeat([]byte("#"), 5000)...), 1}, + } { + root := t.TempDir() + for rel, b := range map[string][]byte{site + "/botocore/cacert.pem": g3, site + "/certifi/cacert.pem": c.certifi} { + p := filepath.Join(root, rel) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, b, 0o600); err != nil { + t.Fatal(err) + } + } + var out, errb bytes.Buffer + code := cli.Run(engine, []string{"scan", "fs", "--detector", "emudhra", "--as-root", "--max-file-size", "4096", root}, &out, &errb) + if code != c.want { + t.Errorf("%s: exit %d, want %d\n%s%s", c.name, code, c.want, out.String(), errb.String()) + } + } +} From 563ee5eb0242733a8b3f06fa345472de727eabdb Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:26:11 +0000 Subject: [PATCH 060/119] engine: files over --max-file-size are told to the detectors that wanted them; FinishSkipper; a path counted once From the round-2 review: - A file over --max-file-size is still the --max-file-size gap, and each scan that asked for it and implements LimitVisitor is now told (VisitOverLimit), so a detector never clears on a file it did not get, whichever limit kept it out. A panic there is a detector failure. - FinishSkipper: a scan can report coverage gaps after Finish, when it knows whether the files it did not check matter. - Gaps and the report's NOTE count each path once: a file over the limits of two detectors has a record for each. - Tests: VisitOverLimit panics (own limit and --max-file-size), what is told for --max-file-size, records below a --root system root, FinishSkipper, per-path counts, FuzzLimits seed {115, 100, 0, 2, 0}, FuzzTar checks that Over is called for --max-file-size only above it. Co-Authored-By: Claude Opus 5.5 --- internal/engine/engine.go | 23 ++++++--- internal/engine/engine_test.go | 5 ++ internal/engine/limit_test.go | 90 +++++++++++++++++++++++++++++++++- internal/engine/run.go | 59 +++++++++++++++++++--- internal/report/report.go | 2 +- internal/report/report_test.go | 16 ++++++ internal/source/source.go | 20 +++++--- internal/source/source_test.go | 6 +-- 8 files changed, 198 insertions(+), 23 deletions(-) diff --git a/internal/engine/engine.go b/internal/engine/engine.go index b4dca01..630f475 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -202,16 +202,27 @@ type Limiter interface { Limit(path string, head []byte, executable bool) int64 } -// LimitVisitor is implemented by a Limiter's Scan when a file it asked for -// and did not get, over its limit, can change a verdict: an sshd_config -// include that may turn PAM off must not let the scan clear a server. -// VisitOverLimit is called instead of Visit, with the file's size (-1 when -// it was found larger while reading). The skips it returns are recorded as -// coverage gaps; when it returns none, the file is a deliberate exclusion. +// LimitVisitor is implemented by a Scan that must know which files it +// asked for and did not get, over its own limit (Limiter) or over +// --max-file-size: an sshd_config include that may turn PAM off must not let +// the scan clear a server. VisitOverLimit is called instead of Visit, with +// the file's size (-1 when it was found larger while reading). For a file +// over its own limit, the skips it returns are recorded as coverage gaps, +// and when it returns none the file is a deliberate exclusion; a file over +// --max-file-size is a gap already, and what it returns is not recorded. type LimitVisitor interface { VisitOverLimit(path string, size int64) []Skip } +// FinishSkipper is implemented by a Scan that decides only at the end which +// of the files it did not check its findings depend on: FinishSkips is +// called after Finish, and what it returns is recorded as coverage gaps +// (sshole: a package database over its limit matters only when an OpenSSH +// server was found). +type FinishSkipper interface { + FinishSkips() []Skip +} + // HeadVisitor is implemented by a Scan that wants to see the first bytes // of every file the walk meets, read in full or not: a record of files // it does not need to read (a runtime download inside an image) without diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go index b8bf6cc..6cc3673 100644 --- a/internal/engine/engine_test.go +++ b/internal/engine/engine_test.go @@ -201,6 +201,11 @@ func TestGaps(t *testing.T) { if g := tg.Gaps(); g != 2 { t.Fatalf("gaps %d, want 2: an archive member named testdata/ is still a gap", g) } + // A path is counted once, however many records it has. + tg.Skipped = append(tg.Skipped, skip("/opt/app.jks", "not checked by another detector", false), skip("/proc", "excluded", true)) + if g, n := tg.Gaps(), tg.SkippedPaths(); g != 2 || n != 4 { + t.Fatalf("gaps %d paths %d, want 2 and 4", g, n) + } } // A detector that panics on one file loses that file, not the scan. diff --git a/internal/engine/limit_test.go b/internal/engine/limit_test.go index 56f435b..2a18b1a 100644 --- a/internal/engine/limit_test.go +++ b/internal/engine/limit_test.go @@ -290,7 +290,7 @@ func TestExistsWithLimits(t *testing.T) { // The limit decision, checked against a model for any file size, limits and // wants: who sees the file, what is recorded, and that Exists holds. func FuzzLimits(f *testing.F) { - for _, s := range [][5]uint16{{100, 100, 0, 3, 0}, {101, 100, 0, 3, 0}, {4096, 4096, 4097, 3, 1}, {4097, 4096, 0, 1, 2}, {5000, 4096, 5000, 2, 3}, {0, 1, 1, 3, 3}, {1, 0, 0, 0, 0}} { + for _, s := range [][5]uint16{{100, 100, 0, 3, 0}, {101, 100, 0, 3, 0}, {4096, 4096, 4097, 3, 1}, {4097, 4096, 0, 1, 2}, {5000, 4096, 5000, 2, 3}, {0, 1, 1, 3, 3}, {1, 0, 0, 0, 0}, {115, 100, 0, 2, 0}} { f.Add(s[0], s[1], s[2], uint8(s[3]), uint8(s[4])) } f.Fuzz(func(t *testing.T, size, limA, limB uint16, wants, maxSel uint8) { @@ -359,3 +359,91 @@ func FuzzLimits(f *testing.F) { } }) } + +// panicOver panics in VisitOverLimit. +type panicOver struct{ gapScan } + +func (p panicOver) NewScan(TargetKind) Scan { return p } +func (p panicOver) VisitOverLimit(string, int64) []Skip { + panic("hostile size") +} + +// A panic in VisitOverLimit loses that file, recorded as a detector +// failure (a gap), and the scan goes on: over its own limit and over +// --max-file-size alike. +func TestVisitOverLimitPanic(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 100<<10), "etc/b": []byte("b")}) + for _, max := range []int64{0, 1000} { + _, g := gapDetector(fmt.Sprintf("t-overpanic%d", max), true) + other := &fake{id: fmt.Sprintf("t-overother%d", max), wants: func(string) bool { return true }} + tg := ScanFS([]Detector{panicOver{g}, detector(other)}, root, Options{AsRoot: true, MaxFileSize: max}) + failed := false + for _, s := range tg.Skipped { + failed = failed || s.Path == "/etc/os-release" && s.DetectorFailed + } + if tg.Error != "" || !failed || tg.Gaps() != 1 || len(*other.seen) == 0 { + t.Errorf("--max-file-size %d: error %q skipped %+v other saw %v", max, tg.Error, tg.Skipped, *other.seen) + } + } +} + +// Files over --max-file-size are told to each scan that asked for them +// (size known, or -1), and the record stays the --max-file-size gap. +func TestVisitOverLimitMaxFileSize(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 2000)}) + _, g := gapDetector("t-overmax", true) + tg := ScanFS([]Detector{g}, root, Options{AsRoot: true, MaxFileSize: 1000}) + if len(*g.sizes) != 1 || (*g.sizes)[0] != 2000 || len(tg.Skipped) != 1 || !strings.Contains(tg.Skipped[0].Reason, "--max-file-size") || tg.Gaps() != 1 { + t.Errorf("sizes %v skipped %+v", *g.sizes, tg.Skipped) + } + // A detector that did not ask for it is not told. + notWanting := &fake{id: "t-overmax-no", wants: func(string) bool { return false }, seen: &[]string{}} + sizes := &[]int64{} + ng := gapScan{limitedReader{limited{notWanting, limit64K}, fakeReader{notWanting}}, true, sizes} + ScanFS([]Detector{ng, detector(&fake{id: "t-overmax-all"})}, root, Options{AsRoot: true, MaxFileSize: 1000}) + if len(*sizes) != 0 { + t.Errorf("told a detector that did not want it: %v", *sizes) + } +} + +// Over-limit records carry the path inside the system root when a +// directory below it is scanned (--root). +func TestLimiterBelowSystemRoot(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 100<<10)}) + _, d := capped("t-caproot", osRelease, limit64K) + tg := ScanFS([]Detector{d}, filepath.Join(root, "etc"), Options{SystemRoot: root}) + if tg.Error != "" || len(tg.Skipped) != 1 || tg.Skipped[0].Path != "/etc/os-release" { + t.Errorf("error %q skipped %+v", tg.Error, tg.Skipped) + } +} + +// finishSkipper reports a gap only at the end. +type finishSkipper struct { + gapScan + found bool +} + +func (f finishSkipper) NewScan(TargetKind) Scan { return f } +func (f finishSkipper) FinishSkips() []Skip { + if !f.found { + return nil + } + return []Skip{{Path: "/etc/os-release", Reason: "needed after all"}} +} + +// FinishSkips adds coverage gaps after Finish; a path with several records +// is counted once. +func TestFinishSkipper(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 100<<10)}) + for _, found := range []bool{false, true} { + _, g := gapDetector(fmt.Sprintf("t-finskip%v", found), false) + tg := ScanFS([]Detector{finishSkipper{g, found}}, root, Options{AsRoot: true}) + want := 0 + if found { + want = 1 + } + if tg.Gaps() != want || tg.SkippedPaths() != 1 { + t.Errorf("found %v: gaps %d paths %d skipped %+v", found, tg.Gaps(), tg.SkippedPaths(), tg.Skipped) + } + } +} diff --git a/internal/engine/run.go b/internal/engine/run.go index f155a73..3cb01f5 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -55,20 +55,32 @@ func (t *Target) Count(v Verdict) int { // which are malformed on purpose. func (t *Target) Gaps() int { n := 0 + gap := map[string]bool{} // a path is counted once, however many records it has for _, s := range t.Skipped { // The test-fixture exemption applies only to paths the operator controls: // real files on a scanned filesystem. Image paths and archive member names // are chosen by whoever built them, and a detector failure is never exempt. fixture := t.Type == Filesystem && strings.Contains(s.Path, "/testdata/") && !strings.Contains(s.Path, "!/") && !s.DetectorFailed - if s.Excluded || strings.HasPrefix(s.Reason, "excluded:") || fixture { + if s.Excluded || strings.HasPrefix(s.Reason, "excluded:") || fixture || gap[s.Path] { continue } + gap[s.Path] = true n++ } return n } +// SkippedPaths counts the paths that were not scanned, each once: a file +// over the limits of two detectors has a record for each. +func (t *Target) SkippedPaths() int { + seen := map[string]bool{} + for _, s := range t.Skipped { + seen[s.Path] = true + } + return len(seen) +} + // Options control a run. type Options struct { MaxFileSize int64 @@ -276,6 +288,9 @@ func (w *walker) sourceOptions(opts Options) source.Options { if limiters[i], ok = d.(Limiter); ok { limited = true } + if _, ok := w.scans[i].(LimitVisitor); ok { + limited = true // it is told about files it asked for and did not get + } } var decide func(p string, head []byte, exe bool) (bool, int64) switch { @@ -284,7 +299,7 @@ func (w *walker) sourceOptions(opts Options) source.Options { decide = func(p string, head []byte, exe bool) (bool, int64) { return w.limit(p, head, exe, readers, limiters) } - so.Over = func(p string, size int64) []source.Skip { return w.tooLarge(w.abs(p), size) } + so.Over = func(p string, size int64, own bool) []source.Skip { return w.tooLarge(w.abs(p), size, own) } case all: decide = func(string, []byte, bool) (bool, int64) { return true, 0 } default: @@ -337,13 +352,26 @@ func (w *walker) limit(p string, head []byte, exe bool, readers []Reader, limite return read, most } -// tooLarge records a file that was not read because it is over the limit -// of every detector that wants it (size -1 when found while reading). -func (w *walker) tooLarge(p string, size int64) []source.Skip { +// tooLarge records a file that was not read (size -1 when found larger +// while reading). Over the limit of every detector that wants it (own), it +// is recorded for each of them; over --max-file-size, the source records +// it as a gap, and each detector that wanted it is only told +// (VisitOverLimit), so a verdict never rests on its absence. +func (w *walker) tooLarge(p string, size int64, own bool) []source.Skip { var out []source.Skip for i, l := range w.limits { - if l.wants && l.bytes > 0 && (size < 0 || size > l.bytes) { + switch { + case !l.wants: + case own && l.bytes > 0 && (size < 0 || size > l.bytes): out = append(out, w.overLimit(i, p, size)...) + case !own: + if lv, ok := w.scans[i].(LimitVisitor); ok { + for _, sk := range w.visitOverLimitSafely(i, lv, p, size) { + if sk.failed { + out = append(out, source.Skip{Path: sk.Path, Reason: sk.Reason, DetectorFailed: true}) + } + } + } } } return out @@ -462,9 +490,28 @@ func (w *walker) finish() { return } w.t.Findings = append(w.t.Findings, check(w.dets[i].Manifest().ID, fs)...) + if fs, ok := s.(FinishSkipper); ok { + skips, err := finishSkipsSafely(fs) + if err != nil { + w.t.Error = fmt.Sprintf("detector %s failed: %v", w.ids[i], err) + return + } + for _, sk := range skips { + w.t.Skipped = append(w.t.Skipped, source.Skip{Path: sk.Path, Reason: sk.Reason}) + } + } } } +func finishSkipsSafely(s FinishSkipper) (skips []Skip, err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("%v", r) + } + }() + return s.FinishSkips(), nil +} + func finishSafely(s Scan, ctx TargetContext) (fs []Finding, err error) { defer func() { if r := recover(); r != nil { diff --git a/internal/report/report.go b/internal/report/report.go index 60a9301..1074be2 100644 --- a/internal/report/report.go +++ b/internal/report/report.go @@ -163,7 +163,7 @@ func Text(w io.Writer, r *Report, o Options) { fmt.Fprintf(w, " %d cleared finding(s) hidden: proven fixed, or copies provably not used (use --show-cleared)\n", hidden) } if len(t.Skipped) > 0 { - fmt.Fprintf(w, " NOTE: %d item(s) were not scanned (%d coverage gaps, the rest deliberate exclusions or test fixtures); they are not covered by this result", len(t.Skipped), t.Gaps()) + fmt.Fprintf(w, " NOTE: %d item(s) were not scanned (%d coverage gaps, the rest deliberate exclusions or test fixtures); they are not covered by this result", t.SkippedPaths(), t.Gaps()) if o.ShowSkipped { fmt.Fprintln(w, ":") for _, s := range t.Skipped { diff --git a/internal/report/report_test.go b/internal/report/report_test.go index 23a1865..89692c9 100644 --- a/internal/report/report_test.go +++ b/internal/report/report_test.go @@ -4,9 +4,11 @@ import ( "bytes" "encoding/json" "reflect" + "strings" "testing" "github.com/DefectDojo/earlylight/internal/engine" + "github.com/DefectDojo/earlylight/internal/source" ) func TestSafe(t *testing.T) { @@ -52,3 +54,17 @@ func TestJSONCarriesKinds(t *testing.T) { t.Errorf("kinds = %+v, want %+v", got.Detectors, want) } } + +// Round-2 review finding 8: a path with a record for each detector that +// left it unchecked is one item. +func TestNoteCountsAPathOnce(t *testing.T) { + tg := &engine.Target{Name: "img", Type: engine.Image, Files: 2, Skipped: []source.Skip{ + {Path: "/usr/bin/gprofng-display-html", Reason: "excluded: larger than the 262144-byte limit of java4shell for this file (300000 bytes)", Excluded: true}, + {Path: "/usr/bin/gprofng-display-html", Reason: "excluded: larger than the 262144-byte limit of sshole for this file (300000 bytes)", Excluded: true}, + }} + var b bytes.Buffer + Text(&b, &Report{Tool: "t", Targets: []*engine.Target{tg}}, Options{}) + if !strings.Contains(b.String(), "NOTE: 1 item(s) were not scanned (0 coverage gaps") { + t.Errorf("%s", b.String()) + } +} diff --git a/internal/source/source.go b/internal/source/source.go index a24c279..12d3cb7 100644 --- a/internal/source/source.go +++ b/internal/source/source.go @@ -57,9 +57,12 @@ type Options struct { // below MaxFileSize is not read past its first bytes. Nil reads every // file. Read func(abs string, head []byte, executable bool) (read bool, limit int64) - // Over records a file over the limit Read set (size -1 when it was found - // larger while reading). Nil records it as a deliberate exclusion. - Over func(abs string, size int64) []Skip + // Over records a file Read chose that is over the limit Read set (own) + // or over MaxFileSize, with its size (-1 when it was found larger while + // reading). A file over its own limit is recorded with what Over returns + // (a deliberate exclusion when Over is nil); one over MaxFileSize is + // always recorded as such, and Over adds what it returns. + Over func(abs string, size int64, own bool) []Skip // IsExecutable decides from a file's first bytes whether it is an executable. IsExecutable func(head []byte) bool // Symlink receives every symbolic link (absolute path, target as written). @@ -90,17 +93,22 @@ func (o Options) bound(limit int64) (int64, bool) { // tooLarge records a file over the limit that applies to it; size is -1 // when it was found larger while reading. func (o Options) tooLarge(abs string, size, most int64, own bool) []Skip { + var told []Skip switch { case own && o.Over != nil: - return o.Over(abs, size) + return o.Over(abs, size, true) + case o.Over != nil: + told = o.Over(abs, size, false) + } + switch { case own && size < 0: return []Skip{{Path: abs, Reason: fmt.Sprintf("excluded: larger than the %d-byte limit set for this file, found while reading", most), Excluded: true}} case own: return []Skip{{Path: abs, Reason: fmt.Sprintf("excluded: larger than the %d-byte limit set for this file (%d bytes)", most, size), Excluded: true}} case size < 0: - return []Skip{{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes) while reading", most)}} + return append([]Skip{{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes) while reading", most)}}, told...) } - return []Skip{{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes)", size)}} + return append([]Skip{{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes)", size)}}, told...) } // Visitor receives each file read. Returning an error stops the walk. diff --git a/internal/source/source_test.go b/internal/source/source_test.go index 92d782b..ee2b976 100644 --- a/internal/source/source_test.go +++ b/internal/source/source_test.go @@ -74,8 +74,8 @@ func FuzzTar(f *testing.F) { var over []Skip limited := Options{MaxFileSize: 1 << 20, Read: func(string, []byte, bool) (bool, int64) { return true, limit }, - Over: func(p string, size int64) []Skip { - if size >= 0 && size <= limit { + Over: func(p string, size int64, own bool) []Skip { + if size >= 0 && size <= limit || !own && size >= 0 && size <= 1<<20 { t.Errorf("%s: %d bytes recorded as over a %d-byte limit", p, size, limit) } over = append(over, Skip{Path: p}) @@ -108,7 +108,7 @@ func TestDirOwnLimitWhileReading(t *testing.T) { } return true, 4096 }, - Over: func(_ string, size int64) []Skip { + Over: func(_ string, size int64, _ bool) []Skip { sizes = append(sizes, size) return []Skip{{Path: "/os-release", Reason: "over"}} }} From b94f7bfa73dd07a21ba105af7f84a6c8bcf7367e Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:26:11 +0000 Subject: [PATCH 061/119] sshole: never clear on a start script or include it did not read; gaps only with a server From the round-2 review: - A start script that was not read (over its limit or --max-file-size, or read only as a file named like sshd_config) and runs at start (the command's, one a start script names, or one in an init directory) can start sshd with UsePAM=no or another config: UsePAM yes is then unknown. - An include over --max-file-size is unread like one over sshole's own limit, at and around the boundary where the two are equal. - Package databases are read up to 16 MiB, as in java4shell. - Files the verdict reads that were not read are coverage gaps only when an OpenSSH server is found (FinishSkips); otherwise exclusions. - Of several tar entries for one path the last decides, read or not. - Tests for each, plus an include too large on disk under --root and the parser's nested-include and directive limits. Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/internal/assess/assess.go | 9 +- detectors/sshole/internal/assess/runtime.go | 60 ++++++++++ .../sshole/internal/assess/unread_test.go | 13 +++ detectors/sshole/limit_internal_test.go | 25 +++- detectors/sshole/limit_test.go | 109 +++++++++++++++++- detectors/sshole/sshole.go | 82 +++++++++---- 6 files changed, 269 insertions(+), 29 deletions(-) diff --git a/detectors/sshole/internal/assess/assess.go b/detectors/sshole/internal/assess/assess.go index c9d65a6..c1422f8 100644 --- a/detectors/sshole/internal/assess/assess.go +++ b/detectors/sshole/internal/assess/assess.go @@ -235,11 +235,12 @@ func assessUnit(in Input, u []*Binary) (Finding, bool) { return f, true } f.UsePAM = strings.ToLower(cfg.Global("usepam", "no")) - if f.PAM && f.UsePAM == "yes" && len(cfg.Unread) > 0 { - // A part of the configuration that was not read can turn PAM off: - // never clear on what was not read. + unread := append(append([]string(nil), cfg.Unread...), in.Startup.unreadStart(in.Resolve, scripts)...) + if f.PAM && f.UsePAM == "yes" && len(unread) > 0 { + // A part of the configuration, or a start script, that was not + // read can turn PAM off: never clear on what was not read. f.Status = Undecided - f.Reason = fmt.Sprintf("this build uses PAM and UsePAM is yes in what was read, but %s was not read and can set UsePAM no", strings.Join(cfg.Unread, ", ")) + f.Reason = fmt.Sprintf("this build uses PAM and UsePAM is yes in what was read, but %s was not read and can set UsePAM no", strings.Join(unread, ", ")) f.Message = fmt.Sprintf("OpenSSH %s server on musl without the *sshole fix; whether PAM checks passwords is unknown", main.Release) return f, true } diff --git a/detectors/sshole/internal/assess/runtime.go b/detectors/sshole/internal/assess/runtime.go index 92e2790..4e2c0ec 100644 --- a/detectors/sshole/internal/assess/runtime.go +++ b/detectors/sshole/internal/assess/runtime.go @@ -14,6 +14,66 @@ type Startup struct { Command []string // Scripts are the image's shell scripts ("#!" files), by path. Scripts map[string][]byte + // Unread are scripts that were not read (larger than the scan reads): + // one that runs at start can start sshd with any settings. + Unread map[string]bool +} + +// unreadStart lists the scripts that run at start and were not read: the +// command's own script, one a start script names, and those in the init +// directories. +func (s Startup) unreadStart(resolve func(string) (string, bool), scripts []script) []string { + if len(s.Unread) == 0 { + return nil + } + var out []string + seen := map[string]bool{} + add := func(p string) { + r := p + if resolve != nil { + if rp, ok := resolve(p); ok { + r = rp + } + } + if !strings.HasPrefix(r, "/") { + for _, d := range pathDirs { + if s.Unread[d+r] { + r = d + r + break + } + } + } + if s.Unread[r] && !seen[r] { + seen[r] = true + out = append(out, r) + } + } + c := s.Command + for len(c) > 1 && isWrapper(path.Base(c[0])) { + c = c[1:] + } + if len(c) > 0 { + add(c[0]) + for _, w := range c[1:] { + if strings.HasPrefix(w, "/") { + add(w) + } + } + } + for _, sc := range scripts { + for _, m := range absPathRE.FindAllString(sc.text, -1) { + add(m) + } + } + for p := range s.Unread { + for _, d := range initDirs { + if strings.HasPrefix(p, d) { + add(p) + } + } + } + sort.Strings(out) + return out } // initDirs hold scripts an init system runs at start whatever the command diff --git a/detectors/sshole/internal/assess/unread_test.go b/detectors/sshole/internal/assess/unread_test.go index cdc344c..8b3778c 100644 --- a/detectors/sshole/internal/assess/unread_test.go +++ b/detectors/sshole/internal/assess/unread_test.go @@ -37,6 +37,19 @@ func TestConfigUnread(t *testing.T) { if c := ParseConfig(m, "/etc/ssh/sshd_config"); len(c.Unread) != 1 || !strings.Contains(c.Unread[0], "more than 256") { t.Errorf("past the include limit: unread %v", c.Unread) } + // Includes nested past the parser's depth. + m = memFiles{} + for i := 0; i <= 17; i++ { + m[fmt.Sprintf("/etc/ssh/%d.conf", i)] = fmt.Sprintf("Include /etc/ssh/%d.conf\n", i+1) + } + m["/etc/ssh/sshd_config"] = "Include /etc/ssh/0.conf\n" + if c := ParseConfig(m, "/etc/ssh/sshd_config"); len(c.Unread) != 1 || !strings.Contains(c.Unread[0], "nested too deeply") { + t.Errorf("nested too deeply: unread %v", c.Unread) + } + // Directives past the parser's limit. + if c := ParseConfig(memFiles{"/etc/ssh/sshd_config": strings.Repeat("Port 22\n", maxDirectives+1) + "UsePAM no\n"}, "/etc/ssh/sshd_config"); len(c.Unread) != 1 || !strings.Contains(c.Unread[0], "directives") { + t.Errorf("past the directive limit: unread %v", c.Unread) + } if c := ParseConfig(memFiles{"/etc/ssh/sshd_config": "UsePAM yes\n"}, "/etc/ssh/sshd_config"); len(c.Unread) != 0 { t.Errorf("all read: unread %v", c.Unread) } diff --git a/detectors/sshole/limit_internal_test.go b/detectors/sshole/limit_internal_test.go index 3945cad..85b961a 100644 --- a/detectors/sshole/limit_internal_test.go +++ b/detectors/sshole/limit_internal_test.go @@ -11,8 +11,7 @@ import ( ) // A hostile account file as large as --max-file-size is not read into -// memory: the detector keeps one only up to 4 MiB, and one over that is a -// coverage gap. +// memory: the detector keeps one only up to 4 MiB. func TestKeptFileBounded(t *testing.T) { root := t.TempDir() if err := os.MkdirAll(filepath.Join(root, "etc"), 0o755); err != nil { @@ -35,8 +34,9 @@ func TestKeptFileBounded(t *testing.T) { if a := after.TotalAlloc - before.TotalAlloc; a > 8<<20 { t.Errorf("a 128 MiB /etc/shadow cost %d bytes", a) } - // The verdict reads it: a coverage gap, not an exclusion. - if len(tg.Skipped) != 1 || tg.Skipped[0].Excluded || !strings.Contains(tg.Skipped[0].Reason, "sshole reads") || tg.Gaps() != 1 { + // With no OpenSSH server in the target, no verdict reads it: an + // exclusion, not a gap. + if len(tg.Skipped) != 1 || !tg.Skipped[0].Excluded || !strings.Contains(tg.Skipped[0].Reason, "limit of sshole") || tg.Gaps() != 0 { t.Errorf("skipped %+v", tg.Skipped) } } @@ -63,3 +63,20 @@ func TestLimits(t *testing.T) { } } } + +// Round-2 review finding 5: of several entries for one path, the last +// decides: an over-limit entry after a read one leaves the path unread, a +// read entry after an over-limit one leaves it read. +func TestDuplicateEntries(t *testing.T) { + const p = "/etc/ssh/sshd_config.d/50-site.conf" + s := (&Detector{}).NewScan(engine.Image).(*scan) + s.Visit(engine.File{Path: p, Data: []byte("UsePAM yes\n")}) + s.VisitOverLimit(p, maxKept+1) + if _, ok := s.files[p]; ok || !s.over[p] { + t.Errorf("read then over: files %v over %v", s.files, s.over) + } + s.Visit(engine.File{Path: p, Data: []byte("UsePAM yes\n")}) + if _, ok := s.files[p]; !ok || s.over[p] || s.unreadScripts[p] { + t.Errorf("over then read: files %v over %v unread %v", s.files, s.over, s.unreadScripts) + } +} diff --git a/detectors/sshole/limit_test.go b/detectors/sshole/limit_test.go index a58165c..d9b12a8 100644 --- a/detectors/sshole/limit_test.go +++ b/detectors/sshole/limit_test.go @@ -136,7 +136,114 @@ func TestFailOnSkipWithLimits(t *testing.T) { } padded(t, root, "etc/shadow", []byte("root:*::0:::::\n"), maxKept+1) _, skipped, code = scanExit(t, "--detector", "sshole", "--as-root", "--fail-on-skip", root) - if code != 3 || len(skipped) != 2 { + gaps := 0 + for _, s := range skipped { + if s.Path == "/etc/shadow" && !s.Excluded { + gaps++ + } + } + if code != 3 || gaps != 1 { t.Errorf("a large /etc/shadow: exit %d skipped %+v", code, skipped) } } + +// sshVerdict returns sshole's single verdict and the exit status. +func sshVerdict(t *testing.T, args ...string) (engine.Verdict, int) { + t.Helper() + fs, _, code := scanExit(t, append([]string{"--detector", "sshole"}, args...)...) + if len(fs) != 1 { + t.Fatalf("findings %+v", fs) + } + return fs[0].Verdict, code +} + +// Round-2 review finding 2: a package database over the old 4 MiB limit is +// read (16 MiB, as java4shell), and with no OpenSSH server in the target a +// file over the limit is no coverage gap. +func TestPackageDBLimit(t *testing.T) { + root := t.TempDir() + write(t, root, "etc/os-release", []byte("ID=alpine\nVERSION_ID=3.22.2\n"), 0o644) + padded(t, root, "lib/apk/db/installed", []byte("P:musl\nV:1.2.5-r10\n\n"), 4500036) + if _, _, code := scanExit(t, "--detector", "sshole", "--as-root", "--fail-on-skip", root); code != 0 { + t.Errorf("a 4.5 MB apk database and no sshd: exit %d", code) + } + padded(t, root, "lib/apk/db/installed", []byte("P:musl\nV:1.2.5-r10\n\n"), 16<<20+1) + if _, skipped, code := scanExit(t, "--detector", "sshole", "--as-root", "--fail-on-skip", root); code != 0 || len(skipped) != 1 || !skipped[0].Excluded { + t.Errorf("an apk database over 16 MiB and no sshd: exit %d skipped %+v", code, skipped) + } + root = alpineRoot(t, "10.0_p1-r11") + db, _ := os.ReadFile(filepath.Join(root, "lib/apk/db/installed")) + padded(t, root, "lib/apk/db/installed", db, 4500036) + if v, code := sshVerdict(t, "--as-root", "--fail-on-skip", root); v != engine.Fixed || code != 0 { + t.Errorf("a 4.5 MB apk database naming the fixed package: %s exit %d", v, code) + } + // Over 16 MiB, the fixed package is not known: not cleared, and a gap. + padded(t, root, "lib/apk/db/installed", db, 16<<20+1) + fs, skipped, _ := scanExit(t, "--detector", "sshole", "--as-root", root) + gap := false + for _, s := range skipped { + gap = gap || s.Path == "/lib/apk/db/installed" && !s.Excluded + } + if len(fs) != 1 || fs[0].Verdict.Cleared() || !gap { + t.Errorf("an apk database over 16 MiB with sshd: %+v skipped %+v", fs, skipped) + } +} + +// Round-2 review finding 3: a start script over the limit that may start +// sshd with PAM off keeps the server from being cleared. +func TestStartScriptOverLimitNeverClears(t *testing.T) { + for _, c := range []struct{ name, rel, text string }{ + {"-o UsePAM=no", "etc/cont-init.d/10-sshd", "#!/bin/sh\nexec /usr/sbin/sshd -D -o UsePAM=no\n"}, + {"-f another config", "etc/cont-init.d/10-sshd", "#!/bin/sh\nexec /usr/sbin/sshd -D -f /etc/ssh/alt_sshd_config\n"}, + // Named like sshd_config, so read up to 4 MiB as a config file, + // but past the script limit. + {"a script read for its name", "etc/cont-init.d/gen-sshd_config.sh", "#!/bin/sh\nexec /usr/sbin/sshd -D -o UsePAM=no\n"}, + } { + root := pamRoot(t) + write(t, root, "etc/ssh/alt_sshd_config", []byte("UsePAM no\n"), 0o644) + write(t, root, c.rel, []byte(c.text), 0o755) + if v, _ := sshVerdict(t, "--as-root", root); v != engine.Vulnerable { + t.Errorf("%s, small: %s", c.name, v) + } + padded(t, root, c.rel, []byte(c.text), 307200) + if v, code := sshVerdict(t, "--as-root", root); v.Cleared() || code == 0 { + t.Errorf("%s, 307,200 bytes: %s exit %d", c.name, v, code) + } + } + // A large script that does not run at start changes nothing. + root := pamRoot(t) + padded(t, root, "opt/install.sh", []byte("#!/bin/sh\n"), 307200) + if v, _ := sshVerdict(t, "--as-root", root); v != engine.Inactive { + t.Errorf("a large script outside the start: %s", v) + } +} + +// Round-2 review finding 4: an include over --max-file-size, not only over +// sshole's own limit, keeps the server from being cleared, at and around +// the boundary where the two limits are equal. +func TestIncludeOverMaxFileSize(t *testing.T) { + for _, c := range []struct { + size int64 + max string + }{{2 << 20, "1048576"}, {maxKept + 1, "4194304"}, {maxKept + 1, "4194305"}, {maxKept, "4194303"}} { + root := pamRoot(t) + padded(t, root, "etc/ssh/sshd_config.d/50-site.conf", []byte("UsePAM no\n"), c.size) + if v, code := sshVerdict(t, "--as-root", "--max-file-size", c.max, "--fail-on-skip", root); v.Cleared() || code != 3 { + t.Errorf("a %d-byte include, --max-file-size %s: %s exit %d", c.size, c.max, v, code) + } + } +} + +// Round-2 review finding 7: an include too large to read from disk under +// --root (a subdirectory scanned, the configuration read from the root) +// keeps the server from being cleared. +func TestIncludeOverLimitOnDisk(t *testing.T) { + root := pamRoot(t) + if v, _ := sshVerdict(t, "--root", root, filepath.Join(root, "usr")); v != engine.Inactive { + t.Fatalf("PAM on, read from disk: %s", v) + } + padded(t, root, "etc/ssh/sshd_config.d/50-site.conf", []byte("UsePAM no\n"), maxKept+1) + if v, _ := sshVerdict(t, "--root", root, filepath.Join(root, "usr")); v.Cleared() { + t.Errorf("an include over the limit on disk: %s", v) + } +} diff --git a/detectors/sshole/sshole.go b/detectors/sshole/sshole.go index 98f6131..34370ab 100644 --- a/detectors/sshole/sshole.go +++ b/detectors/sshole/sshole.go @@ -97,11 +97,21 @@ func (d *Detector) Limit(p string, head []byte, _ bool) int64 { most = maxScript } if keep(p) { - most = max(most, maxKept) + most = max(most, keptLimit(p)) } return most } +// keptLimit is the most read of a file the verdict reads: a package +// database can be large (16 MiB, as java4shell's), the others are small. +func keptLimit(p string) int64 { + switch p { + case "/lib/apk/db/installed", "/usr/lib/apk/db/installed", "/usr/lib/opkg/status": + return maxPackageDB + } + return maxKept +} + // isScript reports a "#!" script: a container's entrypoint or startup step. func isScript(head []byte) bool { return len(head) > 2 && head[0] == '#' && head[1] == '!' } @@ -131,11 +141,14 @@ func keep(p string) bool { strings.Contains(path.Dir(p), "ssh") && (strings.HasSuffix(base, ".conf") || strings.HasSuffix(base, "config")) } -const maxKept = 4 << 20 +const ( + maxKept = 4 << 20 + maxPackageDB = 16 << 20 +) // NewScan starts a filesystem or image scan. func (d *Detector) NewScan(kind engine.TargetKind) engine.Scan { - return &scan{kind: kind, files: map[string][]byte{}, scripts: map[string][]byte{}, over: map[string]bool{}} + return &scan{kind: kind, files: map[string][]byte{}, scripts: map[string][]byte{}, over: map[string]bool{}, unreadScripts: map[string]bool{}} } type scan struct { @@ -144,33 +157,62 @@ type scan struct { files map[string][]byte scripts map[string][]byte scriptBytes int - // over holds the files a verdict reads that were over the limit: - // present, but their content is unknown. + // over holds the files a verdict reads that were not read (over the + // limit or --max-file-size): present, but their content is unknown. over map[string]bool + // unreadScripts are files that may be start scripts and were not read. + unreadScripts map[string]bool } -// VisitOverLimit records a file the verdict reads (an account file, the -// package database, an sshd_config or a file one includes) that is over -// the limit: it is a coverage gap, and a configuration that includes it is -// never taken as turning PAM on. A start script over the limit is only an -// exclusion: the startup analysis never clears a server. -func (s *scan) VisitOverLimit(p string, size int64) []engine.Skip { - if !keep(p) { +// VisitOverLimit records a file the scan asked for and did not get, over +// its limit or --max-file-size. A configuration that includes it, or a +// start script that was not read, never lets a server be cleared, and an +// account file, package database or sshd_config not read is a coverage gap +// once a server is found (FinishSkips). The record here is an exclusion: +// with no OpenSSH server in the target, none of these files matters. +func (s *scan) VisitOverLimit(p string, _ int64) []engine.Skip { + // The last entry for a path wins (a tar can hold several). + delete(s.files, p) + delete(s.scripts, p) + if keep(p) { + s.over[p] = true + } + s.unreadScripts[p] = true // its head is not known here: it may be a script + return nil +} + +// FinishSkips reports the files the verdict reads that were not read, as +// coverage gaps, when an OpenSSH server was found. +func (s *scan) FinishSkips() []engine.Skip { + if len(s.binaries) == 0 { return nil } - s.over[p] = true - return []engine.Skip{{Path: p, Reason: fmt.Sprintf("larger than the %d bytes sshole reads of a file its verdict depends on; not checked", maxKept)}} + var out []engine.Skip + for p := range s.over { + out = append(out, engine.Skip{Path: p, Reason: fmt.Sprintf("larger than the %d bytes sshole reads of a file its verdict depends on; not checked", keptLimit(p))}) + } + sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path }) + return out } func (s *scan) Visit(f engine.File) []engine.Skip { if f.Member { return nil // installed servers only, not copies inside archives } - if isScript(f.Data) && len(f.Data) <= maxScript && s.scriptBytes+len(f.Data) <= maxScripts { - s.scripts[f.Path] = f.Data - s.scriptBytes += len(f.Data) + // The last entry for a path wins (a tar can hold several). + delete(s.over, f.Path) + delete(s.unreadScripts, f.Path) + if isScript(f.Data) { + if len(f.Data) <= maxScript && s.scriptBytes+len(f.Data) <= maxScripts { + s.scripts[f.Path] = f.Data + s.scriptBytes += len(f.Data) + } else { + // Read for its other use (a file named like sshd_config) or + // past the total: not checked as a start script. + s.unreadScripts[f.Path] = true + } } - if keep(f.Path) && len(f.Data) <= maxKept && !archive.IsExecutable(f.Data) { + if keep(f.Path) && int64(len(f.Data)) <= keptLimit(f.Path) && !archive.IsExecutable(f.Data) { s.files[f.Path] = f.Data return nil } @@ -222,7 +264,7 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { Resolve: res.resolve, Branch: branch, Image: s.kind == engine.Image, - Startup: assess.Startup{Command: ctx.Command(), Scripts: s.scripts}, + Startup: assess.Startup{Command: ctx.Command(), Scripts: s.scripts, Unread: s.unreadScripts}, }) out := make([]engine.Finding, 0, len(found)) for _, x := range found { @@ -371,7 +413,7 @@ func (f *files) disk(p string) []byte { return nil } fi, err := os.Lstat(full) - if err != nil || fi.Size() > maxKept { + if err != nil || fi.Size() > keptLimit(p) { return nil } b, err := os.ReadFile(full) From c146f59f5a9abe8c1a414ebfe4d36d44a271e3d9 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:27:09 +0000 Subject: [PATCH 062/119] java4shell: no 'mitigated' when the command's start script was not read From the round-2 review: JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics with a 300 KiB entrypoint that passes JAVA_OPTS=-XX:+UseBASE64Intrinsics was reported mitigated. A file that may be a start script and was not read (over its limit or --max-file-size, or read only as a settings file or package database) is remembered; when the container's command runs one, a mitigation is not reported: the runtime is vulnerable, with the reason. Of several tar entries for one path the last decides. Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/assess/assess.go | 27 ++++++++++- .../java4shell/internal/assess/assess_test.go | 18 ++++++++ detectors/java4shell/java4shell.go | 45 ++++++++++++------- detectors/java4shell/limit_internal_test.go | 19 ++++++++ 4 files changed, 93 insertions(+), 16 deletions(-) diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index 8788525..158cacb 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -74,6 +74,9 @@ type Input struct { Env []string Command []string Scripts map[string]map[string]bool + // UnreadScripts are files that may be start scripts and were not read + // (larger than the scan reads): what they pass to java is unknown. + UnreadScripts map[string]bool // Owners maps installed files to the OS package that installed them. Owners map[string]Package // Resolve follows symbolic links within the target. @@ -236,7 +239,7 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi bs, bwhy := knowledge.JudgeBackport(v) f.Release = bs if bs == knowledge.Vulnerable { - if ok, how := mitigation(in, env, root, v.Feature(), &f); ok { + if ok, how := mitigation(in, env, root, v.Feature(), &f); ok && unreadCommandScript(in) == "" { f.Mitigation = how return f.set(Mitigated, bwhy+"; "+how, what+" carries a backported AVX-512 VBMI Base64 decoder without the fix, mitigated by its JVM options until it is updated") } @@ -262,6 +265,10 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi kwhy += " (judged by the release file: no HotSpot version line was found in the VM library)" } if ok, how := mitigation(in, env, root, v.Feature(), &f); ok { + if u := unreadCommandScript(in); u != "" { + return f.set(Vulnerable, kwhy+"; "+how+", but the container's start script "+u+" was not read (larger than the scan reads) and can pass an option that undoes it", + what+" is vulnerable to Java4Shell") + } f.Mitigation = how return f.set(Mitigated, kwhy+"; "+how, what+" is vulnerable to Java4Shell, mitigated by its JVM options until it is updated") } @@ -477,6 +484,24 @@ func javaHomeIs(in Input, env map[string]string, root string) bool { return false } +// unreadCommandScript is a script the container's command runs that was +// not read, or "". +func unreadCommandScript(in Input) string { + for _, w := range in.Command { + p := w + if in.Resolve != nil { + p = in.Resolve(w) + } + if in.UnreadScripts[p] { + return p + } + if in.UnreadScripts[w] { + return w + } + } + return "" +} + // scriptVarsOf lists the script variables the container's command passes // on: catalina.sh passes CATALINA_OPTS and JAVA_OPTS, and a startup script // passes the ones it names. diff --git a/detectors/java4shell/internal/assess/assess_test.go b/detectors/java4shell/internal/assess/assess_test.go index af8b5fa..91bdfd7 100644 --- a/detectors/java4shell/internal/assess/assess_test.go +++ b/detectors/java4shell/internal/assess/assess_test.go @@ -275,3 +275,21 @@ func TestSymlinkLoopResolve(t *testing.T) { in := Input{Libraries: []*jvm.Library{vulnLib(t, temurin)}, Resolve: loop, Env: []string{}, Command: []string{"java", "-XX:UseAVX=2"}} _ = one(t, in) } + +// Round-2 review finding 6: a start script the command runs that was not +// read can pass an option that undoes a mitigation: not mitigated. +func TestMitigationWithUnreadStartScript(t *testing.T) { + in := Input{Libraries: []*jvm.Library{vulnLib(t, temurin)}, Env: []string{"JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics", "JAVA_OPTS=-XX:+UseBASE64Intrinsics"}, + Command: []string{"/entrypoint.sh"}} + if f := one(t, in); f.Status != Mitigated { + t.Fatalf("read nothing that passes JAVA_OPTS: %+v", f) + } + in.UnreadScripts = map[string]bool{"/entrypoint.sh": true} + if f := one(t, in); f.Status != Vulnerable || !strings.Contains(f.Reason, "/entrypoint.sh was not read") { + t.Errorf("an unread entrypoint: %+v", f) + } + in.Command = []string{"/usr/bin/other"} + if f := one(t, in); f.Status != Mitigated { + t.Errorf("an unread script the command does not run: %+v", f) + } +} diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index d829a84..77fc4dc 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -136,12 +136,20 @@ func (d *Detector) Limit(p string, head []byte, _ bool) int64 { } // VisitOverLimit records a JVM settings file over the limit as a coverage -// gap: an option in it can undo a mitigation the scan would report. The -// other files with a limit are deliberate exclusions: no verdict is cleared -// on them (a runtime is cleared only by its VM library and release file), -// and an os-release, package database, start script or crash log that -// large is not a real one. +// gap: an option in it can undo a mitigation the scan would report. A +// start script not read keeps a mitigation from being reported when the +// container's command runs it. The other files with a limit are deliberate +// exclusions: no verdict is cleared on them (a runtime is cleared only by +// its VM library and release file). func (s *scan) VisitOverLimit(p string, _ int64) []engine.Skip { + // The last entry for a path wins (a tar can hold several). + delete(s.scripts, p) + if base := path.Base(p); !hsErr.MatchString(base) && p != "/etc/os-release" && p != "/usr/lib/os-release" && + len(s.unreadScripts) < maxScripts { + // Its head is not known here: it may be a start script, which + // keeps a mitigation from being reported for the command it runs. + s.unreadScripts[p] = true + } if jvm.SettingKind(p) == "" { return nil } @@ -212,7 +220,7 @@ const ( // NewScan starts a filesystem or image scan. func (d *Detector) NewScan(kind engine.TargetKind) engine.Scan { return &scan{kind: kind, releases: map[string]jvm.Release{}, badReleases: map[string]string{}, - kept: map[string][]byte{}, lists: map[string][]byte{}, scripts: map[string]map[string]bool{}} + kept: map[string][]byte{}, lists: map[string][]byte{}, scripts: map[string]map[string]bool{}, unreadScripts: map[string]bool{}} } type scan struct { @@ -228,8 +236,10 @@ type scan struct { dropped int keptBytes int archives []string // runtime downloads seen by name, not read - optionFiles int // settings files that set JVM options - plainUnits int // systemd units that set none + // unreadScripts may be start scripts and were not read. + unreadScripts map[string]bool + optionFiles int // settings files that set JVM options + plainUnits int // systemd units that set none // limits records the caps this target reached; a capped scan clears // nothing. limits []string @@ -331,6 +341,10 @@ func (s *scan) Visit(f engine.File) []engine.Skip { s.keptBytes += len(f.Data) } } + delete(s.unreadScripts, f.Path) + if isScript(f.Data) && len(f.Data) > maxScript && len(s.unreadScripts) < maxScripts { + s.unreadScripts[f.Path] = true // read as a settings file or package database only + } if isScript(f.Data) && len(f.Data) <= maxScript { vars := map[string]bool{} for _, n := range jvm.ScriptVars { @@ -386,13 +400,14 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { } } in := assess.Input{ - Libraries: s.libs, - Releases: s.releases, - BadReleases: s.badReleases, - Settings: s.settings, - Owners: owners, - Resolve: res.resolve, - Scripts: s.scripts, + Libraries: s.libs, + Releases: s.releases, + BadReleases: s.badReleases, + Settings: s.settings, + Owners: owners, + Resolve: res.resolve, + Scripts: s.scripts, + UnreadScripts: s.unreadScripts, } if s.kind == engine.Image { in.Env = ctx.Env() diff --git a/detectors/java4shell/limit_internal_test.go b/detectors/java4shell/limit_internal_test.go index 7bff66d..b801300 100644 --- a/detectors/java4shell/limit_internal_test.go +++ b/detectors/java4shell/limit_internal_test.go @@ -182,3 +182,22 @@ func TestOverLimitGaps(t *testing.T) { } } } + +// A script over the limit is remembered as unread, and of several entries +// for one path the last decides. +func TestUnreadScripts(t *testing.T) { + s := (&Detector{}).NewScan(engine.Image).(*scan) + s.VisitOverLimit("/entrypoint.sh", 300<<10) + s.VisitOverLimit("/etc/os-release", 300<<10) + if !s.unreadScripts["/entrypoint.sh"] || s.unreadScripts["/etc/os-release"] { + t.Fatalf("unread %v", s.unreadScripts) + } + s.Visit(engine.File{Path: "/entrypoint.sh", Data: []byte("#!/bin/sh\nexec java $JAVA_OPTS -jar /app.jar\n")}) + if s.unreadScripts["/entrypoint.sh"] || !s.scripts["/entrypoint.sh"]["JAVA_OPTS"] { + t.Errorf("read after unread: unread %v scripts %v", s.unreadScripts, s.scripts) + } + s.VisitOverLimit("/entrypoint.sh", 300<<10) + if !s.unreadScripts["/entrypoint.sh"] || s.scripts["/entrypoint.sh"] != nil { + t.Errorf("unread after read: unread %v scripts %v", s.unreadScripts, s.scripts) + } +} From 7c1b4c7df487cbea05ff228a74da5fa51049cd74 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:44:26 +0000 Subject: [PATCH 063/119] java4shell: a Red Hat row needs RHEL; a library that is not the row's build keeps its verdict (round 2, item 1) - A clear now also needs the target's os-release ID=rhel: Rocky, AlmaLinux and CentOS Stream reuse Red Hat's releases and implementor. /etc/os-release (already read for annotations) is passed to assess. - A VM library that proves it is not the row's build (another update or build such as 17.0.21+5 or 17.0.20+8, GraalVM, a pre-release or self-built JDK) keeps its own verdict, vulnerable, with the path's claim in the reason; a missing witness or an unreadable version line still gives unknown. - sameUpstream (knowledge.RedHatUpstream) requires Red Hat's scheme: exactly five plain numbers (17.0.21.0.9a and 17.0.21.0.9_1 no longer match a row). - Tests assert the exact verdict for each case, including those that kill the number-comparison, status-guard and vendor-exactness mutants. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/coverage_test.go | 20 +++++ .../java4shell/internal/assess/assess.go | 55 ++++++++----- .../internal/assess/coverage_test.go | 77 +++++++++++-------- .../java4shell/internal/knowledge/redhat.go | 30 +++++++- .../internal/knowledge/redhat_test.go | 6 ++ detectors/java4shell/java4shell.go | 3 + 6 files changed, 138 insertions(+), 53 deletions(-) diff --git a/detectors/java4shell/coverage_test.go b/detectors/java4shell/coverage_test.go index 76a427c..cc140d1 100644 --- a/detectors/java4shell/coverage_test.go +++ b/detectors/java4shell/coverage_test.go @@ -7,6 +7,7 @@ import ( "strings" "testing" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" "github.com/DefectDojo/earlylight/internal/engine" ) @@ -95,3 +96,22 @@ func TestManifestScoreAndLinks(t *testing.T) { t.Error("the runtime kind does not say GraalVM is affected") } } + +// A Red Hat row clears an installed runtime only on RHEL: the os-release +// is read from the target. +func TestRedHatRowNeedsRHEL(t *testing.T) { + saved := knowledge.RedHatFixed + t.Cleanup(func() { knowledge.RedHatFixed = saved }) + knowledge.RedHatFixed = []knowledge.RedHatFix{{Package: "java-17-openjdk", Dist: "el9_6", EVR: "1:17.0.21.0.9-2.el9_6", Advisory: "RHSA-2026:0000"}} + for id, want := range map[string]engine.Verdict{"rhel": engine.Fixed, "rocky": engine.Unknown} { + root := t.TempDir() + const dir = "usr/lib/jvm/java-17-openjdk-17.0.21.0.9-2.el9_6.x86_64" + write(t, root, dir+"/lib/server/libjvm.so", testlib.Build(testlib.Lib{Version: "17.0.21+9-LTS", VBMI: true})) + write(t, root, dir+"/release", testlib.Release("IMPLEMENTOR", "Red Hat, Inc.", "JAVA_RUNTIME_VERSION", "17.0.21+9-LTS", "JAVA_VERSION", "17.0.21")) + write(t, root, "etc/os-release", []byte("NAME=x\nID=\""+id+"\"\nVERSION_ID=\"9.6\"\n")) + r, _ := run(t, "scan", "fs", "--as-root", root) + if f := byPath(r)["/"+dir]; f.Verdict != want { + t.Errorf("ID=%s: %s, want %s (%s)", id, f.Verdict, want, f.Reason) + } + } +} diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index 243c253..7e1d926 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -79,6 +79,9 @@ type Input struct { Scripts map[string]map[string]bool // Owners maps installed files to the OS package that installed them. Owners map[string]Package + // OSID is the target's os-release ID (rhel, rocky, debian), "" when + // it has none. + OSID string // Resolve follows symbolic links within the target. Resolve func(string) string } @@ -103,10 +106,10 @@ func Run(in Input) []Finding { env := jvm.EnvMap(in.Env) var out []Finding for _, r := range roots { - out = append(out, withFix(redHat(judge(in, env, r, byRoot[r])))) + out = append(out, withFix(redHat(in, judge(in, env, r, byRoot[r])))) } for _, l := range loose { - out = append(out, withFix(redHat(judge(in, env, path.Dir(l.Path), []*jvm.Library{l})))) + out = append(out, withFix(redHat(in, judge(in, env, path.Dir(l.Path), []*jvm.Library{l})))) } return out } @@ -284,12 +287,16 @@ const redHatVendor = "Red Hat, Inc." // a fixed Red Hat build keeps the upstream version in its VM library, so // only the rpm release shows the fix. The rpm is named by the install path // alone (the rpm database is not read), so the table clears a runtime only -// when the runtime confirms it: its VM library is a released HotSpot (not -// GraalVM, not a pre-release or self-built JDK) of exactly the upstream -// update and build the rpm packages, and its release file names Red Hat as -// the implementor. Otherwise the verdict is unknown: the path says fixed, -// the runtime does not show it. -func redHat(f Finding) Finding { +// when the runtime confirms it: +// - its VM library is a released, non-GraalVM HotSpot of exactly the +// update and build the rpm packages; a library that is not keeps its own +// verdict (it proves it is not that build); +// - its release file names Red Hat as the implementor, and the target's +// os-release says RHEL (Rocky, AlmaLinux and CentOS Stream reuse Red +// Hat's releases and implementor); without these, or without a readable +// version line, the verdict is unknown: the path says fixed, the +// runtime does not show it. +func redHat(in Input, f Finding) Finding { if f.Package == nil || f.Package.Manager != "rpm" || f.Status != Vulnerable && f.Status != Mitigated { return f } @@ -297,28 +304,40 @@ func redHat(f Finding) Finding { if !known || st != knowledge.Fixed { return f } - up, uok := knowledge.Parse(knowledge.RPMUpstream(f.Package.Version)) + why += ", by its install path" v, vok := knowledge.Parse(f.Version) + if f.VersionFrom == "vm-library" && vok { + up, build, uok := knowledge.RedHatUpstream(f.Package.Version) + var not string + switch { + case f.GraalVM: + not = "a GraalVM build" + case v.EA || v.SelfBuilt: + not = "a pre-release or self-built JDK" + case !uok || v.Build != build || knowledge.Compare(v.Nums, up) != 0: + not = "another update or build" + } + if not != "" { + f.Reason += "; " + why + ", but its VM library (Java " + f.Version + ") is " + not + ", not that build" + return f + } + } var doubt string switch { case f.VersionFrom != "vm-library" || !vok: doubt = "its VM library's version line could not be read" - case f.GraalVM: - doubt = "its VM library is a GraalVM build, not Red Hat's" - case v.EA || v.SelfBuilt: - doubt = "its VM library is a pre-release or self-built JDK (" + f.Version + ")" - case !uok || up.Build < 0 || v.Build != up.Build || knowledge.Compare(v.Nums, up.Nums) != 0: - doubt = "its VM library is Java " + f.Version + ", not the update and build the rpm packages" case f.Vendor != redHatVendor: - doubt = "its release file does not name Red Hat as the implementor" + doubt = "its release file does not name Red Hat, Inc. as the implementor" + case in.OSID != "rhel": + doubt = "the target's os-release does not say RHEL (ID=rhel); Rocky, AlmaLinux and CentOS Stream reuse Red Hat's releases" } if doubt != "" { f.Release = knowledge.Unknown - return f.set(Unknown, why+", by its install path; but "+doubt+", so the runtime does not show that it is that build", + return f.set(Unknown, why+"; but "+doubt+", so the runtime does not show that it is that build", describe(f, v, vok)+": the install path names Red Hat's fixed build, the runtime does not confirm it") } f.Release, f.Mitigation, f.MitigatedFor = knowledge.Fixed, "", nil - return f.set(Fixed, why+"; its VM library reads Java "+f.Version+", the update and build Red Hat backported the fix into, and its release file names Red Hat", + return f.set(Fixed, why+"; its VM library reads Java "+f.Version+", the update and build Red Hat backported the fix into, its release file names Red Hat and the target is RHEL", describe(f, v, true)+" has Red Hat's backported Java4Shell fix (judged by its rpm release)") } diff --git a/detectors/java4shell/internal/assess/coverage_test.go b/detectors/java4shell/internal/assess/coverage_test.go index 4a612f1..ce87098 100644 --- a/detectors/java4shell/internal/assess/coverage_test.go +++ b/detectors/java4shell/internal/assess/coverage_test.go @@ -114,9 +114,12 @@ func TestRedHatRuntime(t *testing.T) { root, lib, vendor string noVersionLine bool env []string + os string + noStubs bool } + const rh, rhel = "Red Hat, Inc.", "rhel" run := func(c rt) Finding { - l := testlib.Lib{Version: c.lib, VBMI: true} + l := testlib.Lib{Version: c.lib, VBMI: !c.noStubs} if c.noVersionLine { l.Version = "" } @@ -128,11 +131,11 @@ func TestRedHatRuntime(t *testing.T) { Libraries: []*jvm.Library{lib(t, c.root+"/lib/server/libjvm.so", l)}, Releases: map[string]jvm.Release{c.root: rel(t, kv...)}, Env: c.env, + OSID: c.os, } return one(t, in) } - const rh = "Red Hat, Inc." - f := run(rt{el96, "17.0.21+9-LTS", rh, false, nil}) + f := run(rt{root: el96, lib: "17.0.21+9-LTS", vendor: rh, os: rhel}) if f.Status != Vulnerable || f.Package == nil || f.Package.Name != "java-17-openjdk-headless" || f.Package.Version != "17.0.21.0.9-1.el9_6" { t.Fatalf("RHEL 9 rpm: %s %+v (%s)", f.Status, f.Package, f.Reason) } @@ -143,42 +146,52 @@ func TestRedHatRuntime(t *testing.T) { saved := knowledge.RedHatFixed t.Cleanup(func() { knowledge.RedHatFixed = saved }) knowledge.RedHatFixed = []knowledge.RedHatFix{{Package: "java-17-openjdk", Dist: "el9_6", EVR: "1:17.0.21.0.9-2.el9_6", Advisory: "RHSA-2026:0000"}} - if f := run(rt{el96, "17.0.21+9-LTS", rh, false, nil}); f.Status != Vulnerable || !strings.Contains(f.Fix, "17.0.21.0.9-2.el9_6") { + if f := run(rt{root: el96, lib: "17.0.21+9-LTS", vendor: rh, os: rhel}); f.Status != Vulnerable || !strings.Contains(f.Fix, "17.0.21.0.9-2.el9_6") { t.Errorf("older than the listed build: %s (%s) fix %s", f.Status, f.Reason, f.Fix) } - fixed := "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-2.el9_6.x86_64" - if f := run(rt{fixed, "17.0.21+9-LTS", rh, false, nil}); f.Status != Fixed || !strings.Contains(f.Reason, "Red Hat") || f.Fix != "" { - t.Errorf("listed build: %s (%s) fix %q", f.Status, f.Reason, f.Fix) - } - if f := run(rt{"/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-3.el9_6.x86_64", "17.0.21+9-LTS", rh, false, nil}); f.Status != Fixed { - t.Errorf("later build: %s (%s)", f.Status, f.Reason) - } - // A mitigated runtime of the fixed build is fixed too. - if f := run(rt{fixed, "17.0.21+9-LTS", rh, false, []string{"JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics"}}); f.Status != Fixed || f.Mitigation != "" { - t.Errorf("mitigated fixed build: %s (%s)", f.Status, f.Reason) - } - // What the install path alone must not clear: the path names the fixed - // build, but the VM library or the release file does not confirm it. + const fixed = "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-2.el9_6.x86_64" for _, c := range []struct { name string rt rt + want Status }{ - {"another vendor's library under a later release", rt{"/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-99.el9_6.x86_64", "17.0.21+9", "Eclipse Adoptium", false, nil}}, - {"no release-file vendor", rt{fixed, "17.0.21+9-LTS", "", false, nil}}, - {"another build", rt{fixed, "17.0.21+5-LTS", rh, false, nil}}, - {"another update", rt{fixed, "17.0.21.0.3+1-LTS", rh, false, nil}}, - {"pre-release", rt{fixed, "17.0.21-ea+9", rh, false, nil}}, - {"self-built", rt{fixed, "17.0.21-internal+0-adhoc.root.src", rh, false, nil}}, - {"GraalVM", rt{fixed, "17.0.21+9-jvmci-23.0-b12", rh, false, nil}}, - {"version from the release file only", rt{fixed, "17.0.21+9-LTS", rh, true, nil}}, - {"a later update the row does not cover", rt{"/usr/lib/jvm/java-17-openjdk-17.0.21.1.1-1.el9_6.x86_64", "17.0.21.1+1-LTS", rh, false, nil}}, - {"another stream", rt{"/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-9.el9_7.x86_64", "17.0.21+9-LTS", rh, false, nil}}, - {"RHEL 8", rt{"/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-9.el8.x86_64", "17.0.21+9-LTS", rh, false, nil}}, - {"Oracle Linux", rt{"/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-2.0.1.el9_6.x86_64", "17.0.21+9-LTS", "Oracle Corporation", false, nil}}, - {"Fedora", rt{"/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-9.fc41.x86_64", "17.0.21+9", rh, false, nil}}, + {"the listed build", rt{root: fixed, lib: "17.0.21+9-LTS", vendor: rh, os: rhel}, Fixed}, + {"a later build", rt{root: "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-3.el9_6.x86_64", lib: "17.0.21+9-LTS", vendor: rh, os: rhel}, Fixed}, + {"mitigated, of the fixed build", rt{root: fixed, lib: "17.0.21+9-LTS", vendor: rh, os: rhel, env: []string{"JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics"}}, Fixed}, + // Witnesses missing: the path says fixed, nothing confirms it. + {"another vendor's library", rt{root: "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-99.el9_6.x86_64", lib: "17.0.21+9", vendor: "Eclipse Adoptium", os: rhel}, Unknown}, + {"no release-file vendor", rt{root: fixed, lib: "17.0.21+9-LTS", os: rhel}, Unknown}, + {"a vendor that only starts with Red Hat's", rt{root: fixed, lib: "17.0.21+9-LTS", vendor: rh + "x", os: rhel}, Unknown}, + {"version from the release file only", rt{root: fixed, lib: "17.0.21+9-LTS", vendor: rh, os: rhel, noVersionLine: true}, Unknown}, + {"Rocky Linux", rt{root: fixed, lib: "17.0.21+9-LTS", vendor: rh, os: "rocky"}, Unknown}, + {"CentOS Stream", rt{root: fixed, lib: "17.0.21+9-LTS", vendor: rh, os: "centos"}, Unknown}, + {"no os-release", rt{root: fixed, lib: "17.0.21+9-LTS", vendor: rh}, Unknown}, + // The library proves it is not the row's build: its own verdict. + {"another build", rt{root: fixed, lib: "17.0.21+5-LTS", vendor: rh, os: rhel}, Vulnerable}, + {"another update, the same build number", rt{root: fixed, lib: "17.0.20+9-LTS", vendor: rh, os: rhel}, Vulnerable}, + {"another update", rt{root: fixed, lib: "17.0.20+8-LTS", vendor: rh, os: rhel}, Vulnerable}, + {"a five-number update", rt{root: fixed, lib: "17.0.21.0.3+1-LTS", vendor: rh, os: rhel}, Vulnerable}, + {"pre-release", rt{root: fixed, lib: "17.0.21-ea+9", vendor: rh, os: rhel}, Vulnerable}, + {"self-built", rt{root: fixed, lib: "17.0.21-internal+0-adhoc.root.src", vendor: rh, os: rhel}, Vulnerable}, + {"GraalVM", rt{root: fixed, lib: "17.0.21+9-jvmci-23.0-b12", vendor: rh, os: rhel}, Vulnerable}, + // Not the row's: judged by the library. + {"a later update the row does not cover", rt{root: "/usr/lib/jvm/java-17-openjdk-17.0.21.1.1-1.el9_6.x86_64", lib: "17.0.21.1+1-LTS", vendor: rh, os: rhel}, Vulnerable}, + {"another stream", rt{root: "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-9.el9_7.x86_64", lib: "17.0.21+9-LTS", vendor: rh, os: rhel}, Vulnerable}, + {"RHEL 8", rt{root: "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-9.el8.x86_64", lib: "17.0.21+9-LTS", vendor: rh, os: rhel}, Vulnerable}, + {"Oracle Linux", rt{root: "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-2.0.1.el9_6.x86_64", lib: "17.0.21+9-LTS", vendor: "Oracle Corporation", os: "ol"}, Vulnerable}, + {"Fedora", rt{root: "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-9.fc41.x86_64", lib: "17.0.21+9", vendor: rh, os: "fedora"}, Vulnerable}, + // A verdict other than vulnerable is not the table's to change. + {"no decoder stubs", rt{root: fixed, lib: "17.0.21+9-LTS", vendor: rh, os: rhel, noStubs: true}, Unknown}, } { - if f := run(c.rt); f.Status == Fixed || f.Status == NotAffected { - t.Errorf("%s: cleared: %s (%s)", c.name, f.Status, f.Reason) + f := run(c.rt) + if f.Status != c.want { + t.Errorf("%s: %s, want %s (%s)", c.name, f.Status, c.want, f.Reason) + } + if c.want == Fixed && (!strings.Contains(f.Reason, "Red Hat") || f.Fix != "" || f.Mitigation != "") { + t.Errorf("%s: reason %q fix %q mitigation %q", c.name, f.Reason, f.Fix, f.Mitigation) + } + if c.want == Unknown && c.name != "no decoder stubs" && !strings.Contains(f.Reason, "install path") { + t.Errorf("%s: the reason does not say what the path claims: %s", c.name, f.Reason) } } } diff --git a/detectors/java4shell/internal/knowledge/redhat.go b/detectors/java4shell/internal/knowledge/redhat.go index df0ec95..65a7324 100644 --- a/detectors/java4shell/internal/knowledge/redhat.go +++ b/detectors/java4shell/internal/knowledge/redhat.go @@ -86,9 +86,33 @@ func RedHatFixFor(pkg, dist string) (RedHatFix, bool) { // sameUpstream reports whether two Red Hat rpm versions package the same // upstream update and build. func sameUpstream(a, b string) bool { - x, okx := Parse(RPMUpstream(a)) - y, oky := Parse(RPMUpstream(b)) - return okx && oky && x.Build >= 0 && x.Build == y.Build && Compare(x.Nums, y.Nums) == 0 + xn, xb, okx := RedHatUpstream(a) + yn, yb, oky := RedHatUpstream(b) + return okx && oky && xb == yb && Compare(xn, yn) == 0 +} + +var redHatVersion = regexp.MustCompile(`^(?:\d+:)?(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)(?:-|$)`) + +// RedHatUpstream reads a Red Hat OpenJDK rpm version in Red Hat's scheme, +// exactly five plain numbers (17.0.21.0.9-2.el9_6 is 17.0.21.0, build 9): +// the update and the build. ok is false for anything else. +func RedHatUpstream(evr string) (nums []int, build int, ok bool) { + m := redHatVersion.FindStringSubmatch(evr) + if m == nil { + return nil, 0, false + } + for _, p := range m[1:5] { + n, err := strconv.Atoi(p) + if err != nil || len(p) > 9 { + return nil, 0, false + } + nums = append(nums, n) + } + b, err := strconv.Atoi(m[5]) + if err != nil || len(m[5]) > 9 { + return nil, 0, false + } + return nums, b, true } // JudgeRedHat judges an rpm of Red Hat's OpenJDK (name and diff --git a/detectors/java4shell/internal/knowledge/redhat_test.go b/detectors/java4shell/internal/knowledge/redhat_test.go index fe0161d..326a5dc 100644 --- a/detectors/java4shell/internal/knowledge/redhat_test.go +++ b/detectors/java4shell/internal/knowledge/redhat_test.go @@ -62,6 +62,12 @@ func TestRedHatTable(t *testing.T) { {"java-17-openjdk-headless", "1:17.0.21.0.10-1.el9_6", "", false}, {"java-21-openjdk-headless", "1:21.0.13.0.9-1.el9_6", "", false}, {"java-17-openjdk-headless", "17.0.21.0.9-1.fc41", "", false}, // not Red Hat + // Not five plain numbers: not Red Hat's scheme, not the row's build. + {"java-17-openjdk-headless", "17.0.21.0.9a-2.el9_6", "", false}, + {"java-17-openjdk-headless", "17.0.21.0.9_1-2.el9_6", "", false}, + {"java-17-openjdk-headless", "17.0.21.0.9.1-2.el9_6", "", false}, + // The same build number of another update. + {"java-17-openjdk-headless", "17.0.20.0.9-3.el9_6", "", false}, {"java-17-amazon-corretto-headless", "17.0.21.0.9-2.el9_6", "", false}, } { st, why, known := JudgeRedHat(c.name, c.evr) diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index e58b583..659b6c3 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -350,6 +350,9 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { Resolve: res.resolve, Scripts: s.scripts, } + if osr := osRelease(s.kept["/etc/os-release"], s.kept["/usr/lib/os-release"]); osr != "" { + in.OSID, _, _ = strings.Cut(osr, " ") + } if s.kind == engine.Image { in.Env = ctx.Env() if in.Env == nil { From fc0cb559508be1363598f16e03339196a8b1d8b2 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:45:40 +0000 Subject: [PATCH 064/119] java4shell: carry the build after a patch number; six-number rpm versions are not settled (round 2, items 3, 4) Build 1 of a fixed release read fixed in some readers: amazoncorretto:17.0.21.1.1 and :27.0.1.1.3, sapmachine/openjdk tags, asdf corretto-17.0.21.1.1, sdkman 17.0.21.1.1-amzn, setup-java 17.0.21.1+1, java-17-amazon-corretto-17.0.21.1.1-1. Judge now reads a fifth number after a patch number as the build (17.0.21.1.1 is 17.0.21.1 build 1) and leaves more numbers unknown; CorrettoJava keeps it; setup-java passes its +N build on. A Corretto rpm with a + build (17.0.21+9-1.amzn2023.1) is now read. An rpm pin whose version does not have Red Hat's five numbers is never cleared (was: only four). Co-Authored-By: Claude Opus 5.5 --- .../internal/knowledge/knowledge.go | 12 +++++ .../java4shell/internal/repo/coverage_test.go | 45 +++++++++++++++++++ detectors/java4shell/internal/repo/repo.go | 35 +++++++++++---- .../java4shell/internal/repo/review_test.go | 2 +- 4 files changed, 84 insertions(+), 10 deletions(-) diff --git a/detectors/java4shell/internal/knowledge/knowledge.go b/detectors/java4shell/internal/knowledge/knowledge.go index b9ad01b..f2b44a6 100644 --- a/detectors/java4shell/internal/knowledge/knowledge.go +++ b/detectors/java4shell/internal/knowledge/knowledge.go @@ -350,6 +350,18 @@ func Judge(v Version) (Status, string) { if !ok { return Unknown, fmt.Sprintf("Java %s is not in this detector's release data", ver) } + // After a patch number (the fourth, small), a fifth number is a build: + // 17.0.21.1.1 is 17.0.21.1 build 1 (Corretto, SapMachine and Red Hat + // write it so), which can predate the fix of 17.0.21.1. + if len(v.Nums) >= 5 && v.Nums[3] <= maxPatch { + if len(v.Nums) > 5 { + return Unknown, fmt.Sprintf("Java %s has more numbers than a Java version and a build: what it names is not known", ver) + } + if v.Build < 0 { + v.Build = v.Nums[4] + } + v.Nums = v.Nums[:4] + } if l.Introduced != nil { c := Compare(v.Nums, l.Introduced) if c == 0 && v.SelfBuilt { diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index 9627297..efe8262 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -350,3 +350,48 @@ func TestRPMGaps(t *testing.T) { t.Errorf("an rpm query reported as an install: %+v", f) } } + +// Round 2, items 3 and 4: the build after a patch number is carried, so +// build 1 of a fixed release (17.0.21.1.1, 27.0.1.1.3, 17.0.21.1+1) is not +// read as fixed; a six-number rpm version is not settled. +func TestBuildOfFixedRelease(t *testing.T) { + res := scan(t, tree(t, map[string]string{ + "Dockerfile": strings.Join([]string{ + "FROM amazoncorretto:17.0.21.1.1", + "FROM amazoncorretto:27.0.1.1.3", + "FROM sapmachine:17.0.21.1.1", + "FROM openjdk:17.0.21.1.1", + "FROM amazoncorretto:17.0.21.1.2", + "RUN dnf install -y java-17-amazon-corretto-17.0.21.1.1-1", + "RUN dnf install -y java-17-openjdk-17.0.21.1.2.3-1.el9", + "RUN dnf install -y java-17-amazon-corretto-headless-17.0.21+9-1.amzn2023.1", + }, "\n") + "\n", + "a/.tool-versions": "java corretto-17.0.21.1.1\n", + "a/.sdkmanrc": "java=17.0.21.1.1-amzn\n", + ".github/workflows/ci.yml": "jobs:\n a:\n steps:\n" + + " - uses: actions/setup-java@v5\n with:\n distribution: temurin\n java-version: 17.0.21.1+1\n" + + " - uses: actions/setup-java@v5\n with:\n distribution: corretto\n java-version: 17.0.21.1+1\n" + + " - uses: actions/setup-java@v5\n with:\n distribution: temurin\n java-version: 17.0.21.1+2\n", + })) + checkAll(t, res, []want{ + {"Dockerfile", 1, RuleImagePin, StatusVulnerable}, + {"Dockerfile", 2, RuleImagePin, StatusVulnerable}, + {"Dockerfile", 3, RuleImagePin, StatusVulnerable}, + {"Dockerfile", 4, RuleImagePin, StatusVulnerable}, + {"Dockerfile", 6, RulePackage, StatusVulnerable}, + {"Dockerfile", 7, RulePackage, StatusUnknown}, + {"Dockerfile", 8, RulePackage, StatusVulnerable}, + {"a/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"a/.sdkmanrc", 1, RuleJavaPin, StatusVulnerable}, + {".github/workflows/ci.yml", 7, RuleJavaPin, StatusVulnerable}, + {".github/workflows/ci.yml", 11, RuleJavaPin, StatusVulnerable}, + }) + for _, l := range []struct { + file string + line int + }{{"Dockerfile", 5}, {".github/workflows/ci.yml", 15}} { + if f, ok := find(res, l.file, l.line); ok { + t.Errorf("%s:%d, a fixed build, reported: %+v", l.file, l.line, f) + } + } +} diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index c372bb8..a1ba599 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -29,6 +29,7 @@ import ( "path/filepath" "regexp" "sort" + "strconv" "strings" "gopkg.in/yaml.v3" @@ -322,7 +323,15 @@ var versionInText = regexp.MustCompile(`(\d{1,3}(?:\.\d{1,9}){0,5})`) // its line has no fix at all. func (s *scanner) judgeVersion(rel string, line, col int, verText, source, vendor string) { tv := TagVersion{Text: verText, Exact: strings.Count(verText, ".") >= 2, OpenJDKBuild: -1} - for _, p := range strings.Split(verText, ".") { + nums := verText + if base, b, ok := strings.Cut(verText, "+"); ok { + // setup-java 17.0.21.1+1: OpenJDK's build. + nums = base + if n, err := strconv.Atoi(b); err == nil && n >= 0 { + tv.OpenJDKBuild = n + } + } + for _, p := range strings.Split(nums, ".") { n := 0 fmt.Sscanf(p, "%d", &n) tv.Nums = append(tv.Nums, n) @@ -474,6 +483,9 @@ func (s *scanner) asdfValue(rel string, line int, value, source string) { // (21.0.5.11.1: Java 21.0.5, build 11) and, since the out-of-band releases, // the OpenJDK patch number there (21.0.13.1.2: Java 21.0.13.1, build 2). // OpenJDK patch numbers are small, so a fourth number above 3 is a build. +// +// A fifth number after a patch number is kept: 17.0.21.1.1 is build 1 of +// 17.0.21.1, which predates the fix. func CorrettoJava(ver string) string { parts := strings.Split(ver, ".") if len(parts) >= 4 { @@ -482,7 +494,6 @@ func CorrettoJava(ver string) string { if n > 3 { return strings.Join(parts[:3], ".") } - return strings.Join(parts[:4], ".") } return ver } @@ -587,7 +598,11 @@ func (s *scanner) setupJava(rel string, v *yaml.Node, dist string, text []string return } before := len(s.findings) - s.judgeVersion(rel, v.Line, 0, m, "actions/setup-java", dist) + judged := m + if b, ok := strings.CutPrefix(ver, m+"+"); ok && b != "" && strings.Trim(b, "0123456789") == "" { + judged = ver // the build decides at a fixed release's boundary + } + s.judgeVersion(rel, v.Line, 0, judged, "actions/setup-java", dist) if len(s.findings) == before { s.movingSetupJava(rel, v, m, dist) return @@ -779,7 +794,7 @@ var ( installRE = regexp.MustCompile(`\b(?:apt-get|apt|apk|dnf|yum|microdnf|tdnf|zypper)\b(?:\s+-{1,2}[\w=./:-]+)*\s+(?:install|add|in)\b`) aptJava = regexp.MustCompile(`\b(openjdk-(\d{1,2})-(?:jre|jdk)(?:-headless)?)\b(=([^\s;&|]+))?`) apkJava = regexp.MustCompile(`\b(openjdk(\d{1,2})(?:-jre|-jdk|-jre-headless|-jmods)?)(?:([=~><]+)([^\s;&|]+))?`) - rpmJava = regexp.MustCompile(`\b(java-(\d{1,2})-(openjdk|amazon-corretto)(?:-headless|-devel|-jdk)?)(?:-(\d[\w.:*?-]*))?`) + rpmJava = regexp.MustCompile(`\b(java-(\d{1,2})-(openjdk|amazon-corretto)(?:-headless|-devel|-jdk)?)(?:-(\d[\w.:*?+~-]*))?`) // rpmLatest is Fedora's and EPEL's java-latest-openjdk: the newest // release the distribution carries, named by no release. rpmLatest = regexp.MustCompile(`^java-latest-openjdk(?:-headless|-devel|-jmods)?(?:-\d[\w.:*?-]*)?$`) @@ -1056,6 +1071,8 @@ func pinnedVersion(h pkgHit) string { up = strings.ReplaceAll(up, "_p", "+") switch { case h.vendor == "corretto": + // Without the rpm or deb release: 17.0.21+9-1.amzn2023.1. + up, _, _ = strings.Cut(up, "-") up = CorrettoJava(up) case h.mgr == "rpm": // Red Hat and Fedora append the build: 17.0.21.0.9 is 17.0.21+9. @@ -1131,11 +1148,11 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { props["current"] = h.ver v, _ := knowledge.Parse(up) st, why := knowledge.Judge(v) - if st == knowledge.Fixed && h.mgr == "rpm" && h.vendor == "distribution" && rpmNumbers(h.ver) == 4 { - // Red Hat and Fedora write five numbers; a fourth number from - // another rpm distribution (openEuler's 17.0.21.2) may be a - // build, not a patch release. - st, why = knowledge.Unknown, fmt.Sprintf("%s has four numbers: outside Red Hat's five-number scheme the fourth may be a build number, not the OpenJDK patch release", h.ver) + if st == knowledge.Fixed && h.mgr == "rpm" && h.vendor == "distribution" && rpmNumbers(h.ver) != 5 { + // Red Hat and Fedora write five numbers; another count + // (openEuler's 17.0.21.2, a six-number version) may hold a + // build where the patch release would be. + st, why = knowledge.Unknown, fmt.Sprintf("%s does not have Red Hat's five numbers: its fourth number may be a build, not the OpenJDK patch release", h.ver) } if st == knowledge.Unknown { s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Reason: why, Props: props, diff --git a/detectors/java4shell/internal/repo/review_test.go b/detectors/java4shell/internal/repo/review_test.go index d907df3..1487f92 100644 --- a/detectors/java4shell/internal/repo/review_test.go +++ b/detectors/java4shell/internal/repo/review_test.go @@ -37,7 +37,7 @@ func TestReviewRepo(t *testing.T) { if f, ok := find(res, "g/.tool-versions", 1); ok { t.Errorf("fixed Corretto reported: %+v", f) } - if CorrettoJava("21.0.5.11.1") != "21.0.5" || CorrettoJava("21.0.13.1.2") != "21.0.13.1" || CorrettoJava("21.0.13.0.11") != "21.0.13.0" { + if CorrettoJava("21.0.5.11.1") != "21.0.5" || CorrettoJava("21.0.13.1.2") != "21.0.13.1.2" || CorrettoJava("21.0.13.0.11") != "21.0.13.0.11" { t.Error("CorrettoJava") } From 964b16cd61148f059fa06d285ca9038d2a10a089 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:47:08 +0000 Subject: [PATCH 065/119] java4shell: rpm and dnf forms that gave nothing (round 2, item 2) Package files are read with any ?query or #fragment removed and in any case (.RPM); rpm options with values (--root /mnt -i) no longer hide the install; a pattern that could match a Java package (*.rpm, java-17-*.rpm) and a Java URL without a file name (download?file=...) are not checked. dnf/yum localinstall, dnf reinstall and dnf5 install are read, and --installroot/--releasever values skipped. zypper's java-17-openjdk=17.0.21.0 is judged. A pre-release version with ~ (21.0.13.1~2ea-1, 21.0.13.1.2~ea) is never fixed. Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/repo/coverage_test.go | 48 ++++++++ detectors/java4shell/internal/repo/repo.go | 105 ++++++++++++++++-- 2 files changed, 141 insertions(+), 12 deletions(-) diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index efe8262..0f21b7d 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -395,3 +395,51 @@ func TestBuildOfFixedRelease(t *testing.T) { } } } + +// Round 2, item 2: rpm and dnf forms that gave nothing. +func TestRPMForms(t *testing.T) { + const f17 = "java-17-openjdk-headless-17.0.21.0.9-1.el9.x86_64" + lines := []string{ + "FROM registry.access.redhat.com/ubi9/ubi", + "RUN dnf install -y https://example.com/" + f17 + ".rpm?raw=true", // 2 + "RUN dnf install -y https://example.com/" + f17 + ".rpm#sha256=abc", // 3 + "RUN dnf install -y /tmp/" + f17 + ".RPM", // 4 + "RUN rpm --root /mnt -i /tmp/" + f17 + ".rpm", // 5 + "RUN rpm -ivh *.rpm", // 6 + "RUN rpm -ivh /tmp/java-17-*.rpm", // 7 + "RUN rpm -ivh 'https://example.com/download?file=" + f17 + ".rpm'", // 8 + "RUN dnf localinstall -y /tmp/" + f17 + ".rpm", // 9 + "RUN yum localinstall -y /tmp/" + f17 + ".rpm", // 10 + "RUN dnf5 install -y java-17-openjdk-headless", // 11 + "RUN dnf reinstall -y java-21-openjdk-headless", // 12 + "RUN zypper in -y java-17-openjdk=17.0.21.0", // 13 + "RUN apt-get install -y openjdk-21-jre-headless=21.0.13.1~2ea-1", // 14 + "RUN dnf install -y java-21-openjdk-headless-21.0.13.1.2~ea-1.el9", // 15 + "RUN dnf --installroot /mnt --releasever 9 install -y java-17-openjdk-headless", // 16 + "RUN rpm -ivh /tmp/epel-release-*.rpm", // 17 + "RUN dnf install -y https://example.com/epel-release-latest-9.noarch.rpm", // 18 + } + res := scan(t, tree(t, map[string]string{"Dockerfile": strings.Join(lines, "\n") + "\n"})) + checkAll(t, res, []want{ + {"Dockerfile", 2, RulePackage, StatusVulnerable}, + {"Dockerfile", 3, RulePackage, StatusVulnerable}, + {"Dockerfile", 4, RulePackage, StatusVulnerable}, + {"Dockerfile", 5, RulePackage, StatusVulnerable}, + {"Dockerfile", 6, RulePackage, StatusUnknown}, + {"Dockerfile", 7, RulePackage, StatusUnknown}, + {"Dockerfile", 8, RulePackage, StatusUnknown}, + {"Dockerfile", 9, RulePackage, StatusVulnerable}, + {"Dockerfile", 10, RulePackage, StatusVulnerable}, + {"Dockerfile", 11, RulePackage, StatusVulnerable}, + {"Dockerfile", 12, RulePackage, StatusVulnerable}, + {"Dockerfile", 13, RulePackage, StatusVulnerable}, + {"Dockerfile", 14, RulePackage, StatusUnknown}, + {"Dockerfile", 15, RulePackage, StatusUnknown}, + {"Dockerfile", 16, RulePackage, StatusVulnerable}, + }) + for _, l := range []int{17, 18} { + if f, ok := find(res, "Dockerfile", l); ok { + t.Errorf("Dockerfile:%d, not Java, reported: %+v", l, f) + } + } +} diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index a1ba599..c6b1d0e 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -791,16 +791,17 @@ func (s *scanner) jibRef(rel string, line, col int, image string) { // ---- Dockerfiles: OS packages and the mitigation a stage sets var ( - installRE = regexp.MustCompile(`\b(?:apt-get|apt|apk|dnf|yum|microdnf|tdnf|zypper)\b(?:\s+-{1,2}[\w=./:-]+)*\s+(?:install|add|in)\b`) + // installRE finds a package tool on a RUN line; installArgs decides + // whether it installs. + installRE = regexp.MustCompile(`\b(?:apt-get|apt|apk|dnf5?|yum|microdnf|tdnf|zypper|rpm)\b`) aptJava = regexp.MustCompile(`\b(openjdk-(\d{1,2})-(?:jre|jdk)(?:-headless)?)\b(=([^\s;&|]+))?`) apkJava = regexp.MustCompile(`\b(openjdk(\d{1,2})(?:-jre|-jdk|-jre-headless|-jmods)?)(?:([=~><]+)([^\s;&|]+))?`) rpmJava = regexp.MustCompile(`\b(java-(\d{1,2})-(openjdk|amazon-corretto)(?:-headless|-devel|-jdk)?)(?:-(\d[\w.:*?+~-]*))?`) // rpmLatest is Fedora's and EPEL's java-latest-openjdk: the newest // release the distribution carries, named by no release. rpmLatest = regexp.MustCompile(`^java-latest-openjdk(?:-headless|-devel|-jmods)?(?:-\d[\w.:*?-]*)?$`) - // rpmInstall is an rpm command that installs or upgrades package files. - // A query (-qip) or an erase (-e) is not an install. - rpmInstall = regexp.MustCompile(`\brpm\b(?:\s+-{1,2}[\w=./:-]+)*?\s+(?:-[a-dfh-pr-zA-UW-Z]*[iUF][a-dfh-pr-zA-UW-Z]*|--install|--upgrade|--freshen)(?:\s|$)`) + // rpmInstallFlag is an rpm option that installs or upgrades package + // files; a query (-qip) or an erase (-e) is not an install. rpmInstallFlag = regexp.MustCompile(`^(?:-[a-dfh-pr-zA-UW-Z]*[iUF][a-dfh-pr-zA-UW-Z]*|--install|--upgrade|--freshen)$`) vendorJava = regexp.MustCompile(`\b((temurin|zulu|msopenjdk|sapmachine)-?(\d{1,2})(?:-ca)?(?:-(?:jdk|jre))?(?:-headless)?)\b(=([^\s;&|]+))?`) defaultJava = regexp.MustCompile(`\b(default-(?:jre|jdk)(?:-headless)?)\b`) @@ -873,12 +874,25 @@ func (s *scanner) dockerfile(rel, text string) { // packages and the vendors' own (Temurin, Corretto, Zulu, Microsoft, // SapMachine), with or without a version. func (s *scanner) packages(rel string, line int, run string) { - if !installRE.MatchString(run) && !rpmInstall.MatchString(run) { + if !installRE.MatchString(run) { return } var hits []pkgHit for _, arg := range installArgs(run) { switch { + case strings.HasPrefix(arg, unreadableArg): + hits = append(hits, pkgHit{name: strings.TrimPrefix(arg, unreadableArg), mgr: "rpm", vendor: "distribution", unreadable: true}) + case zypperArg.MatchString(arg): + m := zypperArg.FindStringSubmatch(arg) + v := "distribution" + if m[3] == "amazon-corretto" { + v = "corretto" + } + op := m[4] + if op == "=" { + op = "" + } + hits = append(hits, pkgHit{name: m[1], feature: atoi(m[2]), op: op, ver: m[5], mgr: "rpm", vendor: v}) case aptArg.MatchString(arg): m := aptArg.FindStringSubmatch(arg) hits = append(hits, pkgHit{name: m[1], feature: atoi(m[2]), op: opOf(m[3]), ver: m[4], mgr: "apt", vendor: "distribution"}) @@ -928,11 +942,12 @@ var ( ) var ( - pkgTools = map[string]bool{"apt-get": true, "apt": true, "apk": true, "dnf": true, "yum": true, "microdnf": true, "tdnf": true, "zypper": true, "rpm": true} - pkgVerbs = map[string]bool{"install": true, "add": true, "in": true, "reinstall": true} + pkgTools = map[string]bool{"apt-get": true, "apt": true, "apk": true, "dnf": true, "dnf5": true, "yum": true, "microdnf": true, "tdnf": true, "zypper": true, "rpm": true} + pkgVerbs = map[string]bool{"install": true, "add": true, "in": true, "reinstall": true, "localinstall": true} // pkgValueFlags are package-manager options followed by a separate value. pkgValueFlags = map[string]bool{"-t": true, "-o": true, "-X": true, "--repository": true, "--virtual": true, "-c": true, "--root": true, - "-p": true, "--target-release": true, "--option": true, "--repo": true, "--setopt": true, "--enablerepo": true, "--disablerepo": true} + "-p": true, "--target-release": true, "--option": true, "--repo": true, "--setopt": true, "--enablerepo": true, "--disablerepo": true, + "--installroot": true, "--releasever": true, "--dbpath": true, "--prefix": true} ) var ( @@ -963,6 +978,49 @@ func packageName(w string) string { return rpmArchRE.ReplaceAllString(name, "") } +// unreadableArg marks a package file installArgs found but could not +// name. +const unreadableArg = "\x00unreadable:" + +// zypperArg is zypper's java-17-openjdk=17.0.21.0 (or >=, <...). +var zypperArg = regexp.MustCompile(`^(java-(\d{1,2})-(openjdk|amazon-corretto)(?:-headless|-devel|-jdk)?)(=|>=|<=|>|<)(\S+)$`) + +// javaWord is a word a Java package file or URL carries. +var javaWord = regexp.MustCompile(`(?i)java|jdk|jre|corretto|temurin|zulu`) + +// globCandidates are names a Java package file could have, for deciding +// whether a pattern (*.rpm) could match one. +var globCandidates = []string{"java-17-openjdk-headless-17.0.21.0.9-1.el9.x86_64.rpm", "java-21-amazon-corretto-devel-21.0.13.1.2-1.x86_64.rpm", + "java-latest-openjdk-25.0.1.0.8-1.rolling.fc41.x86_64.rpm"} + +// rpmFileArg reads a package file argument (local or a URL, with any +// ?query or #fragment): name-version-release.arch.rpm gives the package +// name and version; a pattern that could match a Java package, or a Java +// URL whose file name is not given, is returned marked unreadable. ok is +// false for an argument that is not a package file. +func rpmFileArg(w string) (string, bool) { + u := w + if i := strings.IndexAny(u, "?#"); i >= 0 { + u = u[:i] + } + base := path.Base(u) + if strings.HasSuffix(strings.ToLower(base), ".rpm") { + if strings.ContainsAny(base, "*?[") { + for _, c := range globCandidates { + if ok, _ := path.Match(base, c); ok { + return unreadableArg + w, true + } + } + return "", true + } + return rpmArchRE.ReplaceAllString(base[:len(base)-len(".rpm")], ""), true + } + if strings.Contains(w, "://") && javaWord.MatchString(w) { + return unreadableArg + w, true + } + return "", false +} + // installArgs returns the package arguments of the install commands on a // RUN line: the words after " [flags] install|add", without flags, // their values, paths and URLs. @@ -1001,12 +1059,19 @@ func installArgs(run string) []string { } for j := i + 1; j < len(words); j++ { w := words[j] + if !strings.HasPrefix(w, "-") { + if a, ok := rpmFileArg(w); ok { + if a != "" { + out = append(out, a) + } + continue + } + } switch { - case strings.HasSuffix(w, ".rpm"): - // A package file, local or a URL: its name is - // name-version-release.arch.rpm. - out = append(out, rpmArchRE.ReplaceAllString(strings.TrimSuffix(path.Base(w), ".rpm"), "")) case tool == "rpm": + if pkgValueFlags[w] { + j++ + } case pkgValueFlags[w]: j++ case strings.HasPrefix(w, "-"), strings.Contains(w, "://"), strings.HasPrefix(w, "/"), strings.HasPrefix(w, "$"): @@ -1027,6 +1092,7 @@ type pkgHit struct { feature int // 0: the distribution's default (default-jre) varName bool // the name holds a variable where the release is latest bool // java-latest-openjdk: no release in the name + unreadable bool // a package file whose name cannot be read } func opOf(v string) string { @@ -1058,6 +1124,10 @@ var microsoftLines = map[int]bool{17: true, 21: true, 25: true} var vendorNames = map[string]string{"distribution": "the distribution", "corretto": "Amazon Corretto", "temurin": "Eclipse Temurin", "zulu": "Azul Zulu", "msopenjdk": "Microsoft", "sapmachine": "SapMachine"} +// preRelease reports a Debian or rpm pre-release version: 21.0.13.1~2ea-1 +// sorts before 21.0.13.1 and is not the release. +func preRelease(ver string) bool { return strings.Contains(ver, "~") } + // pinnedVersion is the Java version a package pin fixes, or "" for a pin // that matches several releases (17.*, ~17, 17). func pinnedVersion(h pkgHit) string { @@ -1094,6 +1164,14 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { Fix: "Check which Java release the variable selects: 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update have the fix."}) return } + if h.unreadable { + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, + Props: map[string]string{"package": refs.CleanText(h.name, 120), "manager": h.mgr}, + Reason: "a package file named by a pattern or a URL that does not give its file name: which Java package it is, this scan cannot read", + Message: fmt.Sprintf("installs %s, a package file whose name this scan cannot read: not checked for the Java4Shell fix", refs.CleanText(h.name, 120)), + Fix: "Check which Java package the file is: 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update, or the distribution's backport, have the fix."}) + return + } if h.latest { s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: map[string]string{"package": h.name, "manager": h.mgr}, @@ -1147,6 +1225,9 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { if up := pinnedVersion(h); up != "" { props["current"] = h.ver v, _ := knowledge.Parse(up) + if preRelease(h.ver) { + v.EA = true + } st, why := knowledge.Judge(v) if st == knowledge.Fixed && h.mgr == "rpm" && h.vendor == "distribution" && rpmNumbers(h.ver) != 5 { // Red Hat and Fedora write five numbers; another count From 0895c71d443c2c5e5f3eca0560f2dfca07a3b308 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:48:29 +0000 Subject: [PATCH 066/119] java4shell: GraalVM clears capped at the releases looked at; rows per distribution (round 2, item 5) - GraalVM Community's own numbers clear Java 8 to 16 only for 19.x to 22.3 (minor 0 to 3, not 21.3): 99.9.9.r11-grl and 21.30.0.r11-grl were cleared and are now not checked. - The Java line must end the name and have no leading zero: graalvm-22.3.0+java17.0.9, graalvm-22.3.0+java11+java17 and 22.3.0.r017 are not read as a release. - sdkman graalce is not cleared by GraalVM numbers (only grl was seen with .rNN names). - GraalVMFixed is keyed by distribution (oracle, community) and Java line; a row applies only to builds of its distribution, known from the release file's IMPLEMENTOR, the version-manager name or the image. - graalVersion judges an exact JDK-numbered GraalVM version through JudgeGraalVM with its distribution (a fixed row now clears it instead of reading as not checked with a stale reason), and gives a moving version its own reason. Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/assess/assess.go | 4 +- .../internal/knowledge/coverage_test.go | 52 ++++++++++++++++--- .../java4shell/internal/knowledge/graalvm.go | 47 +++++++++++++---- .../java4shell/internal/repo/coverage_test.go | 22 ++++++++ detectors/java4shell/internal/repo/graalvm.go | 52 ++++++++++++++----- detectors/java4shell/internal/repo/refscan.go | 2 +- detectors/java4shell/internal/repo/repo.go | 4 +- 7 files changed, 149 insertions(+), 34 deletions(-) diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index 7e1d926..b346a77 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -228,7 +228,9 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi } judgeVersion, judgeBackport := knowledge.Judge, knowledge.JudgeBackport if f.GraalVM { - judgeVersion, judgeBackport = knowledge.JudgeGraalVM, knowledge.JudgeBackportGraalVM + dist := knowledge.GraalVMDist(f.Vendor) + judgeVersion = func(v knowledge.Version) (knowledge.Status, string) { return knowledge.JudgeGraalVM(v, dist) } + judgeBackport = knowledge.JudgeBackportGraalVM } ks, kwhy := judgeVersion(v) f.Release = ks diff --git a/detectors/java4shell/internal/knowledge/coverage_test.go b/detectors/java4shell/internal/knowledge/coverage_test.go index 51aaef8..02f4524 100644 --- a/detectors/java4shell/internal/knowledge/coverage_test.go +++ b/detectors/java4shell/internal/knowledge/coverage_test.go @@ -48,17 +48,17 @@ func TestGraalVM(t *testing.T) { {"11.0.33+8-LTS-jvmci-21.3-b99", NotAffected}, } { v, _ := Parse(c.v) - if st, why := JudgeGraalVM(v); st != c.want || why == "" { + if st, why := JudgeGraalVM(v, GraalVMOracle); st != c.want || why == "" { t.Errorf("JudgeGraalVM(%s) = %s (%s), want %s", c.v, st, why, c.want) } } // A published fixed GraalVM build, once listed, clears later builds. saved := GraalVMFixed t.Cleanup(func() { GraalVMFixed = saved }) - GraalVMFixed = map[int]Build{21: {Version: []int{21, 0, 13, 1}, Build: 2}} + GraalVMFixed = map[GraalVMKey]Build{{GraalVMOracle, 21}: {Version: []int{21, 0, 13, 1}, Build: 2}} for v, want := range map[string]Status{"21.0.13.1+2-LTS-jvmci-23.1-b99": Fixed, "21.0.13.1+1-LTS-jvmci-23.1-b99": Vulnerable, "21.0.13.0.3+1-LTS-jvmci-23.1-b99": Vulnerable} { p, _ := Parse(v) - if st, why := JudgeGraalVM(p); st != want { + if st, why := JudgeGraalVM(p, GraalVMOracle); st != want { t.Errorf("with a fixed build listed, JudgeGraalVM(%s) = %s (%s), want %s", v, st, why, want) } } @@ -134,7 +134,7 @@ func TestGraalVMReleaseStrict(t *testing.T) { func TestGraalVMRow(t *testing.T) { saved := GraalVMFixed t.Cleanup(func() { GraalVMFixed = saved }) - GraalVMFixed = map[int]Build{17: {Version: []int{17, 0, 21, 1}, Build: 2}} + GraalVMFixed = map[GraalVMKey]Build{{GraalVMOracle, 17}: {Version: []int{17, 0, 21, 1}, Build: 2}} for v, want := range map[string]Status{ "17.0.21.1+2-jvmci-23.0-b99": Fixed, "17.0.21.1+3-jvmci-23.0-b99": Fixed, @@ -149,7 +149,7 @@ func TestGraalVMRow(t *testing.T) { if !ok { t.Fatalf("Parse(%s)", v) } - if st, why := JudgeGraalVM(p); st != want { + if st, why := JudgeGraalVM(p, GraalVMOracle); st != want { t.Errorf("row 17.0.21.1+2: JudgeGraalVM(%s) = %s (%s), want %s", v, st, why, want) } } @@ -160,13 +160,13 @@ func TestGraalVMRow(t *testing.T) { func TestGraalVMRowLaterBuild(t *testing.T) { saved := GraalVMFixed t.Cleanup(func() { GraalVMFixed = saved }) - GraalVMFixed = map[int]Build{21: {Version: []int{21, 0, 13, 1}, Build: 5}} + GraalVMFixed = map[GraalVMKey]Build{{GraalVMOracle, 21}: {Version: []int{21, 0, 13, 1}, Build: 5}} for v, want := range map[string]Status{ "21.0.13.1+3-jvmci-23.1-b99": Vulnerable, "21.0.13.1+5-jvmci-23.1-b99": Fixed, } { p, _ := Parse(v) - if st, why := JudgeGraalVM(p); st != want { + if st, why := JudgeGraalVM(p, GraalVMOracle); st != want { t.Errorf("row 21.0.13.1+5: JudgeGraalVM(%s) = %s (%s), want %s", v, st, why, want) } } @@ -186,3 +186,41 @@ func TestGraalVMOwnNumbersNotJava(t *testing.T) { } } } + +// Round 2, item 5: a GraalVM row is one distribution's; Community clears +// stop at the GraalVM releases looked at (19 to 22.3). +func TestGraalVMRound2(t *testing.T) { + saved := GraalVMFixed + t.Cleanup(func() { GraalVMFixed = saved }) + GraalVMFixed = map[GraalVMKey]Build{{GraalVMOracle, 17}: {Version: []int{17, 0, 21, 2}, Build: 1}} + for _, c := range []struct { + v, dist string + want Status + }{ + {"17.0.21.2+1-jvmci-23.0-b99", GraalVMOracle, Fixed}, + {"17.0.21.2+1-jvmci-23.0-b99", GraalVMCommunity, Unknown}, // another distribution's row + {"17.0.21.2+1-jvmci-23.0-b99", "", Unknown}, + {"17.0.21.1+2-jvmci-23.0-b99", GraalVMOracle, Vulnerable}, // OpenJDK-fixed, older than the row + } { + p, _ := Parse(c.v) + if st, why := JudgeGraalVM(p, c.dist); st != c.want { + t.Errorf("JudgeGraalVM(%s, %q) = %s (%s), want %s", c.v, c.dist, st, why, c.want) + } + } + for _, c := range []struct { + graal string + java int + want Status + }{ + {"99.9.9", 11, Unknown}, + {"21.30.0", 11, Unknown}, + {"23.0.1", 11, Unknown}, + {"19.3.0", 8, NotAffected}, + {"22.3.0", 11, NotAffected}, + {"22.4.0", 11, Unknown}, + } { + if st, why := JudgeGraalVMRelease(c.graal, c.java, true); st != c.want { + t.Errorf("JudgeGraalVMRelease(%s, %d) = %s (%s), want %s", c.graal, c.java, st, why, c.want) + } + } +} diff --git a/detectors/java4shell/internal/knowledge/graalvm.go b/detectors/java4shell/internal/knowledge/graalvm.go index f479a32..95e78b4 100644 --- a/detectors/java4shell/internal/knowledge/graalvm.go +++ b/detectors/java4shell/internal/knowledge/graalvm.go @@ -22,9 +22,34 @@ type Build struct { Build int // -1: every build of Version } -// GraalVMFixed is, per Java line, the first GraalVM build with the fix. -// Empty: no fixed GraalVM build had been published as of Checked. -var GraalVMFixed = map[int]Build{} +// GraalVM distributions, whose fixed builds are published separately. +const ( + GraalVMOracle = "oracle" // Oracle GraalVM (and GraalVM Enterprise) + GraalVMCommunity = "community" // GraalVM Community Edition +) + +// GraalVMKey is a distribution's Java line. +type GraalVMKey struct { + Dist string + Feature int +} + +// GraalVMFixed is, per distribution and Java line, the first GraalVM build +// with the fix. Empty: no fixed GraalVM build had been published as of +// Checked. +var GraalVMFixed = map[GraalVMKey]Build{} + +// GraalVMDist names the distribution a release file's IMPLEMENTOR names, +// "" when it names neither. +func GraalVMDist(implementor string) string { + switch implementor { + case "GraalVM Community": + return GraalVMCommunity + case "Oracle Corporation": + return GraalVMOracle + } + return "" +} // graalVMAffected names what Oracle lists, for reasons. const graalVMAffected = "Oracle names GraalVM for JDK 17.0.21.0.3 and 21.0.13.0.3 and GraalVM Enterprise Edition 21.3.20.0.3 as affected" @@ -33,10 +58,11 @@ const graalVMAffected = "Oracle names GraalVM for JDK 17.0.21.0.3 and 21.0.13.0. // ("17.0.6+10-jvmci-22.3-b13", "21.0.5+9-LTS-jvmci-23.1-b48"). func IsGraalVM(version string) bool { return strings.Contains(version, "-jvmci-") } -// JudgeGraalVM judges a GraalVM build by its JDK version. It is vulnerable -// wherever the OpenJDK release would be; it is fixed only at or past a -// fixed GraalVM build listed in GraalVMFixed. -func JudgeGraalVM(v Version) (Status, string) { +// JudgeGraalVM judges a GraalVM build of a distribution (GraalVMOracle, +// GraalVMCommunity, "" when not known) by its JDK version. It is +// vulnerable wherever the OpenJDK release would be; it is fixed only at or +// past a fixed build of the same distribution listed in GraalVMFixed. +func JudgeGraalVM(v Version, dist string) (Status, string) { st, why := Judge(v) switch st { case NotAffected: @@ -46,7 +72,7 @@ func JudgeGraalVM(v Version) (Status, string) { } // A row clears only what OpenJDK's data also judges fixed: a vendor // build number in the fourth place or a later update stays unknown. - if fx, ok := GraalVMFixed[v.Feature()]; ok && st == Fixed { + if fx, ok := GraalVMFixed[GraalVMKey{dist, v.Feature()}]; ok && dist != "" && st == Fixed { c := Compare(v.Nums, fx.Version) // A version without its build is taken as the GA build, as for OpenJDK. if c < 0 || c == 0 && fx.Build >= 0 && v.Build >= 0 && v.Build < fx.Build { @@ -112,10 +138,13 @@ func JudgeGraalVMRelease(graal string, java int, community bool) (Status, string nums = append(nums, n) } is213 := Compare(nums[:2], []int{21, 3}) == 0 + // The GraalVM releases looked at are 19.x to 22.3 (minor versions 0 + // to 3); later ones are numbered by the JDK. + looked := nums[0] >= 19 && nums[0] <= 22 && nums[1] <= 3 switch { case java < 8: return Unknown, fmt.Sprintf("%s: not a Java line GraalVM is built for", name) - case java < firstVBMIDecode && community && !is213: + case java < firstVBMIDecode && community && looked && !is213: return NotAffected, fmt.Sprintf("%s is built on OpenJDK %d, which has no x86-64 Base64 decode intrinsic (the Java 11 build of GraalVM Community 22.3.1 carries no decoder stubs)", name, java) case java < firstVBMIDecode: return Unknown, fmt.Sprintf("%s: OpenJDK %d has no decoder, but whether this build carries one is not known (GraalVM Enterprise Edition 21.3.20.0.3 is listed as affected without its Java line, and other vendors' GraalVM builds were not checked)", name, java) diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index 0f21b7d..f391b3b 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -443,3 +443,25 @@ func TestRPMForms(t *testing.T) { } } } + +// Round 2, items 5 and 7: GraalVM names the data cannot settle. +func TestGraalVMRound2Repo(t *testing.T) { + res := scan(t, tree(t, map[string]string{ + "a/.sdkmanrc": "java=99.9.9.r11-grl\n", + "b/.sdkmanrc": "java=21.30.0.r11-grl\n", + "c/.sdkmanrc": "java=22.3.0.r17-graalce\n", + "d/.sdkmanrc": "java=22.3.0.r017-grl\n", + "a/.tool-versions": "java graalvm-22.3.0+java17.0.9\n", + "b/.tool-versions": "java graalvm-22.3.0+java11+java17\n", + "c/.tool-versions": "java mandrel-22.3.1.0-Final+java11\n", + })) + checkAll(t, res, []want{ + {"a/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {"b/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {"c/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {"d/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {"a/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"b/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"c/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + }) +} diff --git a/detectors/java4shell/internal/repo/graalvm.go b/detectors/java4shell/internal/repo/graalvm.go index fe35215..20c7e56 100644 --- a/detectors/java4shell/internal/repo/graalvm.go +++ b/detectors/java4shell/internal/repo/graalvm.go @@ -18,18 +18,32 @@ var graalVendors = map[string]bool{"grl": true, "graal": true, "graalce": true, func isGraal(vendor string) bool { return graalVendors[vendor] } +// graalDist is the GraalVM distribution a vendor name or family names, +// for its fixed builds; "" for NIK, Mandrel and unknown names. +func graalDist(vendor string) string { + switch vendor { + case "graal", "oracle-graalvm", "Oracle GraalVM": + return knowledge.GraalVMOracle + case "graalce", "grl", "graalvm", "graalvm-community", "GraalVM CE", "GraalVM Community": + return knowledge.GraalVMCommunity + } + return "" +} + // graalRelease is a GraalVM release in GraalVM's own numbers with the Java // line it is for: sdkman 22.3.1.r17, asdf graalvm-22.3.1+java17, mandrel // 22.3.1.0-Final+java17. var ( - sdkmanGraal = regexp.MustCompile(`^(\d{1,3}(?:\.\d{1,9}){1,4})\.r(\d{1,2})$`) - javaLine = regexp.MustCompile(`java(\d{1,2})\b`) + sdkmanGraal = regexp.MustCompile(`^(\d{1,3}(?:\.\d{1,9}){1,4})\.r([1-9]\d?)$`) + // javaLine ends the name: graalvm-22.3.0+java17.0.9 and + // graalvm-22.3.0+java11+java17 are not read. + javaLine = regexp.MustCompile(`[+-]java([1-9]\d?)$`) ) // graalTag judges a GraalVM image tag: vulnerable where the OpenJDK // release would be, and otherwise unknown until a fixed GraalVM build is // known (the image has to be read). -func graalTag(tv TagVersion, st knowledge.Status, why string) (knowledge.Status, string) { +func graalTag(tv TagVersion, st knowledge.Status, why, dist string) (knowledge.Status, string) { if knowledge.GraalVMOwnNumber(tv.Text) { return knowledge.Unknown, ownNumberWhy(tv.Text) } @@ -42,7 +56,7 @@ func graalTag(tv TagVersion, st knowledge.Status, why string) (knowledge.Status, if tv.Exact || len(tv.Nums) >= 3 { // No fixed GraalVM build is known, so the newest release a tag // such as 21.0.13 names is not fixed either. - gs, gwhy := knowledge.JudgeGraalVM(knowledge.Version{Nums: tv.Nums, Build: tv.OpenJDKBuild}) + gs, gwhy := knowledge.JudgeGraalVM(knowledge.Version{Nums: tv.Nums, Build: tv.OpenJDKBuild}, dist) return gs, "the tag names Java " + tv.Text + ": " + gwhy } return knowledge.Unknown, why @@ -97,9 +111,11 @@ func (s *scanner) graalOwn(rel string, line int, graal string, java int, communi // graalVersion handles a GraalVM release named by its JDK version // (sdkman 21.0.5-graal, asdf oracle-graalvm-21.0.5) once judgeVersion has -// judged it as a JDK: a fixed or unknown verdict becomes not checked, since -// no fixed GraalVM build is known; a vulnerable one names GraalVM. -func (s *scanner) graalVersion(rel string, line int, tv TagVersion, st knowledge.Status, why, source string, props map[string]string) { +// judged it as a JDK (st, why). An exact version is judged as a GraalVM +// build of its distribution (dist): vulnerable where the JDK is, fixed only +// at a listed fixed build of that distribution, otherwise not checked. A +// moving version is vulnerable where the whole line is, else not checked. +func (s *scanner) graalVersion(rel string, line int, tv TagVersion, st knowledge.Status, why, source, dist string, props map[string]string) { verText := tv.Text if knowledge.GraalVMOwnNumber(verText) { s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, Reason: ownNumberWhy(verText), @@ -108,8 +124,20 @@ func (s *scanner) graalVersion(rel string, line int, tv TagVersion, st knowledge Props: props}) return } - switch st { - case knowledge.NotAffected: + if st == knowledge.NotAffected { + return + } + gs, gwhy := st, why + switch { + case tv.Exact: + gs, gwhy = knowledge.JudgeGraalVM(knowledge.Version{Nums: tv.Nums, Build: tv.OpenJDKBuild}, dist) + case st == knowledge.Vulnerable: + gwhy = "GraalVM: " + why + default: + gs, gwhy = knowledge.Unknown, fmt.Sprintf("the version names the newest GraalVM release of Java %s when it is installed, and no fixed GraalVM build had been published as of %s", verText, knowledge.Checked) + } + switch gs { + case knowledge.Fixed, knowledge.NotAffected: return case knowledge.Vulnerable: rule, level := RuleJavaPin, "warning" @@ -118,14 +146,10 @@ func (s *scanner) graalVersion(rel string, line int, tv TagVersion, st knowledge rule, level = RuleLine, "error" msg = fmt.Sprintf("%s selects GraalVM for Java %s, a line that received no Java4Shell fix", source, verText) } - s.add(Finding{Rule: rule, File: rel, Line: line, Level: level, Status: StatusVulnerable, Reason: "GraalVM: " + why, Message: msg, + s.add(Finding{Rule: rule, File: rel, Line: line, Level: level, Status: StatusVulnerable, Reason: gwhy, Message: msg, Fix: graalFix(tv.Nums[0], source), Props: props}) return } - gwhy := why + "; no fixed GraalVM build had been published as of " + knowledge.Checked - if tv.Exact { - _, gwhy = knowledge.JudgeGraalVM(knowledge.Version{Nums: tv.Nums, Build: -1}) - } s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, Reason: gwhy, Message: fmt.Sprintf("%s selects GraalVM for Java %s: not checked for the Java4Shell fix", source, verText), Fix: "Check that this GraalVM release includes the fix; no fixed GraalVM build had been published as of " + knowledge.Checked + ".", diff --git a/detectors/java4shell/internal/repo/refscan.go b/detectors/java4shell/internal/repo/refscan.go index 4c5cb9b..c0d8c50 100644 --- a/detectors/java4shell/internal/repo/refscan.go +++ b/detectors/java4shell/internal/repo/refscan.go @@ -82,7 +82,7 @@ func (s *scanner) judgeRef(r refs.Ref, opts Options) { props["current"] = tv.Text st, why := JudgeTag(tv) if fam.GraalVM { - st, why = graalTag(tv, st, why) + st, why = graalTag(tv, st, why, graalDist(fam.Vendor)) } switch st { case knowledge.Unknown: diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index c6b1d0e..2bb72a1 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -348,7 +348,7 @@ func (s *scanner) judgeVersion(rel string, line, col int, verText, source, vendo props["vendor"] = vendor } if isGraal(vendor) { - s.graalVersion(rel, line, tv, st, why, source, props) + s.graalVersion(rel, line, tv, st, why, source, graalDist(vendor), props) return } if fx := knowledge.FixedVersion(tv.Nums[0]); fx != "" { @@ -436,7 +436,7 @@ func (s *scanner) sdkmanrc(rel, text string) { } if isGraal(m[2]) { if g, java, ok := graalNamed(m[1]); ok { - s.graalOwn(rel, i+1, g, java, m[2] == "grl" || m[2] == "graalce", strings.TrimSpace(strings.SplitN(l, "=", 2)[1]), ".sdkmanrc") + s.graalOwn(rel, i+1, g, java, m[2] == "grl", strings.TrimSpace(strings.SplitN(l, "=", 2)[1]), ".sdkmanrc") continue } } From f895079b9a1e47d40d358b266f38c508567e1c1f Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:49:14 +0000 Subject: [PATCH 067/119] java4shell: numbers that are not Java versions are not checked anywhere; FACTS.md (round 2, item 6) A version whose second number is not 0 (GraalVM Community's 25.5.5.0.3, 25.1.3) was kept out of Java parsing only in GraalVM names; a bare .java-version or .tool-versions value, another vendor's asdf name (openjdk-25.5.5.0.3), setup-java (oracle 25.1.3) and image tags read it as Java. knowledge.NotJava now marks it, and version files, setup-java and tags report it as not checked. FACTS.md: the Innovation row says where these numbers are kept out and adds asdf's graalvm-community-25.0.5.0.3 naming; the Red Hat row describes the os-release witness and the five-number rule and marks the IMPLEMENTOR text and the 17.0.21+9-LTS line unverified; the closing section no longer says the table overrides the libjvm's version. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/FACTS.md | 7 +++--- .../java4shell/internal/knowledge/graalvm.go | 11 ++++++++- .../java4shell/internal/repo/coverage_test.go | 24 +++++++++++++++++++ detectors/java4shell/internal/repo/images.go | 3 +++ detectors/java4shell/internal/repo/repo.go | 7 ++++++ 5 files changed, 48 insertions(+), 4 deletions(-) diff --git a/detectors/java4shell/FACTS.md b/detectors/java4shell/FACTS.md index ab27f45..835d060 100644 --- a/detectors/java4shell/FACTS.md +++ b/detectors/java4shell/FACTS.md @@ -98,14 +98,14 @@ The lead read these; they could not be fetched from the research host. Facts her | GraalVM EE 21.3 builds: which Java lines exist (JDK 11 and 17 at least; a Java 8 build may exist too, and Oracle's Java 8 Performance Pack does carry the decoder) and which of them Oracle's listing of 21.3.20.0.3 covers are **not verified**. The detector judges a GraalVM JDK 17 build by its version (vulnerable today), a GraalVM JDK 8 or 11 runtime vulnerable when its libjvm carries the decoder stubs, and leaves 21.3.x for Java 8 or 11 named in a version file not checked | Oracle CSPU; **unverified** | | No fixed GraalVM build is known, and GraalVM's fixed builds need not follow OpenJDK's numbering, so the detector judges a GraalVM build at or past the OpenJDK fixed release as **unknown**, never fixed, until a fixed GraalVM build is listed in `knowledge.GraalVMFixed` (empty). A row clears only what OpenJDK's data also judges fixed | lead and reviewer, 2026-11-18; graalvm/graalvm-ce-builds releases | | sdkman and asdf name GraalVM releases in GraalVM's numbers (`22.3.1.r17-grl`, `graalvm-22.3.1+java17`). From the four images above (**inferred** for the releases not looked at): GraalVM Community 22.3.0 for 17, and Community releases for Java 8 to 16 other than 21.3.x, are not affected; 22.3.1 and later for 17, and any release for 18 and later, are vulnerable. Not checked: `22.3.r17` (no patch), 21.3.x for any line, malformed numbers, Java lines below 8, and Liberica NIK and Mandrel releases that would otherwise be cleared (their numbering is assumed to follow GraalVM's, not checked against their releases) | observations above; **inferred** | -| GraalVM Community's Innovation releases carry their own numbers: graal-25.5.5.0.3 is JDK 25.0.5.0.3, graal-25.1.3 is JDK 25.0.3. A number whose second field is not 0 (Java's has been 0 since JDK 10) is GraalVM's own and is never read as a Java version | [graalvm/graalvm-ce-builds releases](https://github.com/graalvm/graalvm-ce-builds/releases) (reviewer, 2026-11-18) | +| GraalVM Community's Innovation releases carry their own numbers: graal-25.5.5.0.3 is JDK 25.0.5.0.3, graal-25.1.3 is JDK 25.0.3; asdf names the same releases by the JDK (`graalvm-community-25.0.5.0.3`). A number whose second field is not 0 (Java's has been 0 since JDK 10) is not read as a Java version anywhere: in a GraalVM name, a bare version file (`.java-version` 25.5.5.0.3), another vendor's name (`openjdk-25.5.5.0.3`), setup-java or an image tag it is not checked | [graalvm/graalvm-ce-builds releases](https://github.com/graalvm/graalvm-ce-builds/releases) (reviewer, 2026-11-18) | | Whether GraalVM Native Image binaries (SubstrateVM, no libjvm) carry a port of the decoder is **not known**; the detector does not look at them | n/a | ## Red Hat | Fact | Source | | --- | --- | -| Red Hat backports fixes into the update it ships, so a fixed Red Hat build can keep the upstream version in its libjvm and differ only in the rpm release. The detector keeps a backport table, `knowledge.RedHatFixed` (package, dist tag such as el9_6, fixed EVR, advisory). A row speaks only to rpm releases of its own stream (a number and that dist tag: not Oracle Linux's 2.0.1.el9 or AlmaLinux's .alma; CentOS Stream's el9 cannot be told from RHEL's el9) and its own upstream update and build. It clears an installed runtime only when the libjvm is a released, non-GraalVM HotSpot of exactly that update and build and the release file names `Red Hat, Inc.`; the rpm itself is named by the install path, since the rpm database is not read, so a contradicting runtime is reported unknown. It is **empty**: Red Hat had published no fixed build on 2026-11-18 | Red Hat CVE page (lead) | +| Red Hat backports fixes into the update it ships, so a fixed Red Hat build can keep the upstream version in its libjvm and differ only in the rpm release. The detector keeps a backport table, `knowledge.RedHatFixed` (package, dist tag such as el9_6, fixed EVR, advisory). A row speaks only to rpm releases of its own stream (a number and that dist tag: not Oracle Linux's 2.0.1.el9 or AlmaLinux's .alma) and its own upstream update and build, written in Red Hat's five plain numbers. It clears an installed runtime only when the libjvm is a released, non-GraalVM HotSpot of exactly that update and build, the release file names `Red Hat, Inc.` and the target's os-release says `ID=rhel` (Rocky, AlmaLinux and CentOS Stream reuse Red Hat's releases and implementor); a library that is another build keeps its own verdict, and a missing witness gives unknown. The rpm itself is named by the install path, since the rpm database is not read. **Unverified:** that Red Hat's release files say `IMPLEMENTOR="Red Hat, Inc."` and its libjvm reads `17.0.21+9-LTS` for rpm 17.0.21.0.9 (no Red Hat image could be read here). The table is **empty**: Red Hat had published no fixed build on 2026-11-18 | Red Hat CVE page (lead); **unverified** layout | | RHEL 8/9 and UBI install the JDK in `/usr/lib/jvm/java-17-openjdk--.` with `jre-17`, `jre` and `/etc/alternatives` symlinks into it; the rpm version appends the build to the update (17.0.21.0.9 is 17.0.21+9). **Not verified on a real image here**: registry.access.redhat.com and cdn-ubi.redhat.com (dnf in `redhat/ubi9`) are unreachable from the research host; the detector's tests use that layout | Red Hat packaging convention; unverified | | UBI OpenJDK images (`registry.access.redhat.com/ubi9/openjdk-21`, `-runtime`, also on registry.redhat.io) are tagged by image release (1.20, 1.20-2.1729089285), not by Java update. With the table empty, the repo scan reports 21 and 25 (every release has the decoder) and 17 at `latest` as vulnerable, other 17 tags (older images could predate 17.0.6) as not checked and pulled. `openjdk-8` and `openjdk-11` are skipped by name, as `eclipse-temurin:11` is (**inferred**: OpenJDK 8 and 11 have no decode intrinsic; Red Hat's builds were not read). Any other line in the name is not checked and pulled | lead; **inferred** | @@ -120,7 +120,8 @@ OpenJDK fix commit and Amazon Corretto's changelog. - The version that decides is the one inside the libjvm (` () for - JRE ()`), read from the binary, with the `release` file as a second witness; the CPU architecture comes from the ELF, PE or Mach-O header. - A packaged JDK (apk, dpkg, rpm) is judged by the same upstream version: no distribution has published a fixed package or a backport - statement yet. Red Hat's fixed builds, once published, go into the Red Hat backport table, which overrides the libjvm's version. + statement yet. Red Hat's fixed builds, once published, go into the Red Hat backport table, which clears a + runtime only when its libjvm is that exact build and the release file and os-release confirm Red Hat (see "Red Hat"). - A GraalVM JDK is judged by its JDK version, but never fixed until a fixed GraalVM build is listed. - Findings carry CVSS 8.1, the OpenJDK and Oracle score. - No marker in the binary separates fixed from unfixed code: the stub is generated at run time by C++ code, and the fix only adds a compare diff --git a/detectors/java4shell/internal/knowledge/graalvm.go b/detectors/java4shell/internal/knowledge/graalvm.go index 95e78b4..7d728c8 100644 --- a/detectors/java4shell/internal/knowledge/graalvm.go +++ b/detectors/java4shell/internal/knowledge/graalvm.go @@ -115,7 +115,16 @@ var ( // since JDK 10. func GraalVMOwnNumber(s string) bool { v, ok := Parse(s) - return ok && v.Feature() >= 10 && len(v.Nums) >= 2 && v.Nums[1] != 0 + return ok && NotJava(v.Nums) +} + +// NotJava reports numbers that are not a Java version: since JDK 10 the +// second number (the interim release) has always been 0. +func NotJava(nums []int) bool { return len(nums) >= 2 && nums[0] >= 10 && nums[1] != 0 } + +// NotJavaWhy says why a version is not judged. +func NotJavaWhy(v string) string { + return fmt.Sprintf("%s is not a Java version: Java's second number has been 0 since JDK 10 (GraalVM Community's own release numbers, such as 25.5.5.0.3 for JDK 25.0.5.0.3, look like this), so which Java update it names is not known", v) } // graalRelease is a well-formed GraalVM release number: two to four diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index f391b3b..f56cea8 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -465,3 +465,27 @@ func TestGraalVMRound2Repo(t *testing.T) { {"c/.tool-versions", 1, RuleNotChecked, StatusUnknown}, }) } + +// Round 2, item 6: a number whose second field is not 0 is not a Java +// version wherever it appears (GraalVM Community's 25.5.5.0.3). +func TestNotJavaNumbers(t *testing.T) { + res := scan(t, tree(t, map[string]string{ + ".java-version": "25.5.5.0.3\n", + "a/.tool-versions": "java 25.5.5.0.3\n", + "b/.tool-versions": "java openjdk-25.5.5.0.3\n", + ".github/workflows/ci.yml": "jobs:\n a:\n steps:\n - uses: actions/setup-java@v5\n with:\n distribution: oracle\n java-version: 25.1.3\n", + "Dockerfile": "FROM eclipse-temurin:25.5.5\n", + })) + checkAll(t, res, []want{ + {".java-version", 1, RuleNotChecked, StatusUnknown}, + {"a/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"b/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {".github/workflows/ci.yml", 7, RuleNotChecked, StatusUnknown}, + {"Dockerfile", 1, RuleNotChecked, StatusUnknown}, + }) + for _, f := range res.Findings { + if !strings.Contains(f.Reason, "not a Java version") { + t.Errorf("%s:%d: %s", f.File, f.Line, f.Reason) + } + } +} diff --git a/detectors/java4shell/internal/repo/images.go b/detectors/java4shell/internal/repo/images.go index 002b002..49b9b11 100644 --- a/detectors/java4shell/internal/repo/images.go +++ b/detectors/java4shell/internal/repo/images.go @@ -163,6 +163,9 @@ func (f Family) ParseTag(tag string) (TagVersion, bool) { // both unfixed and fixed releases is Unknown: the image has to be read. func JudgeTag(tv TagVersion) (knowledge.Status, string) { nums := tv.Nums + if knowledge.NotJava(nums) { + return knowledge.Unknown, "the tag names " + tv.Text + ", which " + strings.TrimPrefix(knowledge.NotJavaWhy(tv.Text), tv.Text+" ") + } feature := nums[0] what := "the tag names Java " + tv.Text if !tv.Exact { diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 2bb72a1..4ec4fbe 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -347,6 +347,13 @@ func (s *scanner) judgeVersion(rel string, line, col int, verText, source, vendo if vendor != "" { props["vendor"] = vendor } + if knowledge.NotJava(tv.Nums) && !isGraal(vendor) { + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, Reason: knowledge.NotJavaWhy(verText), + Message: fmt.Sprintf("%s selects %s, which is not a Java version: not checked for the Java4Shell fix", source, verText), + Fix: "Check which Java release this selects: 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update have the fix.", + Props: props}) + return + } if isGraal(vendor) { s.graalVersion(rel, line, tv, st, why, source, graalDist(vendor), props) return From 314ecc260a11bd3742d69fedef5c2b694ab9a861 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:49:23 +0000 Subject: [PATCH 068/119] java4shell: gofmt Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/internal/repo/coverage_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index f56cea8..6a508ff 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -470,11 +470,11 @@ func TestGraalVMRound2Repo(t *testing.T) { // version wherever it appears (GraalVM Community's 25.5.5.0.3). func TestNotJavaNumbers(t *testing.T) { res := scan(t, tree(t, map[string]string{ - ".java-version": "25.5.5.0.3\n", - "a/.tool-versions": "java 25.5.5.0.3\n", - "b/.tool-versions": "java openjdk-25.5.5.0.3\n", + ".java-version": "25.5.5.0.3\n", + "a/.tool-versions": "java 25.5.5.0.3\n", + "b/.tool-versions": "java openjdk-25.5.5.0.3\n", ".github/workflows/ci.yml": "jobs:\n a:\n steps:\n - uses: actions/setup-java@v5\n with:\n distribution: oracle\n java-version: 25.1.3\n", - "Dockerfile": "FROM eclipse-temurin:25.5.5\n", + "Dockerfile": "FROM eclipse-temurin:25.5.5\n", })) checkAll(t, res, []want{ {".java-version", 1, RuleNotChecked, StatusUnknown}, From e4124bd33fefaca95d83f1b1e8cbe924d155261f Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:49:45 +0000 Subject: [PATCH 069/119] java4shell: asdf musl/jre/lite names; unsettled version-file pins are not checked (round 2, item 8) asdf's temurin-musl, temurin-jre-musl, corretto-musl, liberica-lite and sapmachine-musl names gave nothing; they are read now. An exact pin the release data does not settle (java=17.0.22-tem, temurin-17.0.22+7, setup-java 17.0.22) was dropped; it is now not checked, as an image tag of it is. (The Corretto + form, java-17-amazon-corretto-headless- 17.0.21+9-1.amzn2023.1, was fixed with item 3.) Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/repo/coverage_test.go | 25 +++++++++++++++++++ detectors/java4shell/internal/repo/repo.go | 11 ++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index 6a508ff..4a7e27f 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -489,3 +489,28 @@ func TestNotJavaNumbers(t *testing.T) { } } } + +// Round 2, item 8: asdf's musl, jre and lite names are read; version-file +// pins the data does not settle are not checked, as image tags are. +func TestVersionNamesAndUnsettled(t *testing.T) { + res := scan(t, tree(t, map[string]string{ + "a/.tool-versions": "java temurin-musl-21.0.5+11.0.LTS\n", + "b/.tool-versions": "java temurin-jre-musl-21.0.5+11.0.LTS\n", + "c/.tool-versions": "java corretto-musl-21.0.5.11.1\n", + "d/.tool-versions": "java liberica-lite-21.0.5+11\n", + "e/.tool-versions": "java sapmachine-musl-21.0.5\n", + "f/.tool-versions": "java temurin-17.0.22+7\n", + "a/.sdkmanrc": "java=17.0.22-tem\n", + ".github/workflows/ci.yml": "jobs:\n a:\n steps:\n - uses: actions/setup-java@v5\n with:\n distribution: zulu\n java-version: 17.0.22\n", + })) + checkAll(t, res, []want{ + {"a/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"b/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"c/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"d/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"e/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"f/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"a/.sdkmanrc", 1, RuleNotChecked, StatusUnknown}, + {".github/workflows/ci.yml", 7, RuleNotChecked, StatusUnknown}, + }) +} diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 4ec4fbe..b4f2e43 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -381,6 +381,12 @@ func (s *scanner) judgeVersion(rel string, line, col int, verText, source, vendo s.add(Finding{Rule: RuleLine, File: rel, Line: line, Level: "error", Status: StatusVulnerable, Reason: l.Note, Message: fmt.Sprintf("%s selects Java %s, a line that received no Java4Shell fix", source, verText), Fix: pinFix(tv.Nums[0], source), Props: props}) + } else if tv.Exact { + // A pinned release the data does not settle (17.0.22, a later + // update): not checked, as an image tag of it is. + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, Reason: why, + Message: fmt.Sprintf("%s selects Java %s: not checked for the Java4Shell fix", source, verText), + Fix: fmt.Sprintf("Check that Java %s includes %s.", verText, knowledge.BugRef), Props: props}) } } _ = col @@ -457,9 +463,10 @@ func (s *scanner) sdkmanrc(rel, text string) { } // asdfJava reads asdf-java and mise names: temurin-21.0.5+11.0.LTS, -// corretto-21.0.5.11.1, openjdk-21.0.2, sapmachine-21.0.5, zulu-21.38.21 +// corretto-21.0.5.11.1, openjdk-21.0.2, sapmachine-21.0.5, temurin-jre-musl-21.0.5, +// liberica-lite-21.0.5, zulu-21.38.21 // (a Zulu version, not a Java version: not judged). -var asdfJava = regexp.MustCompile(`^(?:(adoptopenjdk|temurin|corretto|openjdk|sapmachine|liberica|microsoft|oracle|semeru-openj9|semeru|dragonwell|kona|zulu|graalvm|graalvm-community|oracle-graalvm|mandrel|jetbrains)-)?(?:jre-|jdk-|openj9-)?(\d[\d.]*)`) +var asdfJava = regexp.MustCompile(`^(?:(adoptopenjdk|temurin|corretto|openjdk|sapmachine|liberica|microsoft|oracle|semeru-openj9|semeru|dragonwell|kona|zulu|graalvm|graalvm-community|oracle-graalvm|mandrel|jetbrains)-)?(?:(?:jre|jdk|openj9|musl|lite)-)*(\d[\d.]*)`) func (s *scanner) asdfValue(rel string, line int, value, source string) { m := asdfJava.FindStringSubmatch(value) From a359b55da1145ddee7241fb602837597a446679c Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:49:53 +0000 Subject: [PATCH 070/119] java4shell: gofmt Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/repo/coverage_test.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index 4a7e27f..611fc0d 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -494,13 +494,13 @@ func TestNotJavaNumbers(t *testing.T) { // pins the data does not settle are not checked, as image tags are. func TestVersionNamesAndUnsettled(t *testing.T) { res := scan(t, tree(t, map[string]string{ - "a/.tool-versions": "java temurin-musl-21.0.5+11.0.LTS\n", - "b/.tool-versions": "java temurin-jre-musl-21.0.5+11.0.LTS\n", - "c/.tool-versions": "java corretto-musl-21.0.5.11.1\n", - "d/.tool-versions": "java liberica-lite-21.0.5+11\n", - "e/.tool-versions": "java sapmachine-musl-21.0.5\n", - "f/.tool-versions": "java temurin-17.0.22+7\n", - "a/.sdkmanrc": "java=17.0.22-tem\n", + "a/.tool-versions": "java temurin-musl-21.0.5+11.0.LTS\n", + "b/.tool-versions": "java temurin-jre-musl-21.0.5+11.0.LTS\n", + "c/.tool-versions": "java corretto-musl-21.0.5.11.1\n", + "d/.tool-versions": "java liberica-lite-21.0.5+11\n", + "e/.tool-versions": "java sapmachine-musl-21.0.5\n", + "f/.tool-versions": "java temurin-17.0.22+7\n", + "a/.sdkmanrc": "java=17.0.22-tem\n", ".github/workflows/ci.yml": "jobs:\n a:\n steps:\n - uses: actions/setup-java@v5\n with:\n distribution: zulu\n java-version: 17.0.22\n", })) checkAll(t, res, []want{ From ab1c8b3830ca5e1b6f4b90389755dad1a8860022 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 08:34:21 +0000 Subject: [PATCH 071/119] java4shell: six-number versions are judged by their update (round 3, item 1) Round 2 made any version with more than a patch number and a build unknown before its update was compared, so Dragonwell's releases (dragonwell-21.0.8.0.8.9 ... 25.0.5.0.5.8, in asdf and mise), Kona's 17.0.21.0.3.b1 and a Red Hat 17.0.9.0.9.1 pin went from vulnerable to not checked. Judge now judges the first five numbers and turns only a fixed result into unknown. Co-Authored-By: Claude Opus 5.5 --- .../internal/knowledge/coverage_test.go | 26 +++++++++++++++++++ .../internal/knowledge/knowledge.go | 11 +++++++- .../java4shell/internal/repo/coverage_test.go | 20 ++++++++++++++ 3 files changed, 56 insertions(+), 1 deletion(-) diff --git a/detectors/java4shell/internal/knowledge/coverage_test.go b/detectors/java4shell/internal/knowledge/coverage_test.go index 02f4524..29172c9 100644 --- a/detectors/java4shell/internal/knowledge/coverage_test.go +++ b/detectors/java4shell/internal/knowledge/coverage_test.go @@ -224,3 +224,29 @@ func TestGraalVMRound2(t *testing.T) { } } } + +// Round 3, item 1: a six-number version (Dragonwell 21.0.8.0.8.9, Red Hat +// 17.0.9.0.9.1, Kona 17.0.21.0.3.b1) is judged by its update first; the +// extra numbers only keep it from reading fixed. +func TestSixNumbers(t *testing.T) { + for v, want := range map[string]Status{ + "21.0.8.0.8.9": Vulnerable, + "17.0.6.0.6.9": Vulnerable, + "25.0.5.0.5.8": Vulnerable, + "17.0.9.0.9.1": Vulnerable, + "17.0.5.0.5.9": NotAffected, + "21.0.13.1.2.3": Unknown, // would read fixed + "21.0.13.1.1.3": Vulnerable, + "21.0.14.0.1.2": Unknown, + "21.0.13.0.3.1": Vulnerable, + "17.0.21.1.2.99": Unknown, + } { + p, ok := Parse(v) + if !ok { + t.Fatalf("Parse(%s)", v) + } + if st, why := Judge(p); st != want { + t.Errorf("Judge(%s) = %s (%s), want %s", v, st, why, want) + } + } +} diff --git a/detectors/java4shell/internal/knowledge/knowledge.go b/detectors/java4shell/internal/knowledge/knowledge.go index f2b44a6..b6c9657 100644 --- a/detectors/java4shell/internal/knowledge/knowledge.go +++ b/detectors/java4shell/internal/knowledge/knowledge.go @@ -355,7 +355,16 @@ func Judge(v Version) (Status, string) { // write it so), which can predate the fix of 17.0.21.1. if len(v.Nums) >= 5 && v.Nums[3] <= maxPatch { if len(v.Nums) > 5 { - return Unknown, fmt.Sprintf("Java %s has more numbers than a Java version and a build: what it names is not known", ver) + // More numbers (Dragonwell's 21.0.8.0.8.9, a Red Hat + // 17.0.9.0.9.1): the update and build still decide, but what + // the extra numbers name is not known, so it never reads fixed. + w := v + w.Nums = v.Nums[:5] + st, why := Judge(w) + if st == Fixed { + return Unknown, fmt.Sprintf("Java %s has more numbers than a Java version and a build: what it names is not known", ver) + } + return st, why } if v.Build < 0 { v.Build = v.Nums[4] diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index 611fc0d..f3385b4 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -514,3 +514,23 @@ func TestVersionNamesAndUnsettled(t *testing.T) { {".github/workflows/ci.yml", 7, RuleNotChecked, StatusUnknown}, }) } + +// Round 3, item 1: Dragonwell's six-number releases are vulnerable. +func TestDragonwell(t *testing.T) { + res := scan(t, tree(t, map[string]string{ + "a/.tool-versions": "java dragonwell-21.0.8.0.8.9\n", + "b/.tool-versions": "java dragonwell-17.0.6.0.6.9\n", + "c/.tool-versions": "java dragonwell-25.0.5.0.5.8\n", + "mise.toml": "[tools]\njava = \"dragonwell-21.0.8.0.8.9\"\n", + "a/.sdkmanrc": "java=17.0.21.0.3.b1-kona\n", + "Dockerfile": "FROM registry.access.redhat.com/ubi9/ubi\nRUN dnf install -y java-17-openjdk-17.0.9.0.9.1-2.el9\n", + })) + checkAll(t, res, []want{ + {"a/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"b/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"c/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"mise.toml", 2, RuleJavaPin, StatusVulnerable}, + {"a/.sdkmanrc", 1, RuleJavaPin, StatusVulnerable}, + {"Dockerfile", 2, RulePackage, StatusVulnerable}, + }) +} From 6213ff8b7efe4de32f46a7b7577d11bb8232a0a0 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 08:35:05 +0000 Subject: [PATCH 072/119] java4shell: carry +N builds in asdf, mise and jenv names, and Corretto's release build (round 3, items 2, 3) asdf, mise and .java-version names dropped the build after +, so temurin-17.0.21.1+1, liberica-17.0.21.1+1 and liberica-27.0.1.1+3 gave nothing and graalvm-community-17.0.21.1+1 cleared against a Community row; the +N now reaches judgeVersion. Corretto rpm and deb packages put the build in the release (java-17-amazon-corretto-devel-17.0.21.1-1, also as an rpm file or an apt =1:17.0.21.1-1 pin; 27.0.1.1-3): a four-number version with a patch number takes the release's leading number as its build. Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/repo/coverage_test.go | 45 +++++++++++++++++++ detectors/java4shell/internal/repo/repo.go | 41 +++++++++++++---- 2 files changed, 78 insertions(+), 8 deletions(-) diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index f3385b4..f7f1a51 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -534,3 +534,48 @@ func TestDragonwell(t *testing.T) { {"Dockerfile", 2, RulePackage, StatusVulnerable}, }) } + +// Round 3, items 2 and 3: the build after + in asdf, mise and .java-version +// names, and Corretto's build in the rpm or deb release, are carried. +func TestBuildsCarried(t *testing.T) { + saved := knowledge.GraalVMFixed + t.Cleanup(func() { knowledge.GraalVMFixed = saved }) + knowledge.GraalVMFixed = map[knowledge.GraalVMKey]knowledge.Build{{Dist: knowledge.GraalVMCommunity, Feature: 17}: {Version: []int{17, 0, 21, 1}, Build: 2}} + res := scan(t, tree(t, map[string]string{ + "a/.tool-versions": "java temurin-17.0.21.1+1\n", + "b/.tool-versions": "java liberica-17.0.21.1+1\n", + "c/.tool-versions": "java liberica-27.0.1.1+3\n", + "d/.tool-versions": "java graalvm-community-17.0.21.1+1\n", + "e/.tool-versions": "java temurin-17.0.21.1+2\n", + "mise.toml": "[tools]\njava = \"temurin-17.0.21.1+1\"\n", + ".java-version": "temurin64-17.0.21.1+1\n", + "Dockerfile": strings.Join([]string{ + "FROM amazonlinux:2023", + "RUN yum install -y java-17-amazon-corretto-devel-17.0.21.1-1", + "RUN rpm -i /tmp/java-17-amazon-corretto-devel-17.0.21.1-1.x86_64.rpm", + "RUN dnf install -y java-27-amazon-corretto-devel-27.0.1.1-3", + "RUN dnf install -y java-17-amazon-corretto-devel-17.0.21.1-2", + }, "\n") + "\n", + "d/Dockerfile": "FROM ubuntu:24.04\nRUN apt-get install -y java-17-amazon-corretto-jdk=1:17.0.21.1-1\n", + })) + checkAll(t, res, []want{ + {"a/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"b/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"c/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"d/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"mise.toml", 2, RuleJavaPin, StatusVulnerable}, + {".java-version", 1, RuleJavaPin, StatusVulnerable}, + {"Dockerfile", 2, RulePackage, StatusVulnerable}, + {"Dockerfile", 3, RulePackage, StatusVulnerable}, + {"Dockerfile", 4, RulePackage, StatusVulnerable}, + {"d/Dockerfile", 2, RulePackage, StatusVulnerable}, + }) + for _, w := range []struct { + file string + line int + }{{"e/.tool-versions", 1}, {"Dockerfile", 5}} { + if f, ok := find(res, w.file, w.line); ok { + t.Errorf("%s:%d, a fixed build, reported: %+v", w.file, w.line, f) + } + } +} diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index b4f2e43..bdf37e7 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -406,14 +406,16 @@ func (s *scanner) javaVersionFile(rel, text string) { continue } // jenv names: temurin64-21.0.13, openjdk64-17.0.21, 21.0.13. - m := jenvName.FindStringSubmatch(l) - if m == nil { + idx := jenvName.FindStringSubmatchIndex(l) + if idx == nil { return } + m := jenvName.FindStringSubmatch(l) ver := m[2] if strings.HasPrefix(strings.ToLower(m[1]), "corretto") { ver = CorrettoJava(ver) } + ver += plusBuild(l[idx[5]:]) s.judgeVersion(rel, i+1, 0, ver, ".java-version", vendorWord(l)) return // jenv reads the first line } @@ -485,13 +487,29 @@ func (s *scanner) asdfValue(rel string, line int, value, source string) { s.ownNumbers(rel, line, value, source) // their own version numbers return } - ver := m[2] + ver := strings.TrimSuffix(m[2], ".") if m[1] == "corretto" { - ver = CorrettoJava(strings.TrimSuffix(ver, ".")) + ver = CorrettoJava(ver) } - s.judgeVersion(rel, line, 0, strings.TrimSuffix(ver, "."), source, m[1]) + if !strings.HasSuffix(m[2], ".") { + // temurin-17.0.21.1+1: OpenJDK's build after +. + idx := asdfJava.FindStringSubmatchIndex(value) + ver += plusBuild(value[idx[5]:]) + } + s.judgeVersion(rel, line, 0, ver, source, m[1]) } +// plusBuild returns "+N" when rest starts with OpenJDK's build (+11 in +// 21.0.5+11.0.LTS), "" otherwise. +func plusBuild(rest string) string { + if m := plusBuildRE.FindStringSubmatch(rest); m != nil { + return "+" + m[1] + } + return "" +} + +var plusBuildRE = regexp.MustCompile(`^\+(\d{1,9})`) + // CorrettoJava turns an Amazon Corretto version into the Java version it // ships. Corretto has written its build number in the fourth place // (21.0.5.11.1: Java 21.0.5, build 11) and, since the out-of-band releases, @@ -1155,9 +1173,16 @@ func pinnedVersion(h pkgHit) string { up = strings.ReplaceAll(up, "_p", "+") switch { case h.vendor == "corretto": - // Without the rpm or deb release: 17.0.21+9-1.amzn2023.1. - up, _, _ = strings.Cut(up, "-") - up = CorrettoJava(up) + // Without the rpm or deb release: 17.0.21+9-1.amzn2023.1. A + // four-number version whose fourth is a patch number puts the build + // in the release: 17.0.21.1-1 is 17.0.21.1 build 1. + base, release, _ := strings.Cut(up, "-") + up = CorrettoJava(base) + if p := strings.Split(base, "."); len(p) == 4 && !strings.Contains(base, "+") && atoi(p[3]) <= 3 { + if b, _, _ := strings.Cut(release, "."); b != "" && strings.Trim(b, "0123456789") == "" { + up += "+" + b + } + } case h.mgr == "rpm": // Red Hat and Fedora append the build: 17.0.21.0.9 is 17.0.21+9. up = knowledge.RPMUpstream(h.ver) From 4766b4ba4270615e389b5b4ed4a8fd50e77c4080 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 08:36:43 +0000 Subject: [PATCH 073/119] java4shell: Java package files and patterns no reader knows are not checked (round 3, item 4) Vendor rpm files and names gave nothing. Their Java version is now read where the name carries it (Oracle jdk-17.0.9_linux-x64_bin, Zulu ...-ca-jdk17.0.9-linux, Temurin temurin-17-jdk-17.0.13.0.0.11-2 as a file or a dnf argument, its six numbers read as 17.0.13+11, Liberica bellsoft-jdk17.0.9+11, SapMachine sapmachine-jdk-17.0.9-1): vulnerable where the release data says so, otherwise not checked (vendor numbering is never cleared). Any other package file whose name names Java (/tmp/jdk.rpm) and any pattern that could match one (jdk*.rpm, zulu*.rpm, temurin-*.rpm, /rpms/*, java-17-openjdk-17.0.2?.0.9-1.el9) is not checked. rpm --reinstall is an install. URL query strings are cut only from URLs, so a local '?' stays a pattern. Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/repo/coverage_test.go | 43 +++++++++ detectors/java4shell/internal/repo/repo.go | 96 ++++++++++++++++--- 2 files changed, 126 insertions(+), 13 deletions(-) diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index f7f1a51..c79f58f 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -579,3 +579,46 @@ func TestBuildsCarried(t *testing.T) { } } } + +// Round 3, item 4: Java package files and patterns no reader knows are not +// checked; vendor file names carry the Java version. +func TestVendorPackageFiles(t *testing.T) { + lines := []string{ + "FROM registry.access.redhat.com/ubi9/ubi", + "RUN rpm -ivh /tmp/jdk-17.0.9_linux-x64_bin.rpm", // 2 Oracle + "RUN rpm -ivh /tmp/zulu17.46.19-ca-jdk17.0.9-linux.x86_64.rpm", // 3 + "RUN rpm -ivh /tmp/temurin-17-jdk-17.0.13.0.0.11-2.x86_64.rpm", // 4 + "RUN dnf install -y temurin-17-jdk-17.0.13.0.0.11-2", // 5 + "RUN rpm -ivh /tmp/bellsoft-jdk17.0.9+11-linux-amd64.rpm", // 6 + "RUN rpm -ivh /tmp/sapmachine-jdk-17.0.9-1.x86_64.rpm", // 7 + "RUN rpm -ivh /tmp/jdk.rpm", // 8 + "RUN rpm -ivh /tmp/jdk*.rpm", // 9 + "RUN rpm -ivh /tmp/zulu*.rpm", // 10 + "RUN rpm -ivh /tmp/temurin-*.rpm", // 11 + "RUN rpm -ivh /rpms/*", // 12 + "RUN dnf install -y java-17-openjdk-17.0.2?.0.9-1.el9", // 13 + "RUN rpm --reinstall /tmp/java-17-openjdk-headless-17.0.21.0.9-1.el9.x86_64.rpm", // 14 + "RUN rpm -ivh /tmp/jdk-21.0.13.1_linux-x64_bin.rpm", // 15 not cleared + "RUN rpm -ivh /tmp/epel-release-latest-9.noarch.rpm /tmp/nginx-*.rpm", // 16 + } + res := scan(t, tree(t, map[string]string{"Dockerfile": strings.Join(lines, "\n") + "\n"})) + checkAll(t, res, []want{ + {"Dockerfile", 2, RulePackage, StatusVulnerable}, + {"Dockerfile", 3, RulePackage, StatusVulnerable}, + {"Dockerfile", 4, RulePackage, StatusVulnerable}, + {"Dockerfile", 5, RulePackage, StatusVulnerable}, + {"Dockerfile", 6, RulePackage, StatusVulnerable}, + {"Dockerfile", 7, RulePackage, StatusVulnerable}, + {"Dockerfile", 8, RulePackage, StatusUnknown}, + {"Dockerfile", 9, RulePackage, StatusUnknown}, + {"Dockerfile", 10, RulePackage, StatusUnknown}, + {"Dockerfile", 11, RulePackage, StatusUnknown}, + {"Dockerfile", 12, RulePackage, StatusUnknown}, + {"Dockerfile", 13, RulePackage, StatusUnknown}, + {"Dockerfile", 14, RulePackage, StatusVulnerable}, + {"Dockerfile", 15, RulePackage, StatusUnknown}, + }) + if f, ok := find(res, "Dockerfile", 16); ok { + t.Errorf("non-Java files reported: %+v", f) + } +} diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index bdf37e7..4b0b6ab 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -834,7 +834,7 @@ var ( rpmLatest = regexp.MustCompile(`^java-latest-openjdk(?:-headless|-devel|-jmods)?(?:-\d[\w.:*?-]*)?$`) // rpmInstallFlag is an rpm option that installs or upgrades package // files; a query (-qip) or an erase (-e) is not an install. - rpmInstallFlag = regexp.MustCompile(`^(?:-[a-dfh-pr-zA-UW-Z]*[iUF][a-dfh-pr-zA-UW-Z]*|--install|--upgrade|--freshen)$`) + rpmInstallFlag = regexp.MustCompile(`^(?:-[a-dfh-pr-zA-UW-Z]*[iUF][a-dfh-pr-zA-UW-Z]*|--install|--upgrade|--freshen|--reinstall)$`) vendorJava = regexp.MustCompile(`\b((temurin|zulu|msopenjdk|sapmachine)-?(\d{1,2})(?:-ca)?(?:-(?:jdk|jre))?(?:-headless)?)\b(=([^\s;&|]+))?`) defaultJava = regexp.MustCompile(`\b(default-(?:jre|jdk)(?:-headless)?)\b`) envJTO = regexp.MustCompile(`(?i)^\s*ENV\s+`) @@ -911,6 +911,9 @@ func (s *scanner) packages(rel string, line int, run string) { } var hits []pkgHit for _, arg := range installArgs(run) { + fromFile := strings.HasPrefix(arg, fileArg) + arg = strings.TrimPrefix(arg, fileArg) + before := len(hits) switch { case strings.HasPrefix(arg, unreadableArg): hits = append(hits, pkgHit{name: strings.TrimPrefix(arg, unreadableArg), mgr: "rpm", vendor: "distribution", unreadable: true}) @@ -950,6 +953,17 @@ func (s *scanner) packages(rel string, line int, run string) { // release comes from a variable. hits = append(hits, pkgHit{name: arg, mgr: "package", vendor: "distribution", varName: true}) } + if len(hits) > before { + continue + } + // A vendor's package no reader above knows: its file name or rpm + // name may carry the Java version (Oracle, Zulu, Temurin, Liberica + // and SapMachine rpms); otherwise a Java package file is not checked. + if v := vendorFileVersion(arg); v != "" && javaWord.MatchString(arg) { + hits = append(hits, pkgHit{name: arg, mgr: "rpm", vendor: "distribution", ver: v, vendorFile: true}) + } else if fromFile && javaWord.MatchString(arg) { + hits = append(hits, pkgHit{name: arg, mgr: "rpm", vendor: "distribution", unreadable: true}) + } } for _, h := range hits { s.judgePackage(rel, line, h) @@ -1023,7 +1037,8 @@ var javaWord = regexp.MustCompile(`(?i)java|jdk|jre|corretto|temurin|zulu`) // globCandidates are names a Java package file could have, for deciding // whether a pattern (*.rpm) could match one. var globCandidates = []string{"java-17-openjdk-headless-17.0.21.0.9-1.el9.x86_64.rpm", "java-21-amazon-corretto-devel-21.0.13.1.2-1.x86_64.rpm", - "java-latest-openjdk-25.0.1.0.8-1.rolling.fc41.x86_64.rpm"} + "java-latest-openjdk-25.0.1.0.8-1.rolling.fc41.x86_64.rpm", "jdk-17.0.9_linux-x64_bin.rpm", "zulu17.46.19-ca-jdk17.0.9-linux.x86_64.rpm", + "temurin-17-jdk-17.0.13.0.0.11-2.x86_64.rpm", "bellsoft-jdk17.0.9+11-linux-amd64.rpm", "sapmachine-jdk-17.0.9-1.x86_64.rpm"} // rpmFileArg reads a package file argument (local or a URL, with any // ?query or #fragment): name-version-release.arch.rpm gives the package @@ -1032,27 +1047,61 @@ var globCandidates = []string{"java-17-openjdk-headless-17.0.21.0.9-1.el9.x86_64 // false for an argument that is not a package file. func rpmFileArg(w string) (string, bool) { u := w - if i := strings.IndexAny(u, "?#"); i >= 0 { + url := strings.Contains(w, "://") + if i := strings.IndexAny(u, "?#"); url && i >= 0 { u = u[:i] } base := path.Base(u) - if strings.HasSuffix(strings.ToLower(base), ".rpm") { - if strings.ContainsAny(base, "*?[") { - for _, c := range globCandidates { - if ok, _ := path.Match(base, c); ok { - return unreadableArg + w, true - } + if !url && strings.Contains(w, "=") { + return "", false // a version pin (openjdk-17-jdk=17.*), not a file + } + if !url && strings.ContainsAny(base, "*?[") { + // A pattern (*.rpm, jdk*.rpm, /rpms/*, java-17-*): not checked when + // it could match a Java package file. + if javaWord.MatchString(base) { + return unreadableArg + w, true + } + for _, c := range globCandidates { + if ok, _ := path.Match(base, c); ok { + return unreadableArg + w, true } - return "", true } - return rpmArchRE.ReplaceAllString(base[:len(base)-len(".rpm")], ""), true + return "", strings.HasSuffix(strings.ToLower(base), ".rpm") || strings.Contains(w, "/") } - if strings.Contains(w, "://") && javaWord.MatchString(w) { + if strings.HasSuffix(strings.ToLower(base), ".rpm") { + return fileArg + rpmArchRE.ReplaceAllString(base[:len(base)-len(".rpm")], ""), true + } + if url && javaWord.MatchString(w) { return unreadableArg + w, true } return "", false } +// fileArg marks a package name read from a package file's name: one no +// reader knows is still a Java package if its name says so. +const fileArg = "\x00file:" + +// vendorFile finds the Java version in a vendor's package name or file +// name: jdk-17.0.9_linux-x64_bin (Oracle), zulu17.46.19-ca-jdk17.0.9-linux, +// temurin-17-jdk-17.0.13.0.0.11-2, bellsoft-jdk17.0.9+11-linux-amd64, +// sapmachine-jdk-17.0.9-1. +var vendorFile = regexp.MustCompile(`(?i)(?:^|[-_])(?:jdk|jre)-?(\d{1,2}(?:\.\d{1,9}){1,5}(?:\+\d{1,9})?)(?:$|[-_])`) + +// vendorFileVersion reads a vendor package's Java version, "" when it has +// none. Temurin's rpm writes six numbers, the build last +// (17.0.13.0.0.11 is 17.0.13+11). +func vendorFileVersion(name string) string { + m := vendorFile.FindStringSubmatch(name) + if m == nil { + return "" + } + v := m[1] + if p := strings.Split(v, "."); len(p) == 6 && !strings.Contains(v, "+") && strings.HasPrefix(strings.ToLower(name), "temurin") { + v = strings.Join(p[:4], ".") + "+" + p[5] + } + return v +} + // installArgs returns the package arguments of the install commands on a // RUN line: the words after " [flags] install|add", without flags, // their values, paths and URLs. @@ -1125,6 +1174,7 @@ type pkgHit struct { varName bool // the name holds a variable where the release is latest bool // java-latest-openjdk: no release in the name unreadable bool // a package file whose name cannot be read + vendorFile bool // a vendor package read by vendorFileVersion } func opOf(v string) string { @@ -1163,7 +1213,7 @@ func preRelease(ver string) bool { return strings.Contains(ver, "~") } // pinnedVersion is the Java version a package pin fixes, or "" for a pin // that matches several releases (17.*, ~17, 17). func pinnedVersion(h pkgHit) string { - if h.ver == "" || strings.Contains(h.ver, "$") || strings.Contains(h.ver, "*") || strings.Contains(h.op, "~") || strings.ContainsAny(h.op, "<>") { + if h.ver == "" || strings.Contains(h.ver, "$") || strings.ContainsAny(h.ver, "*?[") || strings.Contains(h.op, "~") || strings.ContainsAny(h.op, "<>") { return "" } up := h.ver @@ -1203,6 +1253,26 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { Fix: "Check which Java release the variable selects: 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update have the fix."}) return } + if h.vendorFile { + // Vendor numbering is not checked here: a version the release data + // judges vulnerable is reported, anything else is not checked. + v, _ := knowledge.Parse(h.ver) + st, why := knowledge.Judge(v) + props := map[string]string{"package": refs.CleanText(h.name, 120), "manager": h.mgr, "current": h.ver} + switch st { + case knowledge.NotAffected: + case knowledge.Vulnerable: + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "error", Status: StatusVulnerable, Reason: why, Props: props, + Message: fmt.Sprintf("installs %s (Java %s), without the Java4Shell fix", refs.CleanText(h.name, 120), h.ver), + Fix: "Install the vendor's package of a Java release with the fix (17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update) once it is published, then rebuild. Until then set ENV JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics in this stage."}) + default: + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: props, + Reason: fmt.Sprintf("the package names Java %s in its vendor's own numbering, which this detector does not judge fixed: %s", h.ver, why), + Message: fmt.Sprintf("installs %s (Java %s): not checked for the Java4Shell fix", refs.CleanText(h.name, 120), h.ver), + Fix: "Check the vendor's release notes for the Java4Shell fix (CVE-2026-114938)."}) + } + return + } if h.unreadable { s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: map[string]string{"package": refs.CleanText(h.name, 120), "manager": h.mgr}, From f0fdcf821f0feb119708fca8a10b3e170fa49294 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 08:38:32 +0000 Subject: [PATCH 074/119] java4shell: javafx/crac, GA and EA names, Corretto apk, Zulu and JBR numbers (round 3, item 5) - asdf javafx, fx and crac variants and java-se-ri are read. - asdf and sdkman names without an update are the line's GA or EA build (openjdk-21, sapmachine-21, liberica-21+37, openjdk-21-ea+26, java-se-ri-22+36, sdkman 21-tem) and are judged: 21 vulnerable, 22 a line without a fix, 17 (17.0.0) not affected. A pre-release of the fixed update (openjdk-17.0.21.1-ea+2) read fixed and is now not checked: version names carry -ea through to Judge. - Alpine's amazon-corretto-17=17.0.20.13.1-r0 and amazon-corretto-22 are judged. - A Zulu number that starts with a line without a fix (zulu-22.32.15, zulu-crac-22.32.17) is vulnerable; other Zulu numbers stay not checked. - JetBrains Runtime names carry the Java update (17.0.9b1087.7): vulnerable when older than the fixed update, otherwise not checked. - FACTS.md records these readings, Zulu's as inferred. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/FACTS.md | 1 + .../java4shell/internal/repo/coverage_test.go | 45 +++++++++++ detectors/java4shell/internal/repo/images.go | 4 +- detectors/java4shell/internal/repo/repo.go | 77 ++++++++++++++++--- 4 files changed, 114 insertions(+), 13 deletions(-) diff --git a/detectors/java4shell/FACTS.md b/detectors/java4shell/FACTS.md index 835d060..71928e6 100644 --- a/detectors/java4shell/FACTS.md +++ b/detectors/java4shell/FACTS.md @@ -83,6 +83,7 @@ The lead read these; they could not be fetched from the research host. Facts her | Oracle Java SE | 8u511b33-perf, 17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3 and earlier affected; the fixed Oracle version numbers were not relayed, so Oracle builds after .0.3 are judged by the OpenJDK fixed releases | Oracle CSPU November 2026 | | Oracle GraalVM, GraalVM Community | GraalVM for JDK 17.0.21.0.3 and 21.0.13.0.3 and GraalVM Enterprise Edition 21.3.20.0.3 affected (Oracle). GraalVM Community: the newest release on graalvm/graalvm-ce-builds was published 2026-11-03, before the fix. **No fixed GraalVM build known** (2026-11-18). See "GraalVM" below | Oracle CSPU November 2026; [graalvm/graalvm-ce-builds releases](https://github.com/graalvm/graalvm-ce-builds/releases) (reviewer, 2026-11-18) | | Azul Zulu, BellSoft Liberica | **not checked**: their pages could not be read (HTTP 403/404 for the lead; unreachable here). Docker Hub `azul/zulu-openjdk` and `bellsoft/liberica-openjdk-debian` newest tags were 27.0.1.0.3 / 21.0.13.0.3 on 2026-11-17 (not fixed) | registry-1.docker.io tag list | +| Version-manager names in vendors' own numbers | Azul Zulu's own numbers start with the Java line (asdf `zulu-22.32.15` is JDK 22): a line that received no fix is reported vulnerable from that number alone, other Zulu numbers are not checked (**inferred** from Zulu's naming, not checked against each release). JetBrains Runtime names carry the Java update (`jetbrains-17.0.9b1087.7` is 17.0.9): an update older than the fixed one is vulnerable; the fixed update itself is not checked, since JetBrains may backport into it. Dragonwell writes six numbers (`dragonwell-21.0.8.0.8.9`): judged by the update, never cleared by the extra numbers. A name without an update (asdf `openjdk-21`, `liberica-21+37`, `openjdk-21-ea+26`, sdkman `21-tem`) is the line's GA or early-access build | asdf-java and sdkman version lists (reviewer, 2026-11-18); **inferred** for Zulu | | IBM Semeru | OpenJ9, not HotSpot (see above) | image inspection | | Debian | **not fixed** (2026-11-18): the tracker lists every package vulnerable and unfixed: openjdk-17 bookworm-security 17.0.21+9-1~deb12u1, sid 17.0.21.0.3+1-1; openjdk-21 trixie-security 21.0.13+9-1~deb13u2, forky/sid 21.0.13.0.3+1-1; openjdk-25 trixie-security 25.0.5+8-1~deb13u1, sid 25.0.5.0.3+1-3; openjdk-27 sid 27.0.1.0.3+1-1 | [security-tracker.debian.org CVE-2026-114938](https://security-tracker.debian.org/tracker/CVE-2026-114938) (lead); deb.debian.org and security.debian.org pools | | Ubuntu | **not fixed** (2026-11-18): newest sources openjdk-17 17.0.21.0.3+1-1 (17.0.21.0.3+1-1~XX.04.1 in the stable releases), openjdk-21 21.0.13.0.3+1-1, openjdk-25 25.0.5.0.3+1-3~XX.04.1; none is the fixed update or a backport. The Ubuntu CVE page could not be read | archive.ubuntu.com pool (2026-11-17; openjdk-21 and -17 reread by the reviewer 2026-11-18) | diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index c79f58f..ea16f72 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -622,3 +622,48 @@ func TestVendorPackageFiles(t *testing.T) { t.Errorf("non-Java files reported: %+v", f) } } + +// Round 3, item 5: javafx and crac names, GA and EA names without an +// update, Corretto's apk packages, Zulu's own numbers for a line without a +// fix, and JetBrains Runtime versions. +func TestRound3Names(t *testing.T) { + files := map[string]string{ + "Dockerfile": "FROM alpine:3.23\nRUN apk add amazon-corretto-17=17.0.20.13.1-r0\nRUN apk add amazon-corretto-22\n", + } + add := func(name, value string) { files[name+"/.tool-versions"] = "java " + value + "\n" } + add("a", "liberica-javafx-17.0.9+11") + add("b", "liberica-crac-17.0.9+16") + add("c", "zulu-crac-22.32.17") + add("d", "openjdk-21") + add("e", "sapmachine-21") + add("f", "liberica-21+37") + add("g", "openjdk-21-ea+26") + add("h", "java-se-ri-22+36") + add("i", "zulu-22.32.15") + add("j", "jetbrains-17.0.9b1087.7") + add("k", "openjdk-17") // 17.0.0: before the decoder + add("l", "openjdk-17.0.21.1-ea+2") // pre-release of the fixed update + add("m", "jetbrains-17.0.21b1234.5") + files["a/.sdkmanrc"] = "java=21-tem\n" + res := scan(t, tree(t, files)) + checkAll(t, res, []want{ + {"a/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"b/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"c/.tool-versions", 1, RuleLine, StatusVulnerable}, + {"d/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"e/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"f/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"g/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"h/.tool-versions", 1, RuleLine, StatusVulnerable}, + {"i/.tool-versions", 1, RuleLine, StatusVulnerable}, + {"j/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"l/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"m/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"a/.sdkmanrc", 1, RuleJavaPin, StatusVulnerable}, + {"Dockerfile", 2, RulePackage, StatusVulnerable}, + {"Dockerfile", 3, RuleLine, StatusVulnerable}, + }) + if f, ok := find(res, "k/.tool-versions", 1); ok { + t.Errorf("openjdk-17 (17.0.0) reported: %+v", f) + } +} diff --git a/detectors/java4shell/internal/repo/images.go b/detectors/java4shell/internal/repo/images.go index 49b9b11..0910b09 100644 --- a/detectors/java4shell/internal/repo/images.go +++ b/detectors/java4shell/internal/repo/images.go @@ -112,6 +112,8 @@ type TagVersion struct { // OpenJDKBuild is the OpenJDK build number the tag names, -1 when it // names none (a vendor's own build number, or no build). OpenJDKBuild int + // EA is a pre-release (a version name such as 21-ea+26). + EA bool } // ParseTag reads the Java release a family's tag names. ok is false for a @@ -172,7 +174,7 @@ func JudgeTag(tv TagVersion) (knowledge.Status, string) { what = "the tag names the newest Java " + tv.Text + " release at build time" } if tv.Exact || feature < 17 { - st, why := knowledge.Judge(knowledge.Version{Nums: nums, Build: tv.OpenJDKBuild}) + st, why := knowledge.Judge(knowledge.Version{Nums: nums, Build: tv.OpenJDKBuild, EA: tv.EA}) return st, what + ": " + why } l, ok := knowledge.LineOf(feature) diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 4b0b6ab..5f29702 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -321,8 +321,12 @@ var versionInText = regexp.MustCompile(`(\d{1,3}(?:\.\d{1,9}){0,5})`) // fixed or not affected. A version with fewer numbers than the fix is a // moving pin (the newest release of that line) and is reported only when // its line has no fix at all. -func (s *scanner) judgeVersion(rel string, line, col int, verText, source, vendor string) { - tv := TagVersion{Text: verText, Exact: strings.Count(verText, ".") >= 2, OpenJDKBuild: -1} +// +// ga is true for a name that pins one release even without an update: asdf +// openjdk-21 and sdkman 21-tem are 21 GA. verText may end in OpenJDK's +// build (+26) and be a pre-release (21-ea+26). +func (s *scanner) judgeVersion(rel string, line int, ga bool, verText, source, vendor string) { + tv := TagVersion{Text: verText, Exact: ga || strings.Count(verText, ".") >= 2, OpenJDKBuild: -1} nums := verText if base, b, ok := strings.Cut(verText, "+"); ok { // setup-java 17.0.21.1+1: OpenJDK's build. @@ -331,6 +335,9 @@ func (s *scanner) judgeVersion(rel string, line, col int, verText, source, vendo tv.OpenJDKBuild = n } } + if m := preReleaseSuffix.FindStringIndex(nums); m != nil { + nums, tv.EA = nums[:m[0]], true + } for _, p := range strings.Split(nums, ".") { n := 0 fmt.Sscanf(p, "%d", &n) @@ -389,9 +396,12 @@ func (s *scanner) judgeVersion(rel string, line, col int, verText, source, vendo Fix: fmt.Sprintf("Check that Java %s includes %s.", verText, knowledge.BugRef), Props: props}) } } - _ = col } +// preReleaseSuffix is a pre-release marker in a version name: 21-ea, +// 17.0.21.1-ea, 22-beta. +var preReleaseSuffix = regexp.MustCompile(`-(?:ea|beta|rc)\b.*$`) + func pinFix(feature int, source string) string { if fx := knowledge.FixedVersion(feature); fx != "" { return fmt.Sprintf("Select Java %s or later of the same update in %s once your vendor publishes it (%s), and reinstall.", fx, source, knowledge.VendorStatus()) @@ -416,7 +426,7 @@ func (s *scanner) javaVersionFile(rel, text string) { ver = CorrettoJava(ver) } ver += plusBuild(l[idx[5]:]) - s.judgeVersion(rel, i+1, 0, ver, ".java-version", vendorWord(l)) + s.judgeVersion(rel, i+1, false, ver, ".java-version", vendorWord(l)) return // jenv reads the first line } } @@ -460,7 +470,7 @@ func (s *scanner) sdkmanrc(rel, text string) { s.ownNumbers(rel, i+1, strings.TrimSpace(strings.SplitN(l, "=", 2)[1]), ".sdkmanrc") continue } - s.judgeVersion(rel, i+1, strings.Index(l, m[1]), m[1], ".sdkmanrc", vendor) + s.judgeVersion(rel, i+1, true, m[1], ".sdkmanrc", vendor) } } @@ -468,7 +478,7 @@ func (s *scanner) sdkmanrc(rel, text string) { // corretto-21.0.5.11.1, openjdk-21.0.2, sapmachine-21.0.5, temurin-jre-musl-21.0.5, // liberica-lite-21.0.5, zulu-21.38.21 // (a Zulu version, not a Java version: not judged). -var asdfJava = regexp.MustCompile(`^(?:(adoptopenjdk|temurin|corretto|openjdk|sapmachine|liberica|microsoft|oracle|semeru-openj9|semeru|dragonwell|kona|zulu|graalvm|graalvm-community|oracle-graalvm|mandrel|jetbrains)-)?(?:(?:jre|jdk|openj9|musl|lite)-)*(\d[\d.]*)`) +var asdfJava = regexp.MustCompile(`^(?:(adoptopenjdk|temurin|corretto|openjdk|sapmachine|liberica|microsoft|oracle|semeru-openj9|semeru|dragonwell|kona|zulu|graalvm|graalvm-community|oracle-graalvm|mandrel|jetbrains|java-se-ri)-)?(?:(?:jre|jdk|openj9|musl|lite|javafx|fx|crac)-)*(\d[\d.]*)`) func (s *scanner) asdfValue(rel string, line int, value, source string) { m := asdfJava.FindStringSubmatch(value) @@ -483,7 +493,34 @@ func (s *scanner) asdfValue(rel string, line int, value, source string) { } } switch m[1] { - case "zulu", "graalvm", "mandrel", "jetbrains": + case "zulu": + // Zulu's own numbers start with the Java line (zulu-22.32.15 is + // JDK 22): a line that received no fix is vulnerable whatever the + // rest says; others are not checked. + if f := atoi(m[2]); f > 17 { + if l, ok := knowledge.LineOf(f); ok && l.Fixed == nil { + s.lineToolchain(rel, line, f, source+" ("+refs.CleanText(value, 60)+", Azul Zulu)") + return + } + } + s.ownNumbers(rel, line, value, source) + return + case "jetbrains": + // JetBrains Runtime: 17.0.9b1087.7 is Java 17.0.9 and JetBrains' + // build. Reported where the Java update is older than the fixed + // one; JetBrains' fixed builds are not known, so nothing is cleared. + // The update the fix came in (17.0.21) is not judged: JetBrains + // may backport into it, as Red Hat does. + if v, ok := knowledge.Parse(m[2]); ok && len(v.Nums) >= 3 { + fx, _ := knowledge.Parse(knowledge.FixedVersion(v.Feature())) + if st, _ := knowledge.Judge(v); st == knowledge.Vulnerable && (len(fx.Nums) < 3 || knowledge.Compare(v.Nums[:3], fx.Nums[:3]) < 0) { + s.judgeVersion(rel, line, true, m[2], source, m[1]) + return + } + } + s.ownNumbers(rel, line, value, source) + return + case "graalvm", "mandrel": s.ownNumbers(rel, line, value, source) // their own version numbers return } @@ -492,11 +529,17 @@ func (s *scanner) asdfValue(rel string, line int, value, source string) { ver = CorrettoJava(ver) } if !strings.HasSuffix(m[2], ".") { - // temurin-17.0.21.1+1: OpenJDK's build after +. + // temurin-17.0.21.1+1: OpenJDK's build after +; openjdk-21-ea+26: + // a pre-release and its build. idx := asdfJava.FindStringSubmatchIndex(value) - ver += plusBuild(value[idx[5]:]) + rest := value[idx[5]:] + if e := asdfPreRelease.FindStringSubmatch(rest); e != nil { + ver += "-" + e[1] + rest = rest[len(e[0]):] + } + ver += plusBuild(rest) } - s.judgeVersion(rel, line, 0, ver, source, m[1]) + s.judgeVersion(rel, line, true, ver, source, m[1]) } // plusBuild returns "+N" when rest starts with OpenJDK's build (+11 in @@ -510,6 +553,9 @@ func plusBuild(rest string) string { var plusBuildRE = regexp.MustCompile(`^\+(\d{1,9})`) +// asdfPreRelease is a pre-release marker after an asdf version. +var asdfPreRelease = regexp.MustCompile(`^-(ea|beta|rc)\b`) + // CorrettoJava turns an Amazon Corretto version into the Java version it // ships. Corretto has written its build number in the fourth place // (21.0.5.11.1: Java 21.0.5, build 11) and, since the out-of-band releases, @@ -634,7 +680,7 @@ func (s *scanner) setupJava(rel string, v *yaml.Node, dist string, text []string if b, ok := strings.CutPrefix(ver, m+"+"); ok && b != "" && strings.Trim(b, "0123456789") == "" { judged = ver // the build decides at a fixed release's boundary } - s.judgeVersion(rel, v.Line, 0, judged, "actions/setup-java", dist) + s.judgeVersion(rel, v.Line, false, judged, "actions/setup-java", dist) if len(s.findings) == before { s.movingSetupJava(rel, v, m, dist) return @@ -801,7 +847,7 @@ func (s *scanner) buildpack(rel string, line int, ver string) { return } if strings.Count(ver, ".") >= 2 { - s.judgeVersion(rel, line, 0, ver, "BP_JVM_VERSION (Cloud Native Buildpacks)", "") + s.judgeVersion(rel, line, false, ver, "BP_JVM_VERSION (Cloud Native Buildpacks)", "") } } @@ -946,6 +992,9 @@ func (s *scanner) packages(rel string, line int, run string) { hits = append(hits, pkgHit{name: m[1], feature: atoi(m[3]), op: opOf(m[4]), ver: m[5], mgr: "package", vendor: m[2]}) case defaultArg.MatchString(arg): hits = append(hits, pkgHit{name: arg, mgr: "apt", vendor: "distribution"}) + case apkCorretto.MatchString(arg): + m := apkCorretto.FindStringSubmatch(arg) + hits = append(hits, pkgHit{name: m[1], feature: atoi(m[2]), op: m[3], ver: m[4], mgr: "apk", vendor: "corretto"}) case rpmLatest.MatchString(arg): hits = append(hits, pkgHit{name: arg, mgr: "rpm", vendor: "distribution", latest: true}) case varJavaArg.MatchString(arg): @@ -1028,6 +1077,10 @@ func packageName(w string) string { // name. const unreadableArg = "\x00unreadable:" +// apkCorretto is Amazon's Alpine package: amazon-corretto-17, +// amazon-corretto-17=17.0.20.13.1-r0. +var apkCorretto = regexp.MustCompile(`^(amazon-corretto-(\d{1,2})(?:-jre|-jdk)?)(?:([=~><]+)(\S+))?$`) + // zypperArg is zypper's java-17-openjdk=17.0.21.0 (or >=, <...). var zypperArg = regexp.MustCompile(`^(java-(\d{1,2})-(openjdk|amazon-corretto)(?:-headless|-devel|-jdk)?)(=|>=|<=|>|<)(\S+)$`) From 8db55502b0e26eb9d1996a281916c24adc2109be Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 08:41:52 +0000 Subject: [PATCH 075/119] engine: files met but not read are told to detectors; duplicate entries forgotten; one record per gap From the round-3 review: - A file the walk meets and cannot read (no permission, an I/O error, a file that changes while it is read), and a directory it cannot list, is told to each scan that implements UnreadVisitor, whatever its name or content, and the file exists (Exists). It stays a coverage gap. - When an image names a path twice, every scan that implements Forgetter forgets the first entry before the second is handed out: 'the last entry wins' once, in the engine. - A gap a scan reports in FinishSkips replaces the exclusion record the engine made for it on the same path. - Tests: unreadable files and directories (run as non-root; skipped as root), Forget and its panic, a limit equal to --max-file-size (gap) and one byte under (exclusion), a panic in FinishSkips, a LimitVisitor that is not a Limiter, and the exclusion a late gap replaces. Co-Authored-By: Claude Opus 5.5 --- internal/engine/engine.go | 19 ++++ internal/engine/limit_test.go | 171 ++++++++++++++++++++++++++++++++++ internal/engine/run.go | 66 ++++++++++++- internal/source/source.go | 26 ++++-- 4 files changed, 274 insertions(+), 8 deletions(-) diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 630f475..d043286 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -223,6 +223,25 @@ type FinishSkipper interface { FinishSkips() []Skip } +// UnreadVisitor is implemented by a Scan that must know which files and +// directories the walk met and could not read (no permission, an I/O +// error, a file that changed while it was read), whatever their name or +// content: a verdict must never rest on their absence. VisitUnread is +// called for each, dir set for a directory whose contents could not be +// listed. The walk records each as a coverage gap. +type UnreadVisitor interface { + VisitUnread(path string, dir bool) +} + +// Forgetter is implemented by a Scan that keeps what it was shown by +// path. When a path comes round again (an image filesystem can name one +// file twice; the last entry is the file), Forget is called before the new +// entry is handed out, so nothing of the earlier one survives, nor of what +// was found inside it ("path!/member"). +type Forgetter interface { + Forget(path string) +} + // HeadVisitor is implemented by a Scan that wants to see the first bytes // of every file the walk meets, read in full or not: a record of files // it does not need to read (a runtime download inside an image) without diff --git a/internal/engine/limit_test.go b/internal/engine/limit_test.go index 2a18b1a..28528d0 100644 --- a/internal/engine/limit_test.go +++ b/internal/engine/limit_test.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "runtime" + "sort" "strconv" "strings" "testing" @@ -445,5 +446,175 @@ func TestFinishSkipper(t *testing.T) { if tg.Gaps() != want || tg.SkippedPaths() != 1 { t.Errorf("found %v: gaps %d paths %d skipped %+v", found, tg.Gaps(), tg.SkippedPaths(), tg.Skipped) } + // A gap reported at the end replaces the scan's exclusion record. + if found && (len(tg.Skipped) != 1 || tg.Skipped[0].Excluded) { + t.Errorf("records contradict each other: %+v", tg.Skipped) + } + } +} + +// unreadable makes p unreadable, or skips the test when that cannot be +// done (running as root). +func unreadable(t *testing.T, p string) { + t.Helper() + if err := os.Chmod(p, 0); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.Chmod(p, 0o755) }) + if f, err := os.Open(p); err == nil { + f.Close() + t.Skip("running as root: permissions do not keep a file unread") + } +} + +// unreadScan records what it is told about files it could not read and +// what it is told to forget. +type unreadScan struct { + *fake + unread, forgot *[]string + panicOn string +} + +func (u unreadScan) NewScan(TargetKind) Scan { return u } +func (u unreadScan) VisitUnread(p string, dir bool) { + if p == u.panicOn { + panic("hostile") + } + *u.unread = append(*u.unread, fmt.Sprintf("%s %v", p, dir)) +} +func (u unreadScan) Forget(p string) { + if p == u.panicOn { + panic("hostile") + } + *u.forgot = append(*u.forgot, p) +} + +func newUnreadScan(id string) unreadScan { + return unreadScan{&fake{id: id, seen: &[]string{}}, &[]string{}, &[]string{}, ""} +} + +// Round-3 review finding 1: a file or directory the walk met and could +// not read is told to every scan that asks, exists, and is a gap. +func TestUnreadFilesAndDirs(t *testing.T) { + root := tree(t, map[string][]byte{"etc/ssh/sshd_config.d/50.conf": []byte("UsePAM no\n"), "etc/locked/x": []byte("x"), "etc/ok": []byte("ok")}) + unreadable(t, filepath.Join(root, "etc/ssh/sshd_config.d/50.conf")) + unreadable(t, filepath.Join(root, "etc/locked")) + u := newUnreadScan("t-unread") + var exists []bool + u.finish = func(ctx TargetContext) []Finding { + exists = []bool{ctx.Exists("/etc/ssh/sshd_config.d/50.conf"), ctx.Exists("/etc/ok")} + return nil + } + tg := ScanFS([]Detector{u}, root, Options{AsRoot: true}) + sort.Strings(*u.unread) + if strings.Join(*u.unread, ",") != "/etc/locked true,/etc/ssh/sshd_config.d/50.conf false" { + t.Errorf("told %v", *u.unread) + } + if fmt.Sprint(exists) != "[true true]" || tg.Gaps() != 2 { + t.Errorf("exists %v gaps %d skipped %+v", exists, tg.Gaps(), tg.Skipped) + } + // A panic there is the detector failing on that file. + u = newUnreadScan("t-unread-panic") + u.panicOn = "/etc/ssh/sshd_config.d/50.conf" + tg = ScanFS([]Detector{u}, root, Options{AsRoot: true}) + failed := false + for _, s := range tg.Skipped { + failed = failed || s.Path == u.panicOn && s.DetectorFailed + } + if tg.Error != "" || !failed { + t.Errorf("error %q skipped %+v", tg.Error, tg.Skipped) + } +} + +// Round-3 review finding 2: when an image names a path twice, every scan +// forgets the first entry before it is shown the second. +func TestForgetDuplicateEntries(t *testing.T) { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, body := range []string{"first", "second"} { + tw.WriteHeader(&tar.Header{Name: "etc/a", Mode: 0o644, Size: int64(len(body)), Typeflag: tar.TypeReg}) + tw.Write([]byte(body)) + } + tw.WriteHeader(&tar.Header{Name: "etc/b", Mode: 0o644, Size: 1, Typeflag: tar.TypeReg}) + tw.Write([]byte("b")) + tw.Close() + p := filepath.Join(t.TempDir(), "rootfs.tar") + if err := os.WriteFile(p, buf.Bytes(), 0o600); err != nil { + t.Fatal(err) + } + u := newUnreadScan("t-forget") + ScanImage([]Detector{u}, "rootfs:"+p, Options{}) + if strings.Join(*u.forgot, ",") != "/etc/a" || strings.Join(*u.seen, ",") != "/etc/a,/etc/a,/etc/b" { + t.Errorf("forgot %v seen %v", *u.forgot, *u.seen) + } + u = newUnreadScan("t-forget-panic") + u.panicOn = "/etc/a" + tg := ScanImage([]Detector{u}, "rootfs:"+p, Options{}) + if tg.Error != "" || len(tg.Skipped) != 1 || !tg.Skipped[0].DetectorFailed { + t.Errorf("error %q skipped %+v", tg.Error, tg.Skipped) + } +} + +// A detector's limit equal to --max-file-size is --max-file-size: a larger +// file is a gap. One byte under, it is the detector's own: an exclusion. +func TestLimitAtMaxFileSize(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 2000)}) + for _, c := range []struct { + limit int64 + excluded bool + }{{1000, false}, {999, true}} { + limit := c.limit + _, d := capped(fmt.Sprintf("t-atmax%d", limit), osRelease, func(string) int64 { return limit }) + tg := ScanFS([]Detector{d}, root, Options{AsRoot: true, MaxFileSize: 1000}) + if len(tg.Skipped) != 1 || tg.Skipped[0].Excluded != c.excluded { + t.Errorf("limit %d: skipped %+v", limit, tg.Skipped) + } + } +} + +// panicFinishSkips panics in FinishSkips. +type panicFinishSkips struct{ finishSkipper } + +func (p panicFinishSkips) NewScan(TargetKind) Scan { return p } +func (p panicFinishSkips) FinishSkips() []Skip { panic("late") } + +// A panic in FinishSkips fails the target, as one in Finish does. +func TestFinishSkipsPanic(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": []byte("x")}) + _, g := gapDetector("t-finpanic", false) + tg := ScanFS([]Detector{panicFinishSkips{finishSkipper{g, true}}}, root, Options{AsRoot: true}) + if !strings.Contains(tg.Error, "t-finpanic failed") { + t.Errorf("error %q", tg.Error) + } +} + +// visitorOnly is told about files over --max-file-size without having a +// limit of its own. +type visitorOnly struct { + *fake + fakeReader + sizes *[]int64 +} + +func (v visitorOnly) Manifest() Manifest { return v.fake.Manifest() } +func (v visitorOnly) Load() error { return nil } +func (v visitorOnly) NewScan(TargetKind) Scan { return v } +func (v visitorOnly) Visit(f File) []Skip { return v.fake.Visit(f) } +func (v visitorOnly) Finish(ctx TargetContext) []Finding { return nil } +func (v visitorOnly) Wants(p string, h []byte, e bool) bool { return v.fakeReader.Wants(p, h, e) } +func (v visitorOnly) VisitOverLimit(_ string, size int64) []Skip { + *v.sizes = append(*v.sizes, size) + return nil +} + +// A LimitVisitor that is not a Limiter is told about a file it wanted over +// --max-file-size, and reads every other file as before. +func TestLimitVisitorWithoutLimiter(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 2000), "etc/small": []byte("x")}) + f := &fake{id: "t-visitor-only", wants: func(string) bool { return true }, seen: &[]string{}} + v := visitorOnly{f, fakeReader{f}, &[]int64{}} + tg := ScanFS([]Detector{v}, root, Options{AsRoot: true, MaxFileSize: 1000}) + if fmt.Sprint(*v.sizes) != "[2000]" || strings.Join(*f.seen, ",") != "/etc/small" || tg.Gaps() != 1 { + t.Errorf("sizes %v seen %v skipped %+v", *v.sizes, *f.seen, tg.Skipped) } } diff --git a/internal/engine/run.go b/internal/engine/run.go index 3cb01f5..a8f4856 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -214,6 +214,9 @@ type walker struct { // limit on it, for handing it out (Limiter). limited string limits []fileLimit + // exclusions are the exclusion records made for each scan, by path, so + // a gap the scan reports at the end replaces its exclusion. + exclusions []map[string]string } // fileLimit is one detector's own limit on one file, and whether it asked @@ -314,15 +317,50 @@ func (w *walker) sourceOptions(opts Options) source.Options { } so.Read = func(p string, head []byte, exe bool) (bool, int64) { abs := w.abs(p) + if w.ctx.seen[abs] { + // The path comes round again: this entry is the file. + w.forget(abs) + } // The file exists whether or not any detector reads it, so Exists // does not depend on which detectors ran. w.ctx.seen[abs] = true visitHead(p, head) return decide(abs, head, exe) } + so.Unread = func(p string, dir bool) { + abs := w.abs(p) + if !dir { + w.ctx.seen[abs] = true // it exists, read or not + } + for i, s := range w.scans { + if uv, ok := s.(UnreadVisitor); ok { + w.safely(i, abs, func() { uv.VisitUnread(abs, dir) }) + } + } + } return so } +// forget tells every scan to drop what it kept of p. +func (w *walker) forget(p string) { + for i, s := range w.scans { + if f, ok := s.(Forgetter); ok { + w.safely(i, p, func() { f.Forget(p) }) + } + } +} + +// safely runs one of scan i's hooks on p; a panic is recorded as the +// detector failing on p. +func (w *walker) safely(i int, p string, f func()) { + defer func() { + if r := recover(); r != nil { + w.t.Skipped = append(w.t.Skipped, source.Skip{Path: p, Reason: fmt.Sprintf("detector %s failed on this file (%v); not checked", w.ids[i], r), DetectorFailed: true}) + } + }() + f() +} + // limit decides whether to read a file when some detector has limits of its // own: it is read when any detector wants it, as far as the largest limit of // those that do (--max-file-size when one has none). Each detector's limit @@ -394,8 +432,15 @@ func (w *walker) overLimit(i int, p string, size int64) []source.Skip { if size < 0 { what = "(found while reading)" } - return []source.Skip{{Path: p, Excluded: true, - Reason: fmt.Sprintf("excluded: larger than the %d-byte limit of %s for this file %s", w.limits[i].bytes, w.ids[i], what)}} + reason := fmt.Sprintf("excluded: larger than the %d-byte limit of %s for this file %s", w.limits[i].bytes, w.ids[i], what) + if w.exclusions == nil { + w.exclusions = make([]map[string]string, len(w.scans)) + } + if w.exclusions[i] == nil { + w.exclusions[i] = map[string]string{} + } + w.exclusions[i][p] = reason + return []source.Skip{{Path: p, Excluded: true, Reason: reason}} } // visitOverLimitSafely runs one detector's VisitOverLimit, containing a @@ -497,12 +542,29 @@ func (w *walker) finish() { return } for _, sk := range skips { + w.dropExclusion(i, sk.Path) w.t.Skipped = append(w.t.Skipped, source.Skip{Path: sk.Path, Reason: sk.Reason}) } } } } +// dropExclusion removes the exclusion record made for scan i on p: the +// scan reports p as a gap instead. +func (w *walker) dropExclusion(i int, p string) { + if w.exclusions == nil || w.exclusions[i][p] == "" { + return + } + reason := w.exclusions[i][p] + out := w.t.Skipped[:0] + for _, s := range w.t.Skipped { + if !(s.Excluded && s.Path == p && s.Reason == reason) { + out = append(out, s) + } + } + w.t.Skipped = out +} + func finishSkipsSafely(s FinishSkipper) (skips []Skip, err error) { defer func() { if r := recover(); r != nil { diff --git a/internal/source/source.go b/internal/source/source.go index 12d3cb7..668e9c3 100644 --- a/internal/source/source.go +++ b/internal/source/source.go @@ -63,6 +63,11 @@ type Options struct { // (a deliberate exclusion when Over is nil); one over MaxFileSize is // always recorded as such, and Over adds what it returns. Over func(abs string, size int64, own bool) []Skip + // Unread receives each file the walk met and could not read (it could + // not be opened or read, or changed while it was read), and each + // directory whose contents could not be listed (dir), besides the + // record of it. + Unread func(abs string, dir bool) // IsExecutable decides from a file's first bytes whether it is an executable. IsExecutable func(head []byte) bool // Symlink receives every symbolic link (absolute path, target as written). @@ -90,6 +95,15 @@ func (o Options) bound(limit int64) (int64, bool) { return o.MaxFileSize, false } +// unread records a file or directory the walk met and could not read, and +// tells Unread. +func (o Options) unread(abs, reason string, dir bool) Skip { + if o.Unread != nil { + o.Unread(abs, dir) + } + return Skip{Path: abs, Reason: reason} +} + // tooLarge records a file over the limit that applies to it; size is -1 // when it was found larger while reading. func (o Options) tooLarge(abs string, size, most int64, own bool) []Skip { @@ -152,7 +166,7 @@ func Dir(root string, opts Options, visit Visitor) ([]Skip, int, error) { rel, _ := filepath.Rel(root, p) abs := path.Clean("/" + filepath.ToSlash(rel)) if werr != nil { - skips = append(skips, Skip{Path: abs, Reason: werr.Error()}) + skips = append(skips, opts.unread(abs, werr.Error(), d == nil || d.IsDir())) if d != nil && d.IsDir() { return fs.SkipDir } @@ -182,7 +196,7 @@ func Dir(root string, opts Options, visit Visitor) ([]Skip, int, error) { } fi, err := d.Info() if err != nil { - skips = append(skips, Skip{Path: abs, Reason: err.Error()}) + skips = append(skips, opts.unread(abs, err.Error(), false)) return nil } n++ @@ -206,18 +220,18 @@ func readOne(osPath, abs string, fi fs.FileInfo, opts Options, visit Visitor, sk // only the regular file the walk saw. f, err := os.OpenFile(osPath, os.O_RDONLY|openNoFollow, 0) if err != nil { - *skips = append(*skips, Skip{Path: abs, Reason: err.Error()}) + *skips = append(*skips, opts.unread(abs, err.Error(), false)) return nil } defer f.Close() if st, err := f.Stat(); err != nil || !st.Mode().IsRegular() || !os.SameFile(st, fi) { - *skips = append(*skips, Skip{Path: abs, Reason: "changed while it was being scanned (no longer the same regular file); not read"}) + *skips = append(*skips, opts.unread(abs, "changed while it was being scanned (no longer the same regular file); not read", false)) return nil } head := make([]byte, headSize) k, err := io.ReadFull(f, head) if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) && !errors.Is(err, io.EOF) { - *skips = append(*skips, Skip{Path: abs, Reason: err.Error()}) + *skips = append(*skips, opts.unread(abs, err.Error(), false)) return nil } head = head[:k] @@ -242,7 +256,7 @@ func readOne(osPath, abs string, fi fs.FileInfo, opts Options, visit Visitor, sk } rest, err := io.ReadAll(r) if err != nil { - *skips = append(*skips, Skip{Path: abs, Reason: err.Error()}) + *skips = append(*skips, opts.unread(abs, err.Error(), false)) return nil } data := append(head, rest...) From 4c64e505b8ed4ccaedc28e7ac791ad0b1c7bc85b Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 08:45:24 +0000 Subject: [PATCH 076/119] sshole: never clear on what could not be read; a start script behind a wrapper is read From the round-3 review: - A file or directory the walk could not read (no permission, an I/O error) is treated like one over a size limit: an include in it, or a start script in it or in an init directory that could not be listed, makes UsePAM yes unknown, and an unreadable login shell still exists. - What was kept of a path is forgotten when an image names it again (engine.Forgetter), for start scripts as for other files. - The start scripts and includes that kept a verdict unknown are coverage gaps (FinishSkips), replacing their exclusion records, and the reason no longer states a size limit the file may not have hit. - Found by the new lookup tests: a start script behind a wrapper with arguments of its own ('tini -- /entrypoint.sh', 'gosu app ...') was never read, so one that turns PAM off was cleared. Every word of the command that names a script is now read. - Tests: unreadable include, start script, include and init directories and login shell (non-root only), duplicate image entries for a start script, the gap record of a script that kept a verdict unknown, the start-command lookups (PATH, symbolic link, named by a script, behind a wrapper) for read and unread scripts, and a 5 MiB package database read from disk under --root. Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/internal/assess/assess.go | 4 + detectors/sshole/internal/assess/runtime.go | 92 ++++++---- .../sshole/internal/assess/unread_test.go | 95 ++++++++++ detectors/sshole/limit_internal_test.go | 32 ++-- detectors/sshole/limit_test.go | 166 ++++++++++++++++++ detectors/sshole/sshole.go | 120 ++++++++++--- 6 files changed, 436 insertions(+), 73 deletions(-) diff --git a/detectors/sshole/internal/assess/assess.go b/detectors/sshole/internal/assess/assess.go index c1422f8..d30d005 100644 --- a/detectors/sshole/internal/assess/assess.go +++ b/detectors/sshole/internal/assess/assess.go @@ -75,6 +75,9 @@ type Finding struct { AtStart []string `json:"at_start,omitempty"` // Missing lists the conditions that do not hold today. Missing []string `json:"missing,omitempty"` + // Unread lists what was not read and kept the verdict from being + // decided (an include, a start script). + Unread []string `json:"unread,omitempty"` } // Input is a target's evidence. @@ -240,6 +243,7 @@ func assessUnit(in Input, u []*Binary) (Finding, bool) { // A part of the configuration, or a start script, that was not // read can turn PAM off: never clear on what was not read. f.Status = Undecided + f.Unread = unread f.Reason = fmt.Sprintf("this build uses PAM and UsePAM is yes in what was read, but %s was not read and can set UsePAM no", strings.Join(unread, ", ")) f.Message = fmt.Sprintf("OpenSSH %s server on musl without the *sshole fix; whether PAM checks passwords is unknown", main.Release) return f, true diff --git a/detectors/sshole/internal/assess/runtime.go b/detectors/sshole/internal/assess/runtime.go index 4e2c0ec..5417dcb 100644 --- a/detectors/sshole/internal/assess/runtime.go +++ b/detectors/sshole/internal/assess/runtime.go @@ -14,16 +14,33 @@ type Startup struct { Command []string // Scripts are the image's shell scripts ("#!" files), by path. Scripts map[string][]byte - // Unread are scripts that were not read (larger than the scan reads): - // one that runs at start can start sshd with any settings. - Unread map[string]bool + // Unread are scripts that were not read (over a size limit, or + // unreadable): one that runs at start can start sshd with any + // settings. UnreadDirs could not be listed; UnreadAll stands for more + // unread files than were recorded. + Unread map[string]bool + UnreadDirs []string + UnreadAll bool +} + +// inUnreadDir is the directory that was not listed that holds p, or "". +func (s Startup) inUnreadDir(p string) string { + for _, d := range s.UnreadDirs { + if p == d || strings.HasPrefix(p, strings.TrimSuffix(d, "/")+"/") { + return d + } + } + return "" } // unreadStart lists the scripts that run at start and were not read: the // command's own script, one a start script names, and those in the init // directories. func (s Startup) unreadStart(resolve func(string) (string, bool), scripts []script) []string { - if len(s.Unread) == 0 { + if s.UnreadAll { + return []string{"more files than the scan records"} + } + if len(s.Unread) == 0 && len(s.UnreadDirs) == 0 { return nil } var out []string @@ -43,22 +60,24 @@ func (s Startup) unreadStart(resolve func(string) (string, bool), scripts []scri } } } - if s.Unread[r] && !seen[r] { + if !strings.HasPrefix(r, "/") { + for _, d := range pathDirs { + if s.inUnreadDir(d+r) != "" { + r = d + r + break + } + } + } + if d := s.inUnreadDir(r); d != "" { + r = d // a script in a directory that was not listed + } + if (s.Unread[r] || s.inUnreadDir(r) != "") && !seen[r] { seen[r] = true out = append(out, r) } } - c := s.Command - for len(c) > 1 && isWrapper(path.Base(c[0])) { - c = c[1:] - } - if len(c) > 0 { - add(c[0]) - for _, w := range c[1:] { - if strings.HasPrefix(w, "/") { - add(w) - } - } + for _, w := range s.Command { + add(w) } for _, sc := range scripts { for _, m := range absPathRE.FindAllString(sc.text, -1) { @@ -72,6 +91,14 @@ func (s Startup) unreadStart(resolve func(string) (string, bool), scripts []scri } } } + for _, u := range s.UnreadDirs { + for _, d := range initDirs { + // An init directory that was not listed, or one inside it. + if strings.HasPrefix(d, strings.TrimSuffix(u, "/")+"/") || strings.HasPrefix(u+"/", d) { + add(u) + } + } + } sort.Strings(out) return out } @@ -114,23 +141,20 @@ func (s Startup) startScripts(resolve func(string) (string, bool)) []script { } } if len(s.Command) > 0 { + // Every word of the command that names a script: wrappers take + // arguments of their own ("tini --", "gosu USER", "su-exec USER"), + // so the script is not always the first word after them. c := s.Command - for len(c) > 1 && isWrapper(path.Base(c[0])) { - c = c[1:] - } - if isShell(path.Base(c[0])) { - for i := 1; i < len(c); i++ { - if c[i] == "-c" && i+1 < len(c) { - out = append(out, script{where: "the container command", text: c[i+1]}) - break - } - if strings.HasPrefix(c[i], "/") { - add(c[i]) - break + for i, w := range c { + if isShell(path.Base(w)) { + for j := i + 1; j < len(c); j++ { + if c[j] == "-c" && j+1 < len(c) { + out = append(out, script{where: "the container command", text: c[j+1]}) + break + } } } - } else { - add(c[0]) + add(w) } // One level of scripts the command's scripts name. for _, sc := range append([]script(nil), out...) { @@ -158,14 +182,6 @@ type script struct{ where, text string } var absPathRE = regexp.MustCompile(`/[A-Za-z0-9_./-]+`) -func isWrapper(b string) bool { - switch b { - case "tini", "dumb-init", "su-exec", "gosu", "env", "exec", "catatonit", "s6-svscan": - return true - } - return false -} - func isShell(b string) bool { switch b { case "sh", "bash", "ash", "dash", "busybox": diff --git a/detectors/sshole/internal/assess/unread_test.go b/detectors/sshole/internal/assess/unread_test.go index 8b3778c..8764435 100644 --- a/detectors/sshole/internal/assess/unread_test.go +++ b/detectors/sshole/internal/assess/unread_test.go @@ -54,3 +54,98 @@ func TestConfigUnread(t *testing.T) { t.Errorf("all read: unread %v", c.Unread) } } + +// Round-3 review finding 5: how the start command finds its scripts, read +// or not: by PATH, through a symbolic link, and named by another script. +func TestStartCommandLookups(t *testing.T) { + resolve := func(p string) (string, bool) { + if p == "/entrypoint" { + return "/usr/local/bin/real-entrypoint.sh", true + } + return p, false + } + read := map[string][]byte{ + "/usr/local/bin/start.sh": []byte("#!/bin/sh\nexec /opt/run.sh\n"), + "/usr/local/bin/real-entrypoint.sh": []byte("#!/bin/sh\nexec /usr/sbin/sshd -D\n"), + "/opt/run.sh": []byte("#!/bin/sh\nexec /usr/sbin/sshd -D -o UsePAM=no\n"), + } + where := func(sc []script) string { + var out []string + for _, s := range sc { + out = append(out, s.where) + } + return strings.Join(out, ",") + } + for _, c := range []struct { + cmd []string + want string + }{ + {[]string{"start.sh"}, "start.sh,/opt/run.sh"}, // PATH, then a script it names + {[]string{"/entrypoint"}, "/entrypoint"}, // a symbolic link + {[]string{"tini", "--", "/bin/sh", "/opt/run.sh"}, "/opt/run.sh"}, // a wrapper and a shell + } { + st := Startup{Command: c.cmd, Scripts: read} + if got := where(st.startScripts(resolve)); got != c.want { + t.Errorf("%v: %s, want %s", c.cmd, got, c.want) + } + } + + // The same lookups find a script that was not read. + for _, c := range []struct { + cmd []string + unread string + dirs []string + want string + }{ + {[]string{"start.sh"}, "/usr/local/bin/start.sh", nil, "/usr/local/bin/start.sh"}, + {[]string{"/entrypoint"}, "/usr/local/bin/real-entrypoint.sh", nil, "/usr/local/bin/real-entrypoint.sh"}, + {[]string{"start.sh"}, "/opt/run.sh", nil, "/opt/run.sh"}, // named by a script that was read + {[]string{"/usr/bin/other"}, "/opt/run.sh", nil, ""}, // not run at start + {nil, "/etc/cont-init.d/10-sshd", nil, "/etc/cont-init.d/10-sshd"}, + {[]string{"start.sh"}, "", []string{"/usr/local/bin"}, "/usr/local/bin"}, // its directory was not listed + {nil, "", []string{"/etc"}, "/etc"}, // holds the init directories + } { + u := map[string]bool{} + if c.unread != "" { + u[c.unread] = true + } + st := Startup{Command: c.cmd, Scripts: map[string][]byte{}, Unread: u, UnreadDirs: c.dirs} + for p, b := range read { + if p != c.unread { + st.Scripts[p] = b + } + } + got := strings.Join(st.unreadStart(resolve, st.startScripts(resolve)), ",") + if got != c.want { + t.Errorf("%v with %q %v unread: %q, want %q", c.cmd, c.unread, c.dirs, got, c.want) + } + } + if got := (Startup{UnreadAll: true}).unreadStart(nil, nil); len(got) != 1 { + t.Errorf("past the record limit: %v", got) + } +} + +// A start script behind a wrapper that takes arguments ("tini --", "gosu +// USER") is read like one named first: one that turns PAM off is not +// cleared. +func TestStartScriptBehindWrapper(t *testing.T) { + for _, cmd := range [][]string{ + {"/entrypoint.sh"}, + {"tini", "--", "/entrypoint.sh"}, + {"/sbin/tini", "-s", "--", "/entrypoint.sh"}, + {"gosu", "app", "/entrypoint.sh"}, + } { + w := newWorld("10.0p2", true, map[string]string{"/etc/ssh/sshd_config": "UsePAM yes\n"}) + in := Input{ + Binaries: w.binaries, Files: w.files, + Accounts: ParseAccounts(w.files.Read("/etc/passwd"), w.files.Read("/etc/shadow"), w.files.Read("/etc/group"), nil), + Resolve: func(p string) (string, bool) { _, ok := w.files[p]; return p, ok }, + Now: w.now(), + Image: true, + Startup: Startup{Command: cmd, Scripts: map[string][]byte{"/entrypoint.sh": []byte("#!/bin/sh\nexec /usr/sbin/sshd -D -o UsePAM=no\n")}}, + } + if f := one(t, Run(in)); f.Status == Inactive { + t.Errorf("%v: %s (%s)", cmd, f.Status, f.Reason) + } + } +} diff --git a/detectors/sshole/limit_internal_test.go b/detectors/sshole/limit_internal_test.go index 85b961a..91c7097 100644 --- a/detectors/sshole/limit_internal_test.go +++ b/detectors/sshole/limit_internal_test.go @@ -64,19 +64,27 @@ func TestLimits(t *testing.T) { } } -// Round-2 review finding 5: of several entries for one path, the last -// decides: an over-limit entry after a read one leaves the path unread, a -// read entry after an over-limit one leaves it read. -func TestDuplicateEntries(t *testing.T) { - const p = "/etc/ssh/sshd_config.d/50-site.conf" +// Round-2 review finding 5, round-3 finding 2: when an image names a path +// again, the engine has the scan forget the first entry, read or not. +func TestForget(t *testing.T) { + const p = "/etc/cont-init.d/10-sshd" s := (&Detector{}).NewScan(engine.Image).(*scan) - s.Visit(engine.File{Path: p, Data: []byte("UsePAM yes\n")}) - s.VisitOverLimit(p, maxKept+1) - if _, ok := s.files[p]; ok || !s.over[p] { - t.Errorf("read then over: files %v over %v", s.files, s.over) + s.Visit(engine.File{Path: p, Data: []byte("#!/bin/sh\nexec /usr/sbin/sshd -D\n")}) + s.Forget(p) + s.VisitOverLimit(p, maxScript+1) + if _, ok := s.scripts[p]; ok || !s.unreadScripts[p] || s.scriptBytes != 0 { + t.Errorf("read then over: scripts %v unread %v bytes %d", s.scripts, s.unreadScripts, s.scriptBytes) } - s.Visit(engine.File{Path: p, Data: []byte("UsePAM yes\n")}) - if _, ok := s.files[p]; !ok || s.over[p] || s.unreadScripts[p] { - t.Errorf("over then read: files %v over %v unread %v", s.files, s.over, s.unreadScripts) + s.Forget(p) + s.Visit(engine.File{Path: p, Data: []byte("#!/bin/sh\n")}) + if _, ok := s.scripts[p]; !ok || s.unreadScripts[p] { + t.Errorf("over then read: scripts %v unread %v", s.scripts, s.unreadScripts) + } + const c = "/etc/ssh/sshd_config.d/50-site.conf" + s.Visit(engine.File{Path: c, Data: []byte("UsePAM yes\n")}) + s.Forget(c) + s.VisitOverLimit(c, maxKept+1) + if _, ok := s.files[c]; ok || !s.over[c] { + t.Errorf("config read then over: files %v over %v", s.files, s.over) } } diff --git a/detectors/sshole/limit_test.go b/detectors/sshole/limit_test.go index d9b12a8..bd11832 100644 --- a/detectors/sshole/limit_test.go +++ b/detectors/sshole/limit_test.go @@ -1,8 +1,10 @@ package sshole_test import ( + "archive/tar" "bytes" "encoding/json" + "fmt" "os" "path/filepath" "strings" @@ -247,3 +249,167 @@ func TestIncludeOverLimitOnDisk(t *testing.T) { t.Errorf("an include over the limit on disk: %s", v) } } + +// unreadable makes p unreadable, or skips the test when that cannot be +// done (running as root). +func unreadable(t *testing.T, p string) { + t.Helper() + if err := os.Chmod(p, 0); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.Chmod(p, 0o755) }) + if f, err := os.Open(p); err == nil { + f.Close() + t.Skip("running as root: permissions do not keep a file unread") + } +} + +// Round-3 review finding 1: an include, a start script or an init +// directory the scan could not read keeps a PAM server from being cleared, +// and an unreadable login shell still exists. +func TestUnreadableNeverClears(t *testing.T) { + for _, c := range []struct{ name, rel, text, lock string }{ + {"an include", "etc/ssh/sshd_config.d/50-site.conf", "UsePAM no\n", ""}, + {"an include directory", "etc/ssh/sshd_config.d/50-site.conf", "UsePAM no\n", "etc/ssh/sshd_config.d"}, + {"a start script", "etc/cont-init.d/10-sshd", "#!/bin/sh\nexec /usr/sbin/sshd -D -o UsePAM=no\n", ""}, + {"an init directory", "etc/cont-init.d/10-sshd", "#!/bin/sh\nexec /usr/sbin/sshd -D -o UsePAM=no\n", "etc/cont-init.d"}, + } { + root := pamRoot(t) + write(t, root, c.rel, []byte(c.text), 0o644) + lock := c.lock + if lock == "" { + lock = c.rel + } + unreadable(t, filepath.Join(root, lock)) + if v, code := sshVerdict(t, "--as-root", root); v.Cleared() || code == 0 { + t.Errorf("%s not readable: %s exit %d", c.name, v, code) + } + } + verdict := func(lock bool) string { + root := alpineRoot(t, "10.0_p1-r10") + write(t, root, "etc/passwd", []byte("root:x:0:0:root:/root:/bin/sh\nalice:x:1000:1000::/home/alice:/bin/sh\nbob:x:1001:1001::/home/bob:/usr/local/bin/menu\n"), 0o644) + write(t, root, "usr/local/bin/menu", []byte("#!/bin/sh\nexec /bin/sh\n"), 0o755) + if lock { + unreadable(t, filepath.Join(root, "usr/local/bin/menu")) + } + fs, _, _ := scanExit(t, "--detector", "sshole", "--as-root", root) + return string(fs[0].Verdict) + "/" + fs[0].Severity + } + if a, b := verdict(false), verdict(true); a != b { + t.Errorf("a login shell that cannot be read: %s, one that can: %s", b, a) + } +} + +// tarOf writes root and then extra entries (path, content) to a rootfs tar. +func tarOf(t *testing.T, root string, extra ...[2]string) string { + t.Helper() + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + err := filepath.Walk(root, func(p string, fi os.FileInfo, err error) error { + if err != nil || p == root { + return err + } + rel, _ := filepath.Rel(root, p) + h, _ := tar.FileInfoHeader(fi, "") + if fi.Mode()&os.ModeSymlink != 0 { + h.Linkname, _ = os.Readlink(p) + } + h.Name = filepath.ToSlash(rel) + if err := tw.WriteHeader(h); err != nil { + return err + } + if fi.Mode().IsRegular() { + b, _ := os.ReadFile(p) + tw.Write(b) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + for _, e := range extra { + tw.WriteHeader(&tar.Header{Name: e[0], Mode: 0o755, Size: int64(len(e[1])), Typeflag: tar.TypeReg}) + tw.Write([]byte(e[1])) + } + tw.Close() + p := filepath.Join(t.TempDir(), "rootfs.tar") + if err := os.WriteFile(p, buf.Bytes(), 0o600); err != nil { + t.Fatal(err) + } + return p +} + +// Round-3 review finding 2: of two image entries for a start script, the +// last is the file, whatever the first was. +func TestDuplicateStartScript(t *testing.T) { + root := pamRoot(t) + const p = "etc/cont-init.d/10-sshd" + for _, c := range []struct { + name string + first, second string + want engine.Verdict + }{ + {"a script that turns PAM off, then plain text", "#!/bin/sh\nexec /usr/sbin/sshd -D -o UsePAM=no\n", "not a script\n", engine.Inactive}, + {"a harmless script, then one that turns PAM off", "#!/bin/sh\ntrue\n", "#!/bin/sh\nexec /usr/sbin/sshd -D -o UsePAM=no\n", engine.Vulnerable}, + {"one over the limit, then a harmless one", "#!/bin/sh\n" + strings.Repeat("#", maxScript), "#!/bin/sh\ntrue\n", engine.Inactive}, + } { + img := tarOf(t, root, [2]string{p, c.first}, [2]string{p, c.second}) + fs, _, _ := scanImage(t, img) + if len(fs) != 1 || fs[0].Verdict != c.want { + t.Errorf("%s: %+v", c.name, fs) + } + } +} + +const maxScript = 256 << 10 + +func scanImage(t *testing.T, img string) ([]engine.Finding, []struct { + Path string `json:"path"` + Excluded bool `json:"excluded"` +}, int) { + t.Helper() + var out, errb bytes.Buffer + code := cli.Run(cfg, []string{"scan", "image", "--format", "json", "--detector", "sshole", "rootfs:" + img}, &out, &errb) + var r struct { + Targets []struct { + Error string `json:"error"` + Findings []engine.Finding `json:"findings"` + Skipped []struct { + Path string `json:"path"` + Excluded bool `json:"excluded"` + } `json:"skipped"` + } `json:"targets"` + } + if err := json.Unmarshal(out.Bytes(), &r); err != nil || len(r.Targets) != 1 || r.Targets[0].Error != "" { + t.Fatalf("%v %+v\n%s", err, r, errb.String()) + } + return r.Targets[0].Findings, r.Targets[0].Skipped, code +} + +// Round-3 review finding 4: a start script that kept the verdict unknown +// is a coverage gap, with one record that does not contradict another. +func TestUnreadStartScriptIsAGap(t *testing.T) { + root := pamRoot(t) + padded(t, root, "etc/cont-init.d/10-sshd", []byte("#!/bin/sh\nexec /usr/sbin/sshd -D -o UsePAM=no\n"), 307200) + fs, skipped, _ := scanExit(t, "--detector", "sshole", "--as-root", root) + var recs []bool + for _, s := range skipped { + if s.Path == "/etc/cont-init.d/10-sshd" { + recs = append(recs, s.Excluded) + } + } + if len(fs) != 1 || fs[0].Verdict != engine.Unknown || fmt.Sprint(recs) != "[false]" { + t.Errorf("findings %+v records %v (skipped %+v)", fs, recs, skipped) + } +} + +// Round-3 review finding 5: a package database between 4 and 16 MiB is +// read from disk under --root. +func TestPackageDBFromDisk(t *testing.T) { + root := alpineRoot(t, "10.0_p1-r11") + db, _ := os.ReadFile(filepath.Join(root, "lib/apk/db/installed")) + padded(t, root, "lib/apk/db/installed", db, 5<<20) + if v, _ := sshVerdict(t, "--root", root, filepath.Join(root, "usr")); v != engine.Fixed { + t.Errorf("a 5 MiB apk database read from disk: %s", v) + } +} diff --git a/detectors/sshole/sshole.go b/detectors/sshole/sshole.go index 34370ab..004caa9 100644 --- a/detectors/sshole/sshole.go +++ b/detectors/sshole/sshole.go @@ -15,7 +15,6 @@ package sshole import ( - "fmt" "os" "path" "path/filepath" @@ -148,7 +147,7 @@ const ( // NewScan starts a filesystem or image scan. func (d *Detector) NewScan(kind engine.TargetKind) engine.Scan { - return &scan{kind: kind, files: map[string][]byte{}, scripts: map[string][]byte{}, over: map[string]bool{}, unreadScripts: map[string]bool{}} + return &scan{kind: kind, files: map[string][]byte{}, scripts: map[string][]byte{}, over: map[string]bool{}, unreadScripts: map[string]bool{}, gaps: map[string]bool{}} } type scan struct { @@ -157,11 +156,32 @@ type scan struct { files map[string][]byte scripts map[string][]byte scriptBytes int - // over holds the files a verdict reads that were not read (over the - // limit or --max-file-size): present, but their content is unknown. + // over holds the files a verdict reads that were not read (over a size + // limit, or unreadable): present, but their content is unknown. over map[string]bool - // unreadScripts are files that may be start scripts and were not read. + // unreadScripts are files that may be start scripts and were not + // read; unreadDirs directories whose contents were not listed. + // Past maxUnread, unreadAll stands for the rest. unreadScripts map[string]bool + unreadDirs []string + unreadAll bool + // gaps are the files that kept a verdict from being decided. + gaps map[string]bool +} + +// maxUnread bounds the unread files and directories one target records. +const maxUnread = 1 << 16 + +// unread records a file that was not read: its content is unknown. +func (s *scan) unread(p string) { + if keep(p) { + s.over[p] = true + } + if len(s.unreadScripts) >= maxUnread { + s.unreadAll = true + return + } + s.unreadScripts[p] = true // its head is not known here: it may be a script } // VisitOverLimit records a file the scan asked for and did not get, over @@ -171,25 +191,57 @@ type scan struct { // once a server is found (FinishSkips). The record here is an exclusion: // with no OpenSSH server in the target, none of these files matters. func (s *scan) VisitOverLimit(p string, _ int64) []engine.Skip { - // The last entry for a path wins (a tar can hold several). + s.unread(p) + return nil +} + +// VisitUnread records a file or directory the walk could not read, as +// VisitOverLimit does: an include or start script in it is unknown. +func (s *scan) VisitUnread(p string, dir bool) { + if !dir { + s.unread(p) + return + } + if len(s.unreadDirs) >= maxUnread { + s.unreadAll = true + return + } + s.unreadDirs = append(s.unreadDirs, p) +} + +// Forget drops what was kept of p: an image names it again. +func (s *scan) Forget(p string) { delete(s.files, p) - delete(s.scripts, p) - if keep(p) { - s.over[p] = true + if b, ok := s.scripts[p]; ok { + s.scriptBytes -= len(b) + delete(s.scripts, p) + } + delete(s.over, p) + delete(s.unreadScripts, p) + bs := s.binaries[:0] + for _, b := range s.binaries { + if b.Path != p { + bs = append(bs, b) + } } - s.unreadScripts[p] = true // its head is not known here: it may be a script - return nil + s.binaries = bs } -// FinishSkips reports the files the verdict reads that were not read, as -// coverage gaps, when an OpenSSH server was found. +// FinishSkips reports, when an OpenSSH server was found, the files the +// verdict reads that were not read and the start scripts that kept a +// verdict from being decided, as coverage gaps. func (s *scan) FinishSkips() []engine.Skip { if len(s.binaries) == 0 { return nil } var out []engine.Skip for p := range s.over { - out = append(out, engine.Skip{Path: p, Reason: fmt.Sprintf("larger than the %d bytes sshole reads of a file its verdict depends on; not checked", keptLimit(p))}) + out = append(out, engine.Skip{Path: p, Reason: "not read (over a size limit, or unreadable), and sshole's verdict depends on it; not checked"}) + } + for p := range s.gaps { + if !s.over[p] { + out = append(out, engine.Skip{Path: p, Reason: "not read (over a size limit, or unreadable), and it can start sshd with other settings, so the verdict is unknown"}) + } } sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path }) return out @@ -199,9 +251,6 @@ func (s *scan) Visit(f engine.File) []engine.Skip { if f.Member { return nil // installed servers only, not copies inside archives } - // The last entry for a path wins (a tar can hold several). - delete(s.over, f.Path) - delete(s.unreadScripts, f.Path) if isScript(f.Data) { if len(f.Data) <= maxScript && s.scriptBytes+len(f.Data) <= maxScripts { s.scripts[f.Path] = f.Data @@ -209,7 +258,8 @@ func (s *scan) Visit(f engine.File) []engine.Skip { } else { // Read for its other use (a file named like sshd_config) or // past the total: not checked as a start script. - s.unreadScripts[f.Path] = true + s.unread(f.Path) + delete(s.over, f.Path) // read as a file the verdict reads } } if keep(f.Path) && int64(len(f.Data)) <= keptLimit(f.Path) && !archive.IsExecutable(f.Data) { @@ -226,7 +276,7 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { if len(s.binaries) == 0 { return nil } - fs := &files{kept: s.files, over: s.over, root: ctx.SystemRoot()} + fs := &files{kept: s.files, over: s.over, unreadDirs: s.unreadDirs, root: ctx.SystemRoot()} links, _ := ctx.Links() res := resolver{links: links, exists: func(p string) bool { if ctx.Exists(p) { @@ -264,10 +314,15 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { Resolve: res.resolve, Branch: branch, Image: s.kind == engine.Image, - Startup: assess.Startup{Command: ctx.Command(), Scripts: s.scripts, Unread: s.unreadScripts}, + Startup: assess.Startup{Command: ctx.Command(), Scripts: s.scripts, Unread: s.unreadScripts, UnreadDirs: s.unreadDirs, UnreadAll: s.unreadAll}, }) out := make([]engine.Finding, 0, len(found)) for _, x := range found { + for _, p := range x.Unread { + if s.unreadScripts[p] || s.over[p] || fs.inUnreadDir(p) { + s.gaps[p] = true + } + } out = append(out, finding(x)) } return out @@ -337,15 +392,28 @@ func yes(b bool) string { // root's own files from disk. type files struct { kept map[string][]byte - over map[string]bool // present but larger than maxKept: Read is nil - root string + over map[string]bool // present but not read: Read is nil + // unreadDirs could not be listed: a pattern in one matches a file + // that cannot be read. + unreadDirs []string + root string +} + +// inUnreadDir reports whether p lies in a directory that was not listed. +func (f *files) inUnreadDir(p string) bool { + for _, d := range f.unreadDirs { + if p == d || strings.HasPrefix(p, strings.TrimSuffix(d, "/")+"/") { + return true + } + } + return false } func (f *files) Read(p string) []byte { if b, ok := f.kept[p]; ok { return b } - if f.root == "" || f.over[p] { + if f.root == "" || f.over[p] || f.inUnreadDir(p) { return nil } return f.disk(p) @@ -438,6 +506,12 @@ func (f *files) Glob(pattern string) []string { for p := range f.over { match(p) } + if f.inUnreadDir(path.Dir(pattern)) && !seen[pattern] { + // What it matches there is unknown: stand for it with the pattern, + // which Read cannot give. + seen[pattern] = true + out = append(out, pattern) + } if f.root != "" { if full, ok := f.diskPath(pattern); ok { ms, _ := filepath.Glob(full) From 9f7b3ebbeb19b4489ea6721d593f26556b11aeb8 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 08:46:45 +0000 Subject: [PATCH 077/119] java4shell: settings gaps only with a runtime; unread files and duplicate entries handled From the round-3 review: - A JVM settings file not read is a coverage gap only when the target holds a runtime (FinishSkips), replacing its exclusion record. - A file or directory the walk could not read is treated like one over a size limit (VisitUnread): a start script the command runs in it keeps a mitigation from being reported, as does one past the record limit. - What was kept of a path is forgotten when an image names it again (Forget): kept files, dpkg lists, script variables, settings, VM libraries, release files, crash logs and runtime downloads. - Tests: settings gap with and without a runtime, the backported-decoder path with an unread start script, a script behind a wrapper in a directory that could not be listed, a >256 KiB script read only as a settings file, and Forget. Co-Authored-By: Claude Opus 5.5 --- .../java4shell/internal/assess/assess.go | 21 +++- .../java4shell/internal/assess/assess_test.go | 23 ++++ detectors/java4shell/java4shell.go | 114 ++++++++++++++---- detectors/java4shell/limit_internal_test.go | 112 +++++++++++------ 4 files changed, 209 insertions(+), 61 deletions(-) diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index 158cacb..2987d95 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -77,6 +77,10 @@ type Input struct { // UnreadScripts are files that may be start scripts and were not read // (larger than the scan reads): what they pass to java is unknown. UnreadScripts map[string]bool + // UnreadDirs could not be listed; UnreadAll stands for more unread + // files than were recorded. + UnreadDirs []string + UnreadAll bool // Owners maps installed files to the OS package that installed them. Owners map[string]Package // Resolve follows symbolic links within the target. @@ -487,16 +491,23 @@ func javaHomeIs(in Input, env map[string]string, root string) bool { // unreadCommandScript is a script the container's command runs that was // not read, or "". func unreadCommandScript(in Input) string { + if len(in.Command) > 0 && in.UnreadAll { + return "(one of more files than the scan records)" + } for _, w := range in.Command { p := w if in.Resolve != nil { p = in.Resolve(w) } - if in.UnreadScripts[p] { - return p - } - if in.UnreadScripts[w] { - return w + for _, c := range []string{p, w} { + if in.UnreadScripts[c] { + return c + } + for _, d := range in.UnreadDirs { + if strings.HasPrefix(c, strings.TrimSuffix(d, "/")+"/") { + return c + } + } } } return "" diff --git a/detectors/java4shell/internal/assess/assess_test.go b/detectors/java4shell/internal/assess/assess_test.go index 91bdfd7..31dd375 100644 --- a/detectors/java4shell/internal/assess/assess_test.go +++ b/detectors/java4shell/internal/assess/assess_test.go @@ -292,4 +292,27 @@ func TestMitigationWithUnreadStartScript(t *testing.T) { if f := one(t, in); f.Status != Mitigated { t.Errorf("an unread script the command does not run: %+v", f) } + // Behind a wrapper, in a directory that could not be listed, or past + // the record limit. + in.UnreadScripts = nil + in.Command, in.UnreadDirs = []string{"tini", "--", "/opt/app/start.sh"}, []string{"/opt/app"} + if f := one(t, in); f.Status != Vulnerable { + t.Errorf("a start script in a directory not listed: %+v", f) + } + in.UnreadDirs, in.UnreadAll = nil, true + if f := one(t, in); f.Status != Vulnerable { + t.Errorf("past the record limit: %+v", f) + } + + // Round-3 review finding 5: the same for a backported decoder (Oracle + // 8 Performance Pack). + in = Input{Libraries: []*jvm.Library{lib(t, temurin+"/lib/server/libjvm.so", testlib.Lib{Version: "1.8.0_511-perf-b33", VBMI: true})}, + Env: []string{"JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics"}, Command: []string{"/entrypoint.sh"}} + if f := one(t, in); f.Status != Mitigated { + t.Fatalf("backport, script read: %+v", f) + } + in.UnreadScripts = map[string]bool{"/entrypoint.sh": true} + if f := one(t, in); f.Status != Vulnerable { + t.Errorf("backport, script not read: %+v", f) + } } diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 77fc4dc..3feefa6 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -23,6 +23,7 @@ import ( "fmt" "path" "regexp" + "slices" "sort" "strings" @@ -135,25 +136,83 @@ func (d *Detector) Limit(p string, head []byte, _ bool) int64 { return most } -// VisitOverLimit records a JVM settings file over the limit as a coverage -// gap: an option in it can undo a mitigation the scan would report. A -// start script not read keeps a mitigation from being reported when the -// container's command runs it. The other files with a limit are deliberate -// exclusions: no verdict is cleared on them (a runtime is cleared only by -// its VM library and release file). +// VisitOverLimit records a file the scan asked for and did not get, over +// its limit or --max-file-size. A JVM settings file not read is a coverage +// gap once a runtime is found (FinishSkips): an option in it can undo a +// mitigation the scan would report. A start script not read keeps a +// mitigation from being reported when the container's command runs it. +// The other files with a limit are deliberate exclusions: no verdict is +// cleared on them (a runtime is cleared only by its VM library and release +// file). func (s *scan) VisitOverLimit(p string, _ int64) []engine.Skip { - // The last entry for a path wins (a tar can hold several). - delete(s.scripts, p) - if base := path.Base(p); !hsErr.MatchString(base) && p != "/etc/os-release" && p != "/usr/lib/os-release" && - len(s.unreadScripts) < maxScripts { - // Its head is not known here: it may be a start script, which - // keeps a mitigation from being reported for the command it runs. - s.unreadScripts[p] = true + s.notRead(p) + return nil +} + +// VisitUnread records a file or directory the walk could not read, as +// VisitOverLimit does. +func (s *scan) VisitUnread(p string, dir bool) { + if !dir { + s.notRead(p) + } else if len(s.unreadDirs) < maxScripts { + s.unreadDirs = append(s.unreadDirs, p) + } else { + s.unreadAll = true } - if jvm.SettingKind(p) == "" { +} + +func (s *scan) notRead(p string) { + if jvm.SettingKind(p) != "" && len(s.overSettings) < maxSettings { + s.overSettings[p] = true + } + if hsErr.MatchString(path.Base(p)) || p == "/etc/os-release" || p == "/usr/lib/os-release" { + return + } + if len(s.unreadScripts) >= maxScripts { + s.unreadAll = true + return + } + // Its head is not known here: it may be a start script, which keeps a + // mitigation from being reported for the command it runs. + s.unreadScripts[p] = true +} + +// FinishSkips reports the JVM settings files not read as coverage gaps +// when the target holds a runtime. +func (s *scan) FinishSkips() []engine.Skip { + if len(s.libs) == 0 { return nil } - return []engine.Skip{{Path: p, Reason: fmt.Sprintf("larger than the %d MiB java4shell reads of a JVM settings file; its options are not checked", maxSetting>>20)}} + var out []engine.Skip + for p := range s.overSettings { + out = append(out, engine.Skip{Path: p, Reason: "a JVM settings file not read (over a size limit, or unreadable); its options are not checked"}) + } + sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path }) + return out +} + +// Forget drops what was kept of p: an image names it again. +func (s *scan) Forget(p string) { + if b, ok := s.kept[p]; ok { + s.keptBytes -= len(b) + delete(s.kept, p) + } + if assess.IsDpkgList(p) { + k := strings.TrimSuffix(path.Base(p), ".list") + s.keptBytes -= len(s.lists[k]) + delete(s.lists, k) + } + delete(s.scripts, p) + delete(s.unreadScripts, p) + delete(s.overSettings, p) + if path.Base(p) == "release" { + delete(s.releases, path.Dir(p)) + delete(s.badReleases, path.Dir(p)) + } + s.libs = slices.DeleteFunc(s.libs, func(l *jvm.Library) bool { return l.Path == p }) + s.settings = slices.DeleteFunc(s.settings, func(st jvm.Setting) bool { return st.File == p }) + s.crashes = slices.DeleteFunc(s.crashes, func(c crash) bool { return c.Path == p }) + s.archives = slices.DeleteFunc(s.archives, func(a string) bool { return a == p }) } var hsErr = regexp.MustCompile(`^hs_err_pid\d{1,10}\.log$`) @@ -220,7 +279,7 @@ const ( // NewScan starts a filesystem or image scan. func (d *Detector) NewScan(kind engine.TargetKind) engine.Scan { return &scan{kind: kind, releases: map[string]jvm.Release{}, badReleases: map[string]string{}, - kept: map[string][]byte{}, lists: map[string][]byte{}, scripts: map[string]map[string]bool{}, unreadScripts: map[string]bool{}} + kept: map[string][]byte{}, lists: map[string][]byte{}, scripts: map[string]map[string]bool{}, unreadScripts: map[string]bool{}, overSettings: map[string]bool{}} } type scan struct { @@ -236,10 +295,15 @@ type scan struct { dropped int keptBytes int archives []string // runtime downloads seen by name, not read - // unreadScripts may be start scripts and were not read. + // unreadScripts may be start scripts and were not read; unreadDirs + // could not be listed; unreadAll stands for more than were recorded. unreadScripts map[string]bool - optionFiles int // settings files that set JVM options - plainUnits int // systemd units that set none + unreadDirs []string + unreadAll bool + // overSettings are JVM settings files not read. + overSettings map[string]bool + optionFiles int // settings files that set JVM options + plainUnits int // systemd units that set none // limits records the caps this target reached; a capped scan clears // nothing. limits []string @@ -341,9 +405,13 @@ func (s *scan) Visit(f engine.File) []engine.Skip { s.keptBytes += len(f.Data) } } - delete(s.unreadScripts, f.Path) - if isScript(f.Data) && len(f.Data) > maxScript && len(s.unreadScripts) < maxScripts { - s.unreadScripts[f.Path] = true // read as a settings file or package database only + if isScript(f.Data) && len(f.Data) > maxScript { + // Read as a settings file or package database only. + if len(s.unreadScripts) < maxScripts { + s.unreadScripts[f.Path] = true + } else { + s.unreadAll = true + } } if isScript(f.Data) && len(f.Data) <= maxScript { vars := map[string]bool{} @@ -408,6 +476,8 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { Resolve: res.resolve, Scripts: s.scripts, UnreadScripts: s.unreadScripts, + UnreadDirs: s.unreadDirs, + UnreadAll: s.unreadAll, } if s.kind == engine.Image { in.Env = ctx.Env() diff --git a/detectors/java4shell/limit_internal_test.go b/detectors/java4shell/limit_internal_test.go index b801300..2140d51 100644 --- a/detectors/java4shell/limit_internal_test.go +++ b/detectors/java4shell/limit_internal_test.go @@ -3,12 +3,14 @@ package java4shell import ( "archive/tar" "bytes" + "fmt" "os" "path/filepath" "runtime" "strings" "testing" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" "github.com/DefectDojo/earlylight/internal/engine" ) @@ -142,49 +144,63 @@ func TestOSReleaseAtLimit(t *testing.T) { } } -// A JVM settings file over the limit is a coverage gap; the other files -// with a limit are deliberate exclusions. +// A JVM settings file over the limit is a coverage gap when the target +// holds a runtime, an exclusion when it does not; the other files with a +// limit are exclusions. func TestOverLimitGaps(t *testing.T) { - root := t.TempDir() - for rel, size := range map[string]int64{ - "opt/atlassian/confluence/bin/setenv.sh": maxSetting + 1, - "etc/os-release": maxOSRelease + 1, - "opt/install.sh": maxScript + 1, - "var/lib/dpkg/status": maxKept + 1, - } { - p := filepath.Join(root, rel) - if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { - t.Fatal(err) + for _, runtime := range []bool{false, true} { + root := t.TempDir() + for rel, size := range map[string]int64{ + "opt/atlassian/confluence/bin/setenv.sh": maxSetting + 1, + "etc/os-release": maxOSRelease + 1, + "opt/install.sh": maxScript + 1, + "var/lib/dpkg/status": maxKept + 1, + } { + p := filepath.Join(root, rel) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + head := []byte("X=1\n") + if strings.HasSuffix(rel, ".sh") { + head = []byte("#!/bin/sh\n") + } + if err := os.WriteFile(p, head, 0o644); err != nil { + t.Fatal(err) + } + if err := os.Truncate(p, size); err != nil { + t.Fatal(err) + } } - head := []byte("X=1\n") - if strings.HasSuffix(rel, ".sh") { - head = []byte("#!/bin/sh\n") + if runtime { + p := filepath.Join(root, "opt/atlassian/confluence/jre/lib/server/libjvm.so") + os.MkdirAll(filepath.Dir(p), 0o755) + if err := os.WriteFile(p, testlib.Build(testlib.Lib{Version: "17.0.12+7", VBMI: true}), 0o644); err != nil { + t.Fatal(err) + } } - if err := os.WriteFile(p, head, 0o644); err != nil { - t.Fatal(err) + tg := engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true}) + got := map[string][]bool{} + for _, s := range tg.Skipped { + got[s.Path] = append(got[s.Path], s.Excluded) } - if err := os.Truncate(p, size); err != nil { - t.Fatal(err) + settings := "[true]" + if runtime { + settings = "[false]" // one record: the gap replaces the exclusion } - } - tg := engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true}) - got := map[string]bool{} - for _, s := range tg.Skipped { - got[s.Path] = s.Excluded - } - want := map[string]bool{"/opt/atlassian/confluence/bin/setenv.sh": false, "/etc/os-release": true, "/opt/install.sh": true, "/var/lib/dpkg/status": true} - if len(got) != len(want) || tg.Gaps() != 1 { - t.Fatalf("skipped %+v", tg.Skipped) - } - for p, ex := range want { - if got[p] != ex { - t.Errorf("%s: excluded %v, want %v", p, got[p], ex) + want := map[string]string{"/opt/atlassian/confluence/bin/setenv.sh": settings, "/etc/os-release": "[true]", "/opt/install.sh": "[true]", "/var/lib/dpkg/status": "[true]"} + if len(got) != len(want) { + t.Fatalf("runtime %v: skipped %+v", runtime, tg.Skipped) + } + for p, ex := range want { + if fmt.Sprint(got[p]) != ex { + t.Errorf("runtime %v: %s: excluded %v, want %s", runtime, p, got[p], ex) + } } } } -// A script over the limit is remembered as unread, and of several entries -// for one path the last decides. +// A script over the limit is remembered as unread, as is one read only as +// a settings file (over the script limit); Forget drops either. func TestUnreadScripts(t *testing.T) { s := (&Detector{}).NewScan(engine.Image).(*scan) s.VisitOverLimit("/entrypoint.sh", 300<<10) @@ -192,12 +208,40 @@ func TestUnreadScripts(t *testing.T) { if !s.unreadScripts["/entrypoint.sh"] || s.unreadScripts["/etc/os-release"] { t.Fatalf("unread %v", s.unreadScripts) } + s.Forget("/entrypoint.sh") s.Visit(engine.File{Path: "/entrypoint.sh", Data: []byte("#!/bin/sh\nexec java $JAVA_OPTS -jar /app.jar\n")}) if s.unreadScripts["/entrypoint.sh"] || !s.scripts["/entrypoint.sh"]["JAVA_OPTS"] { t.Errorf("read after unread: unread %v scripts %v", s.unreadScripts, s.scripts) } + s.Forget("/entrypoint.sh") s.VisitOverLimit("/entrypoint.sh", 300<<10) if !s.unreadScripts["/entrypoint.sh"] || s.scripts["/entrypoint.sh"] != nil { t.Errorf("unread after read: unread %v scripts %v", s.unreadScripts, s.scripts) } + // setenv.sh is read up to 1 MiB as a settings file, past the script + // limit: not checked as a start script. + big := append([]byte("#!/bin/sh\nJAVA_OPTS=\"$JAVA_OPTS -XX:+UseBASE64Intrinsics\"\n"), make([]byte, maxScript)...) + s.Visit(engine.File{Path: "/opt/app/bin/setenv.sh", Data: big}) + if !s.unreadScripts["/opt/app/bin/setenv.sh"] { + t.Errorf("a %d-byte script read as a settings file: unread %v", len(big), s.unreadScripts) + } +} + +// Forget drops everything kept of a path. +func TestForget(t *testing.T) { + s := (&Detector{}).NewScan(engine.Image).(*scan) + lib := testlib.Build(testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true}) + s.Visit(engine.File{Path: "/opt/java/lib/server/libjvm.so", Data: lib}) + s.Visit(engine.File{Path: "/opt/java/release", Data: testlib.Release("JAVA_VERSION", "21.0.13")}) + s.Visit(engine.File{Path: "/var/lib/dpkg/status", Data: []byte("Package: x\n")}) + s.Visit(engine.File{Path: "/opt/app/bin/setenv.sh", Data: []byte("JAVA_OPTS=-XX:-UseBASE64Intrinsics\n")}) + if len(s.libs) != 1 || len(s.releases) != 1 || len(s.kept) != 1 || len(s.settings) != 1 { + t.Fatalf("libs %d releases %d kept %d settings %d", len(s.libs), len(s.releases), len(s.kept), len(s.settings)) + } + for _, p := range []string{"/opt/java/lib/server/libjvm.so", "/opt/java/release", "/var/lib/dpkg/status", "/opt/app/bin/setenv.sh"} { + s.Forget(p) + } + if len(s.libs)+len(s.releases)+len(s.kept)+len(s.settings) != 0 || s.keptBytes != 0 { + t.Errorf("libs %d releases %d kept %d settings %d bytes %d", len(s.libs), len(s.releases), len(s.kept), len(s.settings), s.keptBytes) + } } From 5c027efb64cc01c9ab1f7333218c6c378100635a Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 08:47:10 +0000 Subject: [PATCH 078/119] emudhra: forget an earlier entry for a path an image names again From the round-3 review: an image that names certifi's bundle twice, a read one then one over --max-file-size, cleared botocore's bundle on the first. The scan now forgets what it kept and found of a path, and inside it, when the path comes round again (engine.Forgetter). Co-Authored-By: Claude Opus 5.5 --- detectors/emudhra/emudhra.go | 15 +++++++++++++++ detectors/emudhra/limit_test.go | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/detectors/emudhra/emudhra.go b/detectors/emudhra/emudhra.go index c2c7a93..cd85119 100644 --- a/detectors/emudhra/emudhra.go +++ b/detectors/emudhra/emudhra.go @@ -10,6 +10,7 @@ package emudhra import ( "context" + "slices" "strings" "time" @@ -102,6 +103,20 @@ func keep(p string) bool { return p == "/etc/ca-certificates.conf" || strings.HasSuffix(p, "/certifi/core.py") } +// Forget drops what was found in p, and inside it: an image names it +// again, and the last entry is the file. +func (s *scan) Forget(p string) { + delete(s.files, p) + delete(s.scanned, p) + in := func(q string) bool { return q == p || strings.HasPrefix(q, p+"!/") } + s.findings = slices.DeleteFunc(s.findings, func(x detect.Finding) bool { return in(x.Path) }) + for k := range s.dedupe { + if in(k[:strings.IndexByte(k, 0)]) { + delete(s.dedupe, k) + } + } +} + func (s *scan) Visit(f engine.File) []engine.Skip { if keep(f.Path) { s.files[f.Path] = f.Data // raw path: lookups must never alias another file diff --git a/detectors/emudhra/limit_test.go b/detectors/emudhra/limit_test.go index e3e8edf..38bd26b 100644 --- a/detectors/emudhra/limit_test.go +++ b/detectors/emudhra/limit_test.go @@ -1,6 +1,7 @@ package emudhra_test import ( + "archive/tar" "bytes" "os" "path/filepath" @@ -43,3 +44,36 @@ func TestBotocoreNotClearedByUnreadCertifi(t *testing.T) { } } } + +// Round-3 review finding 2: of two image entries for certifi's bundle, the +// last is the file: one over --max-file-size after a read one does not +// clear botocore's bundle. +func TestCertifiNamedTwice(t *testing.T) { + g3, err := os.ReadFile(filepath.Join(g3Bundle(t), "cacert.pem")) + if err != nil { + t.Fatal(err) + } + site := "usr/lib/python3/site-packages/" + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, e := range []struct { + name string + body []byte + }{ + {site + "botocore/cacert.pem", g3}, + {site + "certifi/cacert.pem", []byte("# empty bundle\n")}, + {site + "certifi/cacert.pem", append(g3, bytes.Repeat([]byte("#"), 5000)...)}, + } { + tw.WriteHeader(&tar.Header{Name: e.name, Mode: 0o644, Size: int64(len(e.body)), Typeflag: tar.TypeReg}) + tw.Write(e.body) + } + tw.Close() + img := filepath.Join(t.TempDir(), "rootfs.tar") + if err := os.WriteFile(img, buf.Bytes(), 0o600); err != nil { + t.Fatal(err) + } + var out, errb bytes.Buffer + if code := cli.Run(engine, []string{"scan", "image", "--detector", "emudhra", "--max-file-size", "4096", "rootfs:" + img}, &out, &errb); code != 1 { + t.Errorf("exit %d, want 1\n%s%s", code, out.String(), errb.String()) + } +} From eb09dd4ed8246baa1ed8c49e04094772fcb1616e Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 08:47:36 +0000 Subject: [PATCH 079/119] brotli, php2shell: forget an earlier entry for a path an image names again From the round-3 review ('the last entry wins' for every detector): when an image names a path twice, what was found in or kept of the first entry is dropped (engine.Forgetter). Co-Authored-By: Claude Opus 5.5 --- detectors/brotli/brotli.go | 10 ++++++++++ detectors/brotli/forget_internal_test.go | 17 +++++++++++++++++ detectors/php2shell/forget_internal_test.go | 19 +++++++++++++++++++ detectors/php2shell/php2shell.go | 8 ++++++++ 4 files changed, 54 insertions(+) create mode 100644 detectors/brotli/forget_internal_test.go create mode 100644 detectors/php2shell/forget_internal_test.go diff --git a/detectors/brotli/brotli.go b/detectors/brotli/brotli.go index 433f2c0..e6fc361 100644 --- a/detectors/brotli/brotli.go +++ b/detectors/brotli/brotli.go @@ -16,6 +16,8 @@ import ( "github.com/DefectDojo/earlylight/detectors/brotli/internal/fingerprint" "github.com/DefectDojo/earlylight/internal/archive" "github.com/DefectDojo/earlylight/internal/engine" + "slices" + "strings" ) // ID is the detector's ID. @@ -82,6 +84,14 @@ func (d *Detector) NewScan(engine.TargetKind) engine.Scan { return &scan{} } type scan struct{ findings []engine.Finding } +// Forget drops what was found in p, and inside it: an image names it +// again, and the last entry is the file. +func (s *scan) Forget(p string) { + s.findings = slices.DeleteFunc(s.findings, func(f engine.Finding) bool { + return f.Path == p || strings.HasPrefix(f.Path, p+"!/") + }) +} + func (s *scan) Visit(f engine.File) []engine.Skip { if !archive.IsExecutable(f.Data) && !fingerprint.IsWasm(f.Data) { return nil diff --git a/detectors/brotli/forget_internal_test.go b/detectors/brotli/forget_internal_test.go new file mode 100644 index 0000000..1fe136c --- /dev/null +++ b/detectors/brotli/forget_internal_test.go @@ -0,0 +1,17 @@ +package brotli + +import ( + "testing" + + "github.com/DefectDojo/earlylight/internal/engine" +) + +// When an image names a path again, what was found in the first entry, +// and inside it, is dropped. +func TestForget(t *testing.T) { + s := &scan{findings: []engine.Finding{{Path: "/a"}, {Path: "/a!/x.so"}, {Path: "/ab"}, {Path: "/b"}}} + s.Forget("/a") + if len(s.findings) != 2 || s.findings[0].Path != "/ab" || s.findings[1].Path != "/b" { + t.Errorf("%+v", s.findings) + } +} diff --git a/detectors/php2shell/forget_internal_test.go b/detectors/php2shell/forget_internal_test.go new file mode 100644 index 0000000..1e9bf28 --- /dev/null +++ b/detectors/php2shell/forget_internal_test.go @@ -0,0 +1,19 @@ +package php2shell + +import ( + "testing" + + "github.com/DefectDojo/earlylight/detectors/php2shell/internal/detect" +) + +// When an image names a path again, what was kept of the first entry is +// dropped. +func TestForget(t *testing.T) { + c := &collector{dbFiles: map[string][]byte{"/var/lib/dpkg/status": []byte("x")}, + binaries: []*detect.Binary{{Path: "/usr/bin/php"}, {Path: "/usr/bin/php8"}}} + c.Forget("/var/lib/dpkg/status") + c.Forget("/usr/bin/php") + if len(c.dbFiles) != 0 || len(c.binaries) != 1 || c.binaries[0].Path != "/usr/bin/php8" { + t.Errorf("db %v binaries %+v", c.dbFiles, c.binaries) + } +} diff --git a/detectors/php2shell/php2shell.go b/detectors/php2shell/php2shell.go index 383ff3f..c6d8dad 100644 --- a/detectors/php2shell/php2shell.go +++ b/detectors/php2shell/php2shell.go @@ -16,6 +16,7 @@ import ( "context" "fmt" "io" + "slices" "strings" "time" @@ -160,6 +161,13 @@ func upx(head []byte) bool { return bytes.Contains(head, []byte("UPX!")) || (bytes.Contains(head, []byte("UPX0")) && bytes.Contains(head, []byte("UPX1"))) } +// Forget drops what was kept of p: an image names it again, and the last +// entry is the file. +func (c *collector) Forget(p string) { + delete(c.dbFiles, p) + c.binaries = slices.DeleteFunc(c.binaries, func(b *detect.Binary) bool { return b.Path == p }) +} + func (c *collector) Visit(f engine.File) []engine.Skip { if f.Member || excluded(f.Path, c.exclude) { return nil // installed files only, not archive members or excluded paths From 14f6a408efac149614db4a427c381e9dd18e867d Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 09:09:38 +0000 Subject: [PATCH 080/119] java4shell: '=' in package file paths; mise short versions are moving pins; round-4 nits (round 4) 1. A local package file whose path contains '=' (/cache/jdk=17/...rpm, /mnt/v=1/...rpm, /a=b/*.rpm, /a=b/jdk-17.0.9_linux-x64_bin.rpm) was taken for a version pin and dropped. The pin guard now applies only to an argument with no '/' whose part before '=' is not a package file. 2. mise resolves a short version to the newest release, so 'no update = GA build' hid mise pins (graalvm-community-17, oracle-graalvm-17.0, temurin-17, microsoft-17) and raised false alarms (corretto-21, sapmachine-21). In mise files, and in .tool-versions for names other than asdf's own GA names (openjdk, sapmachine, java-se-ri), a short version without a build or pre-release marker is a moving pin: a line without a fix is vulnerable; Corretto and SapMachine are fixed; Temurin, Microsoft (17, 21, 25) and GraalVM are vulnerable; any other vendor or a bare number is not checked. 3. IBM Semeru rpms are OpenJ9 and skipped; -eabeta.N, -rcN, -EA and Liberica's +N-ea are pre-releases; dpkg -i and apt-get install of a .deb file are read like rpm files (Debian name_version_arch becomes a pin; vendor debs by their file name); the not-checked reason for a package file no longer claims it was a pattern or a URL. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/FACTS.md | 2 +- .../java4shell/internal/repo/coverage_test.go | 114 ++++++++++++++++ detectors/java4shell/internal/repo/repo.go | 124 +++++++++++++++--- 3 files changed, 222 insertions(+), 18 deletions(-) diff --git a/detectors/java4shell/FACTS.md b/detectors/java4shell/FACTS.md index 71928e6..0eb80fa 100644 --- a/detectors/java4shell/FACTS.md +++ b/detectors/java4shell/FACTS.md @@ -83,7 +83,7 @@ The lead read these; they could not be fetched from the research host. Facts her | Oracle Java SE | 8u511b33-perf, 17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3 and earlier affected; the fixed Oracle version numbers were not relayed, so Oracle builds after .0.3 are judged by the OpenJDK fixed releases | Oracle CSPU November 2026 | | Oracle GraalVM, GraalVM Community | GraalVM for JDK 17.0.21.0.3 and 21.0.13.0.3 and GraalVM Enterprise Edition 21.3.20.0.3 affected (Oracle). GraalVM Community: the newest release on graalvm/graalvm-ce-builds was published 2026-11-03, before the fix. **No fixed GraalVM build known** (2026-11-18). See "GraalVM" below | Oracle CSPU November 2026; [graalvm/graalvm-ce-builds releases](https://github.com/graalvm/graalvm-ce-builds/releases) (reviewer, 2026-11-18) | | Azul Zulu, BellSoft Liberica | **not checked**: their pages could not be read (HTTP 403/404 for the lead; unreachable here). Docker Hub `azul/zulu-openjdk` and `bellsoft/liberica-openjdk-debian` newest tags were 27.0.1.0.3 / 21.0.13.0.3 on 2026-11-17 (not fixed) | registry-1.docker.io tag list | -| Version-manager names in vendors' own numbers | Azul Zulu's own numbers start with the Java line (asdf `zulu-22.32.15` is JDK 22): a line that received no fix is reported vulnerable from that number alone, other Zulu numbers are not checked (**inferred** from Zulu's naming, not checked against each release). JetBrains Runtime names carry the Java update (`jetbrains-17.0.9b1087.7` is 17.0.9): an update older than the fixed one is vulnerable; the fixed update itself is not checked, since JetBrains may backport into it. Dragonwell writes six numbers (`dragonwell-21.0.8.0.8.9`): judged by the update, never cleared by the extra numbers. A name without an update (asdf `openjdk-21`, `liberica-21+37`, `openjdk-21-ea+26`, sdkman `21-tem`) is the line's GA or early-access build | asdf-java and sdkman version lists (reviewer, 2026-11-18); **inferred** for Zulu | +| Version-manager names in vendors' own numbers | Azul Zulu's own numbers start with the Java line (asdf `zulu-22.32.15` is JDK 22): a line that received no fix is reported vulnerable from that number alone, other Zulu numbers are not checked (**inferred** from Zulu's naming, not checked against each release). JetBrains Runtime names carry the Java update (`jetbrains-17.0.9b1087.7` is 17.0.9): an update older than the fixed one is vulnerable; the fixed update itself is not checked, since JetBrains may backport into it. Dragonwell writes six numbers (`dragonwell-21.0.8.0.8.9`): judged by the update, never cleared by the extra numbers. A name without an update is the line's GA or early-access build where the name pins one release: asdf's own short names (`openjdk-21`, `sapmachine-21`, `java-se-ri-22+36`), any name with a build or a pre-release marker (`liberica-21+37`, `openjdk-21-ea+26`) and sdkman (`21-tem`). mise resolves a short version (`java@temurin-17`, `21`, `corretto-21`) to the newest release when it installs, so in mise files, and for other short names in `.tool-versions`, it is a moving pin judged by the vendor's status as setup-java's is: Corretto and SapMachine fixed, Temurin, Microsoft and GraalVM not, others not checked | asdf-java and sdkman version lists (reviewer, 2026-11-18); **inferred** for Zulu | | IBM Semeru | OpenJ9, not HotSpot (see above) | image inspection | | Debian | **not fixed** (2026-11-18): the tracker lists every package vulnerable and unfixed: openjdk-17 bookworm-security 17.0.21+9-1~deb12u1, sid 17.0.21.0.3+1-1; openjdk-21 trixie-security 21.0.13+9-1~deb13u2, forky/sid 21.0.13.0.3+1-1; openjdk-25 trixie-security 25.0.5+8-1~deb13u1, sid 25.0.5.0.3+1-3; openjdk-27 sid 27.0.1.0.3+1-1 | [security-tracker.debian.org CVE-2026-114938](https://security-tracker.debian.org/tracker/CVE-2026-114938) (lead); deb.debian.org and security.debian.org pools | | Ubuntu | **not fixed** (2026-11-18): newest sources openjdk-17 17.0.21.0.3+1-1 (17.0.21.0.3+1-1~XX.04.1 in the stable releases), openjdk-21 21.0.13.0.3+1-1, openjdk-25 25.0.5.0.3+1-3~XX.04.1; none is the fixed update or a backport. The Ubuntu CVE page could not be read | archive.ubuntu.com pool (2026-11-17; openjdk-21 and -17 reread by the reviewer 2026-11-18) | diff --git a/detectors/java4shell/internal/repo/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go index ea16f72..5bb9f8a 100644 --- a/detectors/java4shell/internal/repo/coverage_test.go +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -667,3 +667,117 @@ func TestRound3Names(t *testing.T) { t.Errorf("openjdk-17 (17.0.0) reported: %+v", f) } } + +// Round 4, item 1: a package file path containing '=' is still a file. +func TestFilePathWithEquals(t *testing.T) { + lines := []string{ + "FROM registry.access.redhat.com/ubi9/ubi", + "RUN rpm -i /cache/jdk=17/java-17-openjdk-17.0.9.0.9-1.el9.x86_64.rpm", // 2 + "RUN dnf install -y /mnt/v=1/java-17-openjdk-17.0.9.0.9-1.el9.x86_64.rpm", // 3 + "RUN rpm -i https://example.com/java-17-openjdk-17.0.9.0.9-1.el9.x86_64.rpm?x=1", // 4 + "RUN rpm -i https://example.com/java-17-openjdk-17.0.9.0.9-1.el9.x86_64.rpm#x=1", // 5 + "RUN rpm -i /a=b/java-17-openjdk-*.rpm", // 6 + "RUN rpm -i /a=b/*.rpm", // 7 + "RUN rpm -i /a=b/jdk-17.0.9_linux-x64_bin.rpm", // 8 + "RUN apt-get install -y openjdk-17-jdk=17.*", // 9 a pin, not a file + } + res := scan(t, tree(t, map[string]string{"Dockerfile": strings.Join(lines, "\n") + "\n"})) + checkAll(t, res, []want{ + {"Dockerfile", 2, RulePackage, StatusVulnerable}, + {"Dockerfile", 3, RulePackage, StatusVulnerable}, + {"Dockerfile", 4, RulePackage, StatusVulnerable}, + {"Dockerfile", 5, RulePackage, StatusVulnerable}, + {"Dockerfile", 6, RulePackage, StatusUnknown}, + {"Dockerfile", 7, RulePackage, StatusUnknown}, + {"Dockerfile", 8, RulePackage, StatusVulnerable}, + {"Dockerfile", 9, RulePackage, StatusVulnerable}, + }) +} + +// Round 4, item 2: mise resolves a short version to the newest release, so +// it is a moving pin judged by the vendor's status, as setup-java's is; in +// .tool-versions only asdf's own GA names (openjdk-21, sapmachine-21, +// java-se-ri-22) are exact. +func TestMiseMovingPins(t *testing.T) { + mise := func(v string) string { return "[tools]\njava = \"" + v + "\"\n" } + files := map[string]string{ + "a/mise.toml": mise("temurin-17"), + "b/mise.toml": mise("17"), + "c/mise.toml": mise("corretto-21"), + "d/mise.toml": mise("sapmachine-21"), + "e/mise.toml": mise("graalvm-community-17"), + "f/mise.toml": mise("oracle-graalvm-17.0"), + "g/mise.toml": mise("liberica-17"), + "h/mise.toml": mise("microsoft-17"), + "i/mise.toml": mise("oracle-17"), + "j/mise.toml": mise("dragonwell-17"), + "k/mise.toml": mise("temurin-22"), + "l/mise.toml": mise("openjdk-21"), + "m/mise.toml": mise("temurin-21.0.5+11.0.LTS"), + "a/.tool-versions": "java temurin-17\n", + "b/.tool-versions": "java openjdk-21\n", + "c/.tool-versions": "java corretto-25\n", + "d/.tool-versions": "java kona-17\n", + } + res := scan(t, tree(t, files)) + checkAll(t, res, []want{ + {"a/mise.toml", 2, RuleJavaPin, StatusVulnerable}, + {"b/mise.toml", 2, RuleNotChecked, StatusUnknown}, + {"e/mise.toml", 2, RuleJavaPin, StatusVulnerable}, + {"f/mise.toml", 2, RuleJavaPin, StatusVulnerable}, + {"g/mise.toml", 2, RuleNotChecked, StatusUnknown}, + {"h/mise.toml", 2, RuleJavaPin, StatusVulnerable}, + {"i/mise.toml", 2, RuleNotChecked, StatusUnknown}, + {"j/mise.toml", 2, RuleNotChecked, StatusUnknown}, + {"k/mise.toml", 2, RuleLine, StatusVulnerable}, + {"l/mise.toml", 2, RuleNotChecked, StatusUnknown}, + {"m/mise.toml", 2, RuleJavaPin, StatusVulnerable}, + {"a/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, + {"b/.tool-versions", 1, RuleJavaPin, StatusVulnerable}, // asdf's 21 GA + {"d/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + }) + for _, f := range []string{"c/mise.toml", "d/mise.toml", "c/.tool-versions"} { + if x, ok := find(res, f, 2); ok || func() bool { _, ok := find(res, f, 1); return ok }() { + t.Errorf("%s: Corretto and SapMachine published fixed releases, mise installs them: %+v", f, x) + } + } +} + +// Round 4, item 3. +func TestRound4Nits(t *testing.T) { + files := map[string]string{ + "Dockerfile": strings.Join([]string{ + "FROM ubuntu:24.04", + "RUN rpm -ivh /tmp/ibm-semeru-open-17-jdk-17.0.9.9-1.x86_64.rpm", // 2 OpenJ9 + "RUN dpkg -i /tmp/jdk-17.0.9_linux-x64_bin.deb", // 3 + "RUN apt-get install -y ./zulu17.46.19-ca-jdk17.0.9-linux_amd64.deb", // 4 + "RUN dpkg -i /tmp/bellsoft-jdk17.0.9+11-linux-amd64.deb", // 5 + "RUN dpkg -i /tmp/openjdk-17-jre-headless_17.0.9+9-1_amd64.deb", // 6 + "RUN rpm -i /tmp/java-17-openjdk-headless-17.0.21.1.2.3.4-1.el9.x86_64.rpm", // 7 + "RUN dpkg -l", // 8 + }, "\n") + "\n", + "a/.tool-versions": "java openjdk-17.0.21.1-eabeta.1\n", + "b/.tool-versions": "java openjdk-17.0.21.1-rc1\n", + "c/.tool-versions": "java openjdk-17.0.21.1-EA\n", + "d/.tool-versions": "java liberica-17.0.21.1+2-ea\n", + } + res := scan(t, tree(t, files)) + checkAll(t, res, []want{ + {"Dockerfile", 3, RulePackage, StatusVulnerable}, + {"Dockerfile", 4, RulePackage, StatusVulnerable}, + {"Dockerfile", 5, RulePackage, StatusVulnerable}, + {"Dockerfile", 6, RulePackage, StatusVulnerable}, + {"a/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"b/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"c/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + {"d/.tool-versions", 1, RuleNotChecked, StatusUnknown}, + }) + for _, l := range []int{2, 8} { + if f, ok := find(res, "Dockerfile", l); ok { + t.Errorf("Dockerfile:%d reported: %+v", l, f) + } + } + if f, ok := find(res, "Dockerfile", 7); !ok || f.Status == StatusVulnerable && false || strings.Contains(f.Reason, "named by a pattern or a URL") { + t.Errorf("seven-number rpm file: %+v", f) + } +} diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 5f29702..d4c664d 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -400,7 +400,7 @@ func (s *scanner) judgeVersion(rel string, line int, ga bool, verText, source, v // preReleaseSuffix is a pre-release marker in a version name: 21-ea, // 17.0.21.1-ea, 22-beta. -var preReleaseSuffix = regexp.MustCompile(`-(?:ea|beta|rc)\b.*$`) +var preReleaseSuffix = regexp.MustCompile(`(?i)-(?:ea|beta|rc).*$`) func pinFix(feature int, source string) string { if fx := knowledge.FixedVersion(feature); fx != "" { @@ -480,7 +480,11 @@ func (s *scanner) sdkmanrc(rel, text string) { // (a Zulu version, not a Java version: not judged). var asdfJava = regexp.MustCompile(`^(?:(adoptopenjdk|temurin|corretto|openjdk|sapmachine|liberica|microsoft|oracle|semeru-openj9|semeru|dragonwell|kona|zulu|graalvm|graalvm-community|oracle-graalvm|mandrel|jetbrains|java-se-ri)-)?(?:(?:jre|jdk|openj9|musl|lite|javafx|fx|crac)-)*(\d[\d.]*)`) -func (s *scanner) asdfValue(rel string, line int, value, source string) { +// +// mise is true for a mise file: mise resolves a short version (temurin-17, +// 21) to the newest release when it installs, where asdf takes the name as +// one release (openjdk-21 is 21 GA). +func (s *scanner) asdfValue(rel string, line int, value, source string, mise bool) { m := asdfJava.FindStringSubmatch(value) if m == nil { return @@ -492,6 +496,12 @@ func (s *scanner) asdfValue(rel string, line int, value, source string) { return } } + idx := asdfJava.FindStringSubmatchIndex(value) + if rest := value[idx[5]:]; strings.Count(strings.TrimSuffix(m[2], "."), ".") < 2 && !anyBuildRE.MatchString(rest) && !asdfPreRelease.MatchString(rest) && + (mise || !asdfGANames[m[1]]) { + s.movingPin(rel, line, atoi(m[2]), m[1], value, source) + return + } switch m[1] { case "zulu": // Zulu's own numbers start with the Java line (zulu-22.32.15 is @@ -531,17 +541,69 @@ func (s *scanner) asdfValue(rel string, line int, value, source string) { if !strings.HasSuffix(m[2], ".") { // temurin-17.0.21.1+1: OpenJDK's build after +; openjdk-21-ea+26: // a pre-release and its build. + // Liberica writes the marker after the build (+2-ea). idx := asdfJava.FindStringSubmatchIndex(value) rest := value[idx[5]:] - if e := asdfPreRelease.FindStringSubmatch(rest); e != nil { - ver += "-" + e[1] - rest = rest[len(e[0]):] + if asdfPreRelease.MatchString(rest) { + ver += "-ea" + } + if b := anyBuildRE.FindStringSubmatch(rest); b != nil { + ver += "+" + b[1] } - ver += plusBuild(rest) } s.judgeVersion(rel, line, true, ver, source, m[1]) } +// asdfGANames are the asdf-java names whose short form is one release, +// the line's GA build (openjdk-21, sapmachine-21, java-se-ri-22). +var asdfGANames = map[string]bool{"openjdk": true, "sapmachine": true, "java-se-ri": true} + +// movingPin judges a version-manager pin that installs the newest release +// of a Java line when it runs (mise java@temurin-17, java@21): by the +// line, and for a line with a fix by whether the vendor's newest release +// had it when the data was checked, as setup-java's moving versions are. +func (s *scanner) movingPin(rel string, line, feature int, vendor, value, source string) { + if feature < 17 { + return // Java 8 to 16: no decoder + } + props := map[string]string{"source": source, "current": refs.CleanText(value, 80)} + l, ok := knowledge.LineOf(feature) + switch { + case !ok: + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: props, + Reason: fmt.Sprintf("Java %d is not in this detector's release data (%s)", feature, knowledge.Checked), + Message: fmt.Sprintf("%s selects %s: not checked for the Java4Shell fix", source, refs.CleanText(value, 80))}) + return + case l.Fixed == nil: + s.lineToolchain(rel, line, feature, source+" ("+refs.CleanText(value, 60)+")") + return + } + fx := knowledge.FixedVersion(feature) + props["fixed_in"] = fx + who := "" + switch { + case vendor == "corretto" || vendor == "sapmachine": + return // their newest release has the fix: installed today, it is fixed + case vendor == "temurin" || vendor == "adoptopenjdk": + who = "Eclipse Temurin" + case vendor == "microsoft" && microsoftLines[feature]: + who = "Microsoft" + case isGraal(vendor): + who = "GraalVM (Oracle and the GraalVM project)" + } + if who == "" { + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: props, + Reason: fmt.Sprintf("the version installs the newest %s Java %d when it runs, and whether that release had the fix was not checked", orAny(vendor), feature), + Message: fmt.Sprintf("%s selects %s, the newest release of Java %d at install time: not checked for the Java4Shell fix", source, refs.CleanText(value, 80), feature), + Fix: fmt.Sprintf("Check that the installed release is Java %s or later of the same update.", fx)}) + return + } + s.add(Finding{Rule: RuleJavaPin, File: rel, Line: line, Level: "warning", Status: StatusVulnerable, Props: props, + Reason: fmt.Sprintf("the version installs the newest %s Java %d when it runs, and %s had published no release with the fix as of %s", orAny(vendor), feature, who, knowledge.Checked), + Message: fmt.Sprintf("%s selects %s, the newest release of Java %d at install time, which had no Java4Shell fix yet", source, refs.CleanText(value, 80), feature), + Fix: fmt.Sprintf("Reinstall once %s publishes Java %s or later, or select corretto or sapmachine, whose newest Java %d has the fix.", who, fx, feature)}) +} + // plusBuild returns "+N" when rest starts with OpenJDK's build (+11 in // 21.0.5+11.0.LTS), "" otherwise. func plusBuild(rest string) string { @@ -553,8 +615,12 @@ func plusBuild(rest string) string { var plusBuildRE = regexp.MustCompile(`^\+(\d{1,9})`) +// anyBuildRE is OpenJDK's build anywhere in what follows a version name's +// numbers: +26 in -ea+26, +2 in +2-ea. +var anyBuildRE = regexp.MustCompile(`\+(\d{1,9})`) + // asdfPreRelease is a pre-release marker after an asdf version. -var asdfPreRelease = regexp.MustCompile(`^-(ea|beta|rc)\b`) +var asdfPreRelease = regexp.MustCompile(`(?i)-(?:ea|beta|rc)`) // CorrettoJava turns an Amazon Corretto version into the Java version it // ships. Corretto has written its build number in the fourth place @@ -580,7 +646,7 @@ func (s *scanner) toolVersions(rel, text string) { for i, l := range lines(text) { f := strings.Fields(l) if len(f) >= 2 && f[0] == "java" { - s.asdfValue(rel, i+1, f[1], ".tool-versions") + s.asdfValue(rel, i+1, f[1], ".tool-versions", false) } } } @@ -590,7 +656,7 @@ var miseJava = regexp.MustCompile(`^\s*java\s*=\s*["']([^"']+)["']`) func (s *scanner) mise(rel, text string) { for i, l := range lines(text) { if m := miseJava.FindStringSubmatch(l); m != nil { - s.asdfValue(rel, i+1, m[1], path.Base(rel)) + s.asdfValue(rel, i+1, m[1], path.Base(rel), true) } } } @@ -871,7 +937,7 @@ func (s *scanner) jibRef(rel string, line, col int, image string) { var ( // installRE finds a package tool on a RUN line; installArgs decides // whether it installs. - installRE = regexp.MustCompile(`\b(?:apt-get|apt|apk|dnf5?|yum|microdnf|tdnf|zypper|rpm)\b`) + installRE = regexp.MustCompile(`\b(?:apt-get|apt|apk|dnf5?|yum|microdnf|tdnf|zypper|rpm|dpkg)\b`) aptJava = regexp.MustCompile(`\b(openjdk-(\d{1,2})-(?:jre|jdk)(?:-headless)?)\b(=([^\s;&|]+))?`) apkJava = regexp.MustCompile(`\b(openjdk(\d{1,2})(?:-jre|-jdk|-jre-headless|-jmods)?)(?:([=~><]+)([^\s;&|]+))?`) rpmJava = regexp.MustCompile(`\b(java-(\d{1,2})-(openjdk|amazon-corretto)(?:-headless|-devel|-jdk)?)(?:-(\d[\w.:*?+~-]*))?`) @@ -880,6 +946,8 @@ var ( rpmLatest = regexp.MustCompile(`^java-latest-openjdk(?:-headless|-devel|-jmods)?(?:-\d[\w.:*?-]*)?$`) // rpmInstallFlag is an rpm option that installs or upgrades package // files; a query (-qip) or an erase (-e) is not an install. + // dpkgInstallFlag is dpkg's install option (-i, --install). + dpkgInstallFlag = regexp.MustCompile(`^(?:-[a-zA-Z]*i[a-zA-Z]*|--install)$`) rpmInstallFlag = regexp.MustCompile(`^(?:-[a-dfh-pr-zA-UW-Z]*[iUF][a-dfh-pr-zA-UW-Z]*|--install|--upgrade|--freshen|--reinstall)$`) vendorJava = regexp.MustCompile(`\b((temurin|zulu|msopenjdk|sapmachine)-?(\d{1,2})(?:-ca)?(?:-(?:jdk|jre))?(?:-headless)?)\b(=([^\s;&|]+))?`) defaultJava = regexp.MustCompile(`\b(default-(?:jre|jdk)(?:-headless)?)\b`) @@ -1008,6 +1076,9 @@ func (s *scanner) packages(rel string, line int, run string) { // A vendor's package no reader above knows: its file name or rpm // name may carry the Java version (Oracle, Zulu, Temurin, Liberica // and SapMachine rpms); otherwise a Java package file is not checked. + if openJ9Name.MatchString(arg) { + continue // IBM Semeru: OpenJ9, not HotSpot + } if v := vendorFileVersion(arg); v != "" && javaWord.MatchString(arg) { hits = append(hits, pkgHit{name: arg, mgr: "rpm", vendor: "distribution", ver: v, vendorFile: true}) } else if fromFile && javaWord.MatchString(arg) { @@ -1037,7 +1108,7 @@ var ( ) var ( - pkgTools = map[string]bool{"apt-get": true, "apt": true, "apk": true, "dnf": true, "dnf5": true, "yum": true, "microdnf": true, "tdnf": true, "zypper": true, "rpm": true} + pkgTools = map[string]bool{"apt-get": true, "apt": true, "apk": true, "dnf": true, "dnf5": true, "yum": true, "microdnf": true, "tdnf": true, "zypper": true, "rpm": true, "dpkg": true} pkgVerbs = map[string]bool{"install": true, "add": true, "in": true, "reinstall": true, "localinstall": true} // pkgValueFlags are package-manager options followed by a separate value. pkgValueFlags = map[string]bool{"-t": true, "-o": true, "-X": true, "--repository": true, "--virtual": true, "-c": true, "--root": true, @@ -1105,7 +1176,7 @@ func rpmFileArg(w string) (string, bool) { u = u[:i] } base := path.Base(u) - if !url && strings.Contains(w, "=") { + if pre, _, pin := strings.Cut(w, "="); !url && pin && !strings.Contains(w, "/") && !strings.Contains(strings.ToLower(pre), ".rpm") && !strings.Contains(strings.ToLower(pre), ".deb") { return "", false // a version pin (openjdk-17-jdk=17.*), not a file } if !url && strings.ContainsAny(base, "*?[") { @@ -1124,12 +1195,30 @@ func rpmFileArg(w string) (string, bool) { if strings.HasSuffix(strings.ToLower(base), ".rpm") { return fileArg + rpmArchRE.ReplaceAllString(base[:len(base)-len(".rpm")], ""), true } + if strings.HasSuffix(strings.ToLower(base), ".deb") { + return fileArg + debFileName(base[:len(base)-len(".deb")]), true + } if url && javaWord.MatchString(w) { return unreadableArg + w, true } return "", false } +// debFileName turns a Debian package file's name (name_version_arch) into +// a name=version pin a reader knows; a vendor's file name +// (jdk-17.0.9_linux-x64_bin) is kept as it is. +func debFileName(raw string) string { + if p := strings.Split(raw, "_"); len(p) == 3 { + if c := p[0] + "=" + p[1]; aptArg.MatchString(c) || vendorArg.MatchString(c) { + return c + } + } + return raw +} + +// openJ9Name is an IBM Semeru or OpenJ9 package: not HotSpot, not affected. +var openJ9Name = regexp.MustCompile(`(?i)semeru|openj9`) + // fileArg marks a package name read from a package file's name: one no // reader knows is still a Java package if its name says so. const fileArg = "\x00file:" @@ -1174,7 +1263,7 @@ func installArgs(run string) []string { i++ installs := false for i < len(words) && strings.HasPrefix(words[i], "-") { - if tool == "rpm" && rpmInstallFlag.MatchString(words[i]) { + if tool == "rpm" && rpmInstallFlag.MatchString(words[i]) || tool == "dpkg" && dpkgInstallFlag.MatchString(words[i]) { installs = true } if pkgValueFlags[words[i]] { @@ -1182,8 +1271,9 @@ func installArgs(run string) []string { } i++ } - if tool == "rpm" { - // rpm -ivh file.rpm: the package files follow the flags. + if tool == "rpm" || tool == "dpkg" { + // rpm -ivh file.rpm, dpkg -i file.deb: the package files follow + // the flags. if !installs { continue } @@ -1202,7 +1292,7 @@ func installArgs(run string) []string { } } switch { - case tool == "rpm": + case tool == "rpm" || tool == "dpkg": if pkgValueFlags[w] { j++ } @@ -1329,7 +1419,7 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { if h.unreadable { s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: map[string]string{"package": refs.CleanText(h.name, 120), "manager": h.mgr}, - Reason: "a package file named by a pattern or a URL that does not give its file name: which Java package it is, this scan cannot read", + Reason: "a Java package file this scan cannot read: a pattern, a URL that does not give the file name, or a name no reader here knows", Message: fmt.Sprintf("installs %s, a package file whose name this scan cannot read: not checked for the Java4Shell fix", refs.CleanText(h.name, 120)), Fix: "Check which Java package the file is: 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update, or the distribution's backport, have the fix."}) return From 945eb057ae5183d8d54bc9ffd6eb0e272b63652f Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 09:09:44 +0000 Subject: [PATCH 081/119] java4shell: gofmt Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/internal/repo/repo.go | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index d4c664d..7332eab 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -480,7 +480,6 @@ func (s *scanner) sdkmanrc(rel, text string) { // (a Zulu version, not a Java version: not judged). var asdfJava = regexp.MustCompile(`^(?:(adoptopenjdk|temurin|corretto|openjdk|sapmachine|liberica|microsoft|oracle|semeru-openj9|semeru|dragonwell|kona|zulu|graalvm|graalvm-community|oracle-graalvm|mandrel|jetbrains|java-se-ri)-)?(?:(?:jre|jdk|openj9|musl|lite|javafx|fx|crac)-)*(\d[\d.]*)`) -// // mise is true for a mise file: mise resolves a short version (temurin-17, // 21) to the newest release when it installs, where asdf takes the name as // one release (openjdk-21 is 21 GA). @@ -948,12 +947,12 @@ var ( // files; a query (-qip) or an erase (-e) is not an install. // dpkgInstallFlag is dpkg's install option (-i, --install). dpkgInstallFlag = regexp.MustCompile(`^(?:-[a-zA-Z]*i[a-zA-Z]*|--install)$`) - rpmInstallFlag = regexp.MustCompile(`^(?:-[a-dfh-pr-zA-UW-Z]*[iUF][a-dfh-pr-zA-UW-Z]*|--install|--upgrade|--freshen|--reinstall)$`) - vendorJava = regexp.MustCompile(`\b((temurin|zulu|msopenjdk|sapmachine)-?(\d{1,2})(?:-ca)?(?:-(?:jdk|jre))?(?:-headless)?)\b(=([^\s;&|]+))?`) - defaultJava = regexp.MustCompile(`\b(default-(?:jre|jdk)(?:-headless)?)\b`) - envJTO = regexp.MustCompile(`(?i)^\s*ENV\s+`) - cmdLine = regexp.MustCompile(`(?i)^\s*(?:ENTRYPOINT|CMD)\s+`) - fromLine = regexp.MustCompile(`(?i)^\s*FROM\s`) + rpmInstallFlag = regexp.MustCompile(`^(?:-[a-dfh-pr-zA-UW-Z]*[iUF][a-dfh-pr-zA-UW-Z]*|--install|--upgrade|--freshen|--reinstall)$`) + vendorJava = regexp.MustCompile(`\b((temurin|zulu|msopenjdk|sapmachine)-?(\d{1,2})(?:-ca)?(?:-(?:jdk|jre))?(?:-headless)?)\b(=([^\s;&|]+))?`) + defaultJava = regexp.MustCompile(`\b(default-(?:jre|jdk)(?:-headless)?)\b`) + envJTO = regexp.MustCompile(`(?i)^\s*ENV\s+`) + cmdLine = regexp.MustCompile(`(?i)^\s*(?:ENTRYPOINT|CMD)\s+`) + fromLine = regexp.MustCompile(`(?i)^\s*FROM\s`) ) func (s *scanner) dockerfile(rel, text string) { From 74156bb6c894fac45f3cd55393365f270ba286c1 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 09:33:51 +0000 Subject: [PATCH 082/119] sshole: start scripts that start sshd in different ways are each judged; the worst is kept From the final review: an ENTRYPOINT script that starts sshd with -o UsePAM=no and a CMD script that starts it plainly disagreed, so neither command line was applied and sshd_config's UsePAM yes cleared the server (inactive; critical before every command word was read as a script). The same held for two init scripts. Now each distinct command line, and sshd_config alone, is judged and the worst verdict kept: a server is cleared only when every way it can start clears it. Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/internal/assess/assess.go | 81 ++++++++++++++++--- .../sshole/internal/assess/unread_test.go | 39 +++++++++ 2 files changed, 107 insertions(+), 13 deletions(-) diff --git a/detectors/sshole/internal/assess/assess.go b/detectors/sshole/internal/assess/assess.go index d30d005..ee14291 100644 --- a/detectors/sshole/internal/assess/assess.go +++ b/detectors/sshole/internal/assess/assess.go @@ -207,12 +207,62 @@ func assessUnit(in Input, u []*Binary) (Finding, bool) { return f, true } + scripts := in.Startup.startScripts(in.Resolve) + cands, conflict := pickInvocation(invocations(in.Startup, scripts), u) + if !conflict { + var inv invocation + if len(cands) == 1 { + inv = cands[0] + } + return assessStart(in, main, f, why, scripts, inv, len(cands) == 1) + } + // The start scripts start sshd in more than one way, and which one runs + // is not known: judge each, and sshd_config alone, and keep the worst. + // A server is cleared only when every way it can start clears it. + var worst Finding + var where []string + have := false + for _, c := range append(cands, invocation{}) { + if c.where != "" { + where = append(where, c.where) + } + r, ok := assessStart(in, main, f, why, scripts, c, c.binary != "") + if ok && (!have || rank(r) > rank(worst)) { + worst, have = r, true + } + } + if have { + worst.Reason += fmt.Sprintf("; sshd is started in more than one way (%s), and this is the worst of them", strings.Join(where, ", ")) + } + return worst, have +} + +// rank orders verdicts from the least to the most to act on. +func rank(f Finding) int { + switch f.Status { + case Vulnerable: + switch f.Severity { + case "critical": + return 6 + case "high": + return 5 + } + return 4 + case Undecided: + return 3 + case Inactive: + return 2 + } + return 1 +} + +// assessStart judges an unfixed server on musl as one invocation starts it +// (invoked), or as sshd_config alone sets it. +func assessStart(in Input, main *Binary, f Finding, why string, scripts []script, inv invocation, invoked bool) (Finding, bool) { cfgPath := main.Config if cfgPath == "" { cfgPath = "/etc/ssh/sshd_config" } - scripts := in.Startup.startScripts(in.Resolve) - inv, invoked := pickInvocation(invocations(in.Startup, scripts), u) if invoked && inv.config != "" { cfgPath = inv.config } @@ -351,11 +401,11 @@ func targetNames(ts []Target) string { return strings.Join(n, ", ") } -// pickInvocation finds the command line that starts this server: the -// container command's when it runs sshd, else the startup scripts' when they -// all agree. Command lines that disagree are not applied: options must not -// lower a verdict on a guess. -func pickInvocation(invs []invocation, u []*Binary) (invocation, bool) { +// pickInvocation finds the command lines that start this server: the +// container command's when it runs sshd, else the startup scripts' distinct +// ones. More than one (true) means which runs is not known: each is judged +// and the worst kept, so options never lower a verdict on a guess. +func pickInvocation(invs []invocation, u []*Binary) ([]invocation, bool) { var mine []invocation for _, inv := range invs { for _, b := range u { @@ -366,19 +416,24 @@ func pickInvocation(invs []invocation, u []*Binary) (invocation, bool) { } } if len(mine) == 0 { - return invocation{}, false + return nil, false } for _, inv := range mine { if inv.where == "the container command" { - return inv, true + return []invocation{inv}, false } } - for _, inv := range mine[1:] { - if inv.config != mine[0].config || !sameOpts(inv.opts, mine[0].opts) { - return invocation{}, false + var out []invocation + for _, inv := range mine { + dup := false + for _, o := range out { + dup = dup || inv.config == o.config && sameOpts(inv.opts, o.opts) + } + if !dup { + out = append(out, inv) } } - return mine[0], true + return out, len(out) > 1 } func sameOpts(a, b []Directive) bool { diff --git a/detectors/sshole/internal/assess/unread_test.go b/detectors/sshole/internal/assess/unread_test.go index 8764435..befce37 100644 --- a/detectors/sshole/internal/assess/unread_test.go +++ b/detectors/sshole/internal/assess/unread_test.go @@ -149,3 +149,42 @@ func TestStartScriptBehindWrapper(t *testing.T) { } } } + +// Final review finding 2: start scripts that start sshd in different ways +// are each judged, and the worst kept: one that turns PAM off is never +// voided by another that does not. +func TestStartScriptsDisagree(t *testing.T) { + pamOff := "#!/bin/sh\n/usr/sbin/sshd -o UsePAM=no\nexec \"$@\"\n" + plain := "#!/bin/sh\npgrep sshd || /usr/sbin/sshd -D\n" + for _, c := range []struct { + name string + cmd []string + scripts map[string]string + cleared bool + }{ + {"entrypoint then a CMD script", []string{"/entry.sh", "/cmd.sh"}, map[string]string{"/entry.sh": pamOff, "/cmd.sh": plain}, false}, + {"two scripts", []string{"/a.sh", "/b.sh"}, map[string]string{"/a.sh": plain, "/b.sh": pamOff}, false}, + {"a shell and two scripts", []string{"/bin/sh", "/a.sh", "/b.sh"}, map[string]string{"/a.sh": pamOff, "/b.sh": plain}, false}, + {"a CMD found on PATH", []string{"/entry.sh", "start"}, map[string]string{"/entry.sh": pamOff, "/usr/local/bin/start": plain}, false}, + {"two init scripts", nil, map[string]string{"/etc/cont-init.d/10-a": pamOff, "/etc/cont-init.d/20-b": plain}, false}, + {"two scripts that agree", []string{"/a.sh", "/b.sh"}, map[string]string{"/a.sh": plain, "/b.sh": plain}, true}, + } { + w := newWorld("10.0p2", true, map[string]string{"/etc/ssh/sshd_config": "UsePAM yes\n"}) + scripts := map[string][]byte{} + for p, b := range c.scripts { + scripts[p] = []byte(b) + } + in := Input{ + Binaries: w.binaries, Files: w.files, + Accounts: ParseAccounts(w.files.Read("/etc/passwd"), w.files.Read("/etc/shadow"), w.files.Read("/etc/group"), nil), + Resolve: func(p string) (string, bool) { _, ok := w.files[p]; return p, ok }, + Now: w.now(), + Image: true, + Startup: Startup{Command: c.cmd, Scripts: scripts}, + } + f := one(t, Run(in)) + if (f.Status == Inactive) != c.cleared || !c.cleared && (f.Status != Vulnerable || f.Severity != "critical") { + t.Errorf("%s: %s %s (%s)", c.name, f.Status, f.Severity, f.Reason) + } + } +} From 805ecd555ef49cad1a1d2858178e9b1102945c5a Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 09:36:12 +0000 Subject: [PATCH 083/119] image: flatten layers with paths relative to the root; first entry wins in an image, last in a docker export From the final review: go-containerregistry's mutate.Extract writes the top layer first but does not take /usr/sbin/sshd and usr/sbin/sshd for one file, so a lower layer's copy followed the upper one's, and the engine, reading the last entry as the file, forgot the real one (no finding for a real sshd over a placeholder; an upper sshd_config with UsePAM no lost to the lower one, inactive). Whiteouts spelled one way did not hide a file spelled the other. - internal/image flattens layers itself, as mutate.Extract does, with every name made relative to the root first: one entry per path, the top layer's, and whiteouts apply however a name is spelled. - An image stream is read first-entry-wins (source.Options.FirstWins); only a docker export (rootfs:) is last-entry-wins, with Forget. - In a docker export, a path that comes round again as a directory or a link is forgotten too, and Exists no longer holds for it; a path a hard link names is not forgotten, as the link keeps the earlier file. - Tests: flattening two spellings and whiteouts, unsafe names, a docker-archive with a real sshd over a placeholder and an upper sshd_config (sshole), a docker export replacing files with links and directories, and a hard link keeping a Java runtime. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/limit_internal_test.go | 21 +++ detectors/sshole/limit_test.go | 109 ++++++++++++ internal/engine/engine.go | 11 +- internal/engine/limit_test.go | 35 ++++ internal/engine/run.go | 32 +++- internal/image/flatten.go | 178 ++++++++++++++++++++ internal/image/flatten_test.go | 99 +++++++++++ internal/image/image.go | 3 +- internal/source/source.go | 18 ++ 9 files changed, 498 insertions(+), 8 deletions(-) create mode 100644 internal/image/flatten.go create mode 100644 internal/image/flatten_test.go diff --git a/detectors/java4shell/limit_internal_test.go b/detectors/java4shell/limit_internal_test.go index 2140d51..7073118 100644 --- a/detectors/java4shell/limit_internal_test.go +++ b/detectors/java4shell/limit_internal_test.go @@ -245,3 +245,24 @@ func TestForget(t *testing.T) { t.Errorf("libs %d releases %d kept %d settings %d bytes %d", len(s.libs), len(s.releases), len(s.kept), len(s.settings), s.keptBytes) } } + +// Final review finding 3: a hard link to a VM library keeps the runtime +// when a docker export then names the original path again, empty. +func TestHardLinkKeepsRuntime(t *testing.T) { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + lib := testlib.Build(testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true}) + tw.WriteHeader(&tar.Header{Name: "opt/java/lib/server/libjvm.so", Mode: 0o755, Size: int64(len(lib)), Typeflag: tar.TypeReg}) + tw.Write(lib) + tw.WriteHeader(&tar.Header{Name: "opt/copy/lib/server/libjvm.so", Typeflag: tar.TypeLink, Linkname: "opt/java/lib/server/libjvm.so"}) + tw.WriteHeader(&tar.Header{Name: "opt/java/lib/server/libjvm.so", Mode: 0o755, Size: 0, Typeflag: tar.TypeReg}) + tw.Close() + p := filepath.Join(t.TempDir(), "rootfs.tar") + if err := os.WriteFile(p, buf.Bytes(), 0o600); err != nil { + t.Fatal(err) + } + tg := engine.ScanImage([]engine.Detector{&Detector{}}, "rootfs:"+p, engine.Options{}) + if tg.Error != "" || len(tg.Findings) != 1 || tg.Findings[0].Verdict != engine.Vulnerable { + t.Errorf("error %q findings %+v", tg.Error, tg.Findings) + } +} diff --git a/detectors/sshole/limit_test.go b/detectors/sshole/limit_test.go index bd11832..55d97b2 100644 --- a/detectors/sshole/limit_test.go +++ b/detectors/sshole/limit_test.go @@ -5,11 +5,18 @@ import ( "bytes" "encoding/json" "fmt" + "io" "os" "path/filepath" "strings" "testing" + "github.com/google/go-containerregistry/pkg/name" + v1 "github.com/google/go-containerregistry/pkg/v1" + "github.com/google/go-containerregistry/pkg/v1/empty" + "github.com/google/go-containerregistry/pkg/v1/mutate" + "github.com/google/go-containerregistry/pkg/v1/tarball" + _ "github.com/DefectDojo/earlylight/detectors/emudhra" // a detector that reads every file "github.com/DefectDojo/earlylight/detectors/sshole/internal/testelf" "github.com/DefectDojo/earlylight/internal/cli" @@ -413,3 +420,105 @@ func TestPackageDBFromDisk(t *testing.T) { t.Errorf("a 5 MiB apk database read from disk: %s", v) } } + +// dirLayer is a layer of root's files, named relative to the root unless +// abs; skip leaves names out. +func dirLayer(t *testing.T, root string, abs bool, skip ...string) v1.Layer { + t.Helper() + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + err := filepath.Walk(root, func(p string, fi os.FileInfo, err error) error { + if err != nil || p == root { + return err + } + rel, _ := filepath.Rel(root, p) + rel = filepath.ToSlash(rel) + for _, s := range skip { + if rel == s { + return nil + } + } + h, _ := tar.FileInfoHeader(fi, "") + if fi.Mode()&os.ModeSymlink != 0 { + h.Linkname, _ = os.Readlink(p) + } + h.Name = rel + if abs { + h.Name = "/" + rel + } + if err := tw.WriteHeader(h); err != nil { + return err + } + if fi.Mode().IsRegular() { + b, _ := os.ReadFile(p) + tw.Write(b) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + tw.Close() + b := buf.Bytes() + l, err := tarball.LayerFromOpener(func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(b)), nil }) + if err != nil { + t.Fatal(err) + } + return l +} + +// dockerArchive writes layers (bottom first) as a docker save archive. +func dockerArchive(t *testing.T, layers ...v1.Layer) string { + t.Helper() + img, err := mutate.AppendLayers(empty.Image, layers...) + if err != nil { + t.Fatal(err) + } + p := filepath.Join(t.TempDir(), "image.tar") + if err := tarball.WriteToFile(p, name.MustParseReference("test/sshole:1"), img); err != nil { + t.Fatal(err) + } + return p +} + +// Final review finding 1: an upper layer that spells a path with a leading +// slash replaces the lower layer's file, as a container runtime extracts +// it: the real sshd over a placeholder is found, and an upper sshd_config +// that turns PAM off is the one read. +func TestUpperLayerSpelledDifferently(t *testing.T) { + scan := func(img string) []engine.Finding { + var out, errb bytes.Buffer + cli.Run(cfg, []string{"scan", "image", "--format", "json", "--detector", "sshole", "docker-archive:" + img}, &out, &errb) + var r struct { + Targets []struct { + Error string `json:"error"` + Findings []engine.Finding `json:"findings"` + } `json:"targets"` + } + if err := json.Unmarshal(out.Bytes(), &r); err != nil || len(r.Targets) != 1 || r.Targets[0].Error != "" { + t.Fatalf("%v %+v %s", err, r, errb.String()) + } + return r.Targets[0].Findings + } + + // The real sshd in the upper layer, a placeholder below. + real := alpineRoot(t, "10.0_p1-r10") + lower := t.TempDir() + write(t, lower, "usr/sbin/sshd", []byte("placeholder"), 0o755) + upper := t.TempDir() + b, _ := os.ReadFile(filepath.Join(real, "usr/sbin/sshd")) + write(t, upper, "usr/sbin/sshd", b, 0o755) + fs := scan(dockerArchive(t, dirLayer(t, real, false, "usr/sbin/sshd"), dirLayer(t, lower, false), dirLayer(t, upper, true))) + if len(fs) != 1 || fs[0].Verdict != engine.Vulnerable || fs[0].Severity != "critical" { + t.Errorf("real sshd over a placeholder: %+v", fs) + } + + // An upper sshd_config that turns PAM off. + root := pamRoot(t) + cfgUp := t.TempDir() + write(t, cfgUp, "etc/ssh/sshd_config", []byte("UsePAM no\n"), 0o644) + fs = scan(dockerArchive(t, dirLayer(t, root, false), dirLayer(t, cfgUp, true))) + if len(fs) != 1 || fs[0].Verdict.Cleared() { + t.Errorf("an upper sshd_config turning PAM off: %+v", fs) + } +} diff --git a/internal/engine/engine.go b/internal/engine/engine.go index d043286..c126190 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -234,10 +234,13 @@ type UnreadVisitor interface { } // Forgetter is implemented by a Scan that keeps what it was shown by -// path. When a path comes round again (an image filesystem can name one -// file twice; the last entry is the file), Forget is called before the new -// entry is handed out, so nothing of the earlier one survives, nor of what -// was found inside it ("path!/member"). +// path. When a path comes round again in a docker export (rootfs:), where +// the last entry is the file, as a file, directory or link, Forget is +// called before the new entry is handed out, so nothing of the earlier one +// survives, nor of what was found inside it ("path!/member"). It is not +// called while a hard link names the path: the link keeps the earlier +// file. A registry or docker-archive image is flattened top layer first, +// each path once. type Forgetter interface { Forget(path string) } diff --git a/internal/engine/limit_test.go b/internal/engine/limit_test.go index 28528d0..f2b4796 100644 --- a/internal/engine/limit_test.go +++ b/internal/engine/limit_test.go @@ -618,3 +618,38 @@ func TestLimitVisitorWithoutLimiter(t *testing.T) { t.Errorf("sizes %v seen %v skipped %+v", *v.sizes, *f.seen, tg.Skipped) } } + +// Final review finding 3: in a docker export, a file a later entry +// replaces with a link or directory is forgotten; one a hard link names +// is not, as the link keeps its content. +func TestReplacedInDockerExport(t *testing.T) { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + reg := func(n, body string) { + tw.WriteHeader(&tar.Header{Name: n, Mode: 0o644, Size: int64(len(body)), Typeflag: tar.TypeReg}) + tw.Write([]byte(body)) + } + reg("etc/a", "1") + tw.WriteHeader(&tar.Header{Name: "etc/a", Typeflag: tar.TypeSymlink, Linkname: "b"}) + reg("etc/d", "1") + tw.WriteHeader(&tar.Header{Name: "etc/d", Typeflag: tar.TypeDir, Mode: 0o755}) + reg("x", "real") + tw.WriteHeader(&tar.Header{Name: "y", Typeflag: tar.TypeLink, Linkname: "x"}) + reg("x", "") + tw.Close() + p := filepath.Join(t.TempDir(), "rootfs.tar") + if err := os.WriteFile(p, buf.Bytes(), 0o600); err != nil { + t.Fatal(err) + } + u := newUnreadScan("t-replaced") + var exists []bool + u.finish = func(ctx TargetContext) []Finding { + exists = []bool{ctx.Exists("/etc/a"), ctx.Exists("/etc/d"), ctx.Exists("/x")} + return nil + } + ScanImage([]Detector{u}, "rootfs:"+p, Options{}) + sort.Strings(*u.forgot) + if strings.Join(*u.forgot, ",") != "/etc/a,/etc/d" || fmt.Sprint(exists) != "[false false true]" { + t.Errorf("forgot %v exists %v", *u.forgot, exists) + } +} diff --git a/internal/engine/run.go b/internal/engine/run.go index a8f4856..70f50cc 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -318,15 +318,24 @@ func (w *walker) sourceOptions(opts Options) source.Options { so.Read = func(p string, head []byte, exe bool) (bool, int64) { abs := w.abs(p) if w.ctx.seen[abs] { - // The path comes round again: this entry is the file. - w.forget(abs) + // The path comes round again in a docker export: this entry + // is the file (a flattened image never repeats a path). + w.replaced(abs) } + // A path that was a link is a file now. + delete(w.ctx.symlinks, abs) + delete(w.ctx.hardlinks, abs) // The file exists whether or not any detector reads it, so Exists // does not depend on which detectors ran. w.ctx.seen[abs] = true visitHead(p, head) return decide(abs, head, exe) } + so.Other = func(p string) { + if abs := w.abs(p); w.ctx.seen[abs] { + w.replaced(abs) + } + } so.Unread = func(p string, dir bool) { abs := w.abs(p) if !dir { @@ -341,6 +350,21 @@ func (w *walker) sourceOptions(opts Options) source.Options { return so } +// replaced handles a file at p that a later entry replaces (a docker +// export names a path again, as a file, directory or link): every scan +// forgets what it kept of p, unless a hard link names p. A hard link keeps +// the earlier file's content (it names the file, not the path), so what +// was found in it stays, under p. +func (w *walker) replaced(p string) { + for _, t := range w.ctx.hardlinks { + if t == p { + return + } + } + w.forget(p) + delete(w.ctx.seen, p) +} + // forget tells every scan to drop what it kept of p. func (w *walker) forget(p string) { for i, s := range w.scans { @@ -688,6 +712,10 @@ func ScanImage(dets []Detector, ref string, opts Options) *Target { defer rc.Close() so := w.sourceOptions(opts) so.Uncounted = source.DefaultExcludes + // A registry or docker-archive image is flattened top layer first: the + // first entry for a path is the file. A docker export (rootfs:) is + // one filesystem, where the last entry is. + so.FirstWins = !strings.HasPrefix(ref, "rootfs:") skips, n, err := source.Tar(rc, so, w.visit) t.Skipped, t.Files = append(t.Skipped, skips...), n if err != nil { diff --git a/internal/image/flatten.go b/internal/image/flatten.go new file mode 100644 index 0000000..328e519 --- /dev/null +++ b/internal/image/flatten.go @@ -0,0 +1,178 @@ +package image + +// Flattening follows go-containerregistry's mutate.Extract (Apache-2.0, +// see THIRD_PARTY_NOTICES.txt), with one change: every entry name is made +// relative to the root first, so "/usr/sbin/sshd" and "usr/sbin/sshd" in +// two layers are one file, as a container runtime extracts them. Without +// it, both are written, the lower layer's copy after the upper one, and a +// whiteout spelled one way does not hide a file spelled the other. + +import ( + "archive/tar" + "errors" + "fmt" + "io" + "path" + "strings" + + v1 "github.com/google/go-containerregistry/pkg/v1" +) + +const ( + whiteoutPrefix = ".wh." + opaqueWhiteout = ".wh..wh..opq" +) + +// flatten returns an image's filesystem as one tar stream, top layer first: +// the first entry for a path is the file, and each path appears once. +func flatten(img v1.Image) io.ReadCloser { + pr, pw := io.Pipe() + go func() { pw.CloseWithError(extract(img, pw)) }() + return pr +} + +func extract(img v1.Image, w io.Writer) error { + tw := tar.NewWriter(w) + defer tw.Close() + fileMap := map[string]bool{} + opaqueDirs := map[string]bool{} + layers, err := img.Layers() + if err != nil { + return fmt.Errorf("retrieving image layers: %w", err) + } + for i := len(layers) - 1; i >= 0; i-- { + if err := extractLayer(tw, fileMap, opaqueDirs, layers[i]); err != nil { + return err + } + } + return nil +} + +// rootName is an entry name relative to the root, "" for the root itself. +func rootName(name string) string { + return strings.TrimPrefix(path.Clean("/"+name), "/") +} + +func extractLayer(tw *tar.Writer, fileMap, opaqueDirs map[string]bool, layer v1.Layer) error { + layerOpaque := map[string]bool{} + rc, err := layer.Uncompressed() + if err != nil { + return fmt.Errorf("reading layer contents: %w", err) + } + defer rc.Close() + tr := tar.NewReader(rc) + for { + h, err := tr.Next() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return fmt.Errorf("reading tar: %w", err) + } + if unsafeArchivePath(h.Name) { + return fmt.Errorf("unsafe tar path %q", h.Name) + } + h.Name = rootName(h.Name) + if h.Name == "" { + continue // the root directory + } + if (h.Typeflag == tar.TypeSymlink || h.Typeflag == tar.TypeLink) && unsafeRelativeLink(h.Name, h.Linkname) { + continue + } + h.Format = tar.FormatPAX + base, dir := path.Base(h.Name), path.Dir(h.Name) + if base == opaqueWhiteout { + layerOpaque[dir] = true + continue + } + tombstone := strings.HasPrefix(base, whiteoutPrefix) + if tombstone { + base = base[len(whiteoutPrefix):] + } + name := h.Name + if h.Typeflag != tar.TypeDir { + name = path.Join(dir, base) + } + if _, ok := fileMap[name]; ok && !tombstone { + continue + } + if inWhiteoutDir(fileMap, name) || inOpaqueDir(opaqueDirs, name) { + continue + } + fileMap[name] = tombstone || h.Typeflag != tar.TypeDir + if tombstone { + continue + } + if err := tw.WriteHeader(h); err != nil { + return err + } + if h.Size > 0 { + if _, err := io.CopyN(tw, tr, h.Size); err != nil { + return err + } + } + } + for d := range layerOpaque { + opaqueDirs[d] = true + } + // Drain the layer so its digest is verified. + if _, err := io.Copy(io.Discard, rc); err != nil { + return fmt.Errorf("verifying layer: %w", err) + } + return nil +} + +func inOpaqueDir(opaqueDirs map[string]bool, file string) bool { + for file != "" { + dir := path.Dir(file) + if file == dir { + break + } + if opaqueDirs[dir] { + return true + } + file = dir + } + return false +} + +func inWhiteoutDir(fileMap map[string]bool, file string) bool { + for file != "" { + dir := path.Dir(file) + if file == dir { + break + } + if fileMap[dir] { + return true + } + file = dir + } + return false +} + +func unsafeArchivePath(name string) bool { + clean := cleanArchivePath(name) + if clean == ".." || strings.HasPrefix(clean, "../") || strings.HasPrefix(name, "\\") { + return true + } + return hasWindowsDrivePrefix(clean) +} + +func unsafeRelativeLink(name, linkname string) bool { + clean := cleanArchivePath(linkname) + if path.IsAbs(clean) { + return false + } + if hasWindowsDrivePrefix(clean) { + return true + } + return strings.HasPrefix(path.Clean(path.Join(path.Dir(name), clean)), "..") +} + +func cleanArchivePath(name string) string { + return path.Clean(strings.ReplaceAll(name, "\\", "/")) +} + +func hasWindowsDrivePrefix(name string) bool { + return len(name) >= 2 && ('A' <= name[0] && name[0] <= 'Z' || 'a' <= name[0] && name[0] <= 'z') && name[1] == ':' +} diff --git a/internal/image/flatten_test.go b/internal/image/flatten_test.go new file mode 100644 index 0000000..f48d4f8 --- /dev/null +++ b/internal/image/flatten_test.go @@ -0,0 +1,99 @@ +package image + +import ( + "archive/tar" + "bytes" + "io" + "testing" + + v1 "github.com/google/go-containerregistry/pkg/v1" + "github.com/google/go-containerregistry/pkg/v1/empty" + "github.com/google/go-containerregistry/pkg/v1/mutate" + "github.com/google/go-containerregistry/pkg/v1/tarball" +) + +// layer builds a layer from (name, content) entries; content "\x00dir" is +// a directory. +func layer(t *testing.T, entries ...[2]string) v1.Layer { + t.Helper() + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, e := range entries { + h := &tar.Header{Name: e[0], Mode: 0o755, Size: int64(len(e[1])), Typeflag: tar.TypeReg} + if e[1] == "\x00dir" { + h.Typeflag, h.Size = tar.TypeDir, 0 + } + if err := tw.WriteHeader(h); err != nil { + t.Fatal(err) + } + if h.Typeflag == tar.TypeReg { + tw.Write([]byte(e[1])) + } + } + tw.Close() + b := buf.Bytes() + l, err := tarball.LayerFromOpener(func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(b)), nil }) + if err != nil { + t.Fatal(err) + } + return l +} + +func entries(t *testing.T, img v1.Image) map[string][]string { + t.Helper() + rc := flatten(img) + defer rc.Close() + out := map[string][]string{} + tr := tar.NewReader(rc) + for { + h, err := tr.Next() + if err == io.EOF { + return out + } + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(tr) + out[h.Name] = append(out[h.Name], string(b)) + } +} + +// Final review finding 1: a path spelled with and without a leading slash +// in two layers is one file, the upper layer's; a whiteout hides it +// whichever way either is spelled. +func TestFlattenOnePathTwoSpellings(t *testing.T) { + img, err := mutate.AppendLayers(empty.Image, + layer(t, [2]string{"usr/sbin/sshd", "placeholder"}, [2]string{"etc/gone", "x"}, [2]string{"/etc/gone2", "x"}, [2]string{"./opt/a", "lower"}), + layer(t, [2]string{"/usr/sbin/sshd", "real"}, [2]string{"/etc/.wh.gone", ""}, [2]string{"etc/.wh.gone2", ""}, [2]string{"opt/a", "upper"})) + if err != nil { + t.Fatal(err) + } + got := entries(t, img) + if s := got["usr/sbin/sshd"]; len(s) != 1 || s[0] != "real" { + t.Errorf("sshd: %q", s) + } + if s := got["opt/a"]; len(s) != 1 || s[0] != "upper" { + t.Errorf("opt/a: %q", s) + } + if _, ok := got["etc/gone"]; ok { + t.Error("a whiteout spelled /etc/.wh.gone did not hide etc/gone") + } + if _, ok := got["etc/gone2"]; ok { + t.Error("a whiteout spelled etc/.wh.gone2 did not hide /etc/gone2") + } + for name := range got { + if len(name) > 0 && name[0] == '/' { + t.Errorf("entry %q is not relative to the root", name) + } + } +} + +// Unsafe names fail the image, as with mutate.Extract. +func TestFlattenUnsafe(t *testing.T) { + img, _ := mutate.AppendLayers(empty.Image, layer(t, [2]string{"../escape", "x"})) + rc := flatten(img) + defer rc.Close() + if _, err := io.ReadAll(rc); err == nil { + t.Error("an unsafe path was accepted") + } +} diff --git a/internal/image/image.go b/internal/image/image.go index c7bfce3..f1b9a5b 100644 --- a/internal/image/image.go +++ b/internal/image/image.go @@ -11,7 +11,6 @@ import ( "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/mutate" "github.com/google/go-containerregistry/pkg/v1/remote" "github.com/google/go-containerregistry/pkg/v1/tarball" ) @@ -62,7 +61,7 @@ func opened(img v1.Image) (*Opened, error) { } } } - o.FS = mutate.Extract(img) + o.FS = flatten(img) return o, nil } diff --git a/internal/source/source.go b/internal/source/source.go index 668e9c3..5667e8e 100644 --- a/internal/source/source.go +++ b/internal/source/source.go @@ -63,6 +63,14 @@ type Options struct { // (a deliberate exclusion when Over is nil); one over MaxFileSize is // always recorded as such, and Over adds what it returns. Over func(abs string, size int64, own bool) []Skip + // FirstWins (Tar): the stream is a flattened image, top layer first, so + // the first entry for a path is the file and later ones are ignored. + // Otherwise (a docker export) the last entry is the file. + FirstWins bool + // Other (Tar) receives each entry that is not a regular file (a + // directory, symbolic link or hard link), before Symlink or Hardlink: + // a path that was a file earlier in the stream is one no longer. + Other func(abs string) // Unread receives each file the walk met and could not read (it could // not be opened or read, or changed while it was read), and each // directory whose contents could not be listed (dir), besides the @@ -274,6 +282,7 @@ func Tar(r io.Reader, opts Options, visit Visitor) ([]Skip, int, error) { var skips []Skip n := 0 tr := tar.NewReader(r) + met := map[string]bool{} // FirstWins: every path seen, of any type for { h, err := tr.Next() if errors.Is(err, io.EOF) { @@ -286,6 +295,15 @@ func Tar(r io.Reader, opts Options, visit Visitor) ([]Skip, int, error) { if excluded(abs, opts.Exclude) { continue } + if opts.FirstWins { + if met[abs] { + continue + } + met[abs] = true + } + if h.Typeflag != tar.TypeReg && h.Typeflag != tar.TypeRegA && opts.Other != nil { //nolint:staticcheck + opts.Other(abs) + } switch h.Typeflag { case tar.TypeSymlink: if opts.Symlink != nil { From 2ca3f48263bcde8813f901533eb1030d7b17875d Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 09:38:05 +0000 Subject: [PATCH 084/119] sshole: what a directory that cannot be listed hides is unknown From the final review: - An Include whose directory cannot be listed (walked, or read from disk under --root; a literal path or a glob, also a glob in the directory part) matches a file that cannot be read: UsePAM yes is unknown. The disk glob no longer ignores a listing error. - A login shell in a directory that cannot be listed is taken to exist, as when it can be read. - An /etc/shadow (or /etc/passwd) that could not be read is said so, not 'no account has a $-style password hash' or 'no account has the password field "*"'. - Tests for each, run as non-root. Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/internal/assess/assess.go | 17 ++++- detectors/sshole/limit_test.go | 54 ++++++++++++++ detectors/sshole/sshole.go | 86 +++++++++++++++++++++- 3 files changed, 152 insertions(+), 5 deletions(-) diff --git a/detectors/sshole/internal/assess/assess.go b/detectors/sshole/internal/assess/assess.go index ee14291..bc3ff86 100644 --- a/detectors/sshole/internal/assess/assess.go +++ b/detectors/sshole/internal/assess/assess.go @@ -82,6 +82,10 @@ type Finding struct { // Input is a target's evidence. type Input struct { + // NotRead reports whether a file may be in the target but was not read + // (over a size limit, unreadable, in a directory not listed): its + // absence is not a fact to state. + NotRead func(p string) bool Binaries []*Binary Owners map[string]Package // apk database: file -> package Files Files @@ -308,9 +312,16 @@ func assessStart(in Input, main *Binary, f Finding, why string, scripts []script donor := PickSalt(in.Accounts) f.Donor = &donor var missing []string - if !in.Accounts.Read { + notRead := func(p string) bool { return in.NotRead != nil && in.NotRead(p) } + switch { + case !in.Accounts.Read && notRead("/etc/passwd"): + missing = append(missing, "/etc/passwd could not be read, so the accounts are unknown") + case !in.Accounts.Read: missing = append(missing, "/etc/passwd is not in the target") - } else if donor.Fails == "none" { + case notRead("/etc/shadow"): + // Never a claim about hashes that were not read. + missing = append(missing, "/etc/shadow could not be read, so the accounts' password fields and hashes are unknown") + case donor.Fails == "none": if donor.Account == "" { missing = append(missing, "no account has a $-style password hash, so sshd falls back to the DES salt \"xx\", which never fails") } else { @@ -343,7 +354,7 @@ func assessStart(in Input, main *Binary, f Finding, why string, scripts []script default: f.Password = "maybe" } - if in.Accounts.Read && stars == 0 { + if in.Accounts.Read && stars == 0 && !notRead("/etc/shadow") { missing = append(missing, "no account has the password field \"*\"") } f.Missing = missing diff --git a/detectors/sshole/limit_test.go b/detectors/sshole/limit_test.go index 55d97b2..4324ee3 100644 --- a/detectors/sshole/limit_test.go +++ b/detectors/sshole/limit_test.go @@ -522,3 +522,57 @@ func TestUpperLayerSpelledDifferently(t *testing.T) { t.Errorf("an upper sshd_config turning PAM off: %+v", fs) } } + +// Final review finding 4: what a directory that cannot be listed hides is +// unknown: an include under it (by path or glob, walked or read from disk +// under --root) keeps a PAM server from being cleared, a login shell in it +// still exists, and an unreadable /etc/shadow makes no claim about hashes. +func TestUnlistableDirectories(t *testing.T) { + for _, c := range []struct { + name, include, rel, lock string + root bool + }{ + {"sshd_config.d under --root", "/etc/ssh/sshd_config.d/*.conf", "etc/ssh/sshd_config.d/50.conf", "etc/ssh/sshd_config.d", true}, + {"a glob directory, walked", "/etc/ssh/conf.d*/x.conf", "etc/ssh/conf.d1/x.conf", "etc/ssh/conf.d1", false}, + {"a glob directory under --root", "/etc/ssh/conf.d*/x.conf", "etc/ssh/conf.d1/x.conf", "etc/ssh/conf.d1", true}, + {"a file under --root", "/etc/ssh/site.conf", "etc/ssh/site.conf", "etc/ssh/site.conf", true}, + } { + root := pamRoot(t) + write(t, root, "etc/ssh/sshd_config", []byte("Include "+c.include+"\nUsePAM yes\n"), 0o644) + write(t, root, c.rel, []byte("UsePAM no\n"), 0o644) + args := []string{"--as-root", root} + if c.root { + args = []string{"--root", root, filepath.Join(root, "usr")} + } + if v, _ := sshVerdict(t, args...); v != engine.Vulnerable { + t.Fatalf("%s, readable: %s", c.name, v) + } + unreadable(t, filepath.Join(root, c.lock)) + if v, code := sshVerdict(t, args...); v.Cleared() || code == 0 { + t.Errorf("%s, not readable: %s exit %d", c.name, v, code) + } + } + + verdict := func(lock bool) string { + root := alpineRoot(t, "10.0_p1-r10") + write(t, root, "etc/passwd", []byte("root:x:0:0:root:/root:/bin/sh\nalice:x:1000:1000::/home/alice:/bin/sh\nbob:x:1001:1001::/home/bob:/opt/shells/menu\n"), 0o644) + write(t, root, "opt/shells/menu", []byte("#!/bin/sh\nexec /bin/sh\n"), 0o755) + if lock { + unreadable(t, filepath.Join(root, "opt/shells")) + } + v, _ := sshVerdict(t, "--as-root", root) + fs, _, _ := scanExit(t, "--detector", "sshole", "--as-root", root) + return string(v) + "/" + fs[0].Severity + } + if a, b := verdict(false), verdict(true); a != b { + t.Errorf("a login shell in a directory that cannot be listed: %s, readable: %s", b, a) + } + + root := alpineRoot(t, "10.0_p1-r10") + unreadable(t, filepath.Join(root, "etc/shadow")) + fs, _, _ := scanExit(t, "--detector", "sshole", "--as-root", root) + if len(fs) != 1 || fs[0].Verdict.Cleared() || strings.Contains(fs[0].Message, "$-style") || strings.Contains(fs[0].Message, "no account has") || + !strings.Contains(fs[0].Message, "/etc/shadow could not be read") { + t.Errorf("unreadable /etc/shadow: %+v", fs) + } +} diff --git a/detectors/sshole/sshole.go b/detectors/sshole/sshole.go index 004caa9..e0f057e 100644 --- a/detectors/sshole/sshole.go +++ b/detectors/sshole/sshole.go @@ -15,6 +15,8 @@ package sshole import ( + "errors" + "io/fs" "os" "path" "path/filepath" @@ -282,7 +284,9 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { if ctx.Exists(p) { return true } - return fs.root != "" && fs.diskRegular(p) + // A path that may be in a directory that was not listed is taken + // to exist: its absence is not known. + return fs.root != "" && fs.diskRegular(p) || fs.mayHide(p) }} acc := assess.ParseAccounts(fs.Read("/etc/passwd"), fs.Read("/etc/shadow"), fs.Read("/etc/group"), fs.tcb()) owners := map[string]assess.Package{} @@ -307,6 +311,7 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { ctx.Annotate("alpine_branch", branch) } found := assess.Run(assess.Input{ + NotRead: fs.notRead, Binaries: s.binaries, Owners: owners, Files: fs, @@ -399,6 +404,83 @@ type files struct { root string } +// mayHide reports whether a file matching pattern (a path or a glob) can +// be in a directory that was not listed, in the walk or on disk under the +// system root: then what it matches is unknown. +func (f *files) mayHide(pattern string) bool { + pc := strings.Split(strings.TrimPrefix(pattern, "/"), "/") + for _, d := range f.unreadDirs { + dc := strings.Split(strings.TrimPrefix(d, "/"), "/") + if len(dc) >= len(pc) { + continue + } + in := true + for i, c := range dc { + if ok, _ := path.Match(pc[i], c); !ok { + in = false + break + } + } + if in { + return true + } + } + return f.root != "" && f.diskHidden(f.root, pc) +} + +// diskHidden reports whether the files under dir matching comps cannot be +// all listed: a directory on the way that exists and cannot be read. It +// never follows a symbolic link. +func (f *files) diskHidden(dir string, comps []string) bool { + unknown := func(err error) bool { return err != nil && !errors.Is(err, fs.ErrNotExist) } + c := comps[0] + if len(comps) == 1 { + if hasMeta(c) { + _, err := os.ReadDir(dir) + return unknown(err) + } + _, err := os.Lstat(filepath.Join(dir, c)) + return unknown(err) + } + if !hasMeta(c) { + next := filepath.Join(dir, c) + fi, err := os.Lstat(next) + if err != nil { + return unknown(err) + } + return fi.IsDir() && f.diskHidden(next, comps[1:]) + } + es, err := os.ReadDir(dir) + if err != nil { + return unknown(err) + } + for _, e := range es { + if ok, _ := path.Match(c, e.Name()); ok && e.IsDir() && f.diskHidden(filepath.Join(dir, e.Name()), comps[1:]) { + return true + } + } + return false +} + +func hasMeta(s string) bool { return strings.ContainsAny(s, "*?[\\") } + +// notRead reports whether a file the verdict reads may be in the target +// but was not read: over a size limit, unreadable, or in a directory that +// could not be listed. +func (f *files) notRead(p string) bool { + if _, ok := f.kept[p]; ok { + return false + } + if f.over[p] || f.mayHide(p) { + return true + } + if f.root == "" { + return false + } + _, ok := f.diskFile(p) + return ok && f.disk(p) == nil +} + // inUnreadDir reports whether p lies in a directory that was not listed. func (f *files) inUnreadDir(p string) bool { for _, d := range f.unreadDirs { @@ -506,7 +588,7 @@ func (f *files) Glob(pattern string) []string { for p := range f.over { match(p) } - if f.inUnreadDir(path.Dir(pattern)) && !seen[pattern] { + if f.mayHide(pattern) && !seen[pattern] { // What it matches there is unknown: stand for it with the pattern, // which Read cannot give. seen[pattern] = true From fa555cc59657a3211b6deedff1341485ee76d6f1 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 09:40:17 +0000 Subject: [PATCH 085/119] engine, java4shell, emudhra: forgetting a path costs what it held From the final review: an image that repeats paths made Forget walk every kept item each time (40,000 units and 100,000 repeats: 38.7 s against 3.2 s). java4shell keeps VM libraries, settings, crash logs and runtime downloads in an ordered list indexed by path, emudhra indexes findings by the file (or archive) they were found in, and the engine counts the hard links that name each path. Forgetting a setting also gives back what it counted toward the caps, so repeats no longer reach 'the scan reached its limit'. Tests: 40,000 units with 100,000 repeats (0.2 s), and 2,000 emudhra findings with 20,000 repeats. Co-Authored-By: Claude Opus 5.5 --- detectors/emudhra/emudhra.go | 32 ++++-- detectors/emudhra/limit_test.go | 55 +++++++++++ detectors/java4shell/java4shell.go | 102 +++++++++++++++----- detectors/java4shell/limit_internal_test.go | 30 +++++- internal/engine/run.go | 31 ++++-- 5 files changed, 205 insertions(+), 45 deletions(-) diff --git a/detectors/emudhra/emudhra.go b/detectors/emudhra/emudhra.go index cd85119..c93aaf6 100644 --- a/detectors/emudhra/emudhra.go +++ b/detectors/emudhra/emudhra.go @@ -10,7 +10,6 @@ package emudhra import ( "context" - "slices" "strings" "time" @@ -72,7 +71,7 @@ func (d *Detector) Load() error { // NewScan starts a filesystem or image scan. func (d *Detector) NewScan(engine.TargetKind) engine.Scan { - return &scan{det: d.det, files: map[string][]byte{}, dedupe: map[string]bool{}, scanned: map[string]bool{}} + return &scan{det: d.det, files: map[string][]byte{}, dedupe: map[string]bool{}, scanned: map[string]bool{}, foundIn: map[string][]int{}} } // Probe checks the certificate chain a TLS server presents. @@ -94,6 +93,10 @@ type scan struct { files map[string][]byte dedupe map[string]bool scanned map[string]bool // certifi bundles visited + // foundIn indexes findings by the file visited (members included); + // gone marks those a later entry for the file dropped. + foundIn map[string][]int + gone []bool } // keep reports whether the assessment rules need this file's content: the @@ -104,17 +107,17 @@ func keep(p string) bool { } // Forget drops what was found in p, and inside it: an image names it -// again, and the last entry is the file. +// again, and the last entry is the file. Findings are indexed by the file +// they were found in, so this costs what p held, not every finding. func (s *scan) Forget(p string) { delete(s.files, p) delete(s.scanned, p) - in := func(q string) bool { return q == p || strings.HasPrefix(q, p+"!/") } - s.findings = slices.DeleteFunc(s.findings, func(x detect.Finding) bool { return in(x.Path) }) - for k := range s.dedupe { - if in(k[:strings.IndexByte(k, 0)]) { - delete(s.dedupe, k) - } + for _, i := range s.foundIn[p] { + x := s.findings[i] + delete(s.dedupe, x.Path+"\x00"+string(x.Kind)+"\x00"+x.SPKI) + s.gone[i] = true } + delete(s.foundIn, p) } func (s *scan) Visit(f engine.File) []engine.Skip { @@ -133,7 +136,10 @@ func (s *scan) Visit(f engine.File) []engine.Skip { continue } s.dedupe[k] = true + outer, _, _ := strings.Cut(f.Path, "!/") // a member is forgotten with its archive + s.foundIn[outer] = append(s.foundIn[outer], len(s.findings)) s.findings = append(s.findings, x) + s.gone = append(s.gone, false) } var out []engine.Skip for _, sk := range skips { @@ -143,7 +149,13 @@ func (s *scan) Visit(f engine.File) []engine.Skip { } func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { - rs := assess.Assess(s.findings, assess.Context{ + found := make([]detect.Finding, 0, len(s.findings)) + for i, x := range s.findings { + if !s.gone[i] { + found = append(found, x) + } + } + rs := assess.Assess(found, assess.Context{ Read: func(p string) []byte { return s.files[p] }, Scanned: func(p string) bool { return s.scanned[p] }, Env: ctx.Env(), diff --git a/detectors/emudhra/limit_test.go b/detectors/emudhra/limit_test.go index 38bd26b..a2e5710 100644 --- a/detectors/emudhra/limit_test.go +++ b/detectors/emudhra/limit_test.go @@ -3,9 +3,12 @@ package emudhra_test import ( "archive/tar" "bytes" + "encoding/json" + "fmt" "os" "path/filepath" "testing" + "time" "github.com/DefectDojo/earlylight/internal/cli" ) @@ -77,3 +80,55 @@ func TestCertifiNamedTwice(t *testing.T) { t.Errorf("exit %d, want 1\n%s%s", code, out.String(), errb.String()) } } + +// Final review finding 5: forgetting a path costs what the path held, not +// every finding kept: an image that repeats paths stays linear. +func TestForgetIsCheap(t *testing.T) { + g3, err := os.ReadFile(filepath.Join(g3Bundle(t), "cacert.pem")) + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + add := func(name string, body []byte) { + tw.WriteHeader(&tar.Header{Name: name, Mode: 0o644, Size: int64(len(body)), Typeflag: tar.TypeReg}) + tw.Write(body) + } + for i := 0; i < 2000; i++ { + add(fmt.Sprintf("certs/%d.pem", i), g3) + } + for i := 0; i < 20000; i++ { + add("certs/0.pem", []byte("x")) + } + tw.Close() + img := filepath.Join(t.TempDir(), "rootfs.tar") + if err := os.WriteFile(img, buf.Bytes(), 0o600); err != nil { + t.Fatal(err) + } + start := time.Now() + var out, errb bytes.Buffer + if code := cli.Run(engine, []string{"scan", "image", "--detector", "emudhra", "--format", "json", "rootfs:" + img}, &out, &errb); code != 1 { + t.Fatalf("exit %d %s", code, errb.String()) + } + if d := time.Since(start); d > 20*time.Second { + t.Errorf("2,000 findings and 20,000 repeats took %s", d) + } + var r struct { + Targets []struct { + Findings []struct { + Path string `json:"path"` + } `json:"findings"` + } `json:"targets"` + } + if err := json.Unmarshal(out.Bytes(), &r); err != nil || len(r.Targets) != 1 { + t.Fatalf("%v", err) + } + for _, f := range r.Targets[0].Findings { + if f.Path == "/certs/0.pem" { + t.Errorf("a finding in the replaced entry survived") + } + } + if n := len(r.Targets[0].Findings); n != 1999 { + t.Errorf("%d findings, want 1999", n) + } +} diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 3feefa6..9cbd9e0 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -23,7 +23,6 @@ import ( "fmt" "path" "regexp" - "slices" "sort" "strings" @@ -180,7 +179,7 @@ func (s *scan) notRead(p string) { // FinishSkips reports the JVM settings files not read as coverage gaps // when the target holds a runtime. func (s *scan) FinishSkips() []engine.Skip { - if len(s.libs) == 0 { + if s.libs.len() == 0 { return nil } var out []engine.Skip @@ -209,10 +208,17 @@ func (s *scan) Forget(p string) { delete(s.releases, path.Dir(p)) delete(s.badReleases, path.Dir(p)) } - s.libs = slices.DeleteFunc(s.libs, func(l *jvm.Library) bool { return l.Path == p }) - s.settings = slices.DeleteFunc(s.settings, func(st jvm.Setting) bool { return st.File == p }) - s.crashes = slices.DeleteFunc(s.crashes, func(c crash) bool { return c.Path == p }) - s.archives = slices.DeleteFunc(s.archives, func(a string) bool { return a == p }) + s.libs.drop(p) + for _, st := range s.settings.drop(p) { + // Give back what it counted toward the caps. + if st.SetsOptions() { + s.optionFiles-- + } else { + s.plainUnits-- + } + } + s.crashes.drop(p) + s.archives.drop(p) } var hsErr = regexp.MustCompile(`^hs_err_pid\d{1,10}\.log$`) @@ -232,8 +238,8 @@ const maxArchivesNoted = 256 // reading them: the detector does not unpack archives, and a runtime that // is not installed is context, not a file left unscanned. func (s *scan) VisitHead(p string, head []byte) { - if len(s.archives) < maxArchivesNoted && jdkArchive.MatchString(path.Base(p)) && archive.IsArchive(head) { - s.archives = append(s.archives, p) + if s.archives.len() < maxArchivesNoted && jdkArchive.MatchString(path.Base(p)) && archive.IsArchive(head) { + s.archives.add(p, p) } } @@ -284,17 +290,17 @@ func (d *Detector) NewScan(kind engine.TargetKind) engine.Scan { type scan struct { kind engine.TargetKind - libs []*jvm.Library + libs pathList[*jvm.Library] releases map[string]jvm.Release badReleases map[string]string - settings []jvm.Setting + settings pathList[jvm.Setting] kept map[string][]byte lists map[string][]byte scripts map[string]map[string]bool - crashes []crash + crashes pathList[crash] dropped int keptBytes int - archives []string // runtime downloads seen by name, not read + archives pathList[string] // runtime downloads seen by name, not read // unreadScripts may be start scripts and were not read; unreadDirs // could not be listed; unreadAll stands for more than were recorded. unreadScripts map[string]bool @@ -326,11 +332,11 @@ func (s *scan) Visit(f engine.File) []engine.Skip { switch { case jvm.IsLibraryName(base): if l, ok := jvm.Inspect(f.Path, f.Data); ok { - if len(s.libs) >= maxLibs { + if s.libs.len() >= maxLibs { s.dropped++ return []engine.Skip{{Path: f.Path, Reason: fmt.Sprintf("more than %d Java VM libraries in one target; not checked", maxLibs)}} } - s.libs = append(s.libs, l) + s.libs.add(f.Path, l) } return nil case base == "release": @@ -347,8 +353,8 @@ func (s *scan) Visit(f engine.File) []engine.Skip { } return nil case hsErr.MatchString(base): - if len(s.crashes) < maxHsErrs && len(f.Data) <= maxHsErr { - s.crashes = append(s.crashes, readCrash(f.Path, f.Data)) + if s.crashes.len() < maxHsErrs && len(f.Data) <= maxHsErr { + s.crashes.add(f.Path, readCrash(f.Path, f.Data)) } return nil } @@ -361,14 +367,14 @@ func (s *scan) Visit(f engine.File) []engine.Skip { case st.SetsOptions() && s.optionFiles >= maxSettings: s.limit(fmt.Sprintf("more than %d files that set JVM options", maxSettings)) case st.SetsOptions(): - s.settings = append(s.settings, st) + s.settings.add(f.Path, st) s.optionFiles++ case st.Kind == "systemd" && s.plainUnits >= maxPlainUnits: s.limit(fmt.Sprintf("more than %d systemd units", maxPlainUnits)) case st.Kind == "systemd": // A unit without JVM options still replaces or extends // another file of the same unit: keep it, uncounted. - s.settings = append(s.settings, st) + s.settings.add(f.Path, st) s.plainUnits++ } } @@ -437,16 +443,16 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { ctx.Annotate("java4shell_scanner_cpu", c) } } - if len(s.crashes) > 0 { - ctx.Annotate("java4shell_crash_logs", s.crashes) + if s.crashes.len() > 0 { + ctx.Annotate("java4shell_crash_logs", s.crashes.list()) } - if len(s.archives) > 0 { - ctx.Annotate("java4shell_runtime_archives", s.archives) + if s.archives.len() > 0 { + ctx.Annotate("java4shell_runtime_archives", s.archives.list()) } if osr := osRelease(s.kept["/etc/os-release"], s.kept["/usr/lib/os-release"]); osr != "" { ctx.Annotate("java4shell_os", osr) } - if len(s.libs) == 0 { + if s.libs.len() == 0 { if len(s.limits) > 0 { ctx.Problem("java4shell: the scan reached its limit on " + strings.Join(s.limits, " and ") + " for one target") } @@ -468,10 +474,10 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { } } in := assess.Input{ - Libraries: s.libs, + Libraries: s.libs.list(), Releases: s.releases, BadReleases: s.badReleases, - Settings: s.settings, + Settings: s.settings.list(), Owners: owners, Resolve: res.resolve, Scripts: s.scripts, @@ -691,3 +697,49 @@ func (s *osScan) Finish(ctx engine.TargetContext) []engine.Finding { } return nil } + +// pathList keeps items in order, and drops those a path added in constant +// time (Forget can run once per file of an image). +type pathList[T any] struct { + items []T + gone []bool + at map[string][]int + live int +} + +func (l *pathList[T]) add(p string, v T) { + if l.at == nil { + l.at = map[string][]int{} + } + l.at[p] = append(l.at[p], len(l.items)) + l.items = append(l.items, v) + l.gone = append(l.gone, false) + l.live++ +} + +// drop removes what p added, and returns it. +func (l *pathList[T]) drop(p string) []T { + var out []T + for _, i := range l.at[p] { + if !l.gone[i] { + l.gone[i] = true + l.live-- + out = append(out, l.items[i]) + } + } + delete(l.at, p) + return out +} + +func (l *pathList[T]) len() int { return l.live } + +// list returns the items not dropped, in the order added. +func (l *pathList[T]) list() []T { + out := make([]T, 0, l.live) + for i, v := range l.items { + if !l.gone[i] { + out = append(out, v) + } + } + return out +} diff --git a/detectors/java4shell/limit_internal_test.go b/detectors/java4shell/limit_internal_test.go index 7073118..5d0a476 100644 --- a/detectors/java4shell/limit_internal_test.go +++ b/detectors/java4shell/limit_internal_test.go @@ -9,6 +9,7 @@ import ( "runtime" "strings" "testing" + "time" "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" "github.com/DefectDojo/earlylight/internal/engine" @@ -235,14 +236,14 @@ func TestForget(t *testing.T) { s.Visit(engine.File{Path: "/opt/java/release", Data: testlib.Release("JAVA_VERSION", "21.0.13")}) s.Visit(engine.File{Path: "/var/lib/dpkg/status", Data: []byte("Package: x\n")}) s.Visit(engine.File{Path: "/opt/app/bin/setenv.sh", Data: []byte("JAVA_OPTS=-XX:-UseBASE64Intrinsics\n")}) - if len(s.libs) != 1 || len(s.releases) != 1 || len(s.kept) != 1 || len(s.settings) != 1 { - t.Fatalf("libs %d releases %d kept %d settings %d", len(s.libs), len(s.releases), len(s.kept), len(s.settings)) + if s.libs.len() != 1 || len(s.releases) != 1 || len(s.kept) != 1 || s.settings.len() != 1 { + t.Fatalf("libs %d releases %d kept %d settings %d", s.libs.len(), len(s.releases), len(s.kept), s.settings.len()) } for _, p := range []string{"/opt/java/lib/server/libjvm.so", "/opt/java/release", "/var/lib/dpkg/status", "/opt/app/bin/setenv.sh"} { s.Forget(p) } - if len(s.libs)+len(s.releases)+len(s.kept)+len(s.settings) != 0 || s.keptBytes != 0 { - t.Errorf("libs %d releases %d kept %d settings %d bytes %d", len(s.libs), len(s.releases), len(s.kept), len(s.settings), s.keptBytes) + if s.libs.len()+len(s.releases)+len(s.kept)+s.settings.len() != 0 || s.keptBytes != 0 { + t.Errorf("libs %d releases %d kept %d settings %d bytes %d", s.libs.len(), len(s.releases), len(s.kept), s.settings.len(), s.keptBytes) } } @@ -266,3 +267,24 @@ func TestHardLinkKeepsRuntime(t *testing.T) { t.Errorf("error %q findings %+v", tg.Error, tg.Findings) } } + +// Final review finding 5: forgetting a path costs what the path held: 40,000 +// units and 100,000 repeats of one stay fast. +func TestForgetIsCheap(t *testing.T) { + s := (&Detector{}).NewScan(engine.Filesystem).(*scan) + unit := []byte("[Service]\nExecStart=/opt/app/bin/start\n") + for i := 0; i < 40000; i++ { + s.Visit(engine.File{Path: fmt.Sprintf("/etc/systemd/system/u%d.service", i), Data: unit}) + } + start := time.Now() + for i := 0; i < 100000; i++ { + s.Forget("/etc/systemd/system/u0.service") + s.Visit(engine.File{Path: "/etc/systemd/system/u0.service", Data: unit}) + } + if d := time.Since(start); d > 10*time.Second { + t.Errorf("100,000 repeats over 40,000 units took %s", d) + } + if n := s.settings.len(); n != 40000 { + t.Errorf("%d settings, want 40000", n) + } +} diff --git a/internal/engine/run.go b/internal/engine/run.go index 70f50cc..1867aca 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -217,6 +217,8 @@ type walker struct { // exclusions are the exclusion records made for each scan, by path, so // a gap the scan reports at the end replaces its exclusion. exclusions []map[string]string + // linked counts the hard links that name each path. + linked map[string]int } // fileLimit is one detector's own limit on one file, and whether it asked @@ -263,7 +265,7 @@ func (w *walker) sourceOptions(opts Options) source.Options { MaxFileSize: opts.MaxFileSize, IsExecutable: archive.IsExecutable, Symlink: func(p, t string) { w.ctx.symlinks[w.abs(p)] = t }, - Hardlink: func(p, t string) { w.ctx.hardlinks[w.abs(p)] = w.abs(t) }, + Hardlink: func(p, t string) { w.setHardlink(w.abs(p), w.abs(t)) }, } type headScan struct { id string @@ -324,7 +326,7 @@ func (w *walker) sourceOptions(opts Options) source.Options { } // A path that was a link is a file now. delete(w.ctx.symlinks, abs) - delete(w.ctx.hardlinks, abs) + w.setHardlink(abs, "") // The file exists whether or not any detector reads it, so Exists // does not depend on which detectors ran. w.ctx.seen[abs] = true @@ -356,15 +358,32 @@ func (w *walker) sourceOptions(opts Options) source.Options { // the earlier file's content (it names the file, not the path), so what // was found in it stays, under p. func (w *walker) replaced(p string) { - for _, t := range w.ctx.hardlinks { - if t == p { - return - } + if w.linked[p] > 0 { + return } w.forget(p) delete(w.ctx.seen, p) } +// setHardlink records that p is a hard link to t ("": p is no longer a +// link), keeping a count of the links that name each path. +func (w *walker) setHardlink(p, t string) { + if old, ok := w.ctx.hardlinks[p]; ok { + if w.linked[old]--; w.linked[old] <= 0 { + delete(w.linked, old) + } + delete(w.ctx.hardlinks, p) + } + if t == "" { + return + } + if w.linked == nil { + w.linked = map[string]int{} + } + w.ctx.hardlinks[p] = t + w.linked[t]++ +} + // forget tells every scan to drop what it kept of p. func (w *walker) forget(p string) { for i, s := range w.scans { From 86e15b45ffbb99e39978b2c76ec3a9723471191c Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 09:40:52 +0000 Subject: [PATCH 086/119] engine: one skip record per path From the final review: a file two detectors left unchecked had a record for each. Records for one path are merged after the scan: a coverage gap if any record is one (with DetectorFailed kept), a deliberate exclusion otherwise, with every distinct reason. Co-Authored-By: Claude Opus 5.5 --- internal/engine/limit_test.go | 23 ++++++++++++++++++++--- internal/engine/run.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/internal/engine/limit_test.go b/internal/engine/limit_test.go index f2b4796..d247dbc 100644 --- a/internal/engine/limit_test.go +++ b/internal/engine/limit_test.go @@ -126,7 +126,8 @@ func TestLimiterWithAnotherReader(t *testing.T) { } } -// A file over the limits of two detectors is recorded for each. +// A file over the limits of two detectors has one record naming each +// (final review finding 6). func TestLimiterTwoLimits(t *testing.T) { root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 100<<10)}) _, ds := capped("t-two1k", osRelease, func(string) int64 { return 1 << 10 }) @@ -136,8 +137,9 @@ func TestLimiterTwoLimits(t *testing.T) { for _, s := range tg.Skipped { got = append(got, s.Reason) } - want := "excluded: larger than the 1024-byte limit of t-two1k for this file (102400 bytes)|" + - "excluded: larger than the 65536-byte limit of t-two64k for this file (102400 bytes)" + // One record for the path, naming both. + want := "excluded: larger than the 1024-byte limit of t-two1k for this file (102400 bytes); " + + "larger than the 65536-byte limit of t-two64k for this file (102400 bytes)" if strings.Join(got, "|") != want { t.Errorf("skipped %q", got) } @@ -653,3 +655,18 @@ func TestReplacedInDockerExport(t *testing.T) { t.Errorf("forgot %v exists %v", *u.forgot, exists) } } + +// A gap and an exclusion for one path are one record: a gap, with both +// reasons. +func TestOneRecordPerPath(t *testing.T) { + got := oneRecordPerPath([]source.Skip{ + {Path: "/a", Reason: "excluded: larger than the 10-byte limit of x for this file (20 bytes)", Excluded: true}, + {Path: "/b", Reason: "permission denied"}, + {Path: "/a", Reason: "not read, and y's verdict depends on it"}, + {Path: "/a", Reason: "detector z failed on this file", DetectorFailed: true}, + }) + if len(got) != 2 || got[0].Path != "/a" || got[0].Excluded || !got[0].DetectorFailed || + got[0].Reason != "not read, and y's verdict depends on it; larger than the 10-byte limit of x for this file (20 bytes); detector z failed on this file" { + t.Errorf("%+v", got) + } +} diff --git a/internal/engine/run.go b/internal/engine/run.go index 1867aca..7ca373d 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -571,6 +571,7 @@ func (w *walker) visitHeadSafely(id string, h HeadVisitor, p string, head []byte } func (w *walker) finish() { + defer func() { w.t.Skipped = oneRecordPerPath(w.t.Skipped) }() for i, s := range w.scans { fs, err := finishSafely(s, w.ctx) if err != nil { @@ -592,6 +593,33 @@ func (w *walker) finish() { } } +// oneRecordPerPath merges the records of one path (two detectors that +// left it unchecked, or a source record and a detector's): a coverage gap +// if any record is one, a deliberate exclusion otherwise, with every +// distinct reason. Paths keep the order they were first recorded in. +func oneRecordPerPath(skips []source.Skip) []source.Skip { + at := map[string]int{} + var out []source.Skip + for _, s := range skips { + i, ok := at[s.Path] + if !ok { + at[s.Path] = len(out) + out = append(out, s) + continue + } + m := &out[i] + switch { + case m.Excluded && !s.Excluded: + // The gap leads; the exclusion's reason follows. + m.Reason, m.Excluded = s.Reason+"; "+strings.TrimPrefix(m.Reason, "excluded: "), false + case !strings.Contains(m.Reason, strings.TrimPrefix(s.Reason, "excluded: ")): + m.Reason += "; " + strings.TrimPrefix(s.Reason, "excluded: ") + } + m.DetectorFailed = m.DetectorFailed || s.DetectorFailed + } + return out +} + // dropExclusion removes the exclusion record made for scan i on p: the // scan reports p as a gap instead. func (w *walker) dropExclusion(i int, p string) { From 54b37166d5d1e6a6c760dc0854eb0bdb4ee435cd Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 09:45:43 +0000 Subject: [PATCH 087/119] engine: FuzzLimits checks the one record per path, with the input that found it Co-Authored-By: Claude Opus 5.5 --- internal/engine/limit_test.go | 19 ++++++++----------- .../testdata/fuzz/FuzzLimits/65084b3e2def00cf | 6 ++++++ 2 files changed, 14 insertions(+), 11 deletions(-) create mode 100644 internal/engine/testdata/fuzz/FuzzLimits/65084b3e2def00cf diff --git a/internal/engine/limit_test.go b/internal/engine/limit_test.go index d247dbc..3f5e745 100644 --- a/internal/engine/limit_test.go +++ b/internal/engine/limit_test.go @@ -342,21 +342,18 @@ func FuzzLimits(f *testing.F) { t.Fatalf("size %d lims %v want %v max %d: detector %d saw %v, want %v (skipped %+v)", size, lims, want, maxSize, i, *fakes[i].seen, sees, tg.Skipped) } } - recorded := 0 - for _, s := range tg.Skipped { - if s.Excluded { - recorded++ - } + // One record for the path names each detector whose own limit kept + // it out (and that wanted it). + if len(tg.Skipped) > 1 { + t.Fatalf("more than one record for one path: %+v", tg.Skipped) } - wantRecords := 0 for i := range lims { - if want[i] && over(i) && (readIt || ownSkip) { - wantRecords++ + named := len(tg.Skipped) == 1 && tg.Skipped[0].Excluded && + strings.Contains(tg.Skipped[0].Reason, fmt.Sprintf("limit of t-fz%d ", i)) + if wantNamed := want[i] && over(i) && (readIt || ownSkip); named != wantNamed { + t.Fatalf("size %d lims %v want %v max %d: detector %d named %v, want %v: %+v", size, lims, want, maxSize, i, named, wantNamed, tg.Skipped) } } - if recorded != wantRecords { - t.Fatalf("size %d lims %v want %v max %d: %d own-limit records, want %d: %+v", size, lims, want, maxSize, recorded, wantRecords, tg.Skipped) - } if !exists { t.Fatalf("Exists false for a file the walk met") } diff --git a/internal/engine/testdata/fuzz/FuzzLimits/65084b3e2def00cf b/internal/engine/testdata/fuzz/FuzzLimits/65084b3e2def00cf new file mode 100644 index 0000000..790a132 --- /dev/null +++ b/internal/engine/testdata/fuzz/FuzzLimits/65084b3e2def00cf @@ -0,0 +1,6 @@ +go test fuzz v1 +uint16(101) +uint16(100) +uint16(44) +byte('\x03') +byte('\x00') From c2a40311e87a74f4c25d709b402075f189c1b16e Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 10:27:53 +0000 Subject: [PATCH 088/119] image: agree with a docker export on deep symlinks, hard links to hidden files and dir-file-dir layers From the round-5 review, against docker export as ground truth: - A symbolic link with more '../' than its depth (or to a name starting with '..') is kept: it resolves at the root. Dropping it resurrected the lower layer's file at its path. - A hard link keeps the content of the file it named when an upper layer removes or replaces that file (RUN ln /a /b; RUN rm /a): the layer is read again for it. A Java runtime reached only through the link was lost. - A non-directory a layer puts where an upper layer has a directory removed the lower directory there: directory, file, directory over three layers no longer resurrects the first directory's files (a stale UsePAM yes include cleared the server). - What the layers do not settle cheaply (two entries for a path in one layer, a whiteout and a file for one path in one layer, a hard link to a file outside its layer, a write or whiteout through a directory that is a symbolic link) is listed as unresolved; the scan forgets what it read there and tells each detector the path was not read. - FuzzFlatten: random multi-layer images give what mutate.Extract gives on clean names, and the same with names spelled with a leading slash; with any entries, no path is written twice. - Tests for each case, in internal/image and through docker-archive with sshole and java4shell. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/limit_internal_test.go | 52 ++++ detectors/sshole/limit_test.go | 69 +++++ internal/engine/run.go | 11 + internal/image/flatten.go | 239 ++++++++++++++--- internal/image/flatten_test.go | 271 ++++++++++++++++++-- internal/image/image.go | 5 +- 6 files changed, 578 insertions(+), 69 deletions(-) diff --git a/detectors/java4shell/limit_internal_test.go b/detectors/java4shell/limit_internal_test.go index 5d0a476..4f3c5b7 100644 --- a/detectors/java4shell/limit_internal_test.go +++ b/detectors/java4shell/limit_internal_test.go @@ -4,6 +4,7 @@ import ( "archive/tar" "bytes" "fmt" + "io" "os" "path/filepath" "runtime" @@ -11,6 +12,12 @@ import ( "testing" "time" + "github.com/google/go-containerregistry/pkg/name" + v1 "github.com/google/go-containerregistry/pkg/v1" + "github.com/google/go-containerregistry/pkg/v1/empty" + "github.com/google/go-containerregistry/pkg/v1/mutate" + "github.com/google/go-containerregistry/pkg/v1/tarball" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" "github.com/DefectDojo/earlylight/internal/engine" ) @@ -288,3 +295,48 @@ func TestForgetIsCheap(t *testing.T) { t.Errorf("%d settings, want 40000", n) } } + +// Round-5 review finding 2a: RUN ln /a /b; RUN rm /a: the hard link keeps +// the runtime, as in a docker export. +func TestHardLinkTargetRemovedInLayer(t *testing.T) { + lib := testlib.Build(testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true}) + layer := func(es ...[3]string) v1.Layer { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, e := range es { + h := &tar.Header{Name: e[1], Mode: 0o755, Typeflag: tar.TypeReg, Size: int64(len(e[2]))} + if e[0] == "h" { + h.Typeflag, h.Size, h.Linkname = tar.TypeLink, 0, e[2] + } + tw.WriteHeader(h) + if e[0] != "h" { + tw.Write([]byte(e[2])) + } + } + tw.Close() + b := buf.Bytes() + l, err := tarball.LayerFromOpener(func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(b)), nil }) + if err != nil { + t.Fatal(err) + } + return l + } + const a = "opt/java/lib/server/libjvm.so" + for _, top := range [][3]string{{"f", "opt/java/lib/server/.wh.libjvm.so", ""}, {"f", a, "replaced"}} { + img, err := mutate.AppendLayers(empty.Image, + layer([3]string{"f", a, string(lib)}), + layer([3]string{"f", a, string(lib)}, [3]string{"h", "opt/copy/lib/server/libjvm.so", a}), + layer(top)) + if err != nil { + t.Fatal(err) + } + p := filepath.Join(t.TempDir(), "image.tar") + if err := tarball.WriteToFile(p, name.MustParseReference("test/j:1"), img); err != nil { + t.Fatal(err) + } + tg := engine.ScanImage([]engine.Detector{&Detector{}}, "docker-archive:"+p, engine.Options{}) + if tg.Error != "" || len(tg.Findings) != 1 || tg.Findings[0].Verdict != engine.Vulnerable || tg.Findings[0].Path != "/opt/copy" { + t.Errorf("%s: error %q findings %+v", top[1], tg.Error, tg.Findings) + } + } +} diff --git a/detectors/sshole/limit_test.go b/detectors/sshole/limit_test.go index 4324ee3..f4f022c 100644 --- a/detectors/sshole/limit_test.go +++ b/detectors/sshole/limit_test.go @@ -576,3 +576,72 @@ func TestUnlistableDirectories(t *testing.T) { t.Errorf("unreadable /etc/shadow: %+v", fs) } } + +// entLayer is a layer of hand-made entries ("d" directory, "f" file, +// "w" whiteout). +func entLayer(t *testing.T, es ...[3]string) v1.Layer { + t.Helper() + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, e := range es { + h := &tar.Header{Name: e[1], Mode: 0o644, Typeflag: tar.TypeReg, Size: int64(len(e[2]))} + if e[0] == "d" { + h.Typeflag, h.Size, h.Mode = tar.TypeDir, 0, 0o755 + } + tw.WriteHeader(h) + tw.Write([]byte(e[2])) + } + tw.Close() + b := buf.Bytes() + l, err := tarball.LayerFromOpener(func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(b)), nil }) + if err != nil { + t.Fatal(err) + } + return l +} + +// Round-5 review finding 2b: a directory, then a file, then a directory +// over three layers: the stale include in the first is gone, as in a +// docker export, and does not turn PAM on. +func TestDirFileDirLayers(t *testing.T) { + root := pamRoot(t) + write(t, root, "etc/ssh/sshd_config", []byte("Include /etc/ssh/sshd_config.d/*.conf\n"), 0o644) + img := dockerArchive(t, dirLayer(t, root, false), + entLayer(t, [3]string{"d", "etc/ssh/sshd_config.d", ""}, [3]string{"f", "etc/ssh/sshd_config.d/10-pam.conf", "UsePAM yes\n"}), + entLayer(t, [3]string{"f", "etc/ssh/sshd_config.d", "not a directory"}), + entLayer(t, [3]string{"d", "etc/ssh/sshd_config.d", ""}, [3]string{"f", "etc/ssh/sshd_config.d/20-x.conf", "Port 22\n"})) + var out, errb bytes.Buffer + cli.Run(cfg, []string{"scan", "image", "--format", "json", "--detector", "sshole", "docker-archive:" + img}, &out, &errb) + var r struct { + Targets []struct { + Findings []engine.Finding `json:"findings"` + } `json:"targets"` + } + if err := json.Unmarshal(out.Bytes(), &r); err != nil || len(r.Targets) != 1 { + t.Fatalf("%v %s", err, errb.String()) + } + if fs := r.Targets[0].Findings; len(fs) != 1 || fs[0].Verdict != engine.Vulnerable || fs[0].Severity != "critical" { + t.Errorf("%+v", fs) + } +} + +// Round-5 review finding 4: two entries for one include in one layer (the +// runtime keeps the last) leave it unresolved: never cleared on the first. +func TestDuplicateInOneLayer(t *testing.T) { + root := pamRoot(t) + img := dockerArchive(t, dirLayer(t, root, false), + entLayer(t, [3]string{"f", "etc/ssh/sshd_config.d/50.conf", "Port 22\n"}, [3]string{"f", "etc/ssh/sshd_config.d/50.conf", "UsePAM no\n"})) + var out, errb bytes.Buffer + cli.Run(cfg, []string{"scan", "image", "--format", "json", "--detector", "sshole", "docker-archive:" + img}, &out, &errb) + var r struct { + Targets []struct { + Findings []engine.Finding `json:"findings"` + } `json:"targets"` + } + if err := json.Unmarshal(out.Bytes(), &r); err != nil || len(r.Targets) != 1 { + t.Fatalf("%v %s", err, errb.String()) + } + if fs := r.Targets[0].Findings; len(fs) != 1 || fs[0].Verdict.Cleared() { + t.Errorf("%+v", fs) + } +} diff --git a/internal/engine/run.go b/internal/engine/run.go index 7ca373d..c4db543 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -727,6 +727,7 @@ func ScanImage(dets []Detector, ref string, opts Options) *Target { t := &Target{Name: ref, Type: Image} w := newWalker(dets, Image, t, opts) var rc io.ReadCloser + var unresolved func() []string if p, ok := strings.CutPrefix(ref, "rootfs:"); ok && opts.Guarded { t.Error = fmt.Sprintf("%q: only registry references are opened for a source tree", "rootfs:"+p) return t @@ -754,6 +755,7 @@ func ScanImage(dets []Detector, ref string, opts Options) *Target { return t } rc, t.Digest, t.Platform, w.ctx.env = o.FS, o.Digest, o.Platform, o.Env + unresolved = o.Unresolved w.ctx.cmd = opts.Override.Apply(o.Entrypoint, o.Cmd) } defer rc.Close() @@ -773,6 +775,15 @@ func ScanImage(dets []Detector, ref string, opts Options) *Target { t.Error = "the image contained no regular files" return t } + if unresolved != nil { + // Paths the layers do not settle: whatever was read there is + // forgotten, and each scan is told it was not read. + for _, p := range unresolved() { + w.forget(p) + so.Unread(p, false) + t.Skipped = append(t.Skipped, source.Skip{Path: p, Reason: "the image's layers do not settle what this file holds (two entries in one layer, a hard link to a file not in its layer, or a write through a symbolic link); not checked"}) + } + } w.finish() return t } diff --git a/internal/image/flatten.go b/internal/image/flatten.go index 328e519..d0b87bf 100644 --- a/internal/image/flatten.go +++ b/internal/image/flatten.go @@ -1,11 +1,26 @@ package image // Flattening follows go-containerregistry's mutate.Extract (Apache-2.0, -// see THIRD_PARTY_NOTICES.txt), with one change: every entry name is made -// relative to the root first, so "/usr/sbin/sshd" and "usr/sbin/sshd" in -// two layers are one file, as a container runtime extracts them. Without -// it, both are written, the lower layer's copy after the upper one, and a -// whiteout spelled one way does not hide a file spelled the other. +// see THIRD_PARTY_NOTICES.txt), changed to agree with what a container +// runtime extracts (docker export is the ground truth): +// +// - Every entry name is made relative to the root first, so +// "/usr/sbin/sshd" and "usr/sbin/sshd" in two layers are one file, and a +// whiteout spelled one way hides a file spelled the other. +// - A symbolic link is kept whatever its target: one with more "../" than +// its depth resolves at the root, and dropping it would resurrect the +// lower layer's file at its path. +// - A file, link or other non-directory a layer puts where an upper layer +// has a directory removed the lower layers' directory there (directory, +// file, directory over three layers): their entries under it are hidden. +// - A hard link keeps the content of the file it named when that file is +// hidden by an upper layer (RUN ln /a /b; RUN rm /a): the layer is read +// again for it. +// +// What the layers do not settle cheaply (two entries for one path in one +// layer, a hard link to a file not in its layer, a write or whiteout +// through a directory that is a symbolic link) is listed as unresolved: +// the scan treats those paths as not read. import ( "archive/tar" @@ -13,6 +28,7 @@ import ( "fmt" "io" "path" + "sort" "strings" v1 "github.com/google/go-containerregistry/pkg/v1" @@ -24,37 +40,68 @@ const ( ) // flatten returns an image's filesystem as one tar stream, top layer first: -// the first entry for a path is the file, and each path appears once. -func flatten(img v1.Image) io.ReadCloser { +// the first entry for a path is the file, and each path appears once. The +// function returns the paths left unresolved, once the stream has ended. +func flatten(img v1.Image) (io.ReadCloser, func() []string) { pr, pw := io.Pipe() - go func() { pw.CloseWithError(extract(img, pw)) }() - return pr + f := &flattener{fileMap: map[string]bool{}, opaqueDirs: map[string]bool{}, written: map[string]bool{}, + links: map[string]string{}, unresolved: map[string]bool{}} + done := make(chan struct{}) + var out []string + go func() { + defer close(done) + err := f.extract(img, pw) + for p := range f.unresolved { + out = append(out, "/"+p) + } + sort.Strings(out) + pw.CloseWithError(err) + }() + return pr, func() []string { + // The reader stops at the tar trailer: take the rest, so the + // writer can finish, and wait for it. + io.Copy(io.Discard, pr) + <-done + return out + } } -func extract(img v1.Image, w io.Writer) error { - tw := tar.NewWriter(w) - defer tw.Close() - fileMap := map[string]bool{} - opaqueDirs := map[string]bool{} +type flattener struct { + tw *tar.Writer + fileMap map[string]bool // path -> hides what is below it (non-directory or whiteout) + opaqueDirs map[string]bool + written map[string]bool // non-directories written, and whiteouts + links map[string]string // symbolic links written: path -> target + unresolved map[string]bool +} + +func (f *flattener) extract(img v1.Image, w io.Writer) error { + f.tw = tar.NewWriter(w) + defer f.tw.Close() layers, err := img.Layers() if err != nil { return fmt.Errorf("retrieving image layers: %w", err) } for i := len(layers) - 1; i >= 0; i-- { - if err := extractLayer(tw, fileMap, opaqueDirs, layers[i]); err != nil { + if err := f.layer(layers[i]); err != nil { return err } } + f.throughLinks() return nil } // rootName is an entry name relative to the root, "" for the root itself. func rootName(name string) string { - return strings.TrimPrefix(path.Clean("/"+name), "/") + return strings.TrimPrefix(path.Clean("/"+strings.ReplaceAll(name, "\\", "/")), "/") } -func extractLayer(tw *tar.Writer, fileMap, opaqueDirs map[string]bool, layer v1.Layer) error { +func (f *flattener) layer(layer v1.Layer) error { layerOpaque := map[string]bool{} + inLayer := map[string]bool{} // names this layer has (value: a directory) + hidden := map[string]bool{} // regular files of this layer not written + here := map[string]bool{} // regular files of this layer written + pending := map[string][]string{} // hidden file -> hard links to fill from it rc, err := layer.Uncompressed() if err != nil { return fmt.Errorf("reading layer contents: %w", err) @@ -76,11 +123,14 @@ func extractLayer(tw *tar.Writer, fileMap, opaqueDirs map[string]bool, layer v1. if h.Name == "" { continue // the root directory } - if (h.Typeflag == tar.TypeSymlink || h.Typeflag == tar.TypeLink) && unsafeRelativeLink(h.Name, h.Linkname) { - continue + if h.Typeflag == tar.TypeLink { + h.Linkname = rootName(h.Linkname) // tar hard links name a path from the root } h.Format = tar.FormatPAX base, dir := path.Base(h.Name), path.Dir(h.Name) + if dir == "." { + dir = "" + } if base == opaqueWhiteout { layerOpaque[dir] = true continue @@ -93,44 +143,164 @@ func extractLayer(tw *tar.Writer, fileMap, opaqueDirs map[string]bool, layer v1. if h.Typeflag != tar.TypeDir { name = path.Join(dir, base) } - if _, ok := fileMap[name]; ok && !tombstone { + isDir := h.Typeflag == tar.TypeDir && !tombstone + if prev, ok := inLayer[name]; ok && !(prev && isDir) { + // Two entries for one path in one layer: the runtime keeps the + // last, this stream the first. + f.unresolved[name] = true + } + inLayer[name] = isDir + regular := h.Typeflag == tar.TypeReg || h.Typeflag == tar.TypeRegA //nolint:staticcheck + if hides, ok := f.fileMap[name]; ok && !tombstone { + if !hides && !isDir { + // An upper layer has a directory where this layer has a + // file: this layer removed the lower directory there. + layerOpaque[name] = true + } + if regular { + hidden[name] = true + } continue } - if inWhiteoutDir(fileMap, name) || inOpaqueDir(opaqueDirs, name) { + if inWhiteoutDir(f.fileMap, name) || inOpaqueDir(f.opaqueDirs, name) { + if regular { + hidden[name] = true + } continue } - fileMap[name] = tombstone || h.Typeflag != tar.TypeDir + f.fileMap[name] = tombstone || !isDir if tombstone { + f.written[name] = true continue } - if err := tw.WriteHeader(h); err != nil { + if h.Typeflag == tar.TypeLink { + switch { + case hidden[h.Linkname]: + // It names a file an upper layer hides: it keeps that file's + // content, written once the layer is read again. + pending[h.Linkname] = append(pending[h.Linkname], name) + f.written[name] = true + continue + case !here[h.Linkname]: + f.unresolved[name] = true // not a file of its own layer + } + } + if err := f.tw.WriteHeader(h); err != nil { return err } if h.Size > 0 { - if _, err := io.CopyN(tw, tr, h.Size); err != nil { + if _, err := io.CopyN(f.tw, tr, h.Size); err != nil { return err } } + if regular { + here[name] = true + } + if !isDir { + f.written[name] = true + } + if h.Typeflag == tar.TypeSymlink { + f.links[name] = h.Linkname + } } for d := range layerOpaque { - opaqueDirs[d] = true + f.opaqueDirs[d] = true } // Drain the layer so its digest is verified. if _, err := io.Copy(io.Discard, rc); err != nil { return fmt.Errorf("verifying layer: %w", err) } + if len(pending) > 0 { + return f.fillLinks(layer, pending) + } + return nil +} + +// fillLinks writes each hard link to a hidden file as a copy of that file, +// read from the layer again. +func (f *flattener) fillLinks(layer v1.Layer, pending map[string][]string) error { + rc, err := layer.Uncompressed() + if err != nil { + return fmt.Errorf("reading layer contents: %w", err) + } + defer rc.Close() + tr := tar.NewReader(rc) + for len(pending) > 0 { + h, err := tr.Next() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return fmt.Errorf("reading tar: %w", err) + } + name := rootName(h.Name) + links, ok := pending[name] + if !ok || h.Typeflag != tar.TypeReg && h.Typeflag != tar.TypeRegA { //nolint:staticcheck + continue + } + delete(pending, name) + b, err := io.ReadAll(io.LimitReader(tr, h.Size)) + if err != nil { + return err + } + for _, l := range links { + hh := *h + hh.Name, hh.Typeflag, hh.Linkname, hh.Format = l, tar.TypeReg, "", tar.FormatPAX + if err := f.tw.WriteHeader(&hh); err != nil { + return err + } + if _, err := f.tw.Write(b); err != nil { + return err + } + } + } + for _, links := range pending { + for _, l := range links { + f.unresolved[l] = true // the file it names was not found + } + } return nil } +// throughLinks finds the entries an upper layer wrote, or whited out, +// under a directory that is a symbolic link in the final filesystem: the +// runtime wrote through the link, to the path it names. Both paths are +// unresolved. +func (f *flattener) throughLinks() { + if len(f.links) == 0 { + return + } + for name := range f.written { + for a := path.Dir(name); a != "." && a != "/" && a != ""; a = path.Dir(a) { + t, ok := f.links[a] + if !ok { + continue + } + to := t + if !path.IsAbs(t) { + to = path.Join(path.Dir(a), t) + } + f.unresolved[name] = true + if r := rootName(to); r != "" { + f.unresolved[path.Join(r, strings.TrimPrefix(name, a+"/"))] = true + } + break + } + } +} + func inOpaqueDir(opaqueDirs map[string]bool, file string) bool { - for file != "" { + for file != "" && file != "." { dir := path.Dir(file) - if file == dir { - break + if dir == "." { + dir = "" } if opaqueDirs[dir] { return true } + if file == dir { + break + } file = dir } return false @@ -139,7 +309,7 @@ func inOpaqueDir(opaqueDirs map[string]bool, file string) bool { func inWhiteoutDir(fileMap map[string]bool, file string) bool { for file != "" { dir := path.Dir(file) - if file == dir { + if file == dir || dir == "." { break } if fileMap[dir] { @@ -158,17 +328,6 @@ func unsafeArchivePath(name string) bool { return hasWindowsDrivePrefix(clean) } -func unsafeRelativeLink(name, linkname string) bool { - clean := cleanArchivePath(linkname) - if path.IsAbs(clean) { - return false - } - if hasWindowsDrivePrefix(clean) { - return true - } - return strings.HasPrefix(path.Clean(path.Join(path.Dir(name), clean)), "..") -} - func cleanArchivePath(name string) string { return path.Clean(strings.ReplaceAll(name, "\\", "/")) } diff --git a/internal/image/flatten_test.go b/internal/image/flatten_test.go index f48d4f8..9fa29dc 100644 --- a/internal/image/flatten_test.go +++ b/internal/image/flatten_test.go @@ -3,7 +3,10 @@ package image import ( "archive/tar" "bytes" + "fmt" "io" + "sort" + "strings" "testing" v1 "github.com/google/go-containerregistry/pkg/v1" @@ -12,22 +15,34 @@ import ( "github.com/google/go-containerregistry/pkg/v1/tarball" ) -// layer builds a layer from (name, content) entries; content "\x00dir" is -// a directory. -func layer(t *testing.T, entries ...[2]string) v1.Layer { +// ent is one layer entry: kind "f" (file), "d", "l" (symlink to body), +// "h" (hard link to body); a name with ".wh." is a whiteout. +type ent struct{ name, kind, body string } + +func f(name, body string) ent { return ent{name, "f", body} } +func d(name string) ent { return ent{name, "d", ""} } +func sl(name, to string) ent { return ent{name, "l", to} } +func hl(name, to string) ent { return ent{name, "h", to} } + +func layerOf(t testing.TB, es ...ent) v1.Layer { t.Helper() var buf bytes.Buffer tw := tar.NewWriter(&buf) - for _, e := range entries { - h := &tar.Header{Name: e[0], Mode: 0o755, Size: int64(len(e[1])), Typeflag: tar.TypeReg} - if e[1] == "\x00dir" { + for _, e := range es { + h := &tar.Header{Name: e.name, Mode: 0o755, Typeflag: tar.TypeReg, Size: int64(len(e.body))} + switch e.kind { + case "d": h.Typeflag, h.Size = tar.TypeDir, 0 + case "l": + h.Typeflag, h.Size, h.Linkname = tar.TypeSymlink, 0, e.body + case "h": + h.Typeflag, h.Size, h.Linkname = tar.TypeLink, 0, e.body } if err := tw.WriteHeader(h); err != nil { t.Fatal(err) } if h.Typeflag == tar.TypeReg { - tw.Write([]byte(e[1])) + tw.Write([]byte(e.body)) } } tw.Close() @@ -39,9 +54,23 @@ func layer(t *testing.T, entries ...[2]string) v1.Layer { return l } -func entries(t *testing.T, img v1.Image) map[string][]string { +func imageOf(t testing.TB, layers ...[]ent) v1.Image { + t.Helper() + var ls []v1.Layer + for _, es := range layers { + ls = append(ls, layerOf(t, es...)) + } + img, err := mutate.AppendLayers(empty.Image, ls...) + if err != nil { + t.Fatal(err) + } + return img +} + +// read lists a flattened stream: name -> "kind:content" for each entry +// (several when a name repeats). +func read(t testing.TB, rc io.ReadCloser) map[string][]string { t.Helper() - rc := flatten(img) defer rc.Close() out := map[string][]string{} tr := tar.NewReader(rc) @@ -54,26 +83,44 @@ func entries(t *testing.T, img v1.Image) map[string][]string { t.Fatal(err) } b, _ := io.ReadAll(tr) - out[h.Name] = append(out[h.Name], string(b)) + v := "" + switch h.Typeflag { + case tar.TypeDir: + v = "d" + case tar.TypeSymlink: + v = "l:" + h.Linkname + case tar.TypeLink: + v = "h:" + strings.TrimPrefix(h.Linkname, "/") + default: + v = "f:" + string(b) + } + out[h.Name] = append(out[h.Name], v) } } -// Final review finding 1: a path spelled with and without a leading slash -// in two layers is one file, the upper layer's; a whiteout hides it -// whichever way either is spelled. -func TestFlattenOnePathTwoSpellings(t *testing.T) { - img, err := mutate.AppendLayers(empty.Image, - layer(t, [2]string{"usr/sbin/sshd", "placeholder"}, [2]string{"etc/gone", "x"}, [2]string{"/etc/gone2", "x"}, [2]string{"./opt/a", "lower"}), - layer(t, [2]string{"/usr/sbin/sshd", "real"}, [2]string{"/etc/.wh.gone", ""}, [2]string{"etc/.wh.gone2", ""}, [2]string{"opt/a", "upper"})) - if err != nil { - t.Fatal(err) - } - got := entries(t, img) - if s := got["usr/sbin/sshd"]; len(s) != 1 || s[0] != "real" { - t.Errorf("sshd: %q", s) +func flat(t testing.TB, layers ...[]ent) (map[string][]string, []string) { + t.Helper() + rc, unresolved := flatten(imageOf(t, layers...)) + got := read(t, rc) + return got, unresolved() +} + +func one(got map[string][]string, name string) string { + if len(got[name]) != 1 { + return fmt.Sprint(got[name]) } - if s := got["opt/a"]; len(s) != 1 || s[0] != "upper" { - t.Errorf("opt/a: %q", s) + return got[name][0] +} + +// A path spelled with and without a leading slash in two layers is one +// file, the upper layer's; a whiteout hides it whichever way either is +// spelled. +func TestFlattenOnePathTwoSpellings(t *testing.T) { + got, _ := flat(t, + []ent{f("usr/sbin/sshd", "placeholder"), f("etc/gone", "x"), f("/etc/gone2", "x"), f("./opt/a", "lower")}, + []ent{f("/usr/sbin/sshd", "real"), f("/etc/.wh.gone", ""), f("etc/.wh.gone2", ""), f("opt/a", "upper")}) + if one(got, "usr/sbin/sshd") != "f:real" || one(got, "opt/a") != "f:upper" { + t.Errorf("%v", got) } if _, ok := got["etc/gone"]; ok { t.Error("a whiteout spelled /etc/.wh.gone did not hide etc/gone") @@ -82,7 +129,7 @@ func TestFlattenOnePathTwoSpellings(t *testing.T) { t.Error("a whiteout spelled etc/.wh.gone2 did not hide /etc/gone2") } for name := range got { - if len(name) > 0 && name[0] == '/' { + if strings.HasPrefix(name, "/") { t.Errorf("entry %q is not relative to the root", name) } } @@ -90,10 +137,178 @@ func TestFlattenOnePathTwoSpellings(t *testing.T) { // Unsafe names fail the image, as with mutate.Extract. func TestFlattenUnsafe(t *testing.T) { - img, _ := mutate.AppendLayers(empty.Image, layer(t, [2]string{"../escape", "x"})) - rc := flatten(img) + rc, _ := flatten(imageOf(t, []ent{f("../escape", "x")})) defer rc.Close() if _, err := io.ReadAll(rc); err == nil { t.Error("an unsafe path was accepted") } } + +// Round-5 review finding 1 and 2c: a symbolic link with more "../" than +// its depth is kept (it resolves at the root), so the lower file at its +// path stays hidden; so is a root-level link to a name starting with "..". +func TestFlattenDeepSymlink(t *testing.T) { + for _, upper := range []string{"/u/x", "u/x"} { + got, _ := flat(t, []ent{f("u/x", "lower"), f("foo", "foo")}, []ent{sl(upper, "../../../foo"), sl("y", "..data/x")}) + if one(got, "u/x") != "l:../../../foo" || one(got, "y") != "l:..data/x" { + t.Errorf("%s: %v", upper, got) + } + } +} + +// Round-5 review finding 2a: a hard link keeps the content of the file it +// named when a later layer removes or replaces that file. +func TestFlattenHardLinkToHiddenFile(t *testing.T) { + base := []ent{f("a", "orig")} + linked := []ent{f("a", "orig"), hl("b", "a")} // RUN ln /a /b copies /a up + got, unresolved := flat(t, base, linked, []ent{f(".wh.a", "")}) + if one(got, "b") != "f:orig" || len(got["a"]) != 0 || len(unresolved) != 0 { + t.Errorf("rm /a: %v unresolved %v", got, unresolved) + } + got, unresolved = flat(t, base, linked, []ent{f("a", "new")}) + if one(got, "b") != "f:orig" || one(got, "a") != "f:new" || len(unresolved) != 0 { + t.Errorf("echo new > /a: %v unresolved %v", got, unresolved) + } + // A hard link to a file outside its layer is not settled. + _, unresolved = flat(t, base, []ent{hl("b", "a")}, []ent{f("a", "new")}) + if fmt.Sprint(unresolved) != "[/b]" { + t.Errorf("a link to another layer's file: unresolved %v", unresolved) + } +} + +// Round-5 review finding 2b: a directory, then a file, then a directory +// over three layers: the file removed the first directory's entries. +func TestFlattenDirFileDir(t *testing.T) { + got, _ := flat(t, + []ent{d("d"), f("d/inc", "UsePAM yes")}, + []ent{f("d", "a file")}, + []ent{d("d"), f("d/new", "z")}) + if one(got, "d") != "d" || one(got, "d/new") != "f:z" || len(got["d/inc"]) != 0 { + t.Errorf("%v", got) + } +} + +// Round-5 review finding 4: what one layer says twice about a path, and a +// write or whiteout through a directory that is a symbolic link, is +// unresolved. +func TestFlattenUnresolved(t *testing.T) { + for _, c := range []struct { + name string + layers [][]ent + want string + }{ + {"two entries in one layer", [][]ent{{f("a", "1"), f("a", "2")}}, "[/a]"}, + {"whiteout then file", [][]ent{{f("a", "lower")}, {f(".wh.a", ""), f("a", "new")}}, "[/a]"}, + {"file then whiteout", [][]ent{{f("a", "lower")}, {f("a", "new"), f(".wh.a", "")}}, "[/a]"}, + {"a directory twice", [][]ent{{d("d"), d("d"), f("d/x", "1")}}, "[]"}, + {"a write through a symlinked directory", [][]ent{{sl("etc/ssh", "../opt/ssh"), f("opt/ssh/sshd_config", "old")}, {f("etc/ssh/sshd_config", "new")}}, + "[/etc/ssh/sshd_config /opt/ssh/sshd_config]"}, + {"a whiteout through a symlinked directory", [][]ent{{sl("etc/ssh", "/opt/ssh"), f("opt/ssh/sshd_config", "old")}, {f("etc/ssh/.wh.sshd_config", "")}}, + "[/etc/ssh/sshd_config /opt/ssh/sshd_config]"}, + } { + _, unresolved := flat(t, c.layers...) + if fmt.Sprint(unresolved) != c.want { + t.Errorf("%s: unresolved %v, want %s", c.name, unresolved, c.want) + } + } +} + +// fuzzNames are the paths fuzzed images use, each with one kind, so that +// mutate.Extract (which does not handle a path changing kind) is a fair +// reference. +var fuzzNames = []struct{ name, kind string }{ + {"a", "f"}, {"b", "f"}, {"d", "d"}, {"d/x", "f"}, {"d/y", "f"}, {"d/e", "d"}, {"d/e/z", "f"}, {"l", "l"}, +} + +// FuzzFlatten builds random multi-layer images. On clean names it must +// give what mutate.Extract gives; with names spelled with a leading slash, +// the same; and with any entries (kinds changing, hard links, repeats), it +// must never write a path twice or fail on a well-formed image. +func FuzzFlatten(fz *testing.F) { + fz.Add([]byte{0, 1, 2, 3, 0x80, 0x41, 5, 0xff, 7}) + fz.Add([]byte{2, 3, 4, 0x82, 0x90, 0x23, 0x25}) + fz.Add([]byte{0x10, 0x11, 0xc0, 0x13, 0x40, 0x2a, 0x8b}) + fz.Fuzz(func(t *testing.T, data []byte) { + if len(data) > 64 { + return + } + var clean, slashed, wild [][]ent + var cur, curS, curW []ent + used := map[string]bool{} + for i, b := range data { + if b == 0xff || len(cur) == 6 { + clean, slashed, wild = append(clean, cur), append(slashed, curS), append(wild, curW) + cur, curS, curW, used = nil, nil, nil, map[string]bool{} + if b == 0xff { + continue + } + } + n := fuzzNames[int(b)%len(fuzzNames)] + var e ent + switch op := (b >> 3) & 3; { + case op == 3 && n.kind == "d": + e = f(n.name+"/.wh..wh..opq", "") + case op == 3 || op == 2 && n.kind != "d": + dir, base := "", n.name + if j := strings.LastIndexByte(n.name, '/'); j >= 0 { + dir, base = n.name[:j+1], n.name[j+1:] + } + e = f(dir+".wh."+base, "") + case n.kind == "d": + e = d(n.name) + case n.kind == "l": + e = sl(n.name, "d/x") + default: + e = f(n.name, fmt.Sprintf("%d-%d", i, b)) + } + key := strings.Replace(e.name, ".wh.", "", 1) + if !used[key] && !strings.Contains(e.name, ".wh..wh..opq") || strings.Contains(e.name, ".wh..wh..opq") && !used[e.name] { + used[key], used[e.name] = true, true + cur = append(cur, e) + s := e + if b&0x40 != 0 { + s.name = "/" + s.name + } + curS = append(curS, s) + } + // The wild image takes every entry, with kinds changing. + w := e + switch b >> 6 { + case 1: + w = hl(n.name, fuzzNames[int(b>>2)%len(fuzzNames)].name) + case 2: + w = d(n.name) + case 3: + w = f(n.name, "w") + } + curW = append(curW, w) + } + clean, slashed, wild = append(clean, cur), append(slashed, curS), append(wild, curW) + + want := read(t, mutate.Extract(imageOf(t, clean...))) + for _, layers := range [][][]ent{clean, slashed} { + got, unresolved := flat(t, layers...) + if len(unresolved) != 0 { + t.Fatalf("clean image left %v unresolved: %v", unresolved, layers) + } + if a, b := dump(got), dump(want); a != b { + t.Fatalf("layers %v:\nflatten %s\nExtract %s", layers, a, b) + } + } + got, _ := flat(t, wild...) + for name, v := range got { + if len(v) != 1 { + t.Fatalf("%s written %d times: %v (layers %v)", name, len(v), v, wild) + } + } + }) +} + +func dump(m map[string][]string) string { + var out []string + for k, v := range m { + out = append(out, k+"="+strings.Join(v, "|")) + } + sort.Strings(out) + return strings.Join(out, " ") +} diff --git a/internal/image/image.go b/internal/image/image.go index f1b9a5b..40986db 100644 --- a/internal/image/image.go +++ b/internal/image/image.go @@ -19,6 +19,9 @@ import ( type Opened struct { // FS is the final filesystem as a tar stream, whiteouts applied. FS io.ReadCloser + // Unresolved lists, once FS has been read to its end, the paths whose + // content the layers do not settle (see flatten): not read. + Unresolved func() []string // Digest is the image manifest digest. Digest string // Platform is the platform that was opened, when known. @@ -61,7 +64,7 @@ func opened(img v1.Image) (*Opened, error) { } } } - o.FS = flatten(img) + o.FS, o.Unresolved = flatten(img) return o, nil } From 11cb3fe2b836c55788e807f0762233d0bbfae74c Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 10:28:28 +0000 Subject: [PATCH 089/119] sshole: a script the command passes as an argument does not clear on its own From the round-5 review: ENTRYPOINT ["/entry.sh", "/opt/tools/debug.sh"] with entry.sh running supervisord and debug.sh running sshd -o UsePAM=yes, and UsePAM no in sshd_config, was cleared (inactive; critical before every command word was read as a script). The first command word that names a script is the program; a later one is an argument, which may not run, so sshd_config alone is judged too whenever a command line comes from one, and the worst verdict is kept. Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/internal/assess/assess.go | 12 +++++-- detectors/sshole/internal/assess/runtime.go | 19 +++++++++++- .../sshole/internal/assess/unread_test.go | 31 +++++++++++++++++++ 3 files changed, 58 insertions(+), 4 deletions(-) diff --git a/detectors/sshole/internal/assess/assess.go b/detectors/sshole/internal/assess/assess.go index bc3ff86..0cc44ae 100644 --- a/detectors/sshole/internal/assess/assess.go +++ b/detectors/sshole/internal/assess/assess.go @@ -414,8 +414,10 @@ func targetNames(ts []Target) string { // pickInvocation finds the command lines that start this server: the // container command's when it runs sshd, else the startup scripts' distinct -// ones. More than one (true) means which runs is not known: each is judged -// and the worst kept, so options never lower a verdict on a guess. +// ones. More than one, or one in a script the command only passes as an +// argument (true), means which runs is not known: each, and sshd_config +// alone, is judged and the worst kept, so options never lower a verdict on +// a guess. func pickInvocation(invs []invocation, u []*Binary) ([]invocation, bool) { var mine []invocation for _, inv := range invs { @@ -435,7 +437,9 @@ func pickInvocation(invs []invocation, u []*Binary) ([]invocation, bool) { } } var out []invocation + arg := false for _, inv := range mine { + arg = arg || inv.arg dup := false for _, o := range out { dup = dup || inv.config == o.config && sameOpts(inv.opts, o.opts) @@ -444,7 +448,9 @@ func pickInvocation(invs []invocation, u []*Binary) ([]invocation, bool) { out = append(out, inv) } } - return out, len(out) > 1 + // A command line in a script passed as an argument may not run: then + // sshd_config alone is judged too. + return out, len(out) > 1 || arg } func sameOpts(a, b []Directive) bool { diff --git a/detectors/sshole/internal/assess/runtime.go b/detectors/sshole/internal/assess/runtime.go index 5417dcb..274fc0b 100644 --- a/detectors/sshole/internal/assess/runtime.go +++ b/detectors/sshole/internal/assess/runtime.go @@ -144,8 +144,12 @@ func (s Startup) startScripts(resolve func(string) (string, bool)) []script { // Every word of the command that names a script: wrappers take // arguments of their own ("tini --", "gosu USER", "su-exec USER"), // so the script is not always the first word after them. + // The first is the program the command runs; a later one is an + // argument to it, which may or may not run (arg). c := s.Command + program := false for i, w := range c { + n := len(out) if isShell(path.Base(w)) { for j := i + 1; j < len(c); j++ { if c[j] == "-c" && j+1 < len(c) { @@ -155,6 +159,10 @@ func (s Startup) startScripts(resolve func(string) (string, bool)) []script { } } add(w) + for k := n; k < len(out); k++ { + out[k].arg = program + program = true + } } // One level of scripts the command's scripts name. for _, sc := range append([]script(nil), out...) { @@ -178,7 +186,12 @@ func (s Startup) startScripts(resolve func(string) (string, bool)) []script { return out } -type script struct{ where, text string } +type script struct { + where, text string + // arg is set for a script the command names after its program: an + // argument, which may not run. + arg bool +} var absPathRE = regexp.MustCompile(`/[A-Za-z0-9_./-]+`) @@ -196,6 +209,9 @@ type invocation struct { config string opts []Directive where string + // arg: found in a script the command passes as an argument, which may + // not run. + arg bool } // invocations finds sshd command lines in the container command and the @@ -209,6 +225,7 @@ func invocations(s Startup, scripts []script) []invocation { for _, line := range strings.Split(sc.text, "\n") { for _, part := range splitCommands(line) { if inv, ok := parseSSHD(fieldsQuoted(part), sc.where); ok { + inv.arg = sc.arg out = append(out, inv) } } diff --git a/detectors/sshole/internal/assess/unread_test.go b/detectors/sshole/internal/assess/unread_test.go index befce37..94f4b8d 100644 --- a/detectors/sshole/internal/assess/unread_test.go +++ b/detectors/sshole/internal/assess/unread_test.go @@ -188,3 +188,34 @@ func TestStartScriptsDisagree(t *testing.T) { } } } + +// Round-5 review finding 3: a script the command passes as an argument +// may not run: its sshd options never clear a server that sshd_config +// alone leaves exposed. +func TestArgumentScript(t *testing.T) { + sup := "#!/bin/sh\nexec supervisord\n" + debug := "#!/bin/sh\n/usr/sbin/sshd -D -o UsePAM=yes\n" + for _, c := range []struct { + name string + cmd []string + cleared bool + }{ + {"ENTRYPOINT with an argument", []string{"/entry.sh", "/opt/tools/debug.sh"}, false}, + {"tini, then the argument", []string{"tini", "--", "/entry.sh", "/opt/tools/debug.sh"}, false}, + {"the script as the program", []string{"/opt/tools/debug.sh"}, true}, + } { + w := newWorld("10.0p2", true, map[string]string{"/etc/ssh/sshd_config": "UsePAM no\n"}) + in := Input{ + Binaries: w.binaries, Files: w.files, + Accounts: ParseAccounts(w.files.Read("/etc/passwd"), w.files.Read("/etc/shadow"), w.files.Read("/etc/group"), nil), + Resolve: func(p string) (string, bool) { _, ok := w.files[p]; return p, ok }, + Now: w.now(), + Image: true, + Startup: Startup{Command: c.cmd, Scripts: map[string][]byte{"/entry.sh": []byte(sup), "/opt/tools/debug.sh": []byte(debug)}}, + } + f := one(t, Run(in)) + if (f.Status == Inactive) != c.cleared || !c.cleared && (f.Status != Vulnerable || f.Severity != "critical") { + t.Errorf("%s: %s %s (%s)", c.name, f.Status, f.Severity, f.Reason) + } + } +} From a941b18f221da67d36646f1df1679964458071b9 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 10:51:49 +0000 Subject: [PATCH 090/119] java4shell: a Red Hat row does not clear on /usr/lib/os-release when /etc/os-release was not read The coverage round clears a Red Hat runtime at a fixed rpm release only when the target's os-release says ID=rhel. The size-limit round made an /etc/os-release over 64 KiB, over --max-file-size or unreadable a file the scan is told about and does not see, and the os-release lookup then fell back to /usr/lib/os-release, which the system reads only when /etc/os-release does not exist. So the two together cleared a runtime on a file standing in for one that was not read. The scan now remembers an /etc/os-release it met and did not read (Forget drops it when an image names the path again) and gives the verdict no OS ID then, so the runtime is reported unknown. The java4shell_os annotation, which clears nothing, still falls back. Co-Authored-By: Claude Fable 5.2 --- detectors/java4shell/java4shell.go | 39 ++++++-- .../java4shell/osrelease_internal_test.go | 99 +++++++++++++++++++ 2 files changed, 129 insertions(+), 9 deletions(-) create mode 100644 detectors/java4shell/osrelease_internal_test.go diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 9fe6fea..4710301 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -142,10 +142,10 @@ func (d *Detector) Limit(p string, head []byte, _ bool) int64 { // its limit or --max-file-size. A JVM settings file not read is a coverage // gap once a runtime is found (FinishSkips): an option in it can undo a // mitigation the scan would report. A start script not read keeps a -// mitigation from being reported when the container's command runs it. -// The other files with a limit are deliberate exclusions: no verdict is -// cleared on them (a runtime is cleared only by its VM library and release -// file). +// mitigation from being reported when the container's command runs it. An +// /etc/os-release not read keeps a Red Hat row from clearing a runtime +// (osID). The other files with a limit are deliberate exclusions: no +// verdict is cleared on them. func (s *scan) VisitOverLimit(p string, _ int64) []engine.Skip { s.notRead(p) return nil @@ -167,6 +167,9 @@ func (s *scan) notRead(p string) { if jvm.SettingKind(p) != "" && len(s.overSettings) < maxSettings { s.overSettings[p] = true } + if p == "/etc/os-release" { + s.osUnread = true + } if hsErr.MatchString(path.Base(p)) || p == "/etc/os-release" || p == "/usr/lib/os-release" { return } @@ -204,6 +207,9 @@ func (s *scan) Forget(p string) { s.keptBytes -= len(s.lists[k]) delete(s.lists, k) } + if p == "/etc/os-release" { + s.osUnread = false + } delete(s.scripts, p) delete(s.unreadScripts, p) delete(s.overSettings, p) @@ -311,8 +317,10 @@ type scan struct { unreadAll bool // overSettings are JVM settings files not read. overSettings map[string]bool - optionFiles int // settings files that set JVM options - plainUnits int // systemd units that set none + // osUnread is set when /etc/os-release was met and not read. + osUnread bool + optionFiles int // settings files that set JVM options + plainUnits int // systemd units that set none // limits records the caps this target reached; a capped scan clears // nothing. limits []string @@ -488,9 +496,7 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { UnreadDirs: s.unreadDirs, UnreadAll: s.unreadAll, } - if osr := osRelease(s.kept["/etc/os-release"], s.kept["/usr/lib/os-release"]); osr != "" { - in.OSID, _, _ = strings.Cut(osr, " ") - } + in.OSID = s.osID() if s.kind == engine.Image { in.Env = ctx.Env() if in.Env == nil { @@ -519,6 +525,21 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { return out } +// osID is the target's os-release ID for a verdict (a Red Hat row clears +// a runtime only on RHEL), "" when it is not known. The system reads +// /usr/lib/os-release only when /etc/os-release does not exist, so an +// /etc/os-release the scan met and did not read (over its limit, +// unreadable) leaves the ID unknown: a verdict is never cleared on a file +// that stands in for one not read. The java4shell_os annotation, which +// clears nothing, still falls back. +func (s *scan) osID() string { + if s.osUnread { + return "" + } + id, _, _ := strings.Cut(osRelease(s.kept["/etc/os-release"], s.kept["/usr/lib/os-release"]), " ") + return id +} + var verdicts = map[assess.Status]engine.Verdict{ assess.Vulnerable: engine.Vulnerable, assess.Fixed: engine.Fixed, diff --git a/detectors/java4shell/osrelease_internal_test.go b/detectors/java4shell/osrelease_internal_test.go new file mode 100644 index 0000000..e6fb480 --- /dev/null +++ b/detectors/java4shell/osrelease_internal_test.go @@ -0,0 +1,99 @@ +package java4shell + +import ( + "archive/tar" + "bytes" + "os" + "path/filepath" + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// A Red Hat row clears a runtime on the target's os-release (ID=rhel), so +// the os-release is a file a verdict is cleared on: an /etc/os-release the +// scan met and did not read (over its limit, unreadable) is not stood in +// for by /usr/lib/os-release, which the system reads only when +// /etc/os-release does not exist. +func TestRedHatRowNeedsOSReleaseRead(t *testing.T) { + saved := knowledge.RedHatFixed + t.Cleanup(func() { knowledge.RedHatFixed = saved }) + knowledge.RedHatFixed = []knowledge.RedHatFix{{Package: "java-17-openjdk", Dist: "el9_6", EVR: "1:17.0.21.0.9-2.el9_6", Advisory: "RHSA-2026:0000"}} + + const dir = "usr/lib/jvm/java-17-openjdk-17.0.21.0.9-2.el9_6.x86_64" + lib := testlib.Build(testlib.Lib{Version: "17.0.21+9-LTS", VBMI: true}) + release := testlib.Release("IMPLEMENTOR", "Red Hat, Inc.", "JAVA_RUNTIME_VERSION", "17.0.21+9-LTS", "JAVA_VERSION", "17.0.21") + rhel := []byte("ID=\"rhel\"\nVERSION_ID=\"9.6\"\n") + rocky := []byte("ID=\"rocky\"\nVERSION_ID=\"9.6\"\n") + big := append(append([]byte(nil), rocky...), bytes.Repeat([]byte("# pad\n"), maxOSRelease/6+1)...) + + type entry struct { + name string + data []byte + link string // a symbolic link when set + } + for _, c := range []struct { + name string + entries []entry + want engine.Verdict + os string // the java4shell_os annotation, which may fall back + }{ + {"usr/lib alone, as RHEL lays it out", []entry{{"etc/os-release", nil, "../usr/lib/os-release"}, {"usr/lib/os-release", rhel, ""}}, engine.Fixed, "rhel 9.6"}, + {"etc read", []entry{{"etc/os-release", rhel, ""}, {"usr/lib/os-release", rocky, ""}}, engine.Fixed, "rhel 9.6"}, + {"etc over the limit", []entry{{"etc/os-release", big, ""}, {"usr/lib/os-release", rhel, ""}}, engine.Unknown, "rhel 9.6"}, + {"etc over the limit, named after usr/lib", []entry{{"usr/lib/os-release", rhel, ""}, {"etc/os-release", big, ""}}, engine.Unknown, "rhel 9.6"}, + {"etc read, then named again over the limit", []entry{{"etc/os-release", rhel, ""}, {"usr/lib/os-release", rhel, ""}, {"etc/os-release", big, ""}}, engine.Unknown, "rhel 9.6"}, + {"etc over the limit, then named again and read", []entry{{"etc/os-release", big, ""}, {"usr/lib/os-release", rocky, ""}, {"etc/os-release", rhel, ""}}, engine.Fixed, "rhel 9.6"}, + {"etc over the limit, then a link to usr/lib", []entry{{"etc/os-release", big, ""}, {"usr/lib/os-release", rhel, ""}, {"etc/os-release", nil, "../usr/lib/os-release"}}, engine.Fixed, "rhel 9.6"}, + } { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, e := range append([]entry{{dir + "/lib/server/libjvm.so", lib, ""}, {dir + "/release", release, ""}}, c.entries...) { + h := &tar.Header{Name: e.name, Mode: 0o644, Size: int64(len(e.data)), Typeflag: tar.TypeReg} + if e.link != "" { + h.Typeflag, h.Linkname, h.Size = tar.TypeSymlink, e.link, 0 + } + if err := tw.WriteHeader(h); err != nil { + t.Fatal(err) + } + tw.Write(e.data) + } + tw.Close() + p := filepath.Join(t.TempDir(), "rootfs.tar") + if err := os.WriteFile(p, buf.Bytes(), 0o600); err != nil { + t.Fatal(err) + } + tg := engine.ScanImage([]engine.Detector{&Detector{}}, "rootfs:"+p, engine.Options{}) + if tg.Error != "" || len(tg.Findings) != 1 { + t.Fatalf("%s: error %q findings %+v", c.name, tg.Error, tg.Findings) + } + if f := tg.Findings[0]; f.Verdict != c.want { + t.Errorf("%s: %s, want %s (%s)", c.name, f.Verdict, c.want, f.Reason) + } + if got := tg.Annotations["java4shell_os"]; got != c.os { + t.Errorf("%s: java4shell_os %v, want %s", c.name, got, c.os) + } + } + + // An /etc/os-release that could not be read (no permission, an I/O + // error) is the same. + s := (&Detector{}).NewScan(engine.Filesystem).(*scan) + s.Visit(engine.File{Path: "/usr/lib/os-release", Data: rhel}) + s.VisitUnread("/etc/os-release", false) + if id := s.osID(); id != "" { + t.Errorf("unreadable /etc/os-release: os ID %q, want none", id) + } + s.Forget("/etc/os-release") + if id := s.osID(); id != "rhel" { + t.Errorf("after the unreadable /etc/os-release is forgotten: os ID %q, want rhel", id) + } + // An unread /usr/lib/os-release does not matter when /etc/os-release was read. + s.Visit(engine.File{Path: "/etc/os-release", Data: rocky}) + s.Forget("/usr/lib/os-release") + s.VisitOverLimit("/usr/lib/os-release", maxOSRelease+1) + if id := s.osID(); id != "rocky" { + t.Errorf("os ID %q, want rocky", id) + } +} From 5ff3529d14365ca5082802cf26f13a4290d303b3 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:00:37 +0000 Subject: [PATCH 091/119] java4shell: nor when /etc could not be listed An /etc the walk could not list may hold an os-release, so /usr/lib/os-release does not stand in for it either, and a scan with more unread files than it records gives the verdict no OS ID. The test walks a filesystem with an unlistable /etc and with an /etc/os-release that cannot be opened. Co-Authored-By: Claude Fable 5.2 --- detectors/java4shell/java4shell.go | 16 ++++-- .../java4shell/osrelease_internal_test.go | 49 +++++++++++++++++++ 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 4710301..849ae78 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -529,13 +529,21 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { // a runtime only on RHEL), "" when it is not known. The system reads // /usr/lib/os-release only when /etc/os-release does not exist, so an // /etc/os-release the scan met and did not read (over its limit, -// unreadable) leaves the ID unknown: a verdict is never cleared on a file -// that stands in for one not read. The java4shell_os annotation, which -// clears nothing, still falls back. +// unreadable), or one that a directory the scan could not list may hold, +// leaves the ID unknown: a verdict is never cleared on a file that stands +// in for one not read. The java4shell_os annotation, which clears nothing, +// still falls back. func (s *scan) osID() string { - if s.osUnread { + if s.osUnread || s.unreadAll { return "" } + if s.kept["/etc/os-release"] == nil { + for _, d := range s.unreadDirs { + if d = strings.TrimSuffix(d, "/"); d == "" || d == "/etc" { + return "" + } + } + } id, _, _ := strings.Cut(osRelease(s.kept["/etc/os-release"], s.kept["/usr/lib/os-release"]), " ") return id } diff --git a/detectors/java4shell/osrelease_internal_test.go b/detectors/java4shell/osrelease_internal_test.go index e6fb480..14ab080 100644 --- a/detectors/java4shell/osrelease_internal_test.go +++ b/detectors/java4shell/osrelease_internal_test.go @@ -89,6 +89,55 @@ func TestRedHatRowNeedsOSReleaseRead(t *testing.T) { if id := s.osID(); id != "rhel" { t.Errorf("after the unreadable /etc/os-release is forgotten: os ID %q, want rhel", id) } + // Nor is /usr/lib/os-release trusted when /etc could not be listed. + for dir, want := range map[string]string{"/etc": "", "/": "", "/etc/": "", "/etc/ssh": "rhel", "/opt": "rhel"} { + u := (&Detector{}).NewScan(engine.Filesystem).(*scan) + u.Visit(engine.File{Path: "/usr/lib/os-release", Data: rhel}) + u.VisitUnread(dir, true) + if id := u.osID(); id != want { + t.Errorf("unlistable %s: os ID %q, want %q", dir, id, want) + } + } + // The same through a filesystem walk that cannot list /etc (not as + // root, which can). + if os.Geteuid() != 0 { + root := t.TempDir() + for rel, data := range map[string][]byte{dir + "/lib/server/libjvm.so": lib, dir + "/release": release, "usr/lib/os-release": rhel, "etc/os-release": rocky} { + p := filepath.Join(root, rel) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, data, 0o644); err != nil { + t.Fatal(err) + } + } + etc := filepath.Join(root, "etc") + for mode, want := range map[os.FileMode]engine.Verdict{0o000: engine.Unknown, 0o755: engine.Unknown} { + // 0755: /etc/os-release is read and says rocky. + if err := os.Chmod(etc, mode); err != nil { + t.Fatal(err) + } + tg := engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true}) + os.Chmod(etc, 0o755) + if len(tg.Findings) != 1 || tg.Findings[0].Verdict != want { + t.Errorf("/etc mode %o: findings %+v", mode, tg.Findings) + } + } + // And an /etc/os-release that cannot be opened. + if err := os.Chmod(filepath.Join(etc, "os-release"), 0o000); err != nil { + t.Fatal(err) + } + tg := engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true}) + if len(tg.Findings) != 1 || tg.Findings[0].Verdict != engine.Unknown || tg.Annotations["java4shell_os"] != "rhel 9.6" { + t.Errorf("unreadable /etc/os-release: findings %+v annotations %v", tg.Findings, tg.Annotations) + } + // Without /etc/os-release, /usr/lib/os-release is the system's. + os.Remove(filepath.Join(etc, "os-release")) + tg = engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true}) + if len(tg.Findings) != 1 || tg.Findings[0].Verdict != engine.Fixed { + t.Errorf("no /etc/os-release: findings %+v", tg.Findings) + } + } // An unread /usr/lib/os-release does not matter when /etc/os-release was read. s.Visit(engine.File{Path: "/etc/os-release", Data: rocky}) s.Forget("/usr/lib/os-release") From c18c7e1aea7f0dd658b661d8f9534221bb40b78c Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:08:09 +0000 Subject: [PATCH 092/119] java4shell: /usr/lib/os-release speaks for the target only when /etc/os-release is absent or a link to it Review of the previous two commits: the Red Hat row still cleared on /usr/lib/os-release when /etc/os-release was a file without an ID (empty, or no ID line), or a symbolic or hard link to another file, which the scan does not keep. The system reads /etc/os-release whenever it exists. The verdict's OS ID now comes from the file at /etc/os-release when the walk met one (ID or not), and from /usr/lib/os-release only when nothing is at /etc/os-release or a link there leads to /usr/lib/os-release. Co-Authored-By: Claude Fable 5.2 --- detectors/java4shell/java4shell.go | 37 ++++++++++++----- .../java4shell/osrelease_internal_test.go | 40 +++++++++++++------ 2 files changed, 54 insertions(+), 23 deletions(-) diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 849ae78..1f92e9c 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -469,7 +469,7 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { } return nil } - links, _ := ctx.Links() + links, hardlinks := ctx.Links() res := resolver{links: links} owners := map[string]assess.Package{} for _, db := range []string{"/lib/apk/db/installed", "/usr/lib/apk/db/installed"} { @@ -496,7 +496,7 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { UnreadDirs: s.unreadDirs, UnreadAll: s.unreadAll, } - in.OSID = s.osID() + in.OSID = s.osID(ctx.Exists, res, hardlinks) if s.kind == engine.Image { in.Env = ctx.Env() if in.Env == nil { @@ -527,24 +527,39 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { // osID is the target's os-release ID for a verdict (a Red Hat row clears // a runtime only on RHEL), "" when it is not known. The system reads -// /usr/lib/os-release only when /etc/os-release does not exist, so an -// /etc/os-release the scan met and did not read (over its limit, -// unreadable), or one that a directory the scan could not list may hold, -// leaves the ID unknown: a verdict is never cleared on a file that stands -// in for one not read. The java4shell_os annotation, which clears nothing, -// still falls back. -func (s *scan) osID() string { +// /usr/lib/os-release only when /etc/os-release does not exist, so +// /usr/lib/os-release speaks for the target only when no file is at +// /etc/os-release, or a link there leads to it. A file at /etc/os-release +// is the system's, with an ID or without. One the scan met and did not +// read (over its limit, unreadable), one a directory the scan could not +// list may hold, and a link to any other file (which is not kept) leave +// the ID unknown: a verdict is never cleared on a file that stands in for +// one not read. The java4shell_os annotation, which clears nothing, still +// falls back. +func (s *scan) osID(exists func(string) bool, res resolver, hardlinks map[string]string) string { + const etc, usr = "/etc/os-release", "/usr/lib/os-release" if s.osUnread || s.unreadAll { return "" } - if s.kept["/etc/os-release"] == nil { + file := usr + switch to, hard := hardlinks[etc]; { + case exists(etc): + file = etc + case hard: + if to != usr { + return "" + } + default: for _, d := range s.unreadDirs { if d = strings.TrimSuffix(d, "/"); d == "" || d == "/etc" { return "" } } + if at := res.resolve(etc); at != etc && at != usr { + return "" + } } - id, _, _ := strings.Cut(osRelease(s.kept["/etc/os-release"], s.kept["/usr/lib/os-release"]), " ") + id, _, _ := strings.Cut(osRelease(s.kept[file]), " ") return id } diff --git a/detectors/java4shell/osrelease_internal_test.go b/detectors/java4shell/osrelease_internal_test.go index 14ab080..0c074d8 100644 --- a/detectors/java4shell/osrelease_internal_test.go +++ b/detectors/java4shell/osrelease_internal_test.go @@ -33,6 +33,7 @@ func TestRedHatRowNeedsOSReleaseRead(t *testing.T) { name string data []byte link string // a symbolic link when set + hard bool // link is a hard link } for _, c := range []struct { name string @@ -40,21 +41,33 @@ func TestRedHatRowNeedsOSReleaseRead(t *testing.T) { want engine.Verdict os string // the java4shell_os annotation, which may fall back }{ - {"usr/lib alone, as RHEL lays it out", []entry{{"etc/os-release", nil, "../usr/lib/os-release"}, {"usr/lib/os-release", rhel, ""}}, engine.Fixed, "rhel 9.6"}, - {"etc read", []entry{{"etc/os-release", rhel, ""}, {"usr/lib/os-release", rocky, ""}}, engine.Fixed, "rhel 9.6"}, - {"etc over the limit", []entry{{"etc/os-release", big, ""}, {"usr/lib/os-release", rhel, ""}}, engine.Unknown, "rhel 9.6"}, - {"etc over the limit, named after usr/lib", []entry{{"usr/lib/os-release", rhel, ""}, {"etc/os-release", big, ""}}, engine.Unknown, "rhel 9.6"}, - {"etc read, then named again over the limit", []entry{{"etc/os-release", rhel, ""}, {"usr/lib/os-release", rhel, ""}, {"etc/os-release", big, ""}}, engine.Unknown, "rhel 9.6"}, - {"etc over the limit, then named again and read", []entry{{"etc/os-release", big, ""}, {"usr/lib/os-release", rocky, ""}, {"etc/os-release", rhel, ""}}, engine.Fixed, "rhel 9.6"}, - {"etc over the limit, then a link to usr/lib", []entry{{"etc/os-release", big, ""}, {"usr/lib/os-release", rhel, ""}, {"etc/os-release", nil, "../usr/lib/os-release"}}, engine.Fixed, "rhel 9.6"}, + {"usr/lib alone, as RHEL lays it out", []entry{{"etc/os-release", nil, "../usr/lib/os-release", false}, {"usr/lib/os-release", rhel, "", false}}, engine.Fixed, "rhel 9.6"}, + {"etc read", []entry{{"etc/os-release", rhel, "", false}, {"usr/lib/os-release", rocky, "", false}}, engine.Fixed, "rhel 9.6"}, + {"etc over the limit", []entry{{"etc/os-release", big, "", false}, {"usr/lib/os-release", rhel, "", false}}, engine.Unknown, "rhel 9.6"}, + {"etc over the limit, named after usr/lib", []entry{{"usr/lib/os-release", rhel, "", false}, {"etc/os-release", big, "", false}}, engine.Unknown, "rhel 9.6"}, + {"etc read, then named again over the limit", []entry{{"etc/os-release", rhel, "", false}, {"usr/lib/os-release", rhel, "", false}, {"etc/os-release", big, "", false}}, engine.Unknown, "rhel 9.6"}, + {"etc over the limit, then named again and read", []entry{{"etc/os-release", big, "", false}, {"usr/lib/os-release", rocky, "", false}, {"etc/os-release", rhel, "", false}}, engine.Fixed, "rhel 9.6"}, + // Review: a file at /etc/os-release is the system's even without an + // ID, and a link there to any other file is a file not read. + {"etc empty", []entry{{"etc/os-release", nil, "", false}, {"usr/lib/os-release", rhel, "", false}}, engine.Unknown, "rhel 9.6"}, + {"etc without an ID", []entry{{"etc/os-release", []byte("NAME=x\n"), "", false}, {"usr/lib/os-release", rhel, "", false}}, engine.Unknown, "rhel 9.6"}, + {"etc a link to another file", []entry{{"etc/rocky-release-os", rocky, "", false}, {"etc/os-release", nil, "rocky-release-os", false}, {"usr/lib/os-release", rhel, "", false}}, engine.Unknown, "rhel 9.6"}, + {"etc a hard link to another file", []entry{{"etc/rocky-release-os", rocky, "", false}, {"etc/os-release", nil, "etc/rocky-release-os", true}, {"usr/lib/os-release", rhel, "", false}}, engine.Unknown, "rhel 9.6"}, + {"etc a hard link to usr/lib", []entry{{"usr/lib/os-release", rhel, "", false}, {"etc/os-release", nil, "usr/lib/os-release", true}}, engine.Fixed, "rhel 9.6"}, + {"usr/lib a hard link to etc", []entry{{"etc/os-release", rhel, "", false}, {"usr/lib/os-release", nil, "etc/os-release", true}}, engine.Fixed, "rhel 9.6"}, + {"etc a link through a linked directory", []entry{{"usr/etc/os-release", rocky, "", false}, {"etc", nil, "usr/etc", false}, {"usr/lib/os-release", rhel, "", false}}, engine.Unknown, "rhel 9.6"}, + {"etc over the limit, then a link to usr/lib", []entry{{"etc/os-release", big, "", false}, {"usr/lib/os-release", rhel, "", false}, {"etc/os-release", nil, "../usr/lib/os-release", false}}, engine.Fixed, "rhel 9.6"}, } { var buf bytes.Buffer tw := tar.NewWriter(&buf) - for _, e := range append([]entry{{dir + "/lib/server/libjvm.so", lib, ""}, {dir + "/release", release, ""}}, c.entries...) { + for _, e := range append([]entry{{dir + "/lib/server/libjvm.so", lib, "", false}, {dir + "/release", release, "", false}}, c.entries...) { h := &tar.Header{Name: e.name, Mode: 0o644, Size: int64(len(e.data)), Typeflag: tar.TypeReg} if e.link != "" { h.Typeflag, h.Linkname, h.Size = tar.TypeSymlink, e.link, 0 } + if e.hard { + h.Typeflag = tar.TypeLink + } if err := tw.WriteHeader(h); err != nil { t.Fatal(err) } @@ -79,14 +92,17 @@ func TestRedHatRowNeedsOSReleaseRead(t *testing.T) { // An /etc/os-release that could not be read (no permission, an I/O // error) is the same. + osID := func(s *scan) string { + return s.osID(func(p string) bool { _, ok := s.kept[p]; return ok }, resolver{}, nil) + } s := (&Detector{}).NewScan(engine.Filesystem).(*scan) s.Visit(engine.File{Path: "/usr/lib/os-release", Data: rhel}) s.VisitUnread("/etc/os-release", false) - if id := s.osID(); id != "" { + if id := osID(s); id != "" { t.Errorf("unreadable /etc/os-release: os ID %q, want none", id) } s.Forget("/etc/os-release") - if id := s.osID(); id != "rhel" { + if id := osID(s); id != "rhel" { t.Errorf("after the unreadable /etc/os-release is forgotten: os ID %q, want rhel", id) } // Nor is /usr/lib/os-release trusted when /etc could not be listed. @@ -94,7 +110,7 @@ func TestRedHatRowNeedsOSReleaseRead(t *testing.T) { u := (&Detector{}).NewScan(engine.Filesystem).(*scan) u.Visit(engine.File{Path: "/usr/lib/os-release", Data: rhel}) u.VisitUnread(dir, true) - if id := u.osID(); id != want { + if id := osID(u); id != want { t.Errorf("unlistable %s: os ID %q, want %q", dir, id, want) } } @@ -142,7 +158,7 @@ func TestRedHatRowNeedsOSReleaseRead(t *testing.T) { s.Visit(engine.File{Path: "/etc/os-release", Data: rocky}) s.Forget("/usr/lib/os-release") s.VisitOverLimit("/usr/lib/os-release", maxOSRelease+1) - if id := s.osID(); id != "rocky" { + if id := osID(s); id != "rocky" { t.Errorf("os ID %q, want rocky", id) } } From ab9090c3836ecbe37d3625ae2eec1ade5b949246 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:20:22 +0000 Subject: [PATCH 093/119] sshole: what the command passes as an argument never lowers the verdict Final review A1. Reading every word of the command for start scripts let an argument decide: against main, vulnerable/critical became inactive for - a script after a program that is a binary, is missing or was not read (the first script word was taken as the program), - a script that an argument script names (it lost the argument mark), - an sh -c text after the program (taken as the command's own sshd line, even when it only mentions sshd), - an argument script that writes "UsePAM yes" (it cancelled what a start script exposes). The program is now the first word that is not a wrapper, a shell, one of their options or an assignment, script or not; everything after it is an argument, and so is what an argument names. An argument's sshd line is judged with sshd_config alone, worst kept, and only a script that certainly runs can turn PAM on. Co-Authored-By: Claude Fable 5.2 --- .../sshole/internal/assess/argument_test.go | 43 +++++++++++++++++++ detectors/sshole/internal/assess/assess.go | 4 +- detectors/sshole/internal/assess/runtime.go | 38 +++++++++++++++- 3 files changed, 82 insertions(+), 3 deletions(-) create mode 100644 detectors/sshole/internal/assess/argument_test.go diff --git a/detectors/sshole/internal/assess/argument_test.go b/detectors/sshole/internal/assess/argument_test.go new file mode 100644 index 0000000..9d0644d --- /dev/null +++ b/detectors/sshole/internal/assess/argument_test.go @@ -0,0 +1,43 @@ +package assess + +import "testing" + +// Final review A1: each case is a server sshd_config +// alone leaves exposed (UsePAM no on a PAM build); none may be cleared by a +// script or text the command only passes as an argument. +func TestArgumentNeverLowers(t *testing.T) { + sup := "#!/bin/sh\nexec supervisord\n" + yes := "#!/bin/sh\n/usr/sbin/sshd -D -o UsePAM=yes\n" + for _, c := range []struct { + name string + cmd []string + scripts map[string]string + cfg string + want string // status/severity + }{ + {"A: binary program, script argument", []string{"/usr/bin/app", "--hook", "/opt/debug.sh"}, map[string]string{"/opt/debug.sh": yes}, "UsePAM no\n", "vulnerable/critical"}, + {"A: argument word found in PATH", []string{"/usr/bin/app", "start"}, map[string]string{"/usr/bin/start": yes}, "UsePAM no\n", "vulnerable/critical"}, + {"B: argument script names the script", []string{"/entry.sh", "/opt/debug.sh"}, map[string]string{"/entry.sh": sup, "/opt/debug.sh": "#!/bin/sh\n. /opt/real.sh\n", "/opt/real.sh": yes}, "UsePAM no\n", "vulnerable/critical"}, + {"C: sh -c text as arguments", []string{"/entry.sh", "sh", "-c", "sshd -D -o UsePAM=yes"}, map[string]string{"/entry.sh": "#!/bin/sh\nexec /usr/sbin/sshd -D -o UsePAM=no\n"}, "UsePAM no\n", "vulnerable/critical"}, + {"C: sh -c text that only mentions sshd", []string{"/entry.sh", "sh", "-c", "while pgrep sshd >/dev/null; do sleep 5; done"}, map[string]string{"/entry.sh": "#!/bin/sh\n/usr/sbin/sshd -o UsePAM=no\nexec \"$@\"\n"}, "UsePAM yes\n", "vulnerable/critical"}, + {"E: argument script says UsePAM yes", []string{"/entry.sh", "/opt/alt.sh"}, map[string]string{"/entry.sh": "#!/bin/sh\nsed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config\nexec /usr/sbin/sshd -D\n", "/opt/alt.sh": "#!/bin/sh\necho 'UsePAM yes' >> /etc/ssh/sshd_config\n"}, "PasswordAuthentication no\nUsePAM no\n", "vulnerable/high"}, + } { + w := newWorld("10.0p2", true, map[string]string{"/etc/ssh/sshd_config": c.cfg}) + scripts := map[string][]byte{} + for k, v := range c.scripts { + scripts[k] = []byte(v) + } + in := Input{ + Binaries: w.binaries, Files: w.files, + Accounts: ParseAccounts(w.files.Read("/etc/passwd"), w.files.Read("/etc/shadow"), w.files.Read("/etc/group"), nil), + Resolve: func(p string) (string, bool) { _, ok := w.files[p]; return p, ok }, + Now: w.now(), + Image: true, + Startup: Startup{Command: c.cmd, Scripts: scripts}, + } + f := one(t, Run(in)) + if got := string(f.Status) + "/" + f.Severity; got != c.want { + t.Errorf("%s: got %s, want %s (%s)", c.name, got, c.want, f.Reason) + } + } +} diff --git a/detectors/sshole/internal/assess/assess.go b/detectors/sshole/internal/assess/assess.go index 0cc44ae..74f9829 100644 --- a/detectors/sshole/internal/assess/assess.go +++ b/detectors/sshole/internal/assess/assess.go @@ -432,7 +432,9 @@ func pickInvocation(invs []invocation, u []*Binary) ([]invocation, bool) { return nil, false } for _, inv := range mine { - if inv.where == "the container command" { + // The command's own sshd line decides alone; an sh -c text the + // command passes as an argument is judged with the others. + if inv.where == "the container command" && !inv.arg { return []invocation{inv}, false } } diff --git a/detectors/sshole/internal/assess/runtime.go b/detectors/sshole/internal/assess/runtime.go index 274fc0b..2eb0c9f 100644 --- a/detectors/sshole/internal/assess/runtime.go +++ b/detectors/sshole/internal/assess/runtime.go @@ -161,13 +161,23 @@ func (s Startup) startScripts(resolve func(string) (string, bool)) []script { add(w) for k := n; k < len(out); k++ { out[k].arg = program + } + // The program is the first word that is not a wrapper, a shell, + // one of their options or an assignment, whether or not it is + // a script that was kept: every word after it is an argument. + if n < len(out) || !beforeProgram(c, i) { program = true } } - // One level of scripts the command's scripts name. + // One level of scripts the command's scripts name: as likely to run + // as the script that names them. for _, sc := range append([]script(nil), out...) { for _, m := range absPathRE.FindAllString(sc.text, -1) { + n := len(out) add(m) + for k := n; k < len(out); k++ { + out[k].arg = sc.arg + } } } } @@ -193,6 +203,28 @@ type script struct { arg bool } +// beforeProgram reports whether word i of the command can come before the +// program it runs: a wrapper or a shell, an option, an assignment, or the +// user su-exec and gosu take. +func beforeProgram(c []string, i int) bool { + w := c[i] + b := path.Base(w) + switch b { + case "tini", "dumb-init", "su-exec", "gosu", "env", "exec", "catatonit": + return true + } + if isShell(b) || strings.HasPrefix(w, "-") || strings.Contains(w, "=") && !strings.Contains(w, "/") { + return true + } + if i > 0 { + switch path.Base(c[i-1]) { + case "su-exec", "gosu": + return true + } + } + return false +} + var absPathRE = regexp.MustCompile(`/[A-Za-z0-9_./-]+`) func isShell(b string) bool { @@ -371,7 +403,9 @@ func startupSignals(scripts []script) signals { if pwOnRE.MatchString(sc.text) { g.passwordOn, hit = true, true } - if usePAMOnRE.MatchString(sc.text) { + // Turning PAM on lowers the verdict: only from a script that + // certainly runs, not one the command passes as an argument. + if usePAMOnRE.MatchString(sc.text) && !sc.arg { g.usePAMOn, hit = true, true } for _, re := range starSetRE { From 8ae698a342f57a4231bcad30d9bb51f192adee40 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:22:45 +0000 Subject: [PATCH 094/119] image: a backslash in an entry name is a character, not a separator Final review A2. The flattener read "usr\lib" as usr/lib, so one oddly named file in an upper layer (or earlier in the same layer) hid every lower file under usr/lib, replaced /usr/sbin/php-fpm, or acted as a whiteout: three vulnerable findings on main, none here. Names are only made relative to the root now. unsafeArchivePath still refuses a name that starts with a backslash or escapes when backslashes are read as slashes. Co-Authored-By: Claude Fable 5.2 --- internal/image/flatten.go | 4 +++- internal/image/flatten_test.go | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/internal/image/flatten.go b/internal/image/flatten.go index d0b87bf..4def3f4 100644 --- a/internal/image/flatten.go +++ b/internal/image/flatten.go @@ -92,8 +92,10 @@ func (f *flattener) extract(img v1.Image, w io.Writer) error { } // rootName is an entry name relative to the root, "" for the root itself. +// A backslash stays: it is an ordinary character in a file name, and a +// file named "usr\lib" is not the directory usr/lib. func rootName(name string) string { - return strings.TrimPrefix(path.Clean("/"+strings.ReplaceAll(name, "\\", "/")), "/") + return strings.TrimPrefix(path.Clean("/"+name), "/") } func (f *flattener) layer(layer v1.Layer) error { diff --git a/internal/image/flatten_test.go b/internal/image/flatten_test.go index 9fa29dc..fd8a291 100644 --- a/internal/image/flatten_test.go +++ b/internal/image/flatten_test.go @@ -135,6 +135,28 @@ func TestFlattenOnePathTwoSpellings(t *testing.T) { } } +// Final review A2: a backslash is an ordinary character in a file name. A +// file named "usr\lib" is not the directory usr/lib, hides nothing below +// it and is no whiteout. +func TestFlattenBackslashIsAName(t *testing.T) { + lower := []ent{d("usr"), d("usr/lib"), f("usr/lib/libx.so", "lib"), f("usr/sbin/php-fpm", "php"), f("etc/ssl/ca.pem", "pem")} + for name, layers := range map[string][][]ent{ + "an upper layer": {lower, {f(`usr\lib`, "junk"), f(`usr\sbin\php-fpm`, "junk"), f(`etc\.wh.ssl`, "junk")}}, + "the same layer": {append([]ent{f(`usr\lib`, "junk"), f(`usr\sbin\php-fpm`, "junk"), f(`etc\.wh.ssl`, "junk")}, lower...)}, + } { + got, unresolved := flat(t, layers...) + for p, want := range map[string]string{"usr/lib/libx.so": "f:lib", "usr/sbin/php-fpm": "f:php", "etc/ssl/ca.pem": "f:pem", + `usr\lib`: "f:junk", `usr\sbin\php-fpm`: "f:junk", `etc\.wh.ssl`: "f:junk"} { + if one(got, p) != want { + t.Errorf("%s: %s is %s, want %s", name, p, one(got, p), want) + } + } + if len(unresolved) != 0 { + t.Errorf("%s: unresolved %v", name, unresolved) + } + } +} + // Unsafe names fail the image, as with mutate.Extract. func TestFlattenUnsafe(t *testing.T) { rc, _ := flatten(imageOf(t, []ent{f("../escape", "x")})) From 187a2742f6214bd8d0dcf1e1c86f962c8b26d617 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:25:02 +0000 Subject: [PATCH 095/119] engine, emudhra, brotli, php2shell: a member is forgotten with the file the engine says holds it Final review A3 and A6. Forget(p) took every finding whose path starts with p + "!/" as found inside p. A directory can be named "app!": with a file /opt/app next to it that an image names twice, the vulnerable files under /opt/app!/ were dropped (two findings on main, none here, no skip). engine.File now carries Outer, the file the walk met that holds a member, and emudhra and brotli index what they found by it. brotli and php2shell also forget in the time the path's own entries take rather than a pass over everything kept: 100,000 repeats of one path over 20,000 findings took 65 s in brotli (3 s on main). Co-Authored-By: Claude Fable 5.2 --- detectors/brotli/brotli.go | 41 +++++++++++---- detectors/brotli/forget_internal_test.go | 55 +++++++++++++++++++-- detectors/emudhra/emudhra.go | 7 ++- detectors/emudhra/limit_test.go | 28 +++++++++++ detectors/php2shell/forget_internal_test.go | 35 +++++++++++-- detectors/php2shell/php2shell.go | 36 +++++++++++--- internal/engine/engine.go | 5 ++ internal/engine/run.go | 3 ++ 8 files changed, 185 insertions(+), 25 deletions(-) diff --git a/detectors/brotli/brotli.go b/detectors/brotli/brotli.go index e6fc361..560923f 100644 --- a/detectors/brotli/brotli.go +++ b/detectors/brotli/brotli.go @@ -16,8 +16,6 @@ import ( "github.com/DefectDojo/earlylight/detectors/brotli/internal/fingerprint" "github.com/DefectDojo/earlylight/internal/archive" "github.com/DefectDojo/earlylight/internal/engine" - "slices" - "strings" ) // ID is the detector's ID. @@ -80,16 +78,25 @@ func (d *Detector) Wants(_ string, head []byte, _ bool) bool { } // NewScan starts a filesystem or image scan. -func (d *Detector) NewScan(engine.TargetKind) engine.Scan { return &scan{} } - -type scan struct{ findings []engine.Finding } +func (d *Detector) NewScan(engine.TargetKind) engine.Scan { return &scan{foundIn: map[string][]int{}} } + +type scan struct { + findings []engine.Finding + // foundIn indexes findings by the file the walk met (a member under + // the file that holds it); gone marks those a later entry dropped. + foundIn map[string][]int + gone []bool +} // Forget drops what was found in p, and inside it: an image names it -// again, and the last entry is the file. +// again, and the last entry is the file. "Inside it" is what the engine +// said is a member of p, not a path that starts the same way (a directory +// can be named "app!"). It costs what p held, not every finding. func (s *scan) Forget(p string) { - s.findings = slices.DeleteFunc(s.findings, func(f engine.Finding) bool { - return f.Path == p || strings.HasPrefix(f.Path, p+"!/") - }) + for _, i := range s.foundIn[p] { + s.gone[i] = true + } + delete(s.foundIn, p) } func (s *scan) Visit(f engine.File) []engine.Skip { @@ -97,12 +104,26 @@ func (s *scan) Visit(f engine.File) []engine.Skip { return nil } if x, ok := assess.File(f.Path, f.Data); ok { + outer := f.Path + if f.Member && f.Outer != "" { + outer = f.Outer + } + s.foundIn[outer] = append(s.foundIn[outer], len(s.findings)) s.findings = append(s.findings, finding(x)) + s.gone = append(s.gone, false) } return nil } -func (s *scan) Finish(engine.TargetContext) []engine.Finding { return s.findings } +func (s *scan) Finish(engine.TargetContext) []engine.Finding { + out := make([]engine.Finding, 0, len(s.findings)) + for i, f := range s.findings { + if !s.gone[i] { + out = append(out, f) + } + } + return out +} var verdicts = map[assess.Status]engine.Verdict{ assess.Vulnerable: engine.Vulnerable, diff --git a/detectors/brotli/forget_internal_test.go b/detectors/brotli/forget_internal_test.go index 1fe136c..b7c53ba 100644 --- a/detectors/brotli/forget_internal_test.go +++ b/detectors/brotli/forget_internal_test.go @@ -1,17 +1,64 @@ package brotli import ( + "fmt" "testing" + "time" + "github.com/DefectDojo/earlylight/detectors/brotli/internal/testbin" "github.com/DefectDojo/earlylight/internal/engine" ) +var vulnerable = testbin.ELF([]testbin.Symbol{{Name: "BrotliDecoderDecompressStream", Defined: true}}, testbin.Table("1.0.9")) + +func paths(fs []engine.Finding) string { + var out []string + for _, f := range fs { + out = append(out, f.Path) + } + return fmt.Sprint(out) +} + // When an image names a path again, what was found in the first entry, -// and inside it, is dropped. +// and inside it, is dropped. Final review A3: "inside it" is what the +// engine says is a member of it, not a path that starts the same way: a +// directory named "a!" next to a file "a" is not an archive. func TestForget(t *testing.T) { - s := &scan{findings: []engine.Finding{{Path: "/a"}, {Path: "/a!/x.so"}, {Path: "/ab"}, {Path: "/b"}}} + s := (&Detector{}).NewScan(engine.Image).(*scan) + s.Visit(engine.File{Path: "/a", Data: vulnerable}) + s.Visit(engine.File{Path: "/a!/x.so", Data: vulnerable, Member: true, Outer: "/a"}) + s.Visit(engine.File{Path: "/ab", Data: vulnerable}) + s.Visit(engine.File{Path: "/b", Data: vulnerable}) + s.Visit(engine.File{Path: "/opt/app", Data: []byte("hello")}) + s.Visit(engine.File{Path: "/opt/app!/libbrotlidec.so.1", Data: vulnerable}) // a file in the directory "app!" s.Forget("/a") - if len(s.findings) != 2 || s.findings[0].Path != "/ab" || s.findings[1].Path != "/b" { - t.Errorf("%+v", s.findings) + s.Forget("/opt/app") + if got := paths(s.Finish(nil)); got != "[/ab /b /opt/app!/libbrotlidec.so.1]" { + t.Errorf("after Forget: %s", got) + } + s.Forget("/opt/app!/libbrotlidec.so.1") + s.Visit(engine.File{Path: "/a", Data: vulnerable}) + if got := paths(s.Finish(nil)); got != "[/ab /b /a]" { + t.Errorf("after the second Forget: %s", got) + } +} + +// Final review A6: forgetting a path costs what the path held, not every +// finding kept. +func TestForgetIsCheap(t *testing.T) { + s := (&Detector{}).NewScan(engine.Image).(*scan) + for i := 0; i < 20000; i++ { + s.Visit(engine.File{Path: fmt.Sprintf("/lib/%d.so", i), Data: vulnerable}) + } + start := time.Now() + for i := 0; i < 100000; i++ { + s.Forget("/x") + s.Visit(engine.File{Path: "/x", Data: []byte("x")}) + } + if d := time.Since(start); d > 5*time.Second { + t.Errorf("100,000 repeats over 20,000 findings took %s", d) + } + if n := len(s.Finish(nil)); n != 20000 { + t.Errorf("%d findings, want 20000", n) } } diff --git a/detectors/emudhra/emudhra.go b/detectors/emudhra/emudhra.go index c93aaf6..8754c48 100644 --- a/detectors/emudhra/emudhra.go +++ b/detectors/emudhra/emudhra.go @@ -136,7 +136,12 @@ func (s *scan) Visit(f engine.File) []engine.Skip { continue } s.dedupe[k] = true - outer, _, _ := strings.Cut(f.Path, "!/") // a member is forgotten with its archive + // A member is forgotten with the file that holds it. Only the + // engine knows which that is: a directory can be named "app!". + outer := f.Path + if f.Member && f.Outer != "" { + outer = f.Outer + } s.foundIn[outer] = append(s.foundIn[outer], len(s.findings)) s.findings = append(s.findings, x) s.gone = append(s.gone, false) diff --git a/detectors/emudhra/limit_test.go b/detectors/emudhra/limit_test.go index a2e5710..fa9c4de 100644 --- a/detectors/emudhra/limit_test.go +++ b/detectors/emudhra/limit_test.go @@ -81,6 +81,34 @@ func TestCertifiNamedTwice(t *testing.T) { } } +// Final review A3: a file in a directory named "app!" is not a member of +// the file "app" next to it: it is not forgotten when an image names +// /opt/app again. +func TestForgetIsNotByPrefix(t *testing.T) { + g3, err := os.ReadFile(filepath.Join(g3Bundle(t), "cacert.pem")) + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, e := range []struct { + name string + body []byte + }{{"opt/app", []byte("one")}, {"opt/app!/ca.pem", g3}, {"opt/app", []byte("two")}} { + tw.WriteHeader(&tar.Header{Name: e.name, Mode: 0o644, Size: int64(len(e.body)), Typeflag: tar.TypeReg}) + tw.Write(e.body) + } + tw.Close() + img := filepath.Join(t.TempDir(), "rootfs.tar") + if err := os.WriteFile(img, buf.Bytes(), 0o600); err != nil { + t.Fatal(err) + } + var out, errb bytes.Buffer + if code := cli.Run(engine, []string{"scan", "image", "--detector", "emudhra", "rootfs:" + img}, &out, &errb); code != 1 { + t.Errorf("exit %d, want 1\n%s%s", code, out.String(), errb.String()) + } +} + // Final review finding 5: forgetting a path costs what the path held, not // every finding kept: an image that repeats paths stays linear. func TestForgetIsCheap(t *testing.T) { diff --git a/detectors/php2shell/forget_internal_test.go b/detectors/php2shell/forget_internal_test.go index 1e9bf28..7821098 100644 --- a/detectors/php2shell/forget_internal_test.go +++ b/detectors/php2shell/forget_internal_test.go @@ -1,7 +1,9 @@ package php2shell import ( + "fmt" "testing" + "time" "github.com/DefectDojo/earlylight/detectors/php2shell/internal/detect" ) @@ -9,11 +11,36 @@ import ( // When an image names a path again, what was kept of the first entry is // dropped. func TestForget(t *testing.T) { - c := &collector{dbFiles: map[string][]byte{"/var/lib/dpkg/status": []byte("x")}, - binaries: []*detect.Binary{{Path: "/usr/bin/php"}, {Path: "/usr/bin/php8"}}} + c := &collector{dbFiles: map[string][]byte{"/var/lib/dpkg/status": []byte("x")}} + c.keep(&detect.Binary{Path: "/usr/bin/php"}) + c.keep(&detect.Binary{Path: "/usr/bin/php8"}) c.Forget("/var/lib/dpkg/status") c.Forget("/usr/bin/php") - if len(c.dbFiles) != 0 || len(c.binaries) != 1 || c.binaries[0].Path != "/usr/bin/php8" { - t.Errorf("db %v binaries %+v", c.dbFiles, c.binaries) + if bs := c.kept(); len(c.dbFiles) != 0 || len(bs) != 1 || bs[0].Path != "/usr/bin/php8" { + t.Errorf("db %v binaries %+v", c.dbFiles, bs) + } + c.keep(&detect.Binary{Path: "/usr/bin/php"}) + if bs := c.kept(); len(bs) != 2 || bs[1].Path != "/usr/bin/php" { + t.Errorf("binaries %+v", bs) + } +} + +// Final review A6: forgetting a path costs what the path held, not every +// binary kept. +func TestForgetIsCheap(t *testing.T) { + c := &collector{dbFiles: map[string][]byte{}} + for i := 0; i < 20000; i++ { + c.keep(&detect.Binary{Path: fmt.Sprintf("/usr/bin/php%d", i)}) + } + start := time.Now() + for i := 0; i < 100000; i++ { + c.Forget("/x") + c.keep(&detect.Binary{Path: "/x"}) + } + if d := time.Since(start); d > 5*time.Second { + t.Errorf("100,000 repeats over 20,000 binaries took %s", d) + } + if n := len(c.kept()); n != 20001 { + t.Errorf("%d binaries, want 20001", n) } } diff --git a/detectors/php2shell/php2shell.go b/detectors/php2shell/php2shell.go index c6d8dad..ca9fbb0 100644 --- a/detectors/php2shell/php2shell.go +++ b/detectors/php2shell/php2shell.go @@ -16,7 +16,6 @@ import ( "context" "fmt" "io" - "slices" "strings" "time" @@ -124,8 +123,10 @@ func excluded(p string, ex []string) bool { // collector is php2shell-scan's per-target collector. type collector struct { - data *knowledge.Data + data *knowledge.Data + // binaries are those met, nil once forgotten; binAt indexes them by path. binaries []*detect.Binary + binAt map[string][]int dbFiles map[string][]byte symlinks map[string]string exclude []string @@ -162,10 +163,33 @@ func upx(head []byte) bool { } // Forget drops what was kept of p: an image names it again, and the last -// entry is the file. +// entry is the file. It costs what p held, not every binary kept. func (c *collector) Forget(p string) { delete(c.dbFiles, p) - c.binaries = slices.DeleteFunc(c.binaries, func(b *detect.Binary) bool { return b.Path == p }) + for _, i := range c.binAt[p] { + c.binaries[i] = nil + } + delete(c.binAt, p) +} + +// keep records a binary under its path. +func (c *collector) keep(b *detect.Binary) { + if c.binAt == nil { + c.binAt = map[string][]int{} + } + c.binAt[b.Path] = append(c.binAt[b.Path], len(c.binaries)) + c.binaries = append(c.binaries, b) +} + +// kept returns the binaries not forgotten, in the order met. +func (c *collector) kept() []*detect.Binary { + out := make([]*detect.Binary, 0, len(c.binaries)) + for _, b := range c.binaries { + if b != nil { + out = append(out, b) + } + } + return out } func (c *collector) Visit(f engine.File) []engine.Skip { @@ -185,7 +209,7 @@ func (c *collector) Visit(f engine.File) []engine.Skip { } if exe { if b := detect.Inspect(f.Path, f.Data); b != nil { - c.binaries = append(c.binaries, b) + c.keep(b) } } return nil @@ -216,7 +240,7 @@ func (c *collector) Finish(ctx engine.TargetContext) []engine.Finding { res.AddHardlink(p, target) } } - fs := assess.Run(assess.Input{Binaries: c.binaries, Index: ix, Aliases: res.Aliases, OS: osr, Data: c.data}) + fs := assess.Run(assess.Input{Binaries: c.kept(), Index: ix, Aliases: res.Aliases, OS: osr, Data: c.data}) out := make([]engine.Finding, 0, len(fs)) for _, f := range fs { out = append(out, runtimeFinding(f)) diff --git a/internal/engine/engine.go b/internal/engine/engine.go index c126190..2d24d21 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -125,6 +125,11 @@ type File struct { Executable bool // Member is true for a file found inside an archive or package. Member bool + // Outer is, for a member, the path of the file the walk met that holds + // it (the archive itself, however deep the member is). A scan that + // keeps what it found by file forgets a member with Outer: a path + // that merely contains "!/" is not a member. + Outer string } // Skip records something a detector could not check, and why. diff --git a/internal/engine/run.go b/internal/engine/run.go index c4db543..ee556b1 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -521,6 +521,9 @@ func (w *walker) visit(f source.File) error { member := !first first = false ff := File{Path: p, Data: b, Member: member, Executable: !member && f.Executable} + if member { + ff.Outer = f.Path + } w.send(ff, func(i int) bool { return member && !w.dets[i].Manifest().Archives }) }, func(p, reason string) { w.t.Skipped = append(w.t.Skipped, source.Skip{Path: p, Reason: reason}) }) From 2c2d19b2c054ada3782ee41895eefab3f6a88edc Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:27:40 +0000 Subject: [PATCH 096/119] image: a file written through a lower layer's link stays read Final review A4. A layer that names lib/libbrotlidec.so.1 over a base where lib is a link to usr/lib (crane append, Bazel, Jib and other tools that write tar paths as they are) puts the file at /usr/lib in the container. The flattener listed both paths as unresolved and the engine forgot what it had read at both: three vulnerable findings on main became "no vulnerable findings" with six coverage gaps. The flattener now knows which layer wrote each entry and each link: - the one file written through a link from a lower layer, landing where no link leads on and no layer at or above its own names the path, is the file: it stays read under the name it was written with, and only the path it landed on is unresolved (a lower file there was replaced); - when a layer above every such write names the real path itself, that entry is the file, and only the writes through the link are unresolved; - anything else (a link of the same layer, two links to one directory, a link to a link, the same layer writing both) is unresolved as before. Co-Authored-By: Claude Fable 5.2 --- detectors/brotli/forget_internal_test.go | 4 + detectors/brotli/layers_internal_test.go | 109 +++++++++++++++++++++++ internal/image/flatten.go | 101 +++++++++++++++++---- internal/image/flatten_test.go | 23 ++++- 4 files changed, 218 insertions(+), 19 deletions(-) create mode 100644 detectors/brotli/layers_internal_test.go diff --git a/detectors/brotli/forget_internal_test.go b/detectors/brotli/forget_internal_test.go index b7c53ba..b741ee5 100644 --- a/detectors/brotli/forget_internal_test.go +++ b/detectors/brotli/forget_internal_test.go @@ -11,6 +11,10 @@ import ( var vulnerable = testbin.ELF([]testbin.Symbol{{Name: "BrotliDecoderDecompressStream", Defined: true}}, testbin.Table("1.0.9")) +func testbinFixed() []byte { + return testbin.ELF([]testbin.Symbol{{Name: "BrotliDecoderDecompressStream", Defined: true}}, testbin.Table("1.2.1")) +} + func paths(fs []engine.Finding) string { var out []string for _, f := range fs { diff --git a/detectors/brotli/layers_internal_test.go b/detectors/brotli/layers_internal_test.go new file mode 100644 index 0000000..dc2ea86 --- /dev/null +++ b/detectors/brotli/layers_internal_test.go @@ -0,0 +1,109 @@ +package brotli + +import ( + "archive/tar" + "bytes" + "io" + "path/filepath" + "testing" + + "github.com/google/go-containerregistry/pkg/name" + v1 "github.com/google/go-containerregistry/pkg/v1" + "github.com/google/go-containerregistry/pkg/v1/empty" + "github.com/google/go-containerregistry/pkg/v1/mutate" + "github.com/google/go-containerregistry/pkg/v1/tarball" + + "github.com/DefectDojo/earlylight/internal/engine" +) + +// entry is one layer entry: a file with data, a directory (dir) or a +// symbolic link (link). +type entry struct { + name string + data []byte + dir bool + link string +} + +func archiveOf(t *testing.T, layers ...[]entry) string { + t.Helper() + var ls []v1.Layer + for _, es := range layers { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, e := range es { + h := &tar.Header{Name: e.name, Mode: 0o755, Typeflag: tar.TypeReg, Size: int64(len(e.data))} + switch { + case e.dir: + h.Typeflag = tar.TypeDir + case e.link != "": + h.Typeflag, h.Linkname = tar.TypeSymlink, e.link + } + if err := tw.WriteHeader(h); err != nil { + t.Fatal(err) + } + tw.Write(e.data) + } + tw.Close() + b := buf.Bytes() + l, err := tarball.LayerFromOpener(func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(b)), nil }) + if err != nil { + t.Fatal(err) + } + ls = append(ls, l) + } + img, err := mutate.AppendLayers(empty.Image, ls...) + if err != nil { + t.Fatal(err) + } + p := filepath.Join(t.TempDir(), "image.tar") + if err := tarball.WriteToFile(p, name.MustParseReference("test/brotli:1"), img); err != nil { + t.Fatal(err) + } + return p +} + +// Final review A4: an image whose upper layer names a library as it is +// written, lib/libbrotlidec.so.1, over a base where lib is a link to +// usr/lib (crane append, Bazel, Jib): the container has the library, and +// the scan reports it. The path it landed on is a coverage gap. +func TestWrittenThroughALink(t *testing.T) { + p := archiveOf(t, + []entry{{name: "usr", dir: true}, {name: "usr/lib", dir: true}, {name: "lib", link: "usr/lib"}, {name: "usr/lib/other", data: []byte("x")}}, + []entry{{name: "lib/libbrotlidec.so.1", data: vulnerable}}) + tg := engine.ScanImage([]engine.Detector{&Detector{}}, "docker-archive:"+p, engine.Options{}) + if tg.Error != "" || len(tg.Findings) != 1 || tg.Findings[0].Verdict != engine.Vulnerable || tg.Findings[0].Path != "/lib/libbrotlidec.so.1" { + t.Errorf("error %q findings %+v", tg.Error, tg.Findings) + } + if len(tg.Skipped) != 1 || tg.Skipped[0].Path != "/usr/lib/libbrotlidec.so.1" || tg.Gaps() != 1 { + t.Errorf("skipped %+v", tg.Skipped) + } + // A lower file at the path it landed on was replaced: what it held is + // forgotten, the file written through the link is kept. + fixed := testbinFixed() + p = archiveOf(t, + []entry{{name: "usr/lib", dir: true}, {name: "lib", link: "usr/lib"}, {name: "usr/lib/libbrotlidec.so.1", data: fixed}}, + []entry{{name: "lib/libbrotlidec.so.1", data: vulnerable}}) + tg = engine.ScanImage([]engine.Detector{&Detector{}}, "docker-archive:"+p, engine.Options{}) + if len(tg.Findings) != 1 || tg.Findings[0].Verdict != engine.Vulnerable || tg.Findings[0].Path != "/lib/libbrotlidec.so.1" { + t.Errorf("replaced through the link: findings %+v", tg.Findings) + } + // A higher layer then names the real path: that entry is the file, and + // what was written through the link before it is forgotten. + p = archiveOf(t, + []entry{{name: "usr/lib", dir: true}, {name: "lib", link: "usr/lib"}}, + []entry{{name: "lib/libbrotlidec.so.1", data: fixed}}, + []entry{{name: "usr/lib/libbrotlidec.so.1", data: vulnerable}}) + tg = engine.ScanImage([]engine.Detector{&Detector{}}, "docker-archive:"+p, engine.Options{}) + if len(tg.Findings) != 1 || tg.Findings[0].Verdict != engine.Vulnerable || tg.Findings[0].Path != "/usr/lib/libbrotlidec.so.1" || tg.Gaps() != 1 { + t.Errorf("the real path written afterwards: findings %+v skipped %+v", tg.Findings, tg.Skipped) + } + // Written both ways in one layer, whose order decides: neither is kept. + p = archiveOf(t, + []entry{{name: "usr/lib", dir: true}, {name: "lib", link: "usr/lib"}}, + []entry{{name: "lib/libbrotlidec.so.1", data: fixed}, {name: "usr/lib/libbrotlidec.so.1", data: vulnerable}}) + tg = engine.ScanImage([]engine.Detector{&Detector{}}, "docker-archive:"+p, engine.Options{}) + if len(tg.Findings) != 0 || tg.Gaps() != 2 { + t.Errorf("written both ways: findings %+v skipped %+v", tg.Findings, tg.Skipped) + } +} diff --git a/internal/image/flatten.go b/internal/image/flatten.go index 4def3f4..661746c 100644 --- a/internal/image/flatten.go +++ b/internal/image/flatten.go @@ -20,7 +20,10 @@ package image // What the layers do not settle cheaply (two entries for one path in one // layer, a hard link to a file not in its layer, a write or whiteout // through a directory that is a symbolic link) is listed as unresolved: -// the scan treats those paths as not read. +// the scan treats those paths as not read. A file an upper layer wrote +// through a lower layer's link is the exception when nothing else claims +// the path it landed on: the container has that file, so it stays read +// under the name it was written with (throughLinks). import ( "archive/tar" @@ -44,8 +47,8 @@ const ( // function returns the paths left unresolved, once the stream has ended. func flatten(img v1.Image) (io.ReadCloser, func() []string) { pr, pw := io.Pipe() - f := &flattener{fileMap: map[string]bool{}, opaqueDirs: map[string]bool{}, written: map[string]bool{}, - links: map[string]string{}, unresolved: map[string]bool{}} + f := &flattener{fileMap: map[string]bool{}, opaqueDirs: map[string]bool{}, written: map[string]int{}, + tombs: map[string]bool{}, links: map[string]flatLink{}, unresolved: map[string]bool{}} done := make(chan struct{}) var out []string go func() { @@ -70,11 +73,19 @@ type flattener struct { tw *tar.Writer fileMap map[string]bool // path -> hides what is below it (non-directory or whiteout) opaqueDirs map[string]bool - written map[string]bool // non-directories written, and whiteouts - links map[string]string // symbolic links written: path -> target + cur int // the layer being read (0 is the lowest) + written map[string]int // non-directories written, and whiteouts: path -> layer + tombs map[string]bool // of those, the whiteouts + links map[string]flatLink // symbolic links written unresolved map[string]bool } +// flatLink is a symbolic link written to the stream: its target and layer. +type flatLink struct { + to string + layer int +} + func (f *flattener) extract(img v1.Image, w io.Writer) error { f.tw = tar.NewWriter(w) defer f.tw.Close() @@ -83,6 +94,7 @@ func (f *flattener) extract(img v1.Image, w io.Writer) error { return fmt.Errorf("retrieving image layers: %w", err) } for i := len(layers) - 1; i >= 0; i-- { + f.cur = i if err := f.layer(layers[i]); err != nil { return err } @@ -172,7 +184,7 @@ func (f *flattener) layer(layer v1.Layer) error { } f.fileMap[name] = tombstone || !isDir if tombstone { - f.written[name] = true + f.written[name], f.tombs[name] = f.cur, true continue } if h.Typeflag == tar.TypeLink { @@ -181,7 +193,7 @@ func (f *flattener) layer(layer v1.Layer) error { // It names a file an upper layer hides: it keeps that file's // content, written once the layer is read again. pending[h.Linkname] = append(pending[h.Linkname], name) - f.written[name] = true + f.written[name] = f.cur continue case !here[h.Linkname]: f.unresolved[name] = true // not a file of its own layer @@ -199,10 +211,10 @@ func (f *flattener) layer(layer v1.Layer) error { here[name] = true } if !isDir { - f.written[name] = true + f.written[name] = f.cur } if h.Typeflag == tar.TypeSymlink { - f.links[name] = h.Linkname + f.links[name] = flatLink{h.Linkname, f.cur} } } for d := range layerOpaque { @@ -266,29 +278,82 @@ func (f *flattener) fillLinks(layer v1.Layer, pending map[string][]string) error // throughLinks finds the entries an upper layer wrote, or whited out, // under a directory that is a symbolic link in the final filesystem: the -// runtime wrote through the link, to the path it names. Both paths are -// unresolved. +// runtime wrote through the link, to the path it names. +// +// The path it names is unresolved: a lower layer's file there was replaced +// or removed, and the stream names the new one elsewhere. The entry itself +// is unresolved too. Two cases are certain, and keep what was read: +// +// - The entry is the file: a file (not a whiteout) written by a layer +// above the link's, landing on a path that no link leads on from, that +// no other such write lands on, and that no layer at or above the +// write's names directly. It stays read under the name it was written +// with; dropping it would lose what an image built with paths written +// as they are (lib/libx.so under a lib -> usr/lib link) holds. +// - A layer above every such write names the path itself: that entry is +// the file, and only the writes through the link are unresolved. func (f *flattener) throughLinks() { if len(f.links) == 0 { return } - for name := range f.written { + type write struct { + name string + layer int + sure bool // above the link's layer, and not a whiteout + } + lands := map[string][]write{} + for name, layer := range f.written { for a := path.Dir(name); a != "." && a != "/" && a != ""; a = path.Dir(a) { - t, ok := f.links[a] + l, ok := f.links[a] if !ok { continue } - to := t - if !path.IsAbs(t) { - to = path.Join(path.Dir(a), t) + to := l.to + if !path.IsAbs(to) { + to = path.Join(path.Dir(a), to) } - f.unresolved[name] = true + at := "" if r := rootName(to); r != "" { - f.unresolved[path.Join(r, strings.TrimPrefix(name, a+"/"))] = true + at = path.Join(r, strings.TrimPrefix(name, a+"/")) } + lands[at] = append(lands[at], write{name, layer, l.layer < layer && !f.tombs[name]}) break } } + for at, ws := range lands { + // through: the one write through a link is the file. direct: a + // layer above every such write named the path itself afterwards, + // and that entry is the file. + through, direct := false, false + if at != "" && !f.linked(at) { + top := -1 + for _, w := range ws { + top = max(top, w.layer) + } + d, ok := f.written[at] + through = len(ws) == 1 && ws[0].sure && (!ok || d < top) + direct = ok && d > top + } + if at != "" && !direct { + f.unresolved[at] = true + } + if !through { + for _, w := range ws { + f.unresolved[w.name] = true + } + } + } +} + +// linked reports whether name, or a directory above it, is a symbolic +// link in the stream. +func (f *flattener) linked(name string) bool { + for a := name; a != "." && a != "/" && a != ""; a = path.Dir(a) { + if _, ok := f.links[a]; ok { + return true + } + } + return false } func inOpaqueDir(opaqueDirs map[string]bool, file string) bool { diff --git a/internal/image/flatten_test.go b/internal/image/flatten_test.go index fd8a291..b2c7f6c 100644 --- a/internal/image/flatten_test.go +++ b/internal/image/flatten_test.go @@ -223,8 +223,29 @@ func TestFlattenUnresolved(t *testing.T) { {"whiteout then file", [][]ent{{f("a", "lower")}, {f(".wh.a", ""), f("a", "new")}}, "[/a]"}, {"file then whiteout", [][]ent{{f("a", "lower")}, {f("a", "new"), f(".wh.a", "")}}, "[/a]"}, {"a directory twice", [][]ent{{d("d"), d("d"), f("d/x", "1")}}, "[]"}, + // Final review A4: what an upper layer wrote through a lower + // layer's link is in the container, at the path the link names: + // it stays read under the name it was written with, and only the + // path it landed on is unresolved (a lower file there was + // replaced). {"a write through a symlinked directory", [][]ent{{sl("etc/ssh", "../opt/ssh"), f("opt/ssh/sshd_config", "old")}, {f("etc/ssh/sshd_config", "new")}}, - "[/etc/ssh/sshd_config /opt/ssh/sshd_config]"}, + "[/opt/ssh/sshd_config]"}, + {"a write through a usr-merge link", [][]ent{{d("usr"), d("usr/lib"), sl("lib", "usr/lib"), f("usr/lib/other", "x")}, {f("lib/libx.so", "new")}}, + "[/usr/lib/libx.so]"}, + // A higher layer names the real path afterwards: that is the file. + {"a higher layer writes the real path too", [][]ent{{sl("lib", "usr/lib")}, {f("lib/x", "mid")}, {f("usr/lib/x", "top")}}, + "[/lib/x]"}, + {"a higher layer removes the real path", [][]ent{{sl("lib", "usr/lib")}, {f("lib/x", "mid")}, {f("usr/lib/.wh.x", "")}}, + "[/lib/x]"}, + // Which of the two the container has is not settled: both. + {"the same layer writes the real path too", [][]ent{{sl("lib", "usr/lib")}, {f("lib/x", "a"), f("usr/lib/x", "b")}}, + "[/lib/x /usr/lib/x]"}, + {"the link is of the same layer", [][]ent{{f("lib/x", "a"), sl("lib", "usr/lib")}}, + "[/lib/x /usr/lib/x]"}, + {"two links to one directory", [][]ent{{sl("a", "c"), sl("b", "c")}, {f("a/x", "1")}, {f("b/x", "2")}}, + "[/a/x /b/x /c/x]"}, + {"a link to a link", [][]ent{{sl("a", "b"), sl("b", "c")}, {f("a/x", "1")}}, + "[/a/x /b/x]"}, {"a whiteout through a symlinked directory", [][]ent{{sl("etc/ssh", "/opt/ssh"), f("opt/ssh/sshd_config", "old")}, {f("etc/ssh/.wh.sshd_config", "")}}, "[/etc/ssh/sshd_config /opt/ssh/sshd_config]"}, } { From f6b7ae96f3e859e1c8546e2c1d2fae0f0e9abe04 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:28:49 +0000 Subject: [PATCH 097/119] engine: a path named again under a directory that was a link is not forgotten Final review A5. In a docker export the last entry for a path is the file, so the earlier one is forgotten. When a directory above the path is a symbolic link that points elsewhere by the second entry (or was a link and is a directory now), the two entries are two files: the first still exists where the link led. Three vulnerable findings on main, none here. The walk remembers every path it met as a symbolic link and forgets nothing below one. Co-Authored-By: Claude Fable 5.2 --- detectors/brotli/layers_internal_test.go | 49 ++++++++++++++++++++++++ internal/engine/run.go | 23 +++++++++-- 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/detectors/brotli/layers_internal_test.go b/detectors/brotli/layers_internal_test.go index dc2ea86..5ad38c9 100644 --- a/detectors/brotli/layers_internal_test.go +++ b/detectors/brotli/layers_internal_test.go @@ -4,6 +4,7 @@ import ( "archive/tar" "bytes" "io" + "os" "path/filepath" "testing" @@ -107,3 +108,51 @@ func TestWrittenThroughALink(t *testing.T) { t.Errorf("written both ways: findings %+v skipped %+v", tg.Findings, tg.Skipped) } } + +// Final review A5: a docker export names d/lib twice, and d is a link that +// points somewhere else by the second time: the two entries are two files +// (e/lib and o/lib), so the first is not forgotten. +func TestNamedAgainThroughAMovedLink(t *testing.T) { + export := func(es ...entry) string { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, e := range es { + h := &tar.Header{Name: e.name, Mode: 0o755, Typeflag: tar.TypeReg, Size: int64(len(e.data))} + switch { + case e.dir: + h.Typeflag = tar.TypeDir + case e.link != "": + h.Typeflag, h.Linkname = tar.TypeSymlink, e.link + } + if err := tw.WriteHeader(h); err != nil { + t.Fatal(err) + } + tw.Write(e.data) + } + tw.Close() + p := filepath.Join(t.TempDir(), "rootfs.tar") + if err := os.WriteFile(p, buf.Bytes(), 0o600); err != nil { + t.Fatal(err) + } + return p + } + clean := []byte("clean") + for name, c := range map[string]struct { + entries []entry + want int + }{ + "the link moves": {[]entry{{name: "e", dir: true}, {name: "o", dir: true}, {name: "d", link: "e"}, {name: "d/libbrotlidec.so.1", data: vulnerable}, + {name: "d", link: "o"}, {name: "d/libbrotlidec.so.1", data: clean}}, 1}, + "a link above moves": {[]entry{{name: "e/s", dir: true}, {name: "o/s", dir: true}, {name: "d", link: "e"}, {name: "d/s/libbrotlidec.so.1", data: vulnerable}, + {name: "d", link: "o"}, {name: "d/s/libbrotlidec.so.1", data: clean}}, 1}, + "the link becomes a directory": {[]entry{{name: "e", dir: true}, {name: "d", link: "e"}, {name: "d/libbrotlidec.so.1", data: vulnerable}, + {name: "d", dir: true}, {name: "d/libbrotlidec.so.1", data: clean}}, 1}, + // No link: the last entry is the file. + "a plain directory": {[]entry{{name: "d", dir: true}, {name: "d/libbrotlidec.so.1", data: vulnerable}, {name: "d/libbrotlidec.so.1", data: clean}}, 0}, + } { + tg := engine.ScanImage([]engine.Detector{&Detector{}}, "rootfs:"+export(c.entries...), engine.Options{}) + if tg.Error != "" || len(tg.Findings) != c.want { + t.Errorf("%s: error %q, %d findings, want %d: %+v", name, tg.Error, len(tg.Findings), c.want, tg.Findings) + } + } +} diff --git a/internal/engine/run.go b/internal/engine/run.go index ee556b1..d961acd 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -219,6 +219,9 @@ type walker struct { exclusions []map[string]string // linked counts the hard links that name each path. linked map[string]int + // wasLink holds every path the walk met as a symbolic link, even one + // replaced since. + wasLink map[string]bool } // fileLimit is one detector's own limit on one file, and whether it asked @@ -264,8 +267,15 @@ func (w *walker) sourceOptions(opts Options) source.Options { so := source.Options{ MaxFileSize: opts.MaxFileSize, IsExecutable: archive.IsExecutable, - Symlink: func(p, t string) { w.ctx.symlinks[w.abs(p)] = t }, - Hardlink: func(p, t string) { w.setHardlink(w.abs(p), w.abs(t)) }, + Symlink: func(p, t string) { + abs := w.abs(p) + w.ctx.symlinks[abs] = t + if w.wasLink == nil { + w.wasLink = map[string]bool{} + } + w.wasLink[abs] = true + }, + Hardlink: func(p, t string) { w.setHardlink(w.abs(p), w.abs(t)) }, } type headScan struct { id string @@ -356,11 +366,18 @@ func (w *walker) sourceOptions(opts Options) source.Options { // export names a path again, as a file, directory or link): every scan // forgets what it kept of p, unless a hard link names p. A hard link keeps // the earlier file's content (it names the file, not the path), so what -// was found in it stays, under p. +// was found in it stays, under p. Nor is anything forgotten when a +// directory above p is, or was earlier in the walk, a symbolic link: the +// name then led somewhere else, and the two entries can be two files. func (w *walker) replaced(p string) { if w.linked[p] > 0 { return } + for a := path.Dir(p); a != "/" && a != "."; a = path.Dir(a) { + if w.wasLink[a] { + return + } + } w.forget(p) delete(w.ctx.seen, p) } From 6748a50fa72d6a1b16d2b153b03f35546ede36ac Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:30:14 +0000 Subject: [PATCH 098/119] java4shell: every VM library of a runtime is judged; the worst verdict is the runtime's Final review B1. A runtime directory was judged by one "primary" library and the others were never looked at. A JDK 21 unpacked over a Java 8 directory (lib/amd64/server left behind) was cleared as Java 8; a fixed library dropped into bin/server, a fixed server VM next to a vulnerable minimal or client VM, and an aarch64 server VM next to an x86-64 client VM all cleared a vulnerable runtime. The libraries are still judged as one runtime first (an OpenJ9 runtime's redirector and VM are one VM). Then each other library that states a version or carries the decoder is judged on its own, and the worst of the verdicts is reported, with the library that decided and what the first one alone would have said. Co-Authored-By: Claude Fable 5.2 --- .../java4shell/internal/assess/assess.go | 40 +++++++++- .../internal/assess/libraries_test.go | 74 +++++++++++++++++++ 2 files changed, 113 insertions(+), 1 deletion(-) create mode 100644 detectors/java4shell/internal/assess/libraries_test.go diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index 03790ac..b28f16b 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -113,7 +113,7 @@ func Run(in Input) []Finding { env := jvm.EnvMap(in.Env) var out []Finding for _, r := range roots { - out = append(out, withFix(redHat(in, judge(in, env, r, byRoot[r])))) + out = append(out, withFix(redHat(in, judgeAll(in, env, r, byRoot[r])))) } for _, l := range loose { out = append(out, withFix(redHat(in, judge(in, env, path.Dir(l.Path), []*jvm.Library{l})))) @@ -121,6 +121,44 @@ func Run(in Input) []Finding { return out } +// judgeAll judges a runtime directory by every VM library in it. The +// libraries are first judged as one runtime (an OpenJ9 runtime's +// redirector and VM are one VM, and the server VM speaks first). A +// directory can also hold libraries that are not that VM: a client or +// minimal VM, a Java 8 lib/amd64/server left by an upgrade in place, a file +// put in bin/server. Each other library that states a version or carries +// the decoder is judged on its own, and the worst verdict is the +// runtime's: a library that clears never hides one that does not. +func judgeAll(in Input, env map[string]string, root string, libs []*jvm.Library) Finding { + f := judge(in, env, root, libs) + worst := f + for _, l := range libs { + if l == f.Library || l.OpenJ9 || !l.HotSpot() && !l.VBMIStubs { + continue + } + if x := judge(in, env, root, []*jvm.Library{l}); rank(x.Status) > rank(worst.Status) { + worst = x + } + } + if worst.Library != f.Library { + worst.Reason += fmt.Sprintf("; this runtime holds %d VM libraries and the worst decides (%s alone: %s)", len(libs), f.Library.Path, f.Status) + } + return worst +} + +// rank orders verdicts from cleared to vulnerable. +func rank(s Status) int { + switch s { + case Vulnerable: + return 3 + case Mitigated: + return 2 + case Unknown: + return 1 + } + return 0 +} + func withFix(f Finding) Finding { v, ok := knowledge.Parse(f.Version) f.Fix = fixText(f, v, ok) diff --git a/detectors/java4shell/internal/assess/libraries_test.go b/detectors/java4shell/internal/assess/libraries_test.go new file mode 100644 index 0000000..3cc7295 --- /dev/null +++ b/detectors/java4shell/internal/assess/libraries_test.go @@ -0,0 +1,74 @@ +package assess + +import ( + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" +) + +// Final review B1: a runtime directory can hold several VM libraries +// (server, client, minimal, a Java 8 lib/amd64/server left behind by an +// upgrade in place, a file dropped into bin/server). Every library that +// states a version or carries the decoder is judged, and the worst verdict +// is the runtime's: one library that clears never hides another. +func TestEveryLibraryIsJudged(t *testing.T) { + const root = "/opt/java" + vuln21 := testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true} + for _, c := range []struct { + name string + libs map[string]testlib.Lib + release []string + want Status + decides string // the library the finding names + }{ + {"Java 8 left under lib/amd64, 21 in lib/server", map[string]testlib.Lib{"lib/amd64/server/libjvm.so": {Version: "1.8.0_452-b09"}, "lib/server/libjvm.so": vuln21}, + []string{"JAVA_VERSION", "21.0.13"}, Vulnerable, "lib/server/libjvm.so"}, + {"a fixed library in bin/server", map[string]testlib.Lib{"bin/server/libjvm.so": {Version: "17.0.21.1+2", VBMI: true}, "lib/server/libjvm.so": {Version: "17.0.21+9", VBMI: true}}, + nil, Vulnerable, "lib/server/libjvm.so"}, + {"fixed server, vulnerable minimal", map[string]testlib.Lib{"lib/server/libjvm.so": {Version: "21.0.13.1+2-LTS", VBMI: true}, "lib/minimal/libjvm.so": vuln21}, + nil, Vulnerable, "lib/minimal/libjvm.so"}, + {"aarch64 server, x86-64 client", map[string]testlib.Lib{"lib/server/libjvm.so": {Machine: "aarch64", Version: "21.0.13+9-LTS"}, "lib/client/libjvm.so": vuln21}, + nil, Vulnerable, "lib/client/libjvm.so"}, + {"fixed server, vulnerable lib/libjvm.so", map[string]testlib.Lib{"lib/server/libjvm.so": {Version: "21.0.13.1+2-LTS", VBMI: true}, "lib/libjvm.so": vuln21}, + nil, Vulnerable, "lib/libjvm.so"}, + {"17.0.5 server, 17.0.21 client", map[string]testlib.Lib{"lib/server/libjvm.so": {Version: "17.0.5+8"}, "lib/client/libjvm.so": {Version: "17.0.21+9", VBMI: true}}, + nil, Vulnerable, "lib/client/libjvm.so"}, + {"fixed server, a later update in client", map[string]testlib.Lib{"lib/server/libjvm.so": {Version: "21.0.13.1+2-LTS", VBMI: true}, "lib/client/libjvm.so": {Version: "21.0.14+1", VBMI: true}}, + nil, Unknown, "lib/client/libjvm.so"}, + // Nothing worse: the server library decides, as before. + {"two fixed libraries", map[string]testlib.Lib{"lib/server/libjvm.so": {Version: "21.0.13.1+2-LTS", VBMI: true}, "lib/client/libjvm.so": {Version: "21.0.13.1+2-LTS", VBMI: true}}, + nil, Fixed, "lib/server/libjvm.so"}, + {"two vulnerable libraries", map[string]testlib.Lib{"lib/server/libjvm.so": vuln21, "lib/client/libjvm.so": vuln21}, + nil, Vulnerable, "lib/server/libjvm.so"}, + } { + in := Input{Releases: map[string]jvm.Release{}} + for p, l := range c.libs { + in.Libraries = append(in.Libraries, lib(t, root+"/"+p, l)) + } + if c.release != nil { + in.Releases[root] = rel(t, c.release...) + } + f := one(t, in) + if f.Status != c.want || f.Library == nil || f.Library.Path != root+"/"+c.decides { + t.Errorf("%s: %s by %v, want %s by %s (%s)", c.name, f.Status, f.Library, c.want, c.decides, f.Reason) + } + if len(c.libs) > 1 && f.Library.Path != root+"/lib/server/libjvm.so" && !strings.Contains(f.Reason, "VM libraries") { + t.Errorf("%s: the reason does not say another library decided: %s", c.name, f.Reason) + } + } +} + +// An OpenJ9 runtime's libraries are one VM: its redirector and libj9vm +// are not judged apart. +func TestOpenJ9LibrariesAreOneVM(t *testing.T) { + const root = "/opt/java/openjdk" + in := Input{Releases: map[string]jvm.Release{root: rel(t, "JAVA_VERSION", "21.0.13", "JVM_VARIANT", "Openj9")}} + for _, p := range []string{"/lib/server/libjvm.so", "/lib/default/libjvm.so", "/lib/default/libj9vm29.so"} { + in.Libraries = append(in.Libraries, lib(t, root+p, testlib.Lib{Extra: "OPENJ9_JAVA_OPTIONS"})) + } + if f := one(t, in); f.Status != NotAffected { + t.Errorf("OpenJ9 runtime: %s (%s)", f.Status, f.Reason) + } +} From 72752590ac274cac3aaa1aee98c0105660008328 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:33:22 +0000 Subject: [PATCH 099/119] java4shell: a VM library that is a link to a file with another name makes the runtime unknown Final review B2. The walk hands a file out under its own name: a symbolic link is recorded and not followed, and a hard link in an image names a file read under the name of its first entry. A libjvm.so that is a link to libjvm.so.21, to hotspot.bin or to an object in an ostree store was never read, and the runtime gave no finding, no skip and exit 0. At the end of a scan every symbolic or hard link named like a VM library whose target was not read as one is reported: the runtime it belongs to is unknown when nothing else there was judged, and unknown instead of cleared when its other libraries would clear it. A link to a library that was read is judged there, and a link to nothing in an image is no runtime. Co-Authored-By: Claude Fable 5.2 --- .../java4shell/internal/assess/assess.go | 53 +++++++++- detectors/java4shell/java4shell.go | 44 +++++++- detectors/java4shell/links_internal_test.go | 100 ++++++++++++++++++ 3 files changed, 193 insertions(+), 4 deletions(-) create mode 100644 detectors/java4shell/links_internal_test.go diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index b28f16b..805fe90 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -86,6 +86,9 @@ type Input struct { UnreadAll bool // Owners maps installed files to the OS package that installed them. Owners map[string]Package + // Linked are VM library names that are links to a file the scan did + // not read as a VM library: the runtime there was not judged. + Linked []LinkedLibrary // OSID is the target's os-release ID (rhel, rocky, debian), "" when // it has none. OSID string @@ -93,6 +96,10 @@ type Input struct { Resolve func(string) string } +// LinkedLibrary is a VM library name that is a symbolic or hard link, and +// the file it leads to. +type LinkedLibrary struct{ Path, Target string } + // Run judges every runtime in the target. func Run(in Input) []Finding { byRoot := map[string][]*jvm.Library{} @@ -105,15 +112,34 @@ func Run(in Input) []Finding { } byRoot[root] = append(byRoot[root], l) } + linked := map[string][]LinkedLibrary{} + for _, l := range in.Linked { + root, ok := jvm.Root(l.Path) + if !ok { + root = path.Dir(l.Path) + } + linked[root] = append(linked[root], l) + } roots := make([]string, 0, len(byRoot)) for r := range byRoot { roots = append(roots, r) } + for r := range linked { + if _, ok := byRoot[r]; !ok { + roots = append(roots, r) + } + } sort.Strings(roots) env := jvm.EnvMap(in.Env) var out []Finding for _, r := range roots { - out = append(out, withFix(redHat(in, judgeAll(in, env, r, byRoot[r])))) + f := Finding{Kind: KindRuntime, Path: r} + if libs := byRoot[r]; len(libs) > 0 { + f = redHat(in, judgeAll(in, env, r, libs)) + } else if name, dir, ok := Product(r); ok { + f.Kind, f.Product, f.ProductDir = KindBundled, name, dir + } + out = append(out, withFix(notFollowed(f, linked[r]))) } for _, l := range loose { out = append(out, withFix(redHat(in, judge(in, env, path.Dir(l.Path), []*jvm.Library{l})))) @@ -146,6 +172,31 @@ func judgeAll(in Input, env map[string]string, root string, libs []*jvm.Library) return worst } +// notFollowed applies what a runtime's linked VM libraries leave open: a +// library that is a link to a file with another name was never read, so a +// runtime with nothing else to judge is unknown, and so is one its other +// libraries would clear. +func notFollowed(f Finding, links []LinkedLibrary) Finding { + if len(links) == 0 { + return f + } + sort.Slice(links, func(i, j int) bool { return links[i].Path < links[j].Path }) + why := fmt.Sprintf("its VM library %s is a link to %s, which the scan does not read as a VM library (a symbolic link is not followed, and a hard link in an image is read under the name of its first entry)", links[0].Path, links[0].Target) + if len(links) > 1 { + why += fmt.Sprintf(", and so are %d more", len(links)-1) + } + v, vok := knowledge.Parse(f.Version) + switch { + case f.Library == nil: + return f.set(Unknown, why+": the runtime was not checked", "Java runtime: its VM library is a link the scan did not follow") + case rank(f.Status) == 0: + f.Release = knowledge.Unknown + return f.set(Unknown, f.Reason+"; but "+why+": that library was not checked", describe(f, v, vok)+": one of its VM libraries is a link the scan did not follow") + } + f.Reason += "; " + why + return f +} + // rank orders verdicts from cleared to vulnerable. func rank(s Status) int { switch s { diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 1f92e9c..8e2e711 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -463,14 +463,15 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { if osr := osRelease(s.kept["/etc/os-release"], s.kept["/usr/lib/os-release"]); osr != "" { ctx.Annotate("java4shell_os", osr) } - if s.libs.len() == 0 { + links, hardlinks := ctx.Links() + res := resolver{links: links} + linked := s.linkedLibraries(ctx, res, links, hardlinks) + if s.libs.len() == 0 && len(linked) == 0 { if len(s.limits) > 0 { ctx.Problem("java4shell: the scan reached its limit on " + strings.Join(s.limits, " and ") + " for one target") } return nil } - links, hardlinks := ctx.Links() - res := resolver{links: links} owners := map[string]assess.Package{} for _, db := range []string{"/lib/apk/db/installed", "/usr/lib/apk/db/installed"} { if b := s.kept[db]; b != nil { @@ -495,6 +496,7 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { UnreadScripts: s.unreadScripts, UnreadDirs: s.unreadDirs, UnreadAll: s.unreadAll, + Linked: linked, } in.OSID = s.osID(ctx.Exists, res, hardlinks) if s.kind == engine.Image { @@ -563,6 +565,39 @@ func (s *scan) osID(exists func(string) bool, res resolver, hardlinks map[string return id } +// linkedLibraries lists the VM library names that are links to a file the +// scan did not read as a VM library. The walk hands a file out under its +// own name only: a symbolic link is recorded, not followed, and a hard +// link in an image names a file read under the name of its first entry. +// When that name is not a VM library's, the library was never read. A link +// to a library that was read is judged there, and a link to nothing in an +// image is no runtime. +func (s *scan) linkedLibraries(ctx engine.TargetContext, res resolver, links, hardlinks map[string]string) []assess.LinkedLibrary { + var out []assess.LinkedLibrary + add := func(p, to string) { + if s.libs.has(to) || s.kind == engine.Image && !ctx.Exists(to) { + return + } + if len(out) >= maxLibs { + s.limit(fmt.Sprintf("more than %d Java VM libraries", maxLibs)) + return + } + out = append(out, assess.LinkedLibrary{Path: p, Target: to}) + } + for p := range links { + if jvm.IsLibraryName(path.Base(p)) { + add(p, res.resolve(p)) + } + } + for p, to := range hardlinks { + if jvm.IsLibraryName(path.Base(p)) { + add(p, to) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path }) + return out +} + var verdicts = map[assess.Status]engine.Verdict{ assess.Vulnerable: engine.Vulnerable, assess.Fixed: engine.Fixed, @@ -786,6 +821,9 @@ func (l *pathList[T]) drop(p string) []T { func (l *pathList[T]) len() int { return l.live } +// has reports whether p added an item that was not dropped. +func (l *pathList[T]) has(p string) bool { return len(l.at[p]) > 0 } + // list returns the items not dropped, in the order added. func (l *pathList[T]) list() []T { out := make([]T, 0, l.live) diff --git a/detectors/java4shell/links_internal_test.go b/detectors/java4shell/links_internal_test.go new file mode 100644 index 0000000..27f0c31 --- /dev/null +++ b/detectors/java4shell/links_internal_test.go @@ -0,0 +1,100 @@ +package java4shell + +import ( + "archive/tar" + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// tarEntry is one entry of a docker export: a file, a symbolic link (link) +// or a hard link (hard). +type tarEntry struct { + name string + data []byte + link string + hard bool +} + +func exportOf(t *testing.T, es ...tarEntry) string { + t.Helper() + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, e := range es { + h := &tar.Header{Name: e.name, Mode: 0o755, Size: int64(len(e.data)), Typeflag: tar.TypeReg} + if e.link != "" { + h.Typeflag, h.Linkname = tar.TypeSymlink, e.link + if e.hard { + h.Typeflag = tar.TypeLink + } + } + if err := tw.WriteHeader(h); err != nil { + t.Fatal(err) + } + tw.Write(e.data) + } + tw.Close() + p := filepath.Join(t.TempDir(), "rootfs.tar") + if err := os.WriteFile(p, buf.Bytes(), 0o600); err != nil { + t.Fatal(err) + } + return "rootfs:" + p +} + +// Final review B2: a VM library that is a link to a file with another name +// is never read under its own name, so the scan cannot judge the runtime. +// It says so: the runtime is unknown, not absent. +func TestLibraryThatIsALink(t *testing.T) { + vuln := testlib.Build(testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true}) + fixed := testlib.Build(testlib.Lib{Version: "21.0.13.1+2-LTS", VBMI: true}) + const lib = "opt/jdk/lib/server/libjvm.so" + for _, c := range []struct { + name string + entries []tarEntry + want string // path verdict, ... + }{ + {"a hard link to another name", []tarEntry{{name: "opt/jdk/lib/server/hotspot.bin", data: vuln}, {name: lib, link: "opt/jdk/lib/server/hotspot.bin", hard: true}}, "/opt/jdk unknown"}, + {"a symbolic link to another name", []tarEntry{{name: "opt/jdk/lib/server/libjvm.so.21", data: vuln}, {name: lib, link: "libjvm.so.21"}}, "/opt/jdk unknown"}, + {"an object store", []tarEntry{{name: "sysroot/ostree/repo/objects/ab/cdef.file", data: vuln}, {name: "usr/lib/jvm/java-21/lib/server/libjvm.so", link: "sysroot/ostree/repo/objects/ab/cdef.file", hard: true}}, + "/usr/lib/jvm/java-21 unknown"}, + {"beside a fixed library", []tarEntry{{name: lib, data: fixed}, {name: "opt/jdk/lib/minimal/real", data: vuln}, {name: "opt/jdk/lib/minimal/libjvm.so", link: "real"}}, "/opt/jdk unknown"}, + {"beside a vulnerable library", []tarEntry{{name: lib, data: vuln}, {name: "opt/jdk/lib/minimal/real", data: fixed}, {name: "opt/jdk/lib/minimal/libjvm.so", link: "real"}}, "/opt/jdk vulnerable"}, + // A link to a library that is read under its own name is judged there. + {"a hard link to a library", []tarEntry{{name: lib, data: vuln}, {name: "opt/copy/lib/server/libjvm.so", link: lib, hard: true}}, "/opt/jdk vulnerable"}, + {"a symbolic link to a library", []tarEntry{{name: lib, data: vuln}, {name: "opt/jdk/lib/libjvm.so", link: "server/libjvm.so"}}, "/opt/jdk vulnerable"}, + // A link to nothing is no runtime. + {"a dangling link", []tarEntry{{name: "etc/hostname", data: []byte("x")}, {name: lib, link: "missing.so"}}, ""}, + } { + tg := engine.ScanImage([]engine.Detector{&Detector{}}, exportOf(t, c.entries...), engine.Options{}) + var got []string + for _, f := range tg.Findings { + got = append(got, f.Path+" "+string(f.Verdict)) + } + if tg.Error != "" || strings.Join(got, ", ") != c.want { + t.Errorf("%s: error %q findings [%s], want [%s]", c.name, tg.Error, strings.Join(got, ", "), c.want) + } + } + + // On a filesystem, where a hard link is a file read under each name, + // only the symbolic link is not followed. + root := t.TempDir() + dir := filepath.Join(root, "opt/jdk/lib/server") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "libjvm.so.21"), vuln, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink("libjvm.so.21", filepath.Join(dir, "libjvm.so")); err != nil { + t.Fatal(err) + } + tg := engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true}) + if len(tg.Findings) != 1 || tg.Findings[0].Verdict != engine.Unknown || tg.Findings[0].Path != "/opt/jdk" || !strings.Contains(tg.Findings[0].Reason, "libjvm.so.21") { + t.Errorf("filesystem: %+v", tg.Findings) + } +} From b55ad82a641893399abf29b0323e7c539d795733 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:33:52 +0000 Subject: [PATCH 100/119] java4shell: past the cap on VM libraries the scan clears nothing Final review B4. Every other cap marks the scan as capped (a problem on the target, and no verdict cleared). The cap on VM libraries, the one that leaves a runtime unjudged, only recorded a coverage gap: 4,096 small libraries of another architecture in front of a vulnerable JDK gave "no vulnerable findings" and exit 0. It is a limit like the others now. Co-Authored-By: Claude Fable 5.2 --- detectors/java4shell/java4shell.go | 4 ++- detectors/java4shell/links_internal_test.go | 30 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 8e2e711..52b7324 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -344,7 +344,9 @@ func (s *scan) Visit(f engine.File) []engine.Skip { case jvm.IsLibraryName(base): if l, ok := jvm.Inspect(f.Path, f.Data); ok { if s.libs.len() >= maxLibs { + // A runtime is left unjudged: the scan clears nothing. s.dropped++ + s.limit(fmt.Sprintf("more than %d Java VM libraries", maxLibs)) return []engine.Skip{{Path: f.Path, Reason: fmt.Sprintf("more than %d Java VM libraries in one target; not checked", maxLibs)}} } s.libs.add(f.Path, l) @@ -509,7 +511,7 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { cpu, haveCPU := thisCPU() capped := "" if len(s.limits) > 0 { - capped = "the scan reached its limit on " + strings.Join(s.limits, " and ") + " for one target, so package owners and JVM options may be missing: nothing is cleared" + capped = "the scan reached its limit on " + strings.Join(s.limits, " and ") + " for one target, so runtimes, package owners and JVM options may be missing: nothing is cleared" ctx.Problem("java4shell: " + capped) } var out []engine.Finding diff --git a/detectors/java4shell/links_internal_test.go b/detectors/java4shell/links_internal_test.go index 27f0c31..236beba 100644 --- a/detectors/java4shell/links_internal_test.go +++ b/detectors/java4shell/links_internal_test.go @@ -3,6 +3,7 @@ package java4shell import ( "archive/tar" "bytes" + "fmt" "os" "path/filepath" "strings" @@ -98,3 +99,32 @@ func TestLibraryThatIsALink(t *testing.T) { t.Errorf("filesystem: %+v", tg.Findings) } } + +// Final review B4: past the cap on VM libraries a runtime is dropped +// unjudged, so the scan is capped like any other: nothing is cleared, and +// the target carries a problem. +func TestLibraryCapClearsNothing(t *testing.T) { + root := t.TempDir() + other := testlib.Build(testlib.Lib{Machine: "aarch64", Version: "21.0.13+9-LTS"}) + for i := 0; i < maxLibs; i++ { + p := filepath.Join(root, "a", fmt.Sprintf("%04d", i), "lib/server/libjvm.so") + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, other, 0o644); err != nil { + t.Fatal(err) + } + } + p := filepath.Join(root, "opt/jdk/lib/server/libjvm.so") + os.MkdirAll(filepath.Dir(p), 0o755) + if err := os.WriteFile(p, testlib.Build(testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true}), 0o644); err != nil { + t.Fatal(err) + } + tg := engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true}) + if len(tg.Findings) != maxLibs || tg.Count(engine.Fixed) != 0 || tg.Count(engine.Unknown) != maxLibs { + t.Errorf("%d findings, %d cleared, %d unknown", len(tg.Findings), tg.Count(engine.Fixed), tg.Count(engine.Unknown)) + } + if len(tg.Problems) != 1 || !strings.Contains(tg.Problems[0], "Java VM libraries") || tg.Gaps() != 1 { + t.Errorf("problems %v gaps %d", tg.Problems, tg.Gaps()) + } +} From ba373e09cf369054622bcfb1382efe96133825d2 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:34:27 +0000 Subject: [PATCH 101/119] java4shell: one string does not make a runtime OpenJ9 Final review B3. A libjvm.so with no HotSpot version line and no decoder stubs that contains OPENJ9_JAVA_OPTIONS was taken as OpenJ9's redirector and the runtime was cleared, even under a release file that describes a vulnerable HotSpot build and with no OpenJ9 VM in the runtime. The string now needs a second witness: an OpenJ9 VM library by name (libj9vm) in the runtime, or a release file that names OpenJ9. Without one the runtime is unknown. Co-Authored-By: Claude Fable 5.2 --- .../java4shell/internal/assess/assess.go | 15 +++++++-- .../internal/assess/libraries_test.go | 31 +++++++++++++++++++ detectors/java4shell/internal/jvm/jvm.go | 9 +++++- 3 files changed, 51 insertions(+), 4 deletions(-) diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index 805fe90..bb6b7a8 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -261,16 +261,22 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi // OpenJ9 only from an OpenJ9 library (by name, or the redirector with // no HotSpot version line and no decoder stubs): the release file's // JVM_VARIANT alone does not decide it. + // A library that only carries the redirector's string needs a second + // witness: an OpenJ9 VM library by name, or the release file. relJ9 := hasRel && rel.OpenJ9() - openj9, stubs := false, false + named, redirector, stubs := false, false, false for _, l := range libs { - if l.OpenJ9 { - openj9 = true + switch { + case l.Redirector: + redirector = true + case l.OpenJ9: + named = true } if l.VBMIStubs { stubs = true } } + openj9 := named || redirector && relJ9 // The version: the VM library's own, the release file's otherwise. verText, from := "", "" @@ -310,6 +316,9 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi case openj9: return f.set(NotAffected, "an OpenJ9 VM: the vulnerable decoder is HotSpot code that OpenJ9 does not contain", what+" runs the OpenJ9 VM, not HotSpot") + case lib.Redirector: + return f.set(Unknown, "the VM library has no HotSpot version line and names OPENJ9_JAVA_OPTIONS, as OpenJ9's redirector does, but the runtime holds no OpenJ9 VM library (libj9vm) and its release file does not name OpenJ9: one string does not show which VM it is", + what+": not shown to be OpenJ9 or HotSpot") case len(lib.Archs) == 0 || len(lib.Archs) == 1 && lib.Archs[0] == jvm.Other: return f.set(Unknown, "the VM library's CPU architecture could not be read", what+": CPU architecture unknown") case !lib.Has(jvm.X8664): diff --git a/detectors/java4shell/internal/assess/libraries_test.go b/detectors/java4shell/internal/assess/libraries_test.go index 3cc7295..ce717ee 100644 --- a/detectors/java4shell/internal/assess/libraries_test.go +++ b/detectors/java4shell/internal/assess/libraries_test.go @@ -72,3 +72,34 @@ func TestOpenJ9LibrariesAreOneVM(t *testing.T) { t.Errorf("OpenJ9 runtime: %s (%s)", f.Status, f.Reason) } } + +// Final review B3: the string OPENJ9_JAVA_OPTIONS in a library without a +// version line does not make a runtime OpenJ9 on its own. It needs a second +// witness: an OpenJ9 VM library (libj9vm) in the runtime, or a release file +// that names OpenJ9. +func TestOpenJ9NeedsTwoWitnesses(t *testing.T) { + const root = "/opt/jdk" + redirector := func() *jvm.Library { + return lib(t, root+"/lib/server/libjvm.so", testlib.Lib{Extra: "OPENJ9_JAVA_OPTIONS"}) + } + for _, c := range []struct { + name string + libs []*jvm.Library + release []string + want Status + }{ + {"the string alone", []*jvm.Library{redirector()}, nil, Unknown}, + {"the string under a HotSpot release file", []*jvm.Library{redirector()}, []string{"JAVA_VERSION", "21.0.13", "IMPLEMENTOR", "Eclipse Adoptium"}, Unknown}, + {"the string under a fixed release file", []*jvm.Library{redirector()}, []string{"JAVA_VERSION", "21.0.13.1"}, Unknown}, + {"with a release file that names OpenJ9", []*jvm.Library{redirector()}, []string{"JAVA_VERSION", "21.0.13", "JVM_VARIANT", "Openj9"}, NotAffected}, + {"with an OpenJ9 VM library", []*jvm.Library{redirector(), lib(t, root+"/lib/default/libj9vm29.so", testlib.Lib{})}, nil, NotAffected}, + } { + in := Input{Libraries: c.libs, Releases: map[string]jvm.Release{}} + if c.release != nil { + in.Releases[root] = rel(t, c.release...) + } + if f := one(t, in); f.Status != c.want { + t.Errorf("%s: %s, want %s (%s)", c.name, f.Status, c.want, f.Reason) + } + } +} diff --git a/detectors/java4shell/internal/jvm/jvm.go b/detectors/java4shell/internal/jvm/jvm.go index 3166384..aafa610 100644 --- a/detectors/java4shell/internal/jvm/jvm.go +++ b/detectors/java4shell/internal/jvm/jvm.go @@ -47,6 +47,10 @@ type Library struct { VBMIStubs bool `json:"vbmi_stubs"` // OpenJ9 is true for an OpenJ9 VM library or redirector. OpenJ9 bool `json:"openj9,omitempty"` + // Redirector is true when only the redirector's string says so: the + // file is not named as an OpenJ9 VM library. One string is not proof; + // the verdict asks for a second witness. + Redirector bool `json:"openj9_redirector,omitempty"` // Variant is the VM directory: server, client, minimal, zero, j9vm... Variant string `json:"variant,omitempty"` } @@ -111,8 +115,11 @@ func Inspect(p string, data []byte) (*Library, bool) { // OpenJ9: its VM library by name, or its lib/server redirector, which // has no HotSpot version line, no HotSpot decoder stubs and names // OPENJ9_JAVA_OPTIONS. - if IsOpenJ9Name(base) || l.VMName == "" && !l.VBMIStubs && bytes.Contains(b, []byte("OPENJ9_JAVA_OPTIONS")) { + switch { + case IsOpenJ9Name(base): l.OpenJ9 = true + case l.VMName == "" && !l.VBMIStubs && bytes.Contains(b, []byte("OPENJ9_JAVA_OPTIONS")): + l.OpenJ9, l.Redirector = true, true } return l, true } From aa476254ac07e1a2ce757090cc972fa356315e3c Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:36:58 +0000 Subject: [PATCH 102/119] java4shell: no mitigation is reported past a start script that was not read, however the command reaches it Final review B5. The rule that a mitigation is not reported when the container's start script was not read looked at the command's own words only. With a 310 KiB start script it still said "mitigated" for sh -c "exec /app/start.sh", for a relative path after cd, for a name looked up in PATH behind tini, and for a small script that runs the big one. A start script that was read and itself passes -XX:+UseBASE64Intrinsics was reported as mitigated too. The scan now keeps, for each script it reads, the set of words in it (2,048 bits, so a script is remembered by what it names) and whether it passes an option that turns the decoder back on. A script is reached when the command names it by path or by file name, in any word or shell text, or when a reached script does. No mitigation is reported when a reached script was not read or turns the decoder on, or when there were more scripts than the scan records and the command is not java itself. The verdict was vulnerable in every case and still is; this is the status. Co-Authored-By: Claude Fable 5.2 --- .../java4shell/internal/assess/assess.go | 14 +- .../java4shell/internal/assess/startscript.go | 145 ++++++++++++++++++ .../internal/assess/startscript_test.go | 66 ++++++++ detectors/java4shell/java4shell.go | 28 +++- .../java4shell/startscript_internal_test.go | 80 ++++++++++ 5 files changed, 328 insertions(+), 5 deletions(-) create mode 100644 detectors/java4shell/internal/assess/startscript.go create mode 100644 detectors/java4shell/internal/assess/startscript_test.go create mode 100644 detectors/java4shell/startscript_internal_test.go diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index bb6b7a8..d3f1445 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -84,6 +84,13 @@ type Input struct { // files than were recorded. UnreadDirs []string UnreadAll bool + // ScriptWords holds, for each script that was read, the words in it: + // what it may run. UndoScripts are those that pass an option turning + // the decoder back on (the option is the value). ScriptsOver is set + // when there were more scripts than were recorded. + ScriptWords map[string]WordSet + UndoScripts map[string]string + ScriptsOver bool // Owners maps installed files to the OS package that installed them. Owners map[string]Package // Linked are VM library names that are links to a file the scan did @@ -355,7 +362,7 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi bs, bwhy := judgeBackport(v) f.Release = bs if bs == knowledge.Vulnerable { - if ok, how := mitigation(in, env, root, v.Feature(), &f); ok && unreadCommandScript(in) == "" { + if ok, how := mitigation(in, env, root, v.Feature(), &f); ok && mitigationVoid(in) == "" { f.Mitigation = how return f.set(Mitigated, bwhy+"; "+how, what+" carries a backported AVX-512 VBMI Base64 decoder without the fix, mitigated by its JVM options until it is updated") } @@ -381,9 +388,8 @@ func judge(in Input, env map[string]string, root string, libs []*jvm.Library) Fi kwhy += " (judged by the release file: no HotSpot version line was found in the VM library)" } if ok, how := mitigation(in, env, root, v.Feature(), &f); ok { - if u := unreadCommandScript(in); u != "" { - return f.set(Vulnerable, kwhy+"; "+how+", but the container's start script "+u+" was not read (larger than the scan reads) and can pass an option that undoes it", - what+" is vulnerable to Java4Shell") + if void := mitigationVoid(in); void != "" { + return f.set(Vulnerable, kwhy+"; "+how+", but "+void, what+" is vulnerable to Java4Shell") } f.Mitigation = how return f.set(Mitigated, kwhy+"; "+how, what+" is vulnerable to Java4Shell, mitigated by its JVM options until it is updated") diff --git a/detectors/java4shell/internal/assess/startscript.go b/detectors/java4shell/internal/assess/startscript.go new file mode 100644 index 0000000..b408a4b --- /dev/null +++ b/detectors/java4shell/internal/assess/startscript.go @@ -0,0 +1,145 @@ +package assess + +import ( + "fmt" + "path" + "sort" + "strings" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" +) + +// WordSet is the set of words a start script holds, kept small: a script +// is remembered by what it names, not by its text. A word is a run of +// letters, digits and "_.+-" (so every component of a path is one). The +// set can say a word is there when it is not, never the reverse, which is +// the safe side for its one use: deciding that a script may run another. +type WordSet [32]uint64 + +func nameByte(c byte) bool { + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '.' || c == '+' || c == '-' +} + +// WordsOf returns the words of a script's text, or of a command line. +func WordsOf(text []byte) WordSet { + var ws WordSet + for i := 0; i < len(text); { + if !nameByte(text[i]) { + i++ + continue + } + j := i + for j < len(text) && nameByte(text[j]) { + j++ + } + ws.add(text[i:j]) + i = j + } + return ws +} + +func wordBits(w []byte) [3]uint { + h := uint64(14695981039346656037) // FNV-1a + for _, c := range w { + h = (h ^ uint64(c)) * 1099511628211 + } + return [3]uint{uint(h % 2048), uint((h >> 21) % 2048), uint((h >> 42) % 2048)} +} + +func (ws *WordSet) add(w []byte) { + for _, b := range wordBits(w) { + ws[b/64] |= 1 << (b % 64) + } +} + +// Has reports whether w may be in the set. +func (ws *WordSet) Has(w string) bool { + if w == "" { + return false + } + for _, b := range wordBits([]byte(w)) { + if ws[b/64]&(1<<(b%64)) == 0 { + return false + } + } + return true +} + +func (ws *WordSet) merge(o WordSet) { + for i := range ws { + ws[i] |= o[i] + } +} + +// names reports whether the set holds the file name of p. A name with a +// character no word has cannot be looked up: it is taken as named. +func (ws *WordSet) names(p string) bool { + b := path.Base(p) + for i := 0; i < len(b); i++ { + if !nameByte(b[i]) { + return true + } + } + return ws.Has(b) +} + +// mitigationVoid says why a mitigation the image's options give cannot be +// reported: the container's command reaches a start script that was not +// read, which can pass an option that undoes it, or one that was read and +// does. "" when nothing does. +// +// A script is reached when the command names it, in any word or inside a +// shell text, by path or by file name alone (a name looked up in PATH, a +// path relative to a directory the scan cannot place), or when a script +// that is reached names it the same way. Going by file names reaches too +// much rather than too little. +func mitigationVoid(in Input) string { + if len(in.Command) == 0 { + return "" + } + if u := unreadCommandScript(in); u != "" { + return "the container's start script " + u + " was not read (larger than the scan reads) and can pass an option that undoes it" + } + reached := WordsOf([]byte(strings.Join(jvm.CommandWords(in.Command), " "))) + if in.ScriptsOver && path.Base(in.Command[0]) != "java" { + return "the target holds more start scripts than the scan records, and one the container's command runs can pass an option that undoes it" + } + // Every script the command reaches, through the scripts it reaches. + seen := map[string]bool{} + for changed, rounds := true, 0; changed && rounds < 64; rounds++ { + changed = false + for p, ws := range in.ScriptWords { + if !seen[p] && reached.names(p) { + seen[p], changed = true, true + reached.merge(ws) + } + } + } + for _, u := range sortedKeys(in.UnreadScripts) { + if reached.names(u) { + return "the start script " + u + ", which the container's command can reach, was not read (larger than the scan reads) and can pass an option that undoes it" + } + } + undo := make([]string, 0, len(in.UndoScripts)) + for p := range in.UndoScripts { + undo = append(undo, p) + } + sort.Strings(undo) + for _, p := range undo { + if reached.names(p) { + return fmt.Sprintf("the script %s, which the container's command can reach, passes %s, which turns the decoder back on", p, in.UndoScripts[p]) + } + } + return "" +} + +func sortedKeys(m map[string]bool) []string { + out := make([]string, 0, len(m)) + for k, v := range m { + if v { + out = append(out, k) + } + } + sort.Strings(out) + return out +} diff --git a/detectors/java4shell/internal/assess/startscript_test.go b/detectors/java4shell/internal/assess/startscript_test.go new file mode 100644 index 0000000..a698931 --- /dev/null +++ b/detectors/java4shell/internal/assess/startscript_test.go @@ -0,0 +1,66 @@ +package assess + +import ( + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" +) + +// Final review B5: a mitigation is not reported when a start script the +// command reaches was not read, however the command reaches it (a shell +// text, a name looked up in PATH, a relative path, a script that another +// script runs), or when a script it reaches turns the decoder back on. +// The verdict is vulnerable either way; this is about the status. +func TestMitigationAndTheWaysToAStartScript(t *testing.T) { + const big = "/app/start.sh" // not read + entry := WordsOf([]byte("#!/bin/sh\ncd /app\nexec ./start.sh \"$@\"\n")) + other := WordsOf([]byte("#!/bin/sh\nexec /usr/bin/something-else\n")) + for _, c := range []struct { + name string + cmd []string + scripts map[string]WordSet // read scripts + unread []string + undo map[string]string + want Status + says string + }{ + {"the script itself", []string{big}, nil, []string{big}, nil, Vulnerable, big + " was not read"}, + {"a shell text", []string{"sh", "-c", "exec /app/start.sh"}, nil, []string{big}, nil, Vulnerable, "was not read"}, + {"a shell text with arguments", []string{"sh", "-c", "/app/start.sh --flag"}, nil, []string{big}, nil, Vulnerable, big}, + {"a relative path in a shell text", []string{"/bin/bash", "-c", "cd /app && ./start.sh"}, nil, []string{big}, nil, Vulnerable, big}, + {"a name looked up in PATH", []string{"tini", "--", "start.sh"}, nil, []string{big}, nil, Vulnerable, big}, + {"a script that a read script runs", []string{"/entry.sh"}, map[string]WordSet{"/entry.sh": entry}, []string{big}, nil, Vulnerable, big}, + {"two scripts deep", []string{"/init"}, map[string]WordSet{"/init": WordsOf([]byte("#!/bin/sh\nexec /entry.sh\n")), "/entry.sh": entry}, []string{big}, nil, Vulnerable, big}, + {"more scripts than recorded", []string{"/entry.sh"}, nil, nil, nil, Vulnerable, "more start scripts"}, + {"a read script that turns the decoder on", []string{big}, map[string]WordSet{big: entry}, nil, map[string]string{big: "-XX:+UseBASE64Intrinsics"}, Vulnerable, "passes -XX:+UseBASE64Intrinsics"}, + {"reached through another script", []string{"/entry.sh"}, map[string]WordSet{"/entry.sh": entry, big: other}, nil, map[string]string{big: "-XX:UseAVX=3"}, Vulnerable, "passes -XX:UseAVX=3"}, + // What the command does not reach changes nothing. + {"an unread script nothing runs", []string{"/entry.sh"}, map[string]WordSet{"/entry.sh": other}, []string{big}, nil, Mitigated, ""}, + {"a script nothing runs turns the decoder on", []string{"/entry.sh"}, map[string]WordSet{"/entry.sh": other, big: other}, nil, map[string]string{big: "-XX:+UseBASE64Intrinsics"}, Mitigated, ""}, + {"java itself", []string{"java", "-jar", "/app/app.jar"}, nil, []string{big}, nil, Mitigated, ""}, + } { + in := Input{Libraries: []*jvm.Library{vulnLib(t, temurin)}, Env: []string{"JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics", "PATH=/app:/usr/bin"}, + Command: c.cmd, ScriptWords: c.scripts, UndoScripts: c.undo, UnreadScripts: map[string]bool{}} + for _, u := range c.unread { + in.UnreadScripts[u] = true + } + in.ScriptsOver = c.name == "more scripts than recorded" + f := one(t, in) + if f.Status != c.want || !strings.Contains(f.Reason, c.says) { + t.Errorf("%s: %s, want %s saying %q (%s)", c.name, f.Status, c.want, c.says, f.Reason) + } + } +} + +func TestWordSet(t *testing.T) { + ws := WordsOf([]byte("#!/bin/sh\nexec \"$APP_HOME\"/bin/start-app.sh --port=8080 >>/var/log/app.log\n. ./lib/common.sh\n")) + for _, w := range []string{"sh", "start-app.sh", "common.sh", "app.log", "exec"} { + if !ws.Has(w) { + t.Errorf("%q not in the set", w) + } + } + if ws.Has("catalina.sh") || ws.Has("") { + t.Error("a word that is not there") + } +} diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 52b7324..138df82 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -211,6 +211,8 @@ func (s *scan) Forget(p string) { s.osUnread = false } delete(s.scripts, p) + delete(s.scriptWords, p) + delete(s.undoScripts, p) delete(s.unreadScripts, p) delete(s.overSettings, p) if path.Base(p) == "release" { @@ -252,6 +254,10 @@ func (s *scan) VisitHead(p string, head []byte) { } } +// undoOption is an option in a script's text that turns the decoder back +// on for the java it starts: the intrinsic on, or AVX-512 allowed. +var undoOption = regexp.MustCompile(`-XX:\+UseBASE64Intrinsics\b|-XX:UseBASE64Intrinsics=true\b|-XX:UseAVX=(?:[3-9]|[1-9][0-9]+)\b`) + func isScript(head []byte) bool { return len(head) > 2 && head[0] == '#' && head[1] == '!' } // keep reports the package databases owners are read from. @@ -294,7 +300,8 @@ const ( // NewScan starts a filesystem or image scan. func (d *Detector) NewScan(kind engine.TargetKind) engine.Scan { return &scan{kind: kind, releases: map[string]jvm.Release{}, badReleases: map[string]string{}, - kept: map[string][]byte{}, lists: map[string][]byte{}, scripts: map[string]map[string]bool{}, unreadScripts: map[string]bool{}, overSettings: map[string]bool{}} + kept: map[string][]byte{}, lists: map[string][]byte{}, scripts: map[string]map[string]bool{}, unreadScripts: map[string]bool{}, overSettings: map[string]bool{}, + scriptWords: map[string]assess.WordSet{}, undoScripts: map[string]string{}} } type scan struct { @@ -315,6 +322,12 @@ type scan struct { unreadScripts map[string]bool unreadDirs []string unreadAll bool + // scriptWords holds the words of each script read (what it may run), + // undoScripts the option a script passes that turns the decoder back + // on; scriptsOver stands for more scripts than were recorded. + scriptWords map[string]assess.WordSet + undoScripts map[string]string + scriptsOver bool // overSettings are JVM settings files not read. overSettings map[string]bool // osUnread is set when /etc/os-release was met and not read. @@ -433,6 +446,16 @@ func (s *scan) Visit(f engine.File) []engine.Skip { } } if isScript(f.Data) && len(f.Data) <= maxScript { + // What the script may run, and whether it turns the decoder back + // on: a mitigation is not reported past either (assess). + if len(s.scriptWords) >= maxScripts { + s.scriptsOver = true + } else { + s.scriptWords[f.Path] = assess.WordsOf(f.Data) + if m := undoOption.Find(f.Data); m != nil { + s.undoScripts[f.Path] = string(m) + } + } vars := map[string]bool{} for _, n := range jvm.ScriptVars { if bytes.Contains(f.Data, []byte("$"+n)) || bytes.Contains(f.Data, []byte("${"+n)) { @@ -498,6 +521,9 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { UnreadScripts: s.unreadScripts, UnreadDirs: s.unreadDirs, UnreadAll: s.unreadAll, + ScriptWords: s.scriptWords, + UndoScripts: s.undoScripts, + ScriptsOver: s.scriptsOver, Linked: linked, } in.OSID = s.osID(ctx.Exists, res, hardlinks) diff --git a/detectors/java4shell/startscript_internal_test.go b/detectors/java4shell/startscript_internal_test.go new file mode 100644 index 0000000..b7fdfa3 --- /dev/null +++ b/detectors/java4shell/startscript_internal_test.go @@ -0,0 +1,80 @@ +package java4shell + +import ( + "archive/tar" + "bytes" + "io" + "path/filepath" + "testing" + + "github.com/google/go-containerregistry/pkg/name" + v1 "github.com/google/go-containerregistry/pkg/v1" + "github.com/google/go-containerregistry/pkg/v1/empty" + "github.com/google/go-containerregistry/pkg/v1/mutate" + "github.com/google/go-containerregistry/pkg/v1/tarball" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// Final review B5, through an image: JAVA_TOOL_OPTIONS turns the decoder +// off, and the command reaches a start script that was not read (310 KiB), +// or one that turns it back on. No route to the script reports a +// mitigation. +func TestMitigationNeedsTheStartScript(t *testing.T) { + lib := testlib.Build(testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true}) + big := append([]byte("#!/bin/sh\n"), bytes.Repeat([]byte("# pad\n"), 310<<10/6)...) + big = append(big, "exec java -XX:+UseBASE64Intrinsics -jar /app/app.jar\n"...) + undoes := []byte("#!/bin/sh\nexec java -XX:+UseBASE64Intrinsics -jar /app/app.jar\n") + plain := []byte("#!/bin/sh\nexec java -jar /app/app.jar\n") + image := func(script []byte, cmd ...string) string { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for n, b := range map[string][]byte{"opt/jdk/lib/server/libjvm.so": lib, "app/start.sh": script, "entry.sh": []byte("#!/bin/sh\ncd /app && exec ./start.sh\n")} { + tw.WriteHeader(&tar.Header{Name: n, Mode: 0o755, Size: int64(len(b)), Typeflag: tar.TypeReg}) + tw.Write(b) + } + tw.Close() + b := buf.Bytes() + l, err := tarball.LayerFromOpener(func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(b)), nil }) + if err != nil { + t.Fatal(err) + } + img, err := mutate.AppendLayers(empty.Image, l) + if err != nil { + t.Fatal(err) + } + img, err = mutate.Config(img, v1.Config{Cmd: cmd, Env: []string{"JAVA_TOOL_OPTIONS=-XX:-UseBASE64Intrinsics", "PATH=/app:/usr/bin"}}) + if err != nil { + t.Fatal(err) + } + p := filepath.Join(t.TempDir(), "image.tar") + if err := tarball.WriteToFile(p, name.MustParseReference("test/j:1"), img); err != nil { + t.Fatal(err) + } + return "docker-archive:" + p + } + for _, c := range []struct { + name string + script []byte + cmd []string + want string + }{ + {"unread, run directly", big, []string{"/app/start.sh"}, "vulnerable"}, + {"unread, in a shell text", big, []string{"sh", "-c", "exec /app/start.sh"}, "vulnerable"}, + {"unread, in a shell text with a flag", big, []string{"sh", "-c", "/app/start.sh --flag"}, "vulnerable"}, + {"unread, by a relative path", big, []string{"/bin/bash", "-c", "cd /app && ./start.sh"}, "vulnerable"}, + {"unread, by a name in PATH", big, []string{"tini", "--", "start.sh"}, "vulnerable"}, + {"unread, run by a script that was read", big, []string{"/entry.sh"}, "vulnerable"}, + {"read, and it turns the decoder on", undoes, []string{"/app/start.sh"}, "vulnerable"}, + {"read, turns it on, run by another script", undoes, []string{"/entry.sh"}, "vulnerable"}, + {"read, and it passes nothing", plain, []string{"/app/start.sh"}, "mitigated"}, + {"read, passes nothing, in a shell text", plain, []string{"sh", "-c", "exec /app/start.sh"}, "mitigated"}, + {"unread, and the command is java", big, []string{"java", "-jar", "/app/app.jar"}, "mitigated"}, + } { + tg := engine.ScanImage([]engine.Detector{&Detector{}}, image(c.script, c.cmd...), engine.Options{}) + if tg.Error != "" || len(tg.Findings) != 1 || tg.Findings[0].Verdict != engine.Vulnerable || tg.Findings[0].Facts["status"] != c.want { + t.Errorf("%s: error %q findings %+v", c.name, tg.Error, tg.Findings) + } + } +} From 80ac050a61dd8bfb03adb37c75b428495709cb04 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:40:37 +0000 Subject: [PATCH 103/119] java4shell, refs: a RUN that installs Java is read the way the builder reads it Final review B6 (Dockerfile RUN). The source-tree scan joined RUN lines itself, and an install was missed, with no finding and exit 0, when the continuation held a comment or a blank line, after a tab, in exec form, in a heredoc, under ONBUILD, with a backtick escape, inside a subshell or a group, behind sh -c, with a redirect written onto the package name, with aptitude, or when the package name came from an ARG or ENV of the file. internal/refs now gives its Dockerfile instructions to detectors (Instructions: continuation lines joined as BuildKit joins them, the escape directive, flags, JSON arguments, heredoc bodies, ONBUILD), and java4shell reads RUN from them. Shell texts are unwrapped, ARG and ENV values of the file are put in, and an install whose package names the file does not give (a variable without a value, a command's output) is recorded as not checked. A Dockerfile the parser refuses is not checked either. Co-Authored-By: Claude Fable 5.2 --- .../java4shell/internal/repo/final_test.go | 67 ++++++ detectors/java4shell/internal/repo/repo.go | 197 +++++++++++++++--- internal/refs/dockerfile.go | 7 + internal/refs/instructions.go | 63 ++++++ internal/refs/instructions_test.go | 48 +++++ 5 files changed, 353 insertions(+), 29 deletions(-) create mode 100644 detectors/java4shell/internal/repo/final_test.go create mode 100644 internal/refs/instructions.go create mode 100644 internal/refs/instructions_test.go diff --git a/detectors/java4shell/internal/repo/final_test.go b/detectors/java4shell/internal/repo/final_test.go new file mode 100644 index 0000000..6ad1098 --- /dev/null +++ b/detectors/java4shell/internal/repo/final_test.go @@ -0,0 +1,67 @@ +package repo + +import ( + "context" + "fmt" + "strings" + "testing" +) + +// got lists a scan's findings as "file:line rule status" and its skips as +// "skip file:line". +func got(t *testing.T, dir string) []string { + t.Helper() + res, err := Scan(context.Background(), dir, Options{}) + if err != nil { + t.Fatal(err) + } + var out []string + for _, f := range res.Findings { + out = append(out, fmt.Sprintf("%s:%d %s %s", f.File, f.Line, f.Rule, f.Status)) + } + for _, s := range res.Skips { + out = append(out, fmt.Sprintf("skip %s:%d", s.File, s.Line)) + } + return out +} + +// Final review B6: a RUN that installs an OpenJDK package is read the way +// the builder reads it, whatever its form; an install whose package names +// this file does not give is a gap, not silence. +func TestRunForms(t *testing.T) { + const vuln = "Dockerfile:2 os-package vulnerable" + for name, c := range map[string]struct{ df, want string }{ + "plain": {"FROM debian:12\nRUN apt-get install -y openjdk-17-jdk\n", vuln}, + "a comment in a continuation": {"FROM debian:12\nRUN apt-get update && \\\n # install java\n apt-get install -y openjdk-17-jdk\n", vuln}, + "a comment between packages": {"FROM debian:12\nRUN apt-get install -y curl \\\n # java\n openjdk-17-jdk \\\n git\n", vuln}, + "a blank line": {"FROM debian:12\nRUN apt-get update && \\\n\n apt-get install -y openjdk-17-jdk\n", vuln}, + "a tab after RUN": {"FROM debian:12\nRUN\tapt-get install -y openjdk-17-jdk\n", vuln}, + "exec form": {"FROM debian:12\nRUN [\"apt-get\", \"install\", \"-y\", \"openjdk-17-jdk\"]\n", vuln}, + "exec form of a shell": {"FROM debian:12\nRUN [\"/bin/sh\", \"-c\", \"apt-get update && apt-get install -y openjdk-17-jdk\"]\n", vuln}, + "a heredoc": {"FROM debian:12\nRUN </dev/null 2>&1\n", vuln}, + "aptitude": {"FROM debian:12\nRUN aptitude install -y openjdk-17-jdk\n", vuln}, + "the name in an ARG": {"FROM debian:12\nARG JDK=openjdk-17-jdk\nRUN apt-get install -y ${JDK}\n", "Dockerfile:3 os-package vulnerable"}, + "the name in an ENV": {"FROM debian:12\nENV JAVA_PKG=openjdk-17-jdk\nRUN apt-get install -y \"$JAVA_PKG\"\n", "Dockerfile:3 os-package vulnerable"}, + "an ARG default in braces": {"FROM debian:12\nRUN apt-get install -y ${JDK:-openjdk-17-jdk}\n", vuln}, + "an ARG without a value": {"FROM debian:12\nARG PKGS\nRUN apt-get install -y $PKGS\n", "skip Dockerfile:3"}, + "a command's output": {"FROM debian:12\nRUN apt-get install -y $(cat packages.txt)\n", "skip Dockerfile:2"}, + "apk with a range": {"FROM alpine:3.22\nRUN apk add --no-cache 'openjdk17>17.0.6'\n", vuln}, + // Not an install, and not Java: nothing. + "another package": {"FROM debian:12\nRUN apt-get install -y curl ca-certificates\n", ""}, + "a flag from a variable": {"FROM debian:12\nRUN apt-get install -y $APT_FLAGS curl\n", "skip Dockerfile:2"}, + "a version from a variable": {"FROM debian:12\nRUN apt-get install -y openjdk-17-jdk=${JDK_VERSION}\n", "Dockerfile:2 os-package unknown"}, + "a query": {"FROM debian:12\nRUN rpm -q java-17-openjdk\n", ""}, + "an unterminated heredoc": {"FROM debian:12\nRUN <<]+)([^\s;&|]+))?`) rpmJava = regexp.MustCompile(`\b(java-(\d{1,2})-(openjdk|amazon-corretto)(?:-headless|-devel|-jdk)?)(?:-(\d[\w.:*?+~-]*))?`) @@ -956,7 +967,16 @@ var ( ) func (s *scanner) dockerfile(rel, text string) { - ls := lines(text) + // The instructions as the builder reads them: continuation lines joined + // (comment and blank lines inside one dropped), the escape directive, + // JSON arguments, heredoc bodies, ONBUILD. + ins, err := refs.Instructions([]byte(text)) + if err != nil { + // The image reference scan records the same file when it cannot + // parse it: one record (scanList). + s.unparsed = append(s.unparsed, Skip{File: rel, Reason: "the Dockerfile could not be parsed (" + refs.CleanText(err.Error(), 120) + "): the packages it installs are not checked"}) + return + } from := 0 stageStart := len(s.findings) // endStage marks the packages a stage installs as mitigated when the @@ -983,47 +1003,80 @@ func (s *scanner) dockerfile(rel, text string) { } } defer endStage() - for i := 0; i < len(ls); i++ { - l := ls[i] - // Join continuation lines for matching; report the first line. - full := l - j := i - for strings.HasSuffix(strings.TrimRight(ls[j], " \t"), "\\") && j+1 < len(ls) { - j++ - full = strings.TrimSuffix(strings.TrimRight(full, " \t"), "\\") + " " + ls[j] - } - trim := strings.TrimSpace(full) - switch { - case fromLine.MatchString(trim): + // vars are the ARG defaults and ENV values the file sets, for package + // names a RUN takes from a variable. + vars := map[string]string{} + for _, in := range ins { + switch in.Cmd { + case "from": endStage() - from, stageStart, stageEnv, stageCmd = i+1, len(s.findings), map[string]string{}, nil - case cmdLine.MatchString(trim): - stageCmd = append(stageCmd, commandWords(cmdLine.ReplaceAllString(trim, ""))...) - case envJTO.MatchString(trim): + from, stageStart, stageEnv, stageCmd = in.Line, len(s.findings), map[string]string{}, nil + case "cmd", "entrypoint": + stageCmd = append(stageCmd, commandWords(in.Args)...) + case "arg": + for _, kv := range jvm.Words(in.Args) { + if k, v, ok := strings.Cut(kv, "="); ok { + vars[k] = v + } + } + case "env": // The last ENV of each variable in the stage is what the // image keeps; the mitigation is decided when the stage ends. - body := envJTO.ReplaceAllString(trim, "") - for _, kv := range jvm.Words(body) { + for _, kv := range jvm.Words(in.Args) { if k, v, ok := strings.Cut(kv, "="); ok { - stageEnv[k] = v + stageEnv[k], vars[k] = v, v } } - case strings.HasPrefix(strings.ToUpper(trim), "RUN "): - s.packages(rel, i+1, trim) + case "run": + run := in.Args + if in.JSON != nil { + run = strings.Join(jvm.CommandWords(in.JSON), " ") + } + s.packages(rel, in.Line, run, vars) + for _, body := range in.Heredocs { + s.packages(rel, in.Line, heredocCommands(body), vars) + } } - i = j } } +// heredocCommands turns a heredoc's script into one command line: comment +// lines dropped, continuation lines joined, lines separated by ";". +func heredocCommands(body string) string { + var out []string + cur := "" + for _, l := range lines(body) { + t := strings.TrimSpace(l) + if cur == "" && (t == "" || strings.HasPrefix(t, "#")) { + continue + } + if strings.HasSuffix(t, "\\") { + cur += strings.TrimSuffix(t, "\\") + " " + continue + } + out = append(out, cur+t) + cur = "" + } + if cur != "" { + out = append(out, cur) + } + return strings.Join(out, " ; ") +} + // packages finds the OpenJDK packages a RUN line installs: distribution // packages and the vendors' own (Temurin, Corretto, Zulu, Microsoft, // SapMachine), with or without a version. -func (s *scanner) packages(rel string, line int, run string) { +func (s *scanner) packages(rel string, line int, run string, vars map[string]string) { if !installRE.MatchString(run) { return } var hits []pkgHit - for _, arg := range installArgs(run) { + var opaque []string + for _, arg := range installArgs(expandVars(run, vars), 0) { + if strings.HasPrefix(arg, opaqueArg) { + opaque = append(opaque, strings.TrimPrefix(arg, opaqueArg)) + continue + } fromFile := strings.HasPrefix(arg, fileArg) arg = strings.TrimPrefix(arg, fileArg) before := len(hits) @@ -1087,6 +1140,38 @@ func (s *scanner) packages(rel string, line int, run string) { for _, h := range hits { s.judgePackage(rel, line, h) } + if len(opaque) > 0 { + // The package list is not in this file: a gap, not a finding + // about Java. + s.skips = append(s.skips, Skip{File: rel, Line: line, Reason: fmt.Sprintf("installs packages named by %s, which this file does not set (a variable without a value here, or a command's output): not checked for Java packages", + refs.CleanText(strings.Join(opaque, " "), 120))}) + } +} + +// opaqueArg marks an install argument whose package names this scan +// cannot read: a variable the file does not set, or a command's output. +const opaqueArg = "\x00opaque:" + +var varRef = regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}|\$([A-Za-z_][A-Za-z0-9_]*)`) + +// expandVars puts in the values the Dockerfile's ARG and ENV lines give +// (${NAME}, $NAME, ${NAME:-default}); a variable the file does not set +// stays as written. +func expandVars(run string, vars map[string]string) string { + if !strings.Contains(run, "$") { + return run + } + return varRef.ReplaceAllStringFunc(run, func(m string) string { + g := varRef.FindStringSubmatch(m) + name := g[1] + g[3] + if v, ok := vars[name]; ok && v != "" { + return v + } + if g[2] != "" { + return g[2] + } + return m + }) } // anchored matches the whole of one argument. @@ -1107,7 +1192,7 @@ var ( ) var ( - pkgTools = map[string]bool{"apt-get": true, "apt": true, "apk": true, "dnf": true, "dnf5": true, "yum": true, "microdnf": true, "tdnf": true, "zypper": true, "rpm": true, "dpkg": true} + pkgTools = map[string]bool{"apt-get": true, "aptitude": true, "apt": true, "apk": true, "dnf": true, "dnf5": true, "yum": true, "microdnf": true, "tdnf": true, "zypper": true, "rpm": true, "dpkg": true} pkgVerbs = map[string]bool{"install": true, "add": true, "in": true, "reinstall": true, "localinstall": true} // pkgValueFlags are package-manager options followed by a separate value. pkgValueFlags = map[string]bool{"-t": true, "-o": true, "-X": true, "--repository": true, "--virtual": true, "-c": true, "--root": true, @@ -1246,10 +1331,27 @@ func vendorFileVersion(name string) string { // installArgs returns the package arguments of the install commands on a // RUN line: the words after " [flags] install|add", without flags, // their values, paths and URLs. -func installArgs(run string) []string { +func installArgs(run string, depth int) []string { var out []string for _, cmd := range jvm.SplitCommands(run) { words := jvm.Words(cmd) + // A group or subshell: ( apt-get install x ), { ...; }. + for k, w := range words { + if t := strings.TrimLeft(w, "({"); t != "" { + w = t + } + if !strings.Contains(w, "(") { + if t := strings.TrimRight(w, ")"); t != "" { + w = t + } + } + words[k] = w + } + // sh -c "apt-get install ...": the text is a script of its own. + if text, ok := shellText(words); ok && depth < 4 { + out = append(out, installArgs(text, depth+1)...) + continue + } // The tool: not a flag's value (RUN --mount=...,target=/var/cache/apt). i := 0 for i < len(words) && (strings.HasPrefix(words[i], "-") || !pkgTools[path.Base(words[i])]) { @@ -1281,7 +1383,15 @@ func installArgs(run string) []string { continue } for j := i + 1; j < len(words); j++ { - w := words[j] + w := redirect.ReplaceAllString(words[j], "") + if w == "" { + continue + } + if strings.HasPrefix(w, "$") || strings.HasPrefix(w, "`") { + // A package name this file does not give. + out = append(out, opaqueArg+w) + continue + } if !strings.HasPrefix(w, "-") { if a, ok := rpmFileArg(w); ok { if a != "" { @@ -1308,6 +1418,35 @@ func installArgs(run string) []string { return out } +// redirect is a redirection written onto a word: openjdk-17-jdk>/dev/null, +// x 2>&1. (apk and zypper write version ranges with > and <, followed by +// a version, not by a path or a descriptor.) +var redirect = regexp.MustCompile(`(?:>>?|<)[/&].*$|(?:>>?|<)$`) + +// shellText returns the script of a "sh -c TEXT" command (also -ec, -lc +// and the like, behind env or a path). +func shellText(words []string) (string, bool) { + for i := 0; i < len(words) && i < 4; i++ { + switch path.Base(words[i]) { + case "sh", "bash", "ash", "dash", "zsh", "ksh": + for j := i + 1; j < len(words); j++ { + w := words[j] + if !strings.HasPrefix(w, "-") || strings.HasPrefix(w, "--") { + return "", false + } + if strings.HasSuffix(w, "c") && j+1 < len(words) { + return words[j+1], true + } + } + return "", false + } + if !strings.Contains(words[i], "=") && path.Base(words[i]) != "env" && path.Base(words[i]) != "exec" { + return "", false + } + } + return "", false +} + // pkgHit is one Java package an install names. type pkgHit struct { name, op, ver, mgr string diff --git a/internal/refs/dockerfile.go b/internal/refs/dockerfile.go index a65ad65..00f9846 100644 --- a/internal/refs/dockerfile.go +++ b/internal/refs/dockerfile.go @@ -62,6 +62,8 @@ type dfInstr struct { line int full ptext // the whole instruction after joining continuations, trimmed rest ptext // text after the instruction word and its whitespace + // heredocs are the bodies of the heredocs the instruction opens. + heredocs []string } type dockerfileParse struct { @@ -198,6 +200,7 @@ func parseDockerfile(file string, b []byte) (*dockerfileParse, error) { } for _, doc := range docs { terminated := false + var body strings.Builder for i < len(lines) { c := lines[i] i++ @@ -209,7 +212,11 @@ func parseDockerfile(file string, b []byte) (*dockerfileParse, error) { terminated = true break } + body.WriteString(cand) + body.WriteByte('\n') } + last := &p.instrs[len(p.instrs)-1] + last.heredocs = append(last.heredocs, body.String()) if !terminated { return nil, fmt.Errorf("line %d: unterminated heredoc %q", start, doc.name) } diff --git a/internal/refs/instructions.go b/internal/refs/instructions.go new file mode 100644 index 0000000..ceb1b6c --- /dev/null +++ b/internal/refs/instructions.go @@ -0,0 +1,63 @@ +package refs + +import ( + "encoding/json" + "strings" +) + +// Instruction is one Dockerfile instruction as BuildKit reads it: the +// "# escape=" directive honoured, continuation lines joined, comment and +// blank lines inside a continuation dropped, and the bodies of the +// heredocs it opens attached. Detectors that read more than FROM (the +// packages a RUN installs, the images COPY --from names) start here, so +// that they read a Dockerfile the way the builder does. +type Instruction struct { + // Cmd is the instruction word in lower case; for ONBUILD, the + // instruction it wraps. + Cmd string + // Line is the 1-based line the instruction starts on. + Line int + // Flags are the leading --flags of the arguments, quotes removed + // (--from=builder, --mount=type=bind,from=img, --platform=...). + Flags []string + // Args is what follows the flags. + Args string + // JSON holds the words when the arguments are in JSON (exec) form. + JSON []string + // Heredocs are the bodies of the heredocs the instruction opens + // (RUN <= 0 { + word, after = rest[:i], rest[i+1:] + } + cmd, rest = strings.ToLower(word), strings.TrimSpace(after) + } + x := Instruction{Cmd: cmd, Line: in.line, Args: rest, Heredocs: in.heredocs} + if args, flags, err := extractBuilderFlags(rest); err == nil { + x.Args, x.Flags = args, flags + } + if t := strings.TrimSpace(x.Args); strings.HasPrefix(t, "[") { + var words []string + if json.Unmarshal([]byte(t), &words) == nil { + x.JSON = words + } + } + out = append(out, x) + } + return out, nil +} diff --git a/internal/refs/instructions_test.go b/internal/refs/instructions_test.go new file mode 100644 index 0000000..13b0b9f --- /dev/null +++ b/internal/refs/instructions_test.go @@ -0,0 +1,48 @@ +package refs + +import ( + "fmt" + "testing" +) + +func TestInstructions(t *testing.T) { + df := "# escape=\\\nFROM debian:12 AS base\n" + + "RUN apt-get update && \\\n # a comment in a continuation\n\n apt-get install -y openjdk-17-jdk\n" + + "RUN\t[\"apt-get\", \"install\", \"-y\", \"x\"]\n" + + "RUN --mount=type=bind,from=eclipse-temurin:21,target=/j cp -r /j /opt\n" + + "RUN <= len(want) || got[i] != want[i] { + t.Errorf("instruction %d:\n got %s\nwant %v", i, got[i], want[min(i, len(want)-1)]) + } + } + if len(got) != len(want) { + t.Errorf("%d instructions, want %d", len(got), len(want)) + } + } + bt := "# escape=`\nFROM x\nRUN apt-get update `\n && apt-get install -y openjdk-17-jdk\n" + ins, err = Instructions([]byte(bt)) + if err != nil || len(ins) != 2 || ins[1].Args != "apt-get update && apt-get install -y openjdk-17-jdk" { + t.Errorf("backtick escape: %v %+v", err, ins) + } +} From 1a69140f30bcd590ae6b5d458f4146e4678102d1 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:42:33 +0000 Subject: [PATCH 104/119] java4shell: image references, directories and rpm names the source-tree scan passed in silence Final review B6 (references and the walk). No finding, no skip and exit 0 for each of these before: - FROM image:tag@digest whose tag names a fixed or unaffected release: the digest is the image that runs, so the reference is not checked (and read when the scan is online). A tag that says vulnerable is still reported. - FROM --platform=linux/x86-64, linux/AMD64 or linux: x86-64, judged. - COPY --from=image and RUN --mount=...,from=image: judged like a FROM, never edited by fix. - FROM ${BASE}:${VER} without values: kept as not checked, since a variable can hide a Java image name. - A scan root that is a symbolic link (only image references survived). - Dockerfiles and version files under build, target, vendor, venv, .gradle and the like: the walk now leaves out only what the image reference scan leaves out. - A version or build file that is a symbolic link: recorded as not checked. - rpm names that several Java packages provide (java-17, jre-21-headless, java-sdk-25, java): not checked; a range in one quoted word ('java-17-openjdk >= 17.0.21.1') is read for its package. Co-Authored-By: Claude Fable 5.2 --- .../java4shell/internal/repo/final_test.go | 81 +++++++++++++++++++ detectors/java4shell/internal/repo/refscan.go | 29 +++++-- detectors/java4shell/internal/repo/repo.go | 79 ++++++++++++++++-- 3 files changed, 179 insertions(+), 10 deletions(-) diff --git a/detectors/java4shell/internal/repo/final_test.go b/detectors/java4shell/internal/repo/final_test.go index 6ad1098..7fc1299 100644 --- a/detectors/java4shell/internal/repo/final_test.go +++ b/detectors/java4shell/internal/repo/final_test.go @@ -3,6 +3,8 @@ package repo import ( "context" "fmt" + "os" + "path/filepath" "strings" "testing" ) @@ -65,3 +67,82 @@ func TestRunForms(t *testing.T) { } } } + +const zeroDigest = "sha256:0000000000000000000000000000000000000000000000000000000000000000" + +// Final review B6: image references that were cleared or dropped in +// silence. +func TestReferenceForms(t *testing.T) { + for name, c := range map[string]struct{ df, want string }{ + // A digest decides which image runs: a tag next to it clears nothing. + "a fixed tag with a digest": {"FROM eclipse-temurin:21.0.13.1_2-jre@" + zeroDigest + "\n", "Dockerfile:1 not-checked unknown"}, + "a Java 11 tag with a digest": {"FROM eclipse-temurin:11@" + zeroDigest + "\n", "Dockerfile:1 not-checked unknown"}, + "a vulnerable tag with one": {"FROM eclipse-temurin:21.0.13_9-jre@" + zeroDigest + "\n", "Dockerfile:1 image-pin vulnerable"}, + "a fixed tag": {"FROM sapmachine:21.0.13.1\n", ""}, + // --platform, spelled the ways the builder takes for x86-64. + "linux/x86-64": {"FROM --platform=linux/x86-64 eclipse-temurin:21.0.13_9-jre\n", "Dockerfile:1 image-pin vulnerable"}, + "linux/AMD64": {"FROM --platform=linux/AMD64 eclipse-temurin:21.0.13_9-jre\n", "Dockerfile:1 image-pin vulnerable"}, + "linux": {"FROM --platform=linux eclipse-temurin:21.0.13_9-jre\n", "Dockerfile:1 image-pin vulnerable"}, + "linux/arm64": {"FROM --platform=linux/arm64 eclipse-temurin:21.0.13_9-jre\n", ""}, + // Images a stage copies from or mounts. + "COPY --from an image": {"FROM scratch\nCOPY --from=eclipse-temurin:21.0.13_9-jre /opt/java/openjdk /opt/java/openjdk\n", "Dockerfile:2 image-pin vulnerable"}, + "COPY --link --from": {"FROM debian\nCOPY --link --from=amazoncorretto:21.0.12 /usr/lib/jvm /usr/lib/jvm\n", "Dockerfile:2 image-pin vulnerable"}, + "RUN --mount from an image": {"FROM debian\nRUN --mount=type=bind,from=eclipse-temurin:21.0.13_9-jre,source=/opt/java,target=/j cp -r /j /opt/java\n", "Dockerfile:2 image-pin vulnerable"}, + "COPY --from a moving tag": {"FROM debian\nCOPY --from=eclipse-temurin:21-jre /opt/java/openjdk /opt/java\n", "Dockerfile:2 not-checked unknown"}, + "COPY --from a stage": {"FROM debian AS build\nFROM debian\nCOPY --from=build /x /x\nCOPY --from=0 /y /y\n", ""}, + "COPY --from another image": {"FROM debian\nCOPY --from=busybox:1.36 /bin/busybox /bin/busybox\n", ""}, + "an unresolved Java FROM": {"ARG BASE=eclipse-temurin\nARG VER\nFROM ${BASE}:${VER}\n", "skip Dockerfile:3"}, + "an unresolved FROM, quoted": {"ARG VER\nFROM $IMG:$VER AS b\n", "skip Dockerfile:2"}, + } { + if g := strings.Join(got(t, tree(t, map[string]string{"Dockerfile": c.df})), ", "); g != c.want { + t.Errorf("%s: [%s], want [%s]", name, g, c.want) + } + } +} + +// Final review B6: what the walk left out without a record. +func TestWalkLeavesNothingOut(t *testing.T) { + const run = "FROM debian:12\nRUN apt-get install -y openjdk-17-jdk\n" + for _, dir := range []string{"build", "build/package", "vendor/docker", "target", "venv", ".gradle"} { + if g := strings.Join(got(t, tree(t, map[string]string{dir + "/Dockerfile": run})), ", "); g != dir+"/Dockerfile:2 os-package vulnerable" { + t.Errorf("%s: [%s]", dir, g) + } + } + if g := strings.Join(got(t, tree(t, map[string]string{"target/.java-version": "22\n"})), ", "); g != "target/.java-version:1 java-line vulnerable" { + t.Errorf("target/.java-version: [%s]", g) + } + // A scan root that is a symbolic link is walked at its target. + real := tree(t, map[string]string{".java-version": "22\n"}) + link := filepath.Join(t.TempDir(), "link") + if err := os.Symlink(real, link); err != nil { + t.Fatal(err) + } + if g := strings.Join(got(t, link), ", "); g != ".java-version:1 java-line vulnerable" { + t.Errorf("a linked root: [%s]", g) + } + // A version file that is a symbolic link is not followed, and says so. + dir := tree(t, map[string]string{"out/java-version": "22\n", "app/keep": ""}) + if err := os.Symlink("../out/java-version", filepath.Join(dir, "app/.java-version")); err != nil { + t.Fatal(err) + } + if g := strings.Join(got(t, dir), ", "); g != "skip app/.java-version:0" { + t.Errorf("a linked version file: [%s]", g) + } +} + +// Final review B6: rpm names that install whichever OpenJDK provides them, +// and a version range written in one quoted word. +func TestRpmVirtualNames(t *testing.T) { + for name, c := range map[string]struct{ run, want string }{ + "java-17": {"yum install -y java-17", "Dockerfile:2 os-package unknown"}, + "java and devel": {"yum install -y java java-devel", "Dockerfile:2 os-package unknown, Dockerfile:2 os-package unknown"}, + "jre-21 headless": {"dnf install -y jre-21-headless java-sdk-25", "Dockerfile:2 os-package unknown, Dockerfile:2 os-package unknown"}, + "Java 8 and 11": {"dnf install -y java-11 jre-1.8.0", ""}, + "a quoted range": {"dnf install -y 'java-17-openjdk >= 17.0.21.1'", "Dockerfile:2 os-package vulnerable"}, + "not a Java package": {"dnf install -y javascript-common jreen", ""}, + } { + if g := strings.Join(got(t, tree(t, map[string]string{"Dockerfile": "FROM fedora:43\nRUN " + c.run + "\n"})), ", "); g != c.want { + t.Errorf("%s: [%s], want [%s]", name, g, c.want) + } + } +} diff --git a/detectors/java4shell/internal/repo/refscan.go b/detectors/java4shell/internal/repo/refscan.go index c0d8c50..63ec917 100644 --- a/detectors/java4shell/internal/repo/refscan.go +++ b/detectors/java4shell/internal/repo/refscan.go @@ -19,8 +19,11 @@ func (s *scanner) images(opts Options) { return } for _, sk := range skips { - if sk.Text != "" && !Javaish(sk.Text) { - continue // an unresolved reference that does not look like Java + // An unresolved reference that does not look like Java is left + // out, unless a variable hides its name: FROM ${BASE}:${VER} can be + // a Java image. + if sk.Text != "" && !Javaish(sk.Text) && !strings.Contains(sk.Text, "$") { + continue } s.skips = append(s.skips, Skip{File: sk.File, Line: sk.Line, Reason: sk.Reason}) } @@ -47,9 +50,13 @@ func (s *scanner) judgeRef(r refs.Ref, opts Options) { if img == "" || img == "scratch" || strings.Contains(img, "$") || !amd64(opts) { return } - // FROM --platform=linux/arm64: a stage that is not x86-64. - if p := r.Platform; p != "" && !strings.Contains(p, "$") && !strings.Contains(p, "amd64") && !strings.Contains(p, "x86_64") { - return + // FROM --platform=linux/arm64: a stage that is not x86-64. The builder + // takes amd64, x86_64 and x86-64 in any case, and an OS alone means the + // builder's own architecture. + if p := strings.ToLower(r.Platform); p != "" && !strings.Contains(p, "$") { + if _, arch, ok := strings.Cut(p, "/"); ok && !strings.HasPrefix(arch, "amd64") && !strings.HasPrefix(arch, "x86_64") && !strings.HasPrefix(arch, "x86-64") { + return + } } mit := s.mitigationFor(r) props := map[string]string{"image": img} @@ -72,6 +79,15 @@ func (s *scanner) judgeRef(r refs.Ref, opts Options) { if fam.OpenJ9 { return // OpenJ9: not affected } + // tag@digest: the digest is the image that runs, and the tag next to + // it is only text. A tag that says vulnerable is reported; one that + // would clear is not believed: the image has to be read. + byDigest := func() { + s.add(Finding{Rule: RuleNotChecked, File: r.File, Line: r.Line, Level: "note", Status: StatusUnknown, Pull: img, ref: &r, + Reason: "the reference pins a digest, which decides the image that runs; the tag written next to it does not, so only the image can show which Java release it holds", + Message: fmt.Sprintf("image %s is pinned by digest; it was not read", img), Props: props}) + } + pinned := strings.Contains(img, "@") tv, ok := fam.ParseTag(tag) if !ok { s.add(Finding{Rule: RuleNotChecked, File: r.File, Line: r.Line, Level: "note", Status: StatusUnknown, Pull: img, ref: &r, @@ -91,6 +107,9 @@ func (s *scanner) judgeRef(r refs.Ref, opts Options) { return case knowledge.Vulnerable: default: + if pinned { + byDigest() + } return } feature := tv.Nums[0] diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 60cf661..2724bc3 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -117,13 +117,20 @@ const ( maxFiles = 200000 ) -var skipDirs = map[string]bool{".git": true, "node_modules": true, "vendor": true, ".venv": true, "venv": true, "__pycache__": true, - ".tox": true, "bower_components": true, ".gradle": true, "target": true, "build": true, ".idea": true} +// skipDirs are the directories the image reference scan leaves out too +// (version control and dependency trees). Anything else is walked: a +// Dockerfile under build/ or vendor/ is still one the tree builds. +var skipDirs = map[string]bool{".git": true, ".hg": true, ".svn": true, "node_modules": true, "bower_components": true} // Scan walks root. func Scan(ctx context.Context, root string, opts Options) (Result, error) { var res Result var list []string + // A root that is a symbolic link is walked at its target, as the + // image reference scan does: WalkDir does not descend a linked root. + if r, err := filepath.EvalSymlinks(root); err == nil { + root = r + } err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { if err != nil { rel, _ := filepath.Rel(root, p) @@ -139,14 +146,20 @@ func Scan(ctx context.Context, root string, opts Options) (Result, error) { } return nil } - if !d.Type().IsRegular() { - return nil - } rel, err := filepath.Rel(root, p) if err != nil { return nil } rel = filepath.ToSlash(rel) + if !d.Type().IsRegular() { + // A version or build file that is a symbolic link is not + // followed (it can lead out of the tree): not checked. The image + // reference scan records its own files. + if k := kindOf(rel); d.Type()&fs.ModeSymlink != 0 && k != "" && k != "yaml" && k != "dockerfile" { + res.Skips = append(res.Skips, Skip{File: rel, Reason: "a symbolic link, which is not followed: not checked"}) + } + return nil + } if kindOf(rel) == "" { return nil } @@ -954,6 +967,9 @@ var ( // rpmLatest is Fedora's and EPEL's java-latest-openjdk: the newest // release the distribution carries, named by no release. rpmLatest = regexp.MustCompile(`^java-latest-openjdk(?:-headless|-devel|-jmods)?(?:-\d[\w.:*?-]*)?$`) + // rpmVirtual is an rpm name several OpenJDK packages provide: java, + // java-17, java-devel, jre-21-headless, java-sdk-25, java-1.8.0. + rpmVirtual = regexp.MustCompile(`^(?:java|jre)(?:-(?:1\.)?(\d{1,2})(?:\.0)?)?(?:-(?:headless|devel))?$|^java-sdk(?:-(?:1\.)?(\d{1,2})(?:\.0)?)?$|^java-(\d{1,2})-headless$`) // rpmInstallFlag is an rpm option that installs or upgrades package // files; a query (-qip) or an erase (-e) is not an install. // dpkgInstallFlag is dpkg's install option (-i, --install). @@ -1006,11 +1022,43 @@ func (s *scanner) dockerfile(rel, text string) { // vars are the ARG defaults and ENV values the file sets, for package // names a RUN takes from a variable. vars := map[string]string{} + stages := map[string]bool{} for _, in := range ins { + // COPY --from=image and RUN --mount=...,from=image bring files of + // another image into the stage: the image is judged like a FROM. + for _, fl := range in.Flags { + var img string + switch { + case strings.HasPrefix(fl, "--from="): + img = strings.TrimPrefix(fl, "--from=") + case strings.HasPrefix(fl, "--mount="): + for _, kv := range strings.Split(strings.TrimPrefix(fl, "--mount="), ",") { + if v, ok := strings.CutPrefix(kv, "from="); ok { + img = v + } + } + } + if img == "" || stages[strings.ToLower(img)] || atoi(img) > 0 || img == "0" || strings.Contains(img, "$") { + continue + } + before := len(s.findings) + s.judgeRef(refs.Ref{File: rel, Line: in.Line, Kind: refs.KindDockerfile, Context: strings.ToUpper(in.Cmd) + " from", Text: img, Image: img}, s.opts) + for k := before; k < len(s.findings); k++ { + // Not a FROM: fix does not edit it. + f := &s.findings[k] + if f.Fixable { + f.Fixable, f.edit = false, nil + f.Fix = "Change the image this " + strings.ToUpper(in.Cmd) + " takes files from by hand. " + f.Fix + } + } + } switch in.Cmd { case "from": endStage() from, stageStart, stageEnv, stageCmd = in.Line, len(s.findings), map[string]string{}, nil + if w := strings.Fields(in.Args); len(w) >= 3 && strings.EqualFold(w[len(w)-2], "as") { + stages[strings.ToLower(w[len(w)-1])] = true + } case "cmd", "entrypoint": stageCmd = append(stageCmd, commandWords(in.Args)...) case "arg": @@ -1079,8 +1127,16 @@ func (s *scanner) packages(rel string, line int, run string, vars map[string]str } fromFile := strings.HasPrefix(arg, fileArg) arg = strings.TrimPrefix(arg, fileArg) + // A version range in one quoted word ('java-17-openjdk >= 17.0.21.1'): + // the package is judged without the range. + if name, _, ok := strings.Cut(arg, " "); ok && !fromFile { + arg = name + } before := len(hits) switch { + case rpmVirtual.MatchString(arg): + m := rpmVirtual.FindStringSubmatch(arg) + hits = append(hits, pkgHit{name: arg, feature: atoi(m[1] + m[2] + m[3]), mgr: "rpm", vendor: "distribution", virtual: true}) case strings.HasPrefix(arg, unreadableArg): hits = append(hits, pkgHit{name: strings.TrimPrefix(arg, unreadableArg), mgr: "rpm", vendor: "distribution", unreadable: true}) case zypperArg.MatchString(arg): @@ -1449,6 +1505,8 @@ func shellText(words []string) (string, bool) { // pkgHit is one Java package an install names. type pkgHit struct { + // virtual is an rpm name that names no package (java-17, jre). + virtual bool name, op, ver, mgr string vendor string // distribution, corretto, temurin, zulu, msopenjdk, sapmachine feature int // 0: the distribution's default (default-jre) @@ -1562,6 +1620,17 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { Fix: "Check which Java package the file is: 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update, or the distribution's backport, have the fix."}) return } + if h.virtual { + if h.feature > 0 && h.feature < 17 { + return // Java 8 and 11 are not affected + } + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, + Props: map[string]string{"package": h.name, "manager": h.mgr}, + Reason: "an rpm name that several Java packages provide (the distribution's OpenJDK, a vendor's build): which one is installed, and which release, is not in this file", + Message: fmt.Sprintf("installs %s, a Java runtime named by no package or release: not checked for the Java4Shell fix", refs.CleanText(h.name, 80)), + Fix: "Check the installed runtime: 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update, or the distribution's backport, have the fix."}) + return + } if h.latest { s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "note", Status: StatusUnknown, Props: map[string]string{"package": h.name, "manager": h.mgr}, From 657a46a7a1c975124b45f3e88dc9424d5ba8c792 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:45:23 +0000 Subject: [PATCH 105/119] java4shell: a version file or setup-java step this scan cannot read is not checked, not passed Final review B6 (version files and CI). Each of these gave no finding and exit 0: - .java-version holding a pre-release of a fixed release (27.0.1.1-ea+1, 21.0.13.1-beta+1, -internal), which was cleared as the release; a short version (21, 21.0); a UTF-8 BOM; names in other tools' forms. - .tool-versions with a vendor or word no reader knows (liberica-nik, bisheng, latest). - .sdkmanrc lines with a comment or quotes. - mise files with an array, a table, a quoted key, [tools.java], lts or prefix:, and mise files under other names (.mise/config.toml, mise/config.toml, mise..toml). - setup-java with a range, an early-access build, java-version-file, distribution jdkfile, no version at all, the action's name in another case, in a composite action (action.yml), or through a YAML alias. A pre-release is judged as one (never the release), a short version is the moving pin it is, and every value that selects a Java release in a form the scan does not read is reported as not checked. A version behind a YAML anchor is shared, so fix does not edit it. Co-Authored-By: Claude Fable 5.2 --- .../java4shell/internal/repo/final_test.go | 81 +++++++++ detectors/java4shell/internal/repo/repo.go | 172 +++++++++++++++--- .../java4shell/internal/repo/review_test.go | 5 +- 3 files changed, 234 insertions(+), 24 deletions(-) diff --git a/detectors/java4shell/internal/repo/final_test.go b/detectors/java4shell/internal/repo/final_test.go index 7fc1299..19c1a1a 100644 --- a/detectors/java4shell/internal/repo/final_test.go +++ b/detectors/java4shell/internal/repo/final_test.go @@ -146,3 +146,84 @@ func TestRpmVirtualNames(t *testing.T) { } } } + +// Final review B6: a version file selects a Java release, so a value this +// scan does not read is not checked, never passed in silence; a +// pre-release is never taken as the release. +func TestVersionFilesSayNotChecked(t *testing.T) { + const nc = " not-checked unknown" + for name, c := range map[string]struct{ file, body, want string }{ + "java-version pre-release of the fix": {".java-version", "27.0.1.1-ea+1\n", ".java-version:1"}, + "java-version beta": {".java-version", "21.0.13.1-beta+1\n", ".java-version:1"}, + "java-version internal": {".java-version", "openjdk-21.0.13.1-internal\n", ".java-version:1"}, + "java-version short": {".java-version", "21\n", ".java-version:1"}, + "java-version two numbers": {".java-version", "21.0\n", ".java-version:1"}, + "java-version with a BOM": {".java-version", "\xef\xbb\xbf21.0.13\n", ".java-version:1 java-pin vulnerable"}, + "java-version with a v": {".java-version", "v21.0.13\n", ".java-version:1" + nc}, + "java-version jre name": {".java-version", "temurin-jre-21.0.13\n", ".java-version:1" + nc}, + "java-version sdkman name": {".java-version", "21.0.13.fx-zulu\n", ".java-version:1" + nc}, + "java-version Java 11": {".java-version", "11.0.25\n", ""}, + "tool-versions unknown vendor": {".tool-versions", "java liberica-nik-23.1.5\n", ".tool-versions:1" + nc}, + "tool-versions bisheng": {".tool-versions", "nodejs 22.1.0\njava bisheng-17.0.10\n", ".tool-versions:2" + nc}, + "tool-versions latest": {".tool-versions", "java latest\n", ".tool-versions:1" + nc}, + "sdkmanrc with a comment": {".sdkmanrc", "java=21.0.13-tem # the JDK\n", ".sdkmanrc:1 java-pin vulnerable"}, + "sdkmanrc quoted": {".sdkmanrc", "java=\"21.0.13-tem\"\n", ".sdkmanrc:1 java-pin vulnerable"}, + "sdkmanrc unread": {".sdkmanrc", "java=${JAVA}\n", ".sdkmanrc:1" + nc}, + "mise array": {"mise.toml", "[tools]\njava = [\"temurin-21.0.13+9\", \"17\"]\n", "mise.toml:2 java-pin vulnerable, mise.toml:2" + nc}, + "mise table": {"mise.toml", "[tools]\njava = { version = \"21.0.13\" }\n", "mise.toml:2 java-pin vulnerable"}, + "mise quoted key": {"mise.toml", "[tools]\n\"java\" = \"22\"\n", "mise.toml:2 java-line vulnerable"}, + "mise tools.java": {"mise.toml", "[tools.java]\nversion = \"21.0.13\"\n", "mise.toml:2 java-pin vulnerable"}, + "mise lts": {"mise.toml", "[tools]\njava = \"lts\"\n", "mise.toml:2" + nc}, + "mise prefix": {"mise.toml", "[tools]\njava = \"prefix:21.0.13\"\n", "mise.toml:2" + nc}, + "mise in .mise/config.toml": {".mise/config.toml", "[tools]\njava = \"22\"\n", ".mise/config.toml:2 java-line vulnerable"}, + "mise in .config/mise/config.toml": {".config/mise/config.toml", "[tools]\njava = \"22\"\n", ".config/mise/config.toml:2 java-line vulnerable"}, + "mise.dev.toml": {"mise.dev.toml", "[tools]\njava = \"22\"\n", "mise.dev.toml:2 java-line vulnerable"}, + "another config.toml": {"hugo/config.toml", "[tools]\njava = \"22\"\n", ""}, + } { + g := strings.Join(got(t, tree(t, map[string]string{c.file: c.body})), ", ") + if c.want != "" && !strings.Contains(c.want, " ") { + // Any finding on that line: vulnerable, or not checked. + if !strings.HasPrefix(g, c.want+" ") || strings.Contains(g, ", ") { + t.Errorf("%s: [%s], want one finding at %s", name, g, c.want) + } + continue + } + if g != c.want { + t.Errorf("%s: [%s], want [%s]", name, g, c.want) + } + } +} + +// Final review B6: setup-java steps that were passed in silence. +func TestSetupJavaSaysNotChecked(t *testing.T) { + step := func(with string) string { + return "jobs:\n b:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/setup-java@v4\n with:\n distribution: temurin\n" + with + } + const wf = ".github/workflows/ci.yml" + for name, c := range map[string]struct{ file, body, want string }{ + "a range": {wf, step(" java-version: '>=17'\n"), wf + ":8 not-checked unknown"}, + "a caret range": {wf, step(" java-version: '^17.0.6'\n"), wf + ":8 not-checked unknown"}, + "early access": {wf, step(" java-version: '22-ea'\n"), wf + ":8 not-checked unknown"}, + "early access of the fix": {wf, step(" java-version: '21.0.13.1-ea'\n"), wf + ":8 not-checked unknown"}, + "early access of Java 11": {wf, step(" java-version: '11-ea'\n"), ""}, + "a version file": {wf, step(" java-version-file: backend/pom.xml\n"), wf + ":8 not-checked unknown"}, + "a version file it reads": {wf, step(" java-version-file: .java-version\n"), ""}, + "neither": {wf, step(""), wf + ":5 not-checked unknown"}, + "upper case": {wf, strings.Replace(step(" java-version: 21.0.13\n"), "actions/setup-java", "Actions/Setup-Java", 1), wf + ":8 java-pin vulnerable"}, + "a composite action": {".github/actions/setup/action.yml", "runs:\n using: composite\n steps:\n - uses: actions/setup-java@v4\n with:\n distribution: temurin\n java-version: 21.0.13\n", ".github/actions/setup/action.yml:7 java-pin vulnerable"}, + "action.yml at the root": {"action.yml", "runs:\n using: composite\n steps:\n - uses: actions/setup-java@v4\n with:\n distribution: temurin\n java-version: 22\n", "action.yml:7 java-line vulnerable"}, + "a local archive": {wf, strings.Replace(step(" java-version: 21.0.13.1\n jdkFile: jdk.tar.gz\n"), "distribution: temurin", "distribution: jdkfile", 1), wf + ":8 not-checked unknown"}, + "an alias": {wf, "jobs:\n b:\n steps:\n - uses: actions/setup-java@v4\n with:\n distribution: corretto\n java-version: &jv 17.0.20\n" + + " - uses: actions/setup-java@v4\n with:\n distribution: temurin\n java-version: *jv\n", wf + ":7 java-pin vulnerable, " + wf + ":11 java-pin vulnerable"}, + } { + if g := strings.Join(got(t, tree(t, map[string]string{c.file: c.body})), ", "); g != c.want { + t.Errorf("%s: [%s], want [%s]", name, g, c.want) + } + } + // What an alias or an anchor names is shared: fix does not edit it. + res, err := Scan(context.Background(), tree(t, map[string]string{wf: "jobs:\n b:\n steps:\n - uses: actions/setup-java@v4\n with:\n distribution: corretto\n java-version: &jv 17.0.20\n" + + " - uses: actions/setup-java@v4\n with:\n distribution: corretto\n java-version: *jv\n"}), Options{}) + if err != nil || len(res.Findings) != 2 || res.Findings[0].Fixable || res.Findings[1].Fixable { + t.Errorf("anchored versions: %v %+v", err, res.Findings) + } +} diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 2724bc3..bc3e87b 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -263,9 +263,14 @@ func kindOf(rel string) string { return "sdkmanrc" case lower == ".tool-versions": return "tool-versions" - case lower == "mise.toml" || lower == ".mise.toml" || lower == "mise.local.toml" || lower == ".rtx.toml": + case lower == "mise.toml" || lower == ".mise.toml" || lower == ".rtx.toml", + strings.HasSuffix(lower, ".toml") && (strings.HasPrefix(lower, "mise.") || strings.HasPrefix(lower, ".mise.")), + lower == "config.toml" && (path.Base(path.Dir(rel)) == "mise" || path.Base(path.Dir(rel)) == ".mise"): + // mise.toml, mise.local.toml, mise..toml, .mise/config.toml, + // mise/config.toml, .config/mise/config.toml. return "mise" - case strings.HasPrefix(rel, ".github/workflows/") && (strings.HasSuffix(lower, ".yml") || strings.HasSuffix(lower, ".yaml")): + case strings.HasPrefix(rel, ".github/workflows/") && (strings.HasSuffix(lower, ".yml") || strings.HasSuffix(lower, ".yaml")), + lower == "action.yml" || lower == "action.yaml": // a composite action's steps return "workflow" case lower == "build.gradle" || lower == "build.gradle.kts" || lower == "settings.gradle" || lower == "settings.gradle.kts" || lower == "gradle.properties": return "gradle" @@ -412,9 +417,10 @@ func (s *scanner) judgeVersion(rel string, line int, ga bool, verText, source, v s.add(Finding{Rule: RuleLine, File: rel, Line: line, Level: "error", Status: StatusVulnerable, Reason: l.Note, Message: fmt.Sprintf("%s selects Java %s, a line that received no Java4Shell fix", source, verText), Fix: pinFix(tv.Nums[0], source), Props: props}) - } else if tv.Exact { + } else if tv.Exact || tv.EA { // A pinned release the data does not settle (17.0.22, a later - // update): not checked, as an image tag of it is. + // update), or a pre-release: not checked, as an image tag of + // it is. s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, Reason: why, Message: fmt.Sprintf("%s selects Java %s: not checked for the Java4Shell fix", source, verText), Fix: fmt.Sprintf("Check that Java %s includes %s.", verText, knowledge.BugRef), Props: props}) @@ -433,24 +439,47 @@ func pinFix(feature int, source string) string { return fmt.Sprintf("Java %d received no fix: move %s to a supported release with the fix, such as %s.", feature, source, knowledge.Upgrade(feature)) } +// unread reports a value that selects a Java release in a form this scan +// does not read: not checked, never passed in silence. +func (s *scanner) unread(rel string, line int, value, source string) { + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, + Reason: "the value selects a Java release in a form this scan does not read", + Message: fmt.Sprintf("%s selects %s, which this scan cannot read as a Java release: not checked for the Java4Shell fix", source, refs.CleanText(value, 80)), + Fix: "Check which Java release this selects: 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update have the fix.", + Props: map[string]string{"source": source, "current": refs.CleanText(value, 80)}}) +} + +// versionMarker is a pre-release or self-built marker after a version. +var versionMarker = regexp.MustCompile(`(?i)-(?:ea|beta|rc|internal|snapshot)|adhoc`) + func (s *scanner) javaVersionFile(rel, text string) { for i, l := range lines(text) { - l = strings.TrimSpace(l) + l = strings.TrimSpace(strings.TrimPrefix(l, "\ufeff")) if l == "" || strings.HasPrefix(l, "#") { continue } // jenv names: temurin64-21.0.13, openjdk64-17.0.21, 21.0.13. idx := jenvName.FindStringSubmatchIndex(l) if idx == nil { + s.unread(rel, i+1, l, ".java-version") return } m := jenvName.FindStringSubmatch(l) - ver := m[2] + ver, rest := m[2], l[idx[5]:] if strings.HasPrefix(strings.ToLower(m[1]), "corretto") { ver = CorrettoJava(ver) } - ver += plusBuild(l[idx[5]:]) - s.judgeVersion(rel, i+1, false, ver, ".java-version", vendorWord(l)) + pre, build := versionMarker.MatchString(rest), plusBuild(rest) + if strings.Count(ver, ".") < 2 && !pre && build == "" { + // 21, 21.0: whichever release of the line is installed. + feature, _, _ := strings.Cut(ver, ".") + s.movingPin(rel, i+1, atoi(feature), strings.ToLower(m[1]), l, ".java-version") + return + } + if pre { + ver += "-ea" // never the release itself + } + s.judgeVersion(rel, i+1, false, ver+build, ".java-version", vendorWord(l)) return // jenv reads the first line } } @@ -475,8 +504,19 @@ var sdkmanVendors = map[string]string{"tem": "Eclipse Temurin", "amzn": "Amazon func (s *scanner) sdkmanrc(rel, text string) { for i, l := range lines(text) { + // java=21.0.13-tem, also quoted and with a comment after it. + if c := strings.Index(l, "#"); c >= 0 { + l = l[:c] + } + key, val, ok := strings.Cut(l, "=") + if !ok || strings.TrimSpace(key) != "java" { + continue + } + val = strings.Trim(strings.TrimSpace(val), `"'`) + l = "java=" + val m := sdkmanLine.FindStringSubmatch(l) if m == nil { + s.unread(rel, i+1, val, ".sdkmanrc") continue } vendor := sdkmanVendors[m[2]] @@ -510,6 +550,9 @@ var asdfJava = regexp.MustCompile(`^(?:(adoptopenjdk|temurin|corretto|openjdk|sa func (s *scanner) asdfValue(rel string, line int, value, source string, mise bool) { m := asdfJava.FindStringSubmatch(value) if m == nil { + // A vendor or form no reader here knows (liberica-nik-23.1.5, + // latest, prefix:21): it still selects a Java. + s.unread(rel, line, value, source) return } switch m[1] { @@ -674,12 +717,52 @@ func (s *scanner) toolVersions(rel, text string) { } } -var miseJava = regexp.MustCompile(`^\s*java\s*=\s*["']([^"']+)["']`) +var ( + miseQuoted = regexp.MustCompile(`["']([^"']*)["']`) + miseVersion = regexp.MustCompile(`\bversion\s*=\s*["']([^"']*)["']`) +) +// mise reads the java tool of a mise file: java = "temurin-21", an array +// of versions, a table with a version, a quoted key, and [tools.java] with +// version = "...". A value in any other form is not checked. func (s *scanner) mise(rel, text string) { + section := "" for i, l := range lines(text) { - if m := miseJava.FindStringSubmatch(l); m != nil { - s.asdfValue(rel, i+1, m[1], path.Base(rel), true) + t := strings.TrimSpace(l) + if t == "" || strings.HasPrefix(t, "#") { + continue + } + if strings.HasPrefix(t, "[") { + section = strings.NewReplacer("[", "", "]", "", `"`, "", "'", "", " ", "").Replace(t) + continue + } + key, val, ok := strings.Cut(t, "=") + if !ok { + continue + } + key, val = strings.Trim(strings.TrimSpace(key), `"'`), strings.TrimSpace(val) + var values []string + switch { + case key == "java" && strings.HasPrefix(val, "{"): + if m := miseVersion.FindStringSubmatch(val); m != nil { + values = []string{m[1]} + } + case key == "java" && strings.HasPrefix(val, "["): + for _, m := range miseQuoted.FindAllStringSubmatch(val, 16) { + values = append(values, m[1]) + } + case key == "java", key == "version" && section == "tools.java": + if m := miseQuoted.FindStringSubmatch(val); m != nil && strings.HasPrefix(val, m[0]) { + values = []string{m[1]} + } + default: + continue + } + if len(values) == 0 { + s.unread(rel, i+1, val, path.Base(rel)) + } + for _, v := range values { + s.asdfValue(rel, i+1, v, path.Base(rel), true) } } } @@ -712,21 +795,47 @@ func (s *scanner) workflow(rel string, b []byte) { return } text := lines(string(b)) + note := func(line int, reason, msg string) { + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, Reason: reason, Message: msg, + Fix: "Check which Java release the step installs: 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update have the fix."}) + } walkYAML(&doc, 0, func(m *yaml.Node) { - uses := mapGet(m, "uses") - if uses == nil || !strings.HasPrefix(uses.Value, "actions/setup-java@") { - return - } - with := mapGet(m, "with") - if with == nil { + // GitHub reads the action's name without regard to case. + uses := deref(mapGet(m, "uses")) + if uses == nil || !strings.HasPrefix(strings.ToLower(uses.Value), "actions/setup-java@") { return } + with := deref(mapGet(m, "with")) dist := "" - if d := mapGet(with, "distribution"); d != nil { - dist = d.Value + if d := deref(mapGet(with, "distribution")); d != nil { + dist = strings.ToLower(d.Value) + } + if dist == "semeru" { + return // OpenJ9 } jv := mapGet(with, "java-version") if jv == nil { + // The version comes from a file, or from nowhere this scan sees. + if f := deref(mapGet(with, "java-version-file")); f != nil { + switch strings.ToLower(path.Base(f.Value)) { + case ".java-version", ".tool-versions", ".sdkmanrc": + return // read where it lies + } + note(f.Line, "the step reads the Java version from a file this scan does not read for it", + fmt.Sprintf("setup-java takes the Java version from %s; check that it selects a release with the Java4Shell fix", refs.CleanText(f.Value, 80))) + return + } + note(uses.Line, "the step names no java-version this scan can read", "setup-java without a java-version here: not checked for the Java4Shell fix") + return + } + if jv.Kind == yaml.AliasNode && jv.Alias != nil { + // The value an anchor gives, at the line that uses it; the + // anchor marks it as shared (not edited). + jv = &yaml.Node{Kind: jv.Alias.Kind, Value: jv.Alias.Value, Line: jv.Line, Anchor: jv.Alias.Anchor} + } + if dist == "jdkfile" { + note(jv.Line, "the step installs a JDK archive the workflow supplies; java-version is only its label", + "setup-java installs a JDK from a file (distribution jdkfile): not checked for the Java4Shell fix") return } vals := []*yaml.Node{jv} @@ -738,6 +847,7 @@ func (s *scanner) workflow(rel string, b []byte) { } for _, v := range vals { if v.Kind != yaml.ScalarNode { + note(v.Line, "java-version is not a single value", "setup-java's java-version is not a value this scan reads: not checked for the Java4Shell fix") continue } if strings.Contains(v.Value, "${{") { @@ -753,12 +863,22 @@ func (s *scanner) workflow(rel string, b []byte) { func (s *scanner) setupJava(rel string, v *yaml.Node, dist string, text []string) { ver := strings.TrimSpace(v.Value) - if strings.HasSuffix(ver, "-ea") { - return // an early-access build: not a release this data judges + if ea := strings.TrimSuffix(ver, "-ea"); ea != ver { + // An early-access build: of a line with the decoder, it is not a + // release this data judges, and never the release itself. + if n := atoi(versionInText.FindString(strings.SplitN(ea, ".", 2)[0])); n >= 17 { + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: v.Line, Level: "note", Status: StatusUnknown, + Reason: "an early-access build is not a release, and which build is installed is decided when the job runs", + Message: fmt.Sprintf("setup-java's java-version %q is an early-access build: not checked for the Java4Shell fix", refs.CleanText(ver, 80)), + Fix: "Use a release with the fix: 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update."}) + } + return } ver = strings.TrimSuffix(ver, ".x") m := versionInText.FindString(ver) if m == "" || m != ver && !strings.HasPrefix(ver, m+"+") { + // A range (>=17, ^17.0.6, ~21.0.5) or another form. + s.unread(rel, v.Line, ver, "actions/setup-java") return } if dist == "semeru" { @@ -783,7 +903,7 @@ func (s *scanner) setupJava(rel string, v *yaml.Node, dist string, text []string if f.Rule == RuleJavaPin && publishedFix[dist] && v.Line >= 1 && v.Line <= len(text) { line := text[v.Line-1] col := strings.Index(line, ver) - if col >= 0 && strings.Count(line, ver) == 1 { + if col >= 0 && strings.Count(line, ver) == 1 && v.Anchor == "" { f.Fixable = true f.edit = &pinEdit{file: rel, line: v.Line, col: col, old: ver, kind: "setup-java", feature: feature} f.Fix = fmt.Sprintf("Set java-version to %d: %s's newest Java %d release has the fix (%s), and setup-java installs it.", feature, dist, feature, knowledge.FixedVersion(feature)) @@ -1776,6 +1896,14 @@ func (s *scanner) judgePackage(rel string, line int, h pkgHit) { // ---- YAML helpers +// deref follows a YAML alias to the node its anchor names. +func deref(n *yaml.Node) *yaml.Node { + if n != nil && n.Kind == yaml.AliasNode && n.Alias != nil { + return n.Alias + } + return n +} + func walkYAML(n *yaml.Node, depth int, fn func(m *yaml.Node)) { if n == nil || depth > 64 { return diff --git a/detectors/java4shell/internal/repo/review_test.go b/detectors/java4shell/internal/repo/review_test.go index 1487f92..7748a0b 100644 --- a/detectors/java4shell/internal/repo/review_test.go +++ b/detectors/java4shell/internal/repo/review_test.go @@ -41,9 +41,10 @@ func TestReviewRepo(t *testing.T) { t.Error("CorrettoJava") } - // setup-java early access is not judged or rewritten. + // setup-java early access is not judged or rewritten: it is not + // checked (final review B6: said, not passed in silence). root = tree(t, map[string]string{".github/workflows/a.yml": "jobs:\n a:\n steps:\n - uses: actions/setup-java@v4\n with:\n distribution: corretto\n java-version: '21.0.13-ea'\n"}) - if res := scan(t, root); len(res.Findings) != 0 { + if res := scan(t, root); len(res.Findings) != 1 || res.Findings[0].Rule != RuleNotChecked || res.Findings[0].Fixable { t.Errorf("early access: %+v", res.Findings) } From 37dd76b75d648df00cefb336642181ff981fc11b Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:46:52 +0000 Subject: [PATCH 106/119] java4shell: Jib, buildpack and toolchain settings are read across lines; Compose build arguments are noted Final review B6 (build files). A Jib base image was read only when or from { image = } sat on one line, so a pom or build.gradle in its usual formatting gave nothing; , project.toml's name/value pair for BP_JVM_VERSION, environment("BP_JVM_VERSION", ...), Kotlin's jvmToolchain(22) and Gradle files under other names (convention plugins, app.gradle) were not read. They are now, and a BP_JVM_VERSION in a form that is still not read is reported as not checked. A Compose file that sets a build argument replaces the ARG default a Dockerfile's FROM is read with: that FROM is recorded as not checked for the image the Compose build uses. Co-Authored-By: Claude Fable 5.2 --- .../java4shell/internal/repo/final_test.go | 44 +++++++ detectors/java4shell/internal/repo/refscan.go | 10 ++ detectors/java4shell/internal/repo/repo.go | 112 ++++++++++++++---- 3 files changed, 141 insertions(+), 25 deletions(-) diff --git a/detectors/java4shell/internal/repo/final_test.go b/detectors/java4shell/internal/repo/final_test.go index 19c1a1a..27cd928 100644 --- a/detectors/java4shell/internal/repo/final_test.go +++ b/detectors/java4shell/internal/repo/final_test.go @@ -227,3 +227,47 @@ func TestSetupJavaSaysNotChecked(t *testing.T) { t.Errorf("anchored versions: %v %+v", err, res.Findings) } } + +// Final review B6: Jib, buildpack and toolchain settings were read only +// when written on one line, in one form. +func TestBuildSettingsForms(t *testing.T) { + const img = "eclipse-temurin:21.0.13_9-jre" + for name, c := range map[string]struct{ file, body, want string }{ + "Jib in a pom, as formatted": {"pom.xml", "\n\n \n " + img + "\n \n\n", "pom.xml:4 image-pin vulnerable"}, + "Jib in a pom, on one line": {"pom.xml", "" + img + "\n", "pom.xml:1 image-pin vulnerable"}, + "Jib as a Maven property": {"pom.xml", "\n " + img + "\n\n", "pom.xml:2 image-pin vulnerable"}, + "Jib in Gradle, as formatted": {"build.gradle", "jib {\n from {\n image = \"" + img + "\"\n }\n}\n", "build.gradle:3 image-pin vulnerable"}, + "Jib in Gradle, on one line": {"build.gradle", "jib { from { image = '" + img + "' } }\n", "build.gradle:1 image-pin vulnerable"}, + "project.toml name and value": {"project.toml", "[[build.env]]\nname = \"BP_JVM_VERSION\"\nvalue = \"22\"\n", "project.toml:2 java-line vulnerable"}, + "project.toml value first": {"project.toml", "[[build.env]]\nvalue = \"22\"\nname = \"BP_JVM_VERSION\"\n", "project.toml:3 not-checked unknown"}, + "project.toml pinned": {"project.toml", "[[build.env]]\nname = \"BP_JVM_VERSION\"\nvalue = \"21.0.13\"\n", "project.toml:2 java-pin vulnerable"}, + "Gradle environment call": {"build.gradle", "bootBuildImage {\n environment(\"BP_JVM_VERSION\", \"22\")\n}\n", "build.gradle:2 java-line vulnerable"}, + "Gradle environment index": {"build.gradle", "environment[\"BP_JVM_VERSION\"] = \"21.0.13\"\n", "build.gradle:1 java-pin vulnerable"}, + "Gradle environment map": {"build.gradle", "environment = [\"BP_JVM_VERSION\": \"22\"]\n", "build.gradle:1 java-line vulnerable"}, + "Kotlin jvmToolchain": {"build.gradle.kts", "kotlin {\n jvmToolchain(22)\n}\n", "build.gradle.kts:2 java-line vulnerable"}, + "a convention plugin": {"buildSrc/src/main/kotlin/conv.gradle.kts", "java { toolchain { languageVersion.set(JavaLanguageVersion.of(22)) } }\n", "buildSrc/src/main/kotlin/conv.gradle.kts:1 java-line vulnerable"}, + "a Gradle file by another name": {"app/app.gradle", "java { toolchain { languageVersion = JavaLanguageVersion.of(22) } }\n", "app/app.gradle:1 java-line vulnerable"}, + "a toolchain of a fixed line": {"build.gradle.kts", "kotlin {\n jvmToolchain(21)\n}\n", ""}, + } { + if g := strings.Join(got(t, tree(t, map[string]string{c.file: c.body})), ", "); g != c.want { + t.Errorf("%s: [%s], want [%s]", name, g, c.want) + } + } +} + +// Final review B6: a Compose file that sets a build argument overrides the +// ARG default a FROM is read with: the image that build uses is not +// checked. +func TestComposeBuildArgs(t *testing.T) { + const df = "ARG TAG=21.0.13.1_2-jre\nFROM eclipse-temurin:${TAG}\n" + for name, c := range map[string]struct{ compose, want string }{ + "a map": {"services:\n app:\n build:\n context: .\n args:\n TAG: 21.0.13_9-jre\n", "skip Dockerfile:2"}, + "a list": {"services:\n app:\n build:\n context: .\n args:\n - TAG=21.0.13_9-jre\n", "skip Dockerfile:2"}, + "another argument": {"services:\n app:\n build:\n context: .\n args:\n HTTP_PROXY: http://proxy\n", ""}, + "no arguments": {"services:\n app:\n build: .\n", ""}, + } { + if g := strings.Join(got(t, tree(t, map[string]string{"Dockerfile": df, "docker-compose.yml": c.compose})), ", "); g != c.want { + t.Errorf("%s: [%s], want [%s]", name, g, c.want) + } + } +} diff --git a/detectors/java4shell/internal/repo/refscan.go b/detectors/java4shell/internal/repo/refscan.go index 63ec917..601c00d 100644 --- a/detectors/java4shell/internal/repo/refscan.go +++ b/detectors/java4shell/internal/repo/refscan.go @@ -29,6 +29,16 @@ func (s *scanner) images(opts Options) { } for i := range rs { s.judgeRef(rs[i], opts) + // A Compose file that sets one of the FROM's ARGs as a build + // argument builds on another image than the default read here. + if rs[i].Kind == refs.KindDockerfile { + for _, v := range rs[i].Vars { + if f, ok := s.buildArgs[v.Name]; ok { + s.skips = append(s.skips, Skip{File: rs[i].File, Line: rs[i].Line, Reason: fmt.Sprintf("the FROM is read with the default of ARG %s, which %s sets as a build argument: the image that build uses is not checked", refs.CleanText(v.Name, 60), refs.CleanText(f, 120))}) + break + } + } + } } } diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index bc3e87b..72fd4a1 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -19,6 +19,7 @@ package repo import ( + "bytes" "context" "encoding/json" "errors" @@ -183,7 +184,7 @@ func scanList(ctx context.Context, root string, list []string, opts Options, res } } sort.Strings(list) - s := &scanner{root: root, opts: opts, mitigated: map[string]string{}} + s := &scanner{root: root, opts: opts, mitigated: map[string]string{}, buildArgs: map[string]string{}} for _, rel := range list { if ctx.Err() != nil { return res, ctx.Err() @@ -217,6 +218,8 @@ func scanList(ctx context.Context, root string, list []string, opts Options, res s.maven(rel, text) case "project.toml": s.projectToml(rel, text) + case "yaml": + s.composeArgs(rel, b) } } s.images(opts) @@ -272,7 +275,9 @@ func kindOf(rel string) string { case strings.HasPrefix(rel, ".github/workflows/") && (strings.HasSuffix(lower, ".yml") || strings.HasSuffix(lower, ".yaml")), lower == "action.yml" || lower == "action.yaml": // a composite action's steps return "workflow" - case lower == "build.gradle" || lower == "build.gradle.kts" || lower == "settings.gradle" || lower == "settings.gradle.kts" || lower == "gradle.properties": + case strings.HasSuffix(lower, ".gradle") || strings.HasSuffix(lower, ".gradle.kts") || lower == "gradle.properties": + // build.gradle, settings.gradle, and convention plugins or + // scripts under any name. return "gradle" case lower == "pom.xml" || lower == "toolchains.xml": return "maven" @@ -324,6 +329,44 @@ type scanner struct { mitigated map[string]string // unparsed are Dockerfiles the instruction parser refused. unparsed []Skip + // buildArgs maps a build argument a Compose file sets to that file. + buildArgs map[string]string +} + +// composeArgs records the build arguments a Compose file sets +// (services.*.build.args, as a map or a list of NAME=value): they replace +// the ARG defaults a Dockerfile's FROM is read with. +func (s *scanner) composeArgs(rel string, b []byte) { + if !bytes.Contains(b, []byte("args")) || !bytes.Contains(b, []byte("build")) { + return + } + var doc yaml.Node + if yaml.Unmarshal(b, &doc) != nil { + return // the image reference scan records a file it cannot parse + } + walkYAML(&doc, 0, func(m *yaml.Node) { + args := deref(mapGet(deref(mapGet(m, "build")), "args")) + if args == nil { + return + } + var names []string + switch args.Kind { + case yaml.MappingNode: + for i := 0; i+1 < len(args.Content); i += 2 { + names = append(names, args.Content[i].Value) + } + case yaml.SequenceNode: + for _, a := range args.Content { + n, _, _ := strings.Cut(a.Value, "=") + names = append(names, n) + } + } + for _, n := range names { + if _, ok := s.buildArgs[n]; !ok && n != "" && len(s.buildArgs) < 4096 { + s.buildArgs[n] = rel + } + } + }) } func (s *scanner) add(f Finding) { @@ -951,12 +994,17 @@ func orAny(d string) string { // ---- Gradle, Maven, buildpacks var ( - gradleToolchain = regexp.MustCompile(`JavaLanguageVersion\.of\(\s*["']?(\d{1,2})["']?\s*\)`) + gradleToolchain = regexp.MustCompile(`(?:JavaLanguageVersion\.of|\bjvmToolchain)\(\s*["']?(\d{1,2})["']?\s*\)`) gradleRelease = regexp.MustCompile(`(?:sourceCompatibility|targetCompatibility|options\.release|release\.set)\s*[=(]\s*(?:JavaVersion\.VERSION_|["'])?(\d{1,2})\b`) - bpJVM = regexp.MustCompile(`BP_JVM_VERSION["']?\s*(?:[:=]|to|>)\s*["']?(\d{1,2}(?:\.\d+)*)`) - jibFrom = regexp.MustCompile(`(?:from\s*\{[^}]*?image\s*=\s*|jib\.from\.image\s*=\s*|\s*\s*)["']?([A-Za-z0-9][\w./:@-]*)`) - mavenToolchain = regexp.MustCompile(`\s*\[?(\d{1,2})(?:,\))?\s*`) - enforcerJava = regexp.MustCompile(`(?s)\s*\s*([^<]{1,60})`) + // bpJVM reads BP_JVM_VERSION = "21", "BP_JVM_VERSION": "21", + // environment("BP_JVM_VERSION", "21"), environment["BP_JVM_VERSION"] = "21" + // and project.toml's name = "BP_JVM_VERSION" with value = "21" after it. + bpJVM = regexp.MustCompile(`BP_JVM_VERSION["']?\s*\]?\s*(?:[:=,]|to\b|>|value\s*=)\s*["']?(\d{1,2}(?:\.\d+)*)`) + // jibFrom reads a Jib base image across lines: from { image = "..." }, + // jib.from.image = "...", ..., . + jibFrom = regexp.MustCompile(`(?:\bfrom\s*\{[^}]*?\bimage\s*=\s*|jib\.from\.image\s*=\s*|\s*\s*|\s*)["']?([A-Za-z0-9][\w./:@-]*)`) + mavenToolchain = regexp.MustCompile(`\s*\[?(\d{1,2})(?:,\))?\s*`) + enforcerJava = regexp.MustCompile(`(?s)\s*\s*([^<]{1,60})`) ) // lineToolchain reports a toolchain or release setting that selects a Java @@ -980,10 +1028,37 @@ func (s *scanner) gradle(rel, text string) { fmt.Sscanf(m[1], "%d", &n) s.lineToolchain(rel, i+1, n, "the Gradle toolchain") } - if m := bpJVM.FindStringSubmatch(l); m != nil { - s.buildpack(rel, i+1, m[1]) + } + s.settings(rel, text) +} + +// settings reads what a build file sets across lines: the buildpack's +// BP_JVM_VERSION and a Jib base image. A BP_JVM_VERSION written in a form +// that is not read is not checked. +func (s *scanner) settings(rel, text string) { + lineOf := func(off int) (int, int) { + return strings.Count(text[:off], "\n") + 1, off - (strings.LastIndex(text[:off], "\n") + 1) + } + read := map[int]bool{} // offsets of BP_JVM_VERSION that were read + for _, m := range bpJVM.FindAllStringSubmatchIndex(text, 64) { + read[m[0]] = true + line, _ := lineOf(m[0]) + s.buildpack(rel, line, text[m[2]:m[3]]) + } + for off := 0; ; { + i := strings.Index(text[off:], "BP_JVM_VERSION") + if i < 0 { + break + } + if at := off + i; !read[at] { + line, _ := lineOf(at) + s.unread(rel, line, "BP_JVM_VERSION", "BP_JVM_VERSION (Cloud Native Buildpacks)") } - s.jib(rel, i+1, l) + off += i + len("BP_JVM_VERSION") + } + for _, m := range jibFrom.FindAllStringSubmatchIndex(text, 64) { + line, col := lineOf(m[2]) + s.jibRef(rel, line, col, text[m[2]:m[3]]) } } @@ -1004,11 +1079,8 @@ func (s *scanner) maven(rel, text string) { if strings.Contains(l, "") || strings.Contains(l, "") { inToolchain = false } - if m := bpJVM.FindStringSubmatch(l); m != nil { - s.buildpack(rel, i+1, m[1]) - } - s.jib(rel, i+1, l) } + s.settings(rel, text) for _, m := range enforcerJava.FindAllStringSubmatchIndex(text, -1) { floor := strings.TrimSpace(text[m[2]:m[3]]) line := strings.Count(text[:m[2]], "\n") + 1 @@ -1034,10 +1106,8 @@ func (s *scanner) maven(rel, text string) { } func (s *scanner) projectToml(rel, text string) { + s.settings(rel, text) for i, l := range lines(text) { - if m := bpJVM.FindStringSubmatch(l); m != nil { - s.buildpack(rel, i+1, m[1]) - } if strings.HasSuffix(rel, "jib.yaml") { if m := regexp.MustCompile(`^\s*image\s*:\s*["']?([A-Za-z0-9][\w./:@-]*)`).FindStringSubmatchIndex(l); m != nil { s.jibRef(rel, i+1, m[2], l[m[2]:m[3]]) @@ -1060,14 +1130,6 @@ func (s *scanner) buildpack(rel string, line int, ver string) { } } -func (s *scanner) jib(rel string, line int, l string) { - m := jibFrom.FindStringSubmatchIndex(l) - if m == nil { - return - } - s.jibRef(rel, line, m[2], l[m[2]:m[3]]) -} - // jibRef judges a Jib base image like an image reference. func (s *scanner) jibRef(rel string, line, col int, image string) { r := refs.Ref{File: rel, Line: line, Column: col + 1, Kind: "jib", Context: "jib.from.image", Text: image, Image: image, From fe38fc82ff6dbba9dcb656325ff030d0bb08cf1b Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:48:11 +0000 Subject: [PATCH 107/119] java4shell: fix says what was not checked and does not change a .env value another file uses Final review B7. fix skipped every note that was not of the not-checked rule, so a tree whose only findings were unknown (a package the scan cannot read, a vendor's own package, an Enforcer floor) printed nothing and exited 0 while scan exited 3. Every unknown finding is printed as not checked now, and the exit status is 1. A tag held in a .env variable was edited after counting the variable's uses in the one Compose file that led to it. Another Compose file of the directory that uses the variable for a different image got the new tag too. fix declines when a file next to the .env uses the variable as well. Co-Authored-By: Claude Fable 5.2 --- detectors/java4shell/coverage_test.go | 21 +++++++++++ .../java4shell/internal/repo/final_test.go | 34 ++++++++++++++++++ detectors/java4shell/internal/repo/plan.go | 36 +++++++++++++++++++ detectors/java4shell/repo.go | 7 ++-- 4 files changed, 96 insertions(+), 2 deletions(-) diff --git a/detectors/java4shell/coverage_test.go b/detectors/java4shell/coverage_test.go index cc140d1..8b8ea21 100644 --- a/detectors/java4shell/coverage_test.go +++ b/detectors/java4shell/coverage_test.go @@ -1,6 +1,7 @@ package java4shell_test import ( + "bytes" "github.com/DefectDojo/earlylight/detectors/java4shell" "os" "path/filepath" @@ -9,6 +10,7 @@ import ( "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" + "github.com/DefectDojo/earlylight/internal/cli" "github.com/DefectDojo/earlylight/internal/engine" ) @@ -115,3 +117,22 @@ func TestRedHatRowNeedsRHEL(t *testing.T) { } } } + +// Final review B7: fix says what it could not check and does not exit 0 +// over it: findings the scan reports as unknown are printed as not checked. +func TestFixPrintsUnknowns(t *testing.T) { + for name, files := range map[string]map[string]string{ + "packages it cannot read": {"Dockerfile": "FROM debian\nRUN apt-get install -y zulu21-jdk\nRUN rpm -i https://example.com/dl/jdk.rpm\n"}, + "an Enforcer floor": {"pom.xml": "\n[17.0.6,)\n\n"}, + } { + root := t.TempDir() + for rel, body := range files { + write(t, root, rel, []byte(body)) + } + var out, errb bytes.Buffer + code := cli.Run(cfg, []string{"fix", "--detector", "java4shell", "--dry-run", "--offline", root}, &out, &errb) + if code != 1 || !strings.Contains(out.String(), "not checked") { + t.Errorf("%s: exit %d, output %q %q", name, code, out.String(), errb.String()) + } + } +} diff --git a/detectors/java4shell/internal/repo/final_test.go b/detectors/java4shell/internal/repo/final_test.go index 27cd928..fa9aead 100644 --- a/detectors/java4shell/internal/repo/final_test.go +++ b/detectors/java4shell/internal/repo/final_test.go @@ -271,3 +271,37 @@ func TestComposeBuildArgs(t *testing.T) { } } } + +// Final review B7: a .env value that another Compose file of the directory +// uses too is shared: fix does not change it. +func TestEnvSharedAcrossComposeFiles(t *testing.T) { + reg := Registry{ + Tags: func(context.Context, string) ([]string, error) { + return []string{"21.0.13_9-jre", "21.0.13.1_2-jre"}, nil + }, + Verify: func(context.Context, string, string) (string, error) { return "sha256:abc", nil }, + } + plan := func(files map[string]string) (*Change, error) { + root := tree(t, files) + res, err := Scan(context.Background(), root, Options{}) + if err != nil { + t.Fatal(err) + } + for _, f := range res.Findings { + if f.Fixable { + return Plan(context.Background(), root, f, reg, Options{}) + } + } + t.Fatalf("nothing to fix: %+v", res.Findings) + return nil, nil + } + own := map[string]string{".env": "JAVA_TAG=21.0.13_9-jre\n", "docker-compose.yml": "services:\n a:\n image: eclipse-temurin:${JAVA_TAG}\n"} + if ch, err := plan(own); err != nil || ch.File != ".env" { + t.Errorf("a variable one file uses: %v %+v", err, ch) + } + shared := map[string]string{".env": own[".env"], "docker-compose.yml": own["docker-compose.yml"], + "docker-compose.prod.yml": "services:\n b:\n image: registry.example.com/base/runtime:${JAVA_TAG}\n"} + if ch, err := plan(shared); err == nil { + t.Errorf("a variable two Compose files use was changed: %+v", ch) + } +} diff --git a/detectors/java4shell/internal/repo/plan.go b/detectors/java4shell/internal/repo/plan.go index 675704b..0c51c11 100644 --- a/detectors/java4shell/internal/repo/plan.go +++ b/detectors/java4shell/internal/repo/plan.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "os" + "path" "path/filepath" "regexp" "sort" @@ -159,6 +160,13 @@ func planTag(ctx context.Context, root string, f Finding, reg Registry, opts Opt if n, err := varUses(root, r.File, part.Var, opts); err != nil || n > 1 { return nil, declined("%s gets its tag from %s, which %s uses in more than one place; change it by hand", e.image, part.Var, r.File) } + // A variable set in another file (.env) is read by every Compose + // file next to it. + if file != r.File { + if other, err := varUsedBeside(root, file, r.File, part.Var, opts); err != nil || other != "" { + return nil, declined("%s gets its tag from %s in %s, which %s uses too; change it by hand", e.image, part.Var, file, other) + } + } } digest, err := reg.Verify(ctx, e.image, newImage) if err != nil { @@ -326,6 +334,34 @@ func varUses(root, file, name string, opts Options) (int, error) { return len(re.FindAllIndex(b, -1)), nil } +// varUsedBeside names another file in the directory of def (the file that +// sets a variable) that uses the variable too, "" when only user does. +func varUsedBeside(root, def, user, name string, opts Options) (string, error) { + dir, p := path.Dir(def), root + if dir != "." { + var err error + if p, err = refs.SafePath(root, dir); err != nil { + return "", err + } + } + entries, err := os.ReadDir(p) + if err != nil { + return "", err + } + for _, e := range entries { + rel := path.Join(dir, e.Name()) + if !e.Type().IsRegular() || rel == def || rel == user || kindOf(rel) != "yaml" && kindOf(rel) != "dockerfile" { + continue + } + if n, err := varUses(root, rel, name, opts); err != nil { + return rel, err + } else if n > 0 { + return rel, nil + } + } + return "", nil +} + // baseOSWords name a base OS in a tag's variant. var baseOSWords = []string{"alpine", "jammy", "noble", "focal", "resolute", "plucky", "ubuntu", "debian", "bookworm", "trixie", "bullseye", "ubi", "al2023", "al2", "centos", "rocky", "alma", "windowsservercore", "nanoserver", "distroless", "wolfi", "chainguard"} diff --git a/detectors/java4shell/repo.go b/detectors/java4shell/repo.go index dd333ce..c6db9ea 100644 --- a/detectors/java4shell/repo.go +++ b/detectors/java4shell/repo.go @@ -255,10 +255,13 @@ func (d *Detector) Fix(ctx context.Context, dirs []string, o engine.Options, std continue } // A mitigated pin still needs the update, so fix moves it too. - if f.Level == "note" && f.Rule != repo.RuleNotChecked && f.Status != repo.StatusMitigated { + // What the scan could not check is said, whatever its rule (a + // package it cannot read, an Enforcer floor): fix never + // reports success over it. + if f.Level == "note" && f.Rule != repo.RuleNotChecked && f.Status != repo.StatusMitigated && f.Status != repo.StatusUnknown { continue } - if f.Rule == repo.RuleNotChecked { + if f.Rule == repo.RuleNotChecked || f.Status == repo.StatusUnknown { fmt.Fprintf(stdout, "not checked %s %s\n", where, repo.Printable(f.Message)) code = max(code, 1) continue From 8dbc868a62a9d64fd57cb6b2857d0f152acf748d Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 11:48:24 +0000 Subject: [PATCH 108/119] java4shell: FACTS.md says how several VM libraries, linked libraries and OpenJ9 are judged Co-Authored-By: Claude Fable 5.2 --- detectors/java4shell/FACTS.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/detectors/java4shell/FACTS.md b/detectors/java4shell/FACTS.md index 0eb80fa..c0276f3 100644 --- a/detectors/java4shell/FACTS.md +++ b/detectors/java4shell/FACTS.md @@ -120,6 +120,11 @@ OpenJDK fix commit and Amazon Corretto's changelog. - The version that decides is the one inside the libjvm (` () for - JRE ()`), read from the binary, with the `release` file as a second witness; the CPU architecture comes from the ELF, PE or Mach-O header. +- A runtime directory that holds several VM libraries (server and client or minimal VMs, a Java 8 `lib/amd64/server` left by an upgrade + in place) is judged by every library that states a version or carries the decoder, and the worst verdict is the runtime's. A VM library + that is a symbolic or hard link to a file with another name is never read under its own name, so that runtime is unknown. +- OpenJ9 is taken from an OpenJ9 VM library by name (`libj9vm29.so`). The `lib/server/libjvm.so` redirector's string + (`OPENJ9_JAVA_OPTIONS`) counts only with such a library in the runtime or a release file that names OpenJ9. - A packaged JDK (apk, dpkg, rpm) is judged by the same upstream version: no distribution has published a fixed package or a backport statement yet. Red Hat's fixed builds, once published, go into the Red Hat backport table, which clears a runtime only when its libjvm is that exact build and the release file and os-release confirm Red Hat (see "Red Hat"). From 7f25a681fa78aa56945388bcbb19f9c2f17f0c5c Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 12:16:34 +0000 Subject: [PATCH 109/119] ci: fuzz FuzzFlatten, FuzzLimits and FuzzRPM like the other fuzzers Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f46a670..c2bf1a7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,6 +25,8 @@ jobs: run: | go test ./internal/source -run '^$' -fuzz '^FuzzTar$' -fuzztime 30s go test ./internal/archive -run '^$' -fuzz '^FuzzWalk$' -fuzztime 30s + go test ./internal/image -run '^$' -fuzz '^FuzzFlatten$' -fuzztime 30s + go test ./internal/engine -run '^$' -fuzz '^FuzzLimits$' -fuzztime 30s go test ./detectors/emudhra/internal/detect -run '^$' -fuzz '^FuzzScan$' -fuzztime 30s go test ./detectors/php2shell/internal/detect -run '^$' -fuzz '^FuzzInspect$' -fuzztime 20s go test ./detectors/brotli/internal/fingerprint -run '^$' -fuzz '^FuzzFingerprint$' -fuzztime 30s @@ -36,6 +38,7 @@ jobs: go test ./detectors/java4shell/internal/jvm -run '^$' -fuzz '^FuzzInspect$' -fuzztime 30s go test ./detectors/java4shell/internal/jvm -run '^$' -fuzz '^FuzzSettings$' -fuzztime 30s go test ./detectors/java4shell/internal/knowledge -run '^$' -fuzz '^FuzzParse$' -fuzztime 20s + go test ./detectors/java4shell/internal/knowledge -run '^$' -fuzz '^FuzzRPM$' -fuzztime 15s go test ./detectors/java4shell/internal/repo -run '^$' -fuzz '^FuzzScanText$' -fuzztime 30s go test ./detectors/java4shell/internal/jvm -run '^$' -fuzz '^FuzzParseRelease$' -fuzztime 15s go test ./detectors/java4shell/internal/assess -run '^$' -fuzz '^FuzzAPKOwners$' -fuzztime 15s From e257b1a15b7edb2093dbf0bf0329829034858a98 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 12:17:54 +0000 Subject: [PATCH 110/119] java4shell: README and FACTS.md match the sources: 43 parity cases, CPU models, release dates, ID=rhel README: the parity list counts 43 cases and names the GraalVM CE and Debian sid ones; the Red Hat backport table also needs os-release ID=rhel; the row says how several VM libraries, linked libraries, OpenJ9, the library cap and unread start scripts are judged; 27.0.1.1 was tagged on November 17, not 15; the CPU models follow GCC's CPU tables (the E-core Xeon 6 has no AVX-512). FACTS.md: a sourced row for which CPUs have the four flags (GCC 14.2 -march tables, the research host's EPYC 9B14; cloud prevalence marked inferred); the 18 to 24 row cites the update repositories' last releases; the fixed releases carry their tag dates. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++-- detectors/java4shell/FACTS.md | 11 ++++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 79dcf72..fe91db2 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ One engine for DefectDojo's emerging-vulnerability scanners. Each new vulnerabil | `php2shell` | PHP runtimes vulnerable to CVE-2026-109618 and CVE-2026-109619 ("PHP2Shell"), fixed in PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12 ([GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w), [GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp)). A packaged PHP is judged by its vendor's backport data, never by the version it reports. Also checks the images a source tree builds on and deploys, and can rewrite them to fixed images | `fs`, `image`, `repo`, `fix` | | `brotli` | Brotli decoders vulnerable to CVE-2026-111497 ("Node2Shell", "Broccoli2Shell"), Brotli 1.0.3 through 1.2.0, fixed in 1.0.10, 1.1.1 and 1.2.1 ([GHSA-9v8h-qqgm-4m35](https://github.com/advisories/GHSA-9v8h-qqgm-4m35)): system `libbrotlidec` and every copy bundled into other software (Node.js, .NET, Bun, Electron, Envoy and Istio, Python wheels such as Pillow, pyarrow, duckdb, pycurl and PyMuPDF, brotli4j, and more), on Linux, Windows and macOS. A decoder is judged first by the error code the fix added, so vendor backports are recognised without distribution data; a build that strips it by its own version stamp or by its code, which returns that error code only once fixed. In a source tree it finds the Node.js, .NET and Bun releases and the bundling packages a project pins, and `fix` moves each to the fixed release | `fs`, `image`, `repo`, `fix` | | `sshole` | \*sshole, the OpenSSH password authentication bypass on musl libc fixed in OpenSSH 10.6p2 and in Alpine's openssh packages of November 5, 2026 ([release notes](https://www.openssh.org/releasenotes.html#10.6p2), [writeup](https://sshhole.com)). On musl, sshd from 7.3p1 to 10.6p1 compares an account's password field of `*` with the `*` that crypt returns when it fails, so a crafted password logs in to that account. It judges each installed sshd by its C library, its release and the apk database (Alpine backports keep the release number), then checks what the target's `sshd_config` (Include, Match, PasswordAuthentication, AuthenticationMethods, PermitRootLogin, AllowUsers and the rest) and account files make reachable, and reports the accounts. In an image it also reads the command (`sshd -o` and `-f`) and the startup scripts it runs (entrypoints, s6, cont-init.d), and reports a server as exposed when a startup script turns password logins on, sets a `*` field or sets passwords. OpenWrt's opkg database and its backports (23.05, 24.10, 25.12) count like Alpine's. PAM-checked builds (`UsePAM yes`) are not affected. On a live server it reads the banner and the offered methods and never sends a password. In a source tree it finds Dockerfiles that install an OpenSSH server on Alpine without the fix (package lists in `ARG` and `ENV` too), Ansible apk tasks, Buildroot, OpenWrt and Yocto configurations that build one on musl, and anything that sets a password field to `*`. It also pulls the images the tree references (through the guarded transport, with the command a Compose service or Kubernetes container sets) and judges them like `scan image`. `fix` adds the fixed release floor (in the variable when the list is one), moves an end-of-life Alpine base to a tag on the nearest fixed Alpine release (`alpine:3.14` to `3.16`, `python:3.9-alpine3.14` to `3.9-alpine3.16` after checking that image) as a labelled upgrade, adds upstream commit 4353fdc43 as a patch scoped to the OpenSSH versions it applies to (Buildroot `BR2_GLOBAL_PATCH_DIR`, a version-specific Yocto bbappend), sets Ansible tasks to `state: latest`, and changes `*` to `*NP*` | `fs`, `image`, `host`, `repo`, `fix` | -| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64, fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 on November 15, 2026 by JDK-8393212 ([commit](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b); that this change is the CVE's fix is inferred: the [OpenJDK advisory](https://openjdk.org/groups/vulnerability/advisories/2026-11-17) confirms the component (hotspot/compiler), the lines (17, 21, 25, 27) and the last affected releases (17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3) but names no JDK bug: see the [knowledge table](detectors/java4shell/FACTS.md)). CVSS 8.1 (OpenJDK and Oracle). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel server CPUs from Ice Lake on and some client CPUs, not Alder Lake or Raptor Lake; AMD Zen 4 and later); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds Java runtimes by their VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others); a JDK download sitting in the target (OpenJDK21U-jre_…tar.gz and the like) is recorded by name as context, not read or unpacked. Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; each platform of a multi-arch image is judged on its own with `--platform all`), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness: when the library's version line can be read, the library decides and a different release-file version is only noted; a release file naming OpenJ9 next to HotSpot evidence makes the verdict unknown; and a release file alone does not clear a runtime (OpenJ9 is recognised from its own VM library, not from the release file). No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version and build (the first fixed build of each release, such as 21.0.13.1+2; pre-release builds are not judged fixed, and a self-built JDK at a build boundary is unknown). A GraalVM JDK (a `-jvmci-` version line; Oracle lists GraalVM for JDK 17 and 21 and GraalVM Enterprise 21.3 as affected) is vulnerable where its OpenJDK version is and fixed only at a published fixed GraalVM build (none yet). A Red Hat rpm build is judged by its VM library unless Red Hat's backport table, keyed on the rpm release's stream (el9_6) and upstream build, lists a fixed build and the runtime confirms it (its VM library is that exact update and build, its release file names Red Hat); the table is empty: Red Hat had published none. OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is recorded as a mitigation on a finding that stays vulnerable (status `mitigated`, counted in the exit status): the options can be overridden where the runtime is deployed, and the runtime still needs the update; `_JAVA_OPTIONS` turning the intrinsic back on undoes it. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context; neither clears a runtime. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft, Oracle, GraalVM and Red Hat UBI `openjdk-NN` images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | +| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64, fixed in OpenJDK 17.0.21.1, 21.0.13.1 and 25.0.5.1 (tagged November 15, 2026) and 27.0.1.1 (tagged November 17) by JDK-8393212 ([commit](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b); that this change is the CVE's fix is inferred: the [OpenJDK advisory](https://openjdk.org/groups/vulnerability/advisories/2026-11-17) confirms the component (hotspot/compiler), the lines (17, 21, 25, 27) and the last affected releases (17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3) but names no JDK bug: see the [knowledge table](detectors/java4shell/FACTS.md)). CVSS 8.1 (OpenJDK and Oracle). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (going by GCC's CPU tables: Intel Xeon from Ice Lake on except the E-core Xeon 6, and the client Cannon Lake, Ice Lake, Tiger Lake and Rocket Lake, not Alder Lake or later; AMD Zen 4 and Zen 5; the detector reads the flags, not the model); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds Java runtimes by their VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others); a JDK download sitting in the target (OpenJDK21U-jre_…tar.gz and the like) is recorded by name as context, not read or unpacked. Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; each platform of a multi-arch image is judged on its own with `--platform all`), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness: when the library's version line can be read, the library decides and a different release-file version is only noted; a release file naming OpenJ9 next to HotSpot evidence makes the verdict unknown; and a release file alone does not clear a runtime. A runtime directory with several VM libraries (server, client, minimal, a Java 8 `lib/amd64/server` left by an upgrade in place) is judged by every library that states a version or carries the decoder, and the worst verdict is the runtime's; a VM library that is a link to a file with another name cannot be read under its own name, so that runtime is unknown. OpenJ9 is recognised from its own VM library (`libj9vm29.so`), or from the `libjvm.so` redirector only when a release file also names OpenJ9. Past 4096 VM libraries the scan is capped: no runtime is cleared and the target reports the cap as a problem. No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version and build (the first fixed build of each release, such as 21.0.13.1+2; pre-release builds are not judged fixed, and a self-built JDK at a build boundary is unknown). A GraalVM JDK (a `-jvmci-` version line; Oracle lists GraalVM for JDK 17 and 21 and GraalVM Enterprise 21.3 as affected) is vulnerable where its OpenJDK version is and fixed only at a published fixed GraalVM build (none yet). A Red Hat rpm build is judged by its VM library unless Red Hat's backport table, keyed on the rpm release's stream (el9_6) and upstream build, lists a fixed build and the runtime confirms it (its VM library is that exact update and build, its release file names Red Hat and the target's os-release says `ID=rhel`, so Rocky, AlmaLinux and CentOS Stream are not cleared by it); the table is empty: Red Hat had published none. OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is recorded as a mitigation on a finding that stays vulnerable (status `mitigated`, counted in the exit status): the options can be overridden where the runtime is deployed, and the runtime still needs the update; `_JAVA_OPTIONS` turning the intrinsic back on undoes it, and no mitigation is recorded when the command reaches a start script that was not read or one that turns the intrinsic back on. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context; neither clears a runtime. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft, Oracle, GraalVM and Red Hat UBI `openjdk-NN` images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | The detectors ported from standalone scanners also build as standalone binaries under the names people search for: `emudhra-scan` and `php2shell-scan`. They keep their original commands, flags and exit status rules. `brotli`, `sshole` and `java4shell` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`, `--detector java4shell`). @@ -133,7 +133,7 @@ Every port must give exactly the verdicts of the scanner it came from before it - `parity/brotli.py` has no standalone scanner to compare with, so it checks every decoder in 38 images against the vendor's own fix status: Node.js, .NET, Bun, Envoy and curl images before and after their October 2026 releases, distribution packages pinned to their exact unfixed and backported builds, and the Python wheels ([BROTLI-RESULTS.md](parity/BROTLI-RESULTS.md)). - `parity/brotli_files.py` checks 73 release binaries and packages, unpacked and never run: Node.js, .NET and Bun for Windows and macOS, seven Electron releases, Envoy and Istio, and the packages that bundle the decoder ([BROTLI-FILES-RESULTS.md](parity/BROTLI-FILES-RESULTS.md)). A WebAssembly build of the decoder is the one case it cannot settle: it is reported as unknown. - `parity/sshole.py` builds ten images from `parity/sshole/` (Alpine with the unfixed and the fixed package, password logins off, UsePAM on, root with PermitRootLogin, a Match on address, the current Alpine release, Debian, an entrypoint that turns password logins on at start, and `sshd -o` in the image command) and checks each verdict against the expected one ([SSHOLE-RESULTS.md](parity/SSHOLE-RESULTS.md)). The expected verdicts come from the upstream fix, musl's crypt and shadow code, and the Alpine package that shipped it. -- `parity/java4shell.py` checks 39 cases against verdicts taken from [FACTS.md](detectors/java4shell/FACTS.md), and that each version came from the VM library (not the release file): Temurin 8, 11, 17.0.5, 17.0.6, 17.0.21 and 21.0.13 on Alpine (musl), a musl library under a forged release file, a fixed release rewritten to the build before the fix (synthetic), 18, 20, 21 (also arm64, all platforms of the image, UBI 9), 25 and 27, Corretto (an Amazon Linux rpm and Alpine, before and after Amazon republished their tags with the fix), Zulu, Liberica, SapMachine, Semeru, Elasticsearch's bundled JDK, the fixed SapMachine 21.0.13.1, a jlink image, bundled product runtimes with and without `setenv.sh`, Alpine, Debian and Ubuntu packages, environment, Tomcat CATALINA_OPTS and setenv.sh mitigations and one that is undone, hostile release files and symlink loops, a filesystem scan and an offline source tree ([JAVA4SHELL-RESULTS.md](parity/JAVA4SHELL-RESULTS.md)). +- `parity/java4shell.py` checks 43 cases against verdicts taken from [FACTS.md](detectors/java4shell/FACTS.md), and that each version came from the VM library (not the release file): Temurin 8, 11, 17.0.5, 17.0.6, 18, 20, 21 (also arm64, all platforms of the image, UBI 9), 25 and 27, Temurin 17.0.21 and 21.0.13 on Alpine (musl), a musl library under a forged release file, a fixed release rewritten to the build before the fix (synthetic), Corretto (an Amazon Linux rpm and Alpine, before and after Amazon republished their tags with the fix), Zulu, Liberica, SapMachine, Semeru, GraalVM CE 22.3.0 and 22.3.1 for Java 17 and GraalVM CE for JDK 21, Elasticsearch's bundled JDK, the fixed SapMachine 21.0.13.1, a jlink image, bundled product runtimes with and without `setenv.sh`, Alpine, Debian 12, Debian sid (the five-part 17.0.21.0.3) and Ubuntu packages, environment, Tomcat CATALINA_OPTS and setenv.sh mitigations and one that is undone, hostile release files and symlink loops, a filesystem scan and an offline source tree ([JAVA4SHELL-RESULTS.md](parity/JAVA4SHELL-RESULTS.md)). - `parity/php.py` runs php2shell-scan, this repo's php2shell-scan and Early Light over php2shell-scan's validation matrix: official images, distribution packages, source builds and hostile images. Each finding's complete record is compared field by field. It also covers filesystem scans at and below a system root, repository scans, `fix --dry-run`, and every detector at once ([PHP-RESULTS.md](parity/PHP-RESULTS.md)). ## Adding a detector diff --git a/detectors/java4shell/FACTS.md b/detectors/java4shell/FACTS.md index c0276f3..ae7a353 100644 --- a/detectors/java4shell/FACTS.md +++ b/detectors/java4shell/FACTS.md @@ -25,6 +25,7 @@ The research host cannot reach openjdk.org, oracle.com or access.redhat.com; the | CVE-2026-114938 is listed with CVSS 8.1, component hotspot/compiler, in Amazon Corretto's changelogs of 2026-11-17 | [corretto-17 CHANGELOG 17.0.21.1.2](https://github.com/corretto/corretto-17/blob/17.0.21.1.2/CHANGELOG.md), [corretto-21 21.0.13.1.2](https://github.com/corretto/corretto-21/blob/21.0.13.1.2/CHANGELOG.md), [corretto-25 25.0.5.1.2](https://github.com/corretto/corretto-25/blob/25.0.5.1.2/CHANGELOG.md), [corretto-27 27.0.1.1.4](https://github.com/corretto/corretto-27/blob/27.0.1.1.4/CHANGELOG.md) | | CVE-2026-114938 is JDK-8393212. Neither the Corretto changelogs (CVEs by component) nor the OpenJDK advisory (no JDK bug ids) state the mapping. The advisory does confirm what 8393212 fits: component hotspot/compiler, lines 17, 21, 25 and 27 (the lines with the AVX-512 VBMI decoder), and last affected releases just before the .1 releases that carry 8393212. The public writeups (lead's sources below) describe exactly the code 8393212 changes: the output mask computed from length and padding, `output_len` underflowing on a padding-only tail, `bzhiq(-1, output_len)` giving all ones and `evmovdqub` writing all 64 bytes. **Inferred from that match**, not stated by a source | Corretto changelogs; OpenJDK advisory; Calif and Semgrep writeups as relayed by the lead | | The vulnerable path runs only when the CPU reports AVX-512 VBMI, AVX-512BW and BMI2 and HotSpot keeps them enabled: `if (VM_Version::supports_avx512_vbmi() && VM_Version::supports_avx512bw() && VM_Version::supports_bmi2())`. AVX-512 features need AVX-512F, so the four CPU flags are `avx512f avx512bw avx512vbmi bmi2` | stubGenerator_x86_64.cpp at the fix commit | +| Which CPUs report all four flags. The fix commit and the OpenJDK advisory name no CPU models (the stub tests the flags, not the model), so a model list is guidance; the detector does not use one. GCC's per-CPU ISA tables give all four to Intel `cannonlake`, `icelake-client`, `icelake-server`, `tigerlake`, `rocketlake`, `sapphirerapids`, `emeraldrapids` and `graniterapids` and to AMD `znver4` and `znver5`. They give AVX-512 without VBMI to `skylake-avx512`, `cascadelake` and `cooperlake`, and no AVX-512 to `alderlake`, `raptorlake`, `meteorlake`, `arrowlake`, `lunarlake`, `pantherlake`, the E-core Xeons `sierraforest`, `grandridge` and `clearwaterforest`, or `znver3`. **Observed**: the research host, a Google Cloud VM on an AMD EPYC 9B14 (Zen 4), reports all four. **Not verified**: single SKUs or firmware that differ from GCC's table (early Alder Lake boards could expose AVX-512 with the E-cores off) and hypervisors that hide AVX-512 from a guest. That such CPUs are common on cloud instances is **inferred** from the instance families built on Ice Lake, Sapphire Rapids and Zen 4, not counted | `gcc -march= -dM -E -` (GCC 14.2.0, Alpine 3.22), 2026-11-18; `/proc/cpuinfo` on the research host | | MIME decoding (`isMIME`) skips the AVX-512 path; standard and URL-safe decoding use it | same function, `cmpl(isMIME, 0)` | | `-XX:UseAVX=0/1/2` clears every AVX-512 feature, VBMI included, so the path is not generated | `src/hotspot/cpu/x86/vm_version_x86.cpp`, `if (UseAVX < 3)` block (jdk17u-dev and jdk HEAD) | | `-XX:-UseBASE64Intrinsics` stops the stub being generated at all: `if (UseBASE64Intrinsics) { ... StubRoutines::_base64_decodeBlock = generate_base64_decodeBlock(); }` | stubGenerator_x86_64.cpp | @@ -61,13 +62,13 @@ The lead read these; they could not be fetched from the research host. Facts her | Line | Fixed in | Source | | --- | --- | --- | -| OpenJDK 17 | **17.0.21.1** (`jdk-17.0.21.1+2`, `jdk-17.0.21.1-ga`, 2026-11-15) | openjdk/jdk17u branch `jdk17.0.21.1`, commit `8ea73158af` | -| OpenJDK 21 | **21.0.13.1** (`jdk-21.0.13.1+2`, `-ga`, 2026-11-15) | openjdk/jdk21u branch `jdk21.0.13.1`, commit `8e115fb5c7` | -| OpenJDK 25 | **25.0.5.1** (`jdk-25.0.5.1+2`, `-ga`, 2026-11-15) | openjdk/jdk25u branch `jdk25.0.5.1`, commit `25bb7d35dc` | -| OpenJDK 27 | **27.0.1.1** (`jdk-27.0.1.1+4`, `-ga`) | openjdk/jdk27u branch `jdk27.0.1.1`, commit `564fc7de7e`; master also has it. The `jdk27.0.2` branch does **not** have it yet | +| OpenJDK 17 | **17.0.21.1** (`jdk-17.0.21.1+2`, `jdk-17.0.21.1-ga`, tagged 2026-11-15 23:54 UTC) | openjdk/jdk17u branch `jdk17.0.21.1`, commit `8ea73158af` | +| OpenJDK 21 | **21.0.13.1** (`jdk-21.0.13.1+2`, `-ga`, tagged 2026-11-15 23:54 UTC) | openjdk/jdk21u branch `jdk21.0.13.1`, commit `8e115fb5c7` | +| OpenJDK 25 | **25.0.5.1** (`jdk-25.0.5.1+2`, `-ga`, tagged 2026-11-15 23:54 UTC) | openjdk/jdk25u branch `jdk25.0.5.1`, commit `25bb7d35dc` | +| OpenJDK 27 | **27.0.1.1** (`jdk-27.0.1.1+4`, `-ga`, tagged 2026-11-17: `-ga` 17:57 UTC, `+4` 18:39 UTC) | openjdk/jdk27u branch `jdk27.0.1.1`, commit `564fc7de7e`; master also has it. The `jdk27.0.2` branch does **not** have it yet. Tag dates: the annotated tags' tagger dates in each repository, read 2026-11-18 (17, 21 and 25 were tagged together; the commits they point at are dated 2026-11-15) | | Builds of the fixed releases before the fix landed | **not fixed**: `jdk-17.0.21.1+0` (2026-10-27) and `+1` (2026-11-02), `jdk-21.0.13.1+0` and `+1`, `jdk-25.0.5.1+0` and `+1` do not contain the `cmpl(length, 4)` guard; `+2` (2026-11-15) does. `jdk-27.0.1.1+0` does not; `jdk-27.0.1.1+4` does (27u has no `+1` to `+3` tags). The detector's fixed build per line: 17.0.21.1+2, 21.0.13.1+2, 25.0.5.1+2, 27.0.1.1+4; a version named without its build (a GA tag, a version file) is taken as the GA build. Pre-release and self-built JDKs (`-ea`, `-beta`, `-internal`, `adhoc`) are never judged fixed | `git show :src/hotspot/cpu/x86/stubGenerator_x86_64.cpp` in openjdk/jdk17u, jdk21u, jdk25u, jdk27u, checked 2026-11-18 | | OpenJDK 26 | **no fix**: last release 26.0.2.1 (2026-07), `jdk26u` master unchanged since 2026-08-18 and without the fix | openjdk/jdk26u | -| 18, 19, 20, 22, 23, 24 | **no fix** (end of life) | n/a | +| 18, 19, 20, 22, 23, 24 | **no fix** (end of life). Last releases (date of the commit each `-ga` tag points at): 18.0.2.1 (2022-08), 19.0.2 (2022-11), 20.0.2 (2023-06), 22.0.2 (2024-06), 23.0.2 (2024-11), 24.0.2 (2025-06); no master branch has a commit after 2025-07-15. The OpenJDK advisory and Oracle's CSPU name only the 17, 21, 25 and 27 lines (and Oracle's 8u-perf) | openjdk/jdk18u, jdk19u, jdk20u, jdk22u, jdk23u, jdk24u: newest `-ga` tag and master HEAD with their commit dates, read 2026-11-18; OpenJDK advisory; Oracle CSPU | | JDK 28 (early access) | fix pushed to mainline 2026-11-16; `jdk-28+24` does **not** have it; no later build tagged yet | openjdk/jdk tags | | 17.0.22, 21.0.14, 25.0.6 (January 2027 updates) | **not known**: the -dev repositories (HEAD of 2026-11-17, tags up to `+2`) do not have the fix yet. Embargoed fixes usually reach -dev at the next release; that is an expectation, not a fact, so these versions are reported as unknown | openjdk/jdk17u-dev, jdk21u-dev, jdk25u-dev HEAD | | 17.0.21.0.2 / .0.3, 21.0.13.0.2 / .0.3, 25.0.5.0.2 / .0.3, 27.0.1.0.2 / .0.3 | **not fixed**: these October 2026 out-of-band releases carry CA changes only (8395142, 8395690); the OpenJDK advisory and Oracle name the .0.3 releases as the last affected. Vendors ship them as five-part versions (Oracle and Debian sid 17.0.21.0.3, Microsoft 17.0.21.0.2 / 21.0.13.0.2 / 25.0.5.0.2, Temurin 27.0.1.0.2+1); the detector judges every one vulnerable, from the VM library, the release file, OS package pins, image tags and version files | -dev repo tags `jdk-*.0.3+*`; OpenJDK advisory; Oracle CSPU | From e0356fb36a7baf84e8ac8a9b90532592f74dcede Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 12:46:55 +0000 Subject: [PATCH 111/119] sshole: a -c after the shell's script, a script found on PATH and an option's value do not decide Second final review, finding 1. ab9090c made arguments of the command unable to lower a verdict, but only when the program is the command's first word. Written "sh SCRIPT", the same layouts were still lower than main: - ENTRYPOINT ["/bin/sh","/entry.sh"] with CMD ["sh","-c","while pgrep sshd ..."], entry.sh starting sshd with -o UsePAM=no: critical on main, inactive here. The first shell looked through every later word for a -c and took the one that belongs to the argument shell as the container's command, which then decided alone. The same behind tini and dumb-init, and for ["sh","/entry.sh","-c",TEXT]. - ["sh","entry.sh"] took /usr/local/bin/entry.sh as the program. A shell looks in the working directory first, which the scan does not know. - ["env","-u","start","/usr/bin/app"] took the script /usr/bin/start, the value of -u, as the program; ["bash","-lc","sshd -o LogLevel=DEBUG","entry.sh"] took the text for an assignment and $0 for the program. Now a shell's search for -c stops at its first operand (the script it runs), a script named without a slash after a shell or right after an option is judged as an argument is (with the others, never alone), and an assignment is NAME=value, not any word with "=". It also takes back a false alarm: ["/bin/bash","/entry.sh"] with CMD ["supervisord","-c",conf] read the config path as shell text and reported critical for medium. On the review's 191 image fixtures every one of these is main's verdict again; what is still lower than main is the script behind tini --, su-exec and env that main never read, and an apk database over 4 MiB. Co-Authored-By: Claude Fable 5.2 --- .../sshole/internal/assess/argument_test.go | 56 +++++++++++++++++++ detectors/sshole/internal/assess/runtime.go | 36 +++++++++++- 2 files changed, 89 insertions(+), 3 deletions(-) diff --git a/detectors/sshole/internal/assess/argument_test.go b/detectors/sshole/internal/assess/argument_test.go index 9d0644d..6887959 100644 --- a/detectors/sshole/internal/assess/argument_test.go +++ b/detectors/sshole/internal/assess/argument_test.go @@ -41,3 +41,59 @@ func TestArgumentNeverLowers(t *testing.T) { } } } + +// Second final review, finding 1: the same rule when the entrypoint is +// written "sh SCRIPT". A -c after the shell's script belongs to the script, +// a script named without a slash may not be the one found on PATH, and the +// value of a wrapper's option is not the program. main judged each of +// these by sshd_config and the script it names by path; none may be lower. +func TestShellOperandNeverLowers(t *testing.T) { + yes := "#!/bin/sh\n/usr/sbin/sshd -D -o UsePAM=yes\n" + no := "#!/bin/sh\nexec /usr/sbin/sshd -D -o UsePAM=no\n" + starts := "#!/bin/sh\n/usr/sbin/sshd -o UsePAM=no\nexec \"$@\"\n" + watch := "while pgrep sshd >/dev/null; do sleep 5; done" + for _, c := range []struct { + name string + cmd []string + scripts map[string]string + cfg string + want string // status/severity + }{ + {"sh SCRIPT, then sh -c text that only mentions sshd", []string{"/bin/sh", "/entry.sh", "sh", "-c", watch}, map[string]string{"/entry.sh": starts}, "UsePAM yes\n", "vulnerable/critical"}, + {"dumb-init sh SCRIPT, then sh -c text", []string{"dumb-init", "/bin/sh", "/entry.sh", "sh", "-c", watch}, map[string]string{"/entry.sh": starts}, "UsePAM yes\n", "vulnerable/critical"}, + {"sh SCRIPT, then sh -c text with UsePAM=yes", []string{"/bin/sh", "/entry.sh", "sh", "-c", "sshd -D -o UsePAM=yes"}, map[string]string{"/entry.sh": no}, "UsePAM no\n", "vulnerable/critical"}, + {"tini -- sh SCRIPT, then sh -c text", []string{"/sbin/tini", "--", "/bin/sh", "/entry.sh", "sh", "-c", "sshd -D -o UsePAM=yes"}, map[string]string{"/entry.sh": no}, "UsePAM no\n", "vulnerable/critical"}, + {"sh SCRIPT -c text: the script's own arguments", []string{"sh", "/entry.sh", "-c", "sshd -D -o UsePAM=yes"}, map[string]string{"/entry.sh": no}, "UsePAM no\n", "vulnerable/critical"}, + {"busybox ash SCRIPT -c text", []string{"/bin/busybox", "ash", "/entry.sh", "-c", "sshd -D -o UsePAM=yes"}, map[string]string{"/entry.sh": no}, "UsePAM no\n", "vulnerable/critical"}, + {"bash -o pipefail SCRIPT, then sh -c text", []string{"bash", "-o", "pipefail", "/entry.sh", "sh", "-c", "sshd -D -o UsePAM=yes"}, map[string]string{"/entry.sh": no}, "UsePAM no\n", "vulnerable/critical"}, + {"sh NAME: the script on PATH may not be the one in the working directory", []string{"sh", "entry.sh"}, map[string]string{"/usr/local/bin/entry.sh": yes}, "UsePAM no\n", "vulnerable/critical"}, + {"tini -- bash NAME", []string{"/sbin/tini", "--", "bash", "entry.sh"}, map[string]string{"/usr/local/bin/entry.sh": yes}, "UsePAM no\n", "vulnerable/critical"}, + {"the value of a wrapper's option is not the program", []string{"env", "-u", "start", "/usr/bin/app"}, map[string]string{"/usr/bin/start": yes}, "UsePAM no\n", "vulnerable/critical"}, + {"a -lc text with = in it is not an assignment", []string{"bash", "-lc", "sshd -D -o LogLevel=DEBUG", "entry.sh"}, map[string]string{"/usr/local/bin/entry.sh": yes}, "UsePAM no\n", "vulnerable/critical"}, + // What the command's own shell runs still decides. + {"control: sh -c text is the command", []string{"sh", "-c", "/usr/sbin/sshd -D -o UsePAM=yes"}, nil, "UsePAM no\n", "inactive/"}, + {"control: sh -e -c text", []string{"/bin/sh", "-e", "-c", "/usr/sbin/sshd -D -o UsePAM=yes"}, nil, "UsePAM no\n", "inactive/"}, + {"control: busybox sh -c text", []string{"busybox", "sh", "-c", "/usr/sbin/sshd -D -o UsePAM=yes"}, nil, "UsePAM no\n", "inactive/"}, + {"control: sh /SCRIPT is the program", []string{"/bin/sh", "/entry.sh"}, map[string]string{"/entry.sh": yes}, "UsePAM no\n", "inactive/"}, + {"control: tini -- /SCRIPT", []string{"/sbin/tini", "--", "/entry.sh"}, map[string]string{"/entry.sh": yes}, "UsePAM no\n", "inactive/"}, + {"control: env A=1 /SCRIPT", []string{"env", "A=1", "/entry.sh"}, map[string]string{"/entry.sh": yes}, "UsePAM no\n", "inactive/"}, + } { + w := newWorld("10.0p2", true, map[string]string{"/etc/ssh/sshd_config": c.cfg}) + scripts := map[string][]byte{} + for k, v := range c.scripts { + scripts[k] = []byte(v) + } + in := Input{ + Binaries: w.binaries, Files: w.files, + Accounts: ParseAccounts(w.files.Read("/etc/passwd"), w.files.Read("/etc/shadow"), w.files.Read("/etc/group"), nil), + Resolve: func(p string) (string, bool) { _, ok := w.files[p]; return p, ok }, + Now: w.now(), + Image: true, + Startup: Startup{Command: c.cmd, Scripts: scripts}, + } + f := one(t, Run(in)) + if got := string(f.Status) + "/" + f.Severity; got != c.want { + t.Errorf("%s: got %s, want %s (%s)", c.name, got, c.want, f.Reason) + } + } +} diff --git a/detectors/sshole/internal/assess/runtime.go b/detectors/sshole/internal/assess/runtime.go index 2eb0c9f..5b836c3 100644 --- a/detectors/sshole/internal/assess/runtime.go +++ b/detectors/sshole/internal/assess/runtime.go @@ -147,7 +147,7 @@ func (s Startup) startScripts(resolve func(string) (string, bool)) []script { // The first is the program the command runs; a later one is an // argument to it, which may or may not run (arg). c := s.Command - program := false + program, operand := false, false for i, w := range c { n := len(out) if isShell(path.Base(w)) { @@ -156,11 +156,30 @@ func (s Startup) startScripts(resolve func(string) (string, bool)) []script { out = append(out, script{where: "the container command", text: c[j+1]}) break } + // The shell's options end at its first operand, the + // script it runs: a -c after that is the script's + // argument, or another shell's. + if o := c[j]; !isOption(o) && !isShell(path.Base(o)) { + if j > i+1 && shellOptionValue[c[j-1]] { + continue + } + break + } } } + // A shell looks for a script named without a slash in the + // working directory first, which the scan does not know: the + // one found on PATH may not be the one that runs. And a word + // after an option may be that option's value (env -u NAME), + // not the program. Either is judged as an argument is: with + // the others, never alone. + unsure := !strings.HasPrefix(w, "/") && (operand && !strings.Contains(w, "/") || i > 0 && isOption(c[i-1]) && c[i-1] != "--") + if !isOption(w) { + operand = isShell(path.Base(w)) && !program + } add(w) for k := n; k < len(out); k++ { - out[k].arg = program + out[k].arg = program || unsure && out[k].where != "the container command" } // The program is the first word that is not a wrapper, a shell, // one of their options or an assignment, whether or not it is @@ -213,7 +232,7 @@ func beforeProgram(c []string, i int) bool { case "tini", "dumb-init", "su-exec", "gosu", "env", "exec", "catatonit": return true } - if isShell(b) || strings.HasPrefix(w, "-") || strings.Contains(w, "=") && !strings.Contains(w, "/") { + if isShell(b) || strings.HasPrefix(w, "-") || assignmentRE.MatchString(w) && !strings.Contains(w, "/") { return true } if i > 0 { @@ -225,6 +244,17 @@ func beforeProgram(c []string, i int) bool { return false } +// assignmentRE is a NAME=value word before a program (env A=1 prog). A +// shell text that merely holds "=" (sshd -o LogLevel=DEBUG) is not one. +var assignmentRE = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*=`) + +// isOption reports whether a command word is an option (-e, +x, --). +func isOption(w string) bool { return strings.HasPrefix(w, "-") || strings.HasPrefix(w, "+") } + +// shellOptionValue holds the shell options that take the next word as +// their value: that word is not the script the shell runs. +var shellOptionValue = map[string]bool{"-o": true, "+o": true, "-O": true, "+O": true, "--rcfile": true, "--init-file": true} + var absPathRE = regexp.MustCompile(`/[A-Za-z0-9_./-]+`) func isShell(b string) bool { From 18539ac1d61cf6464642e96ea3dd130fef54364e Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 14:00:27 +0000 Subject: [PATCH 112/119] java4shell: a VM library that was not read or cannot be judged never lets its runtime be cleared Second final review. Three ways a runtime was cleared on the word of one library while another was not judged: - A library with no HotSpot version line and no decoder stubs beside a fixed one. With OpenJ9's string in it the runtime was unknown before ba373e0 (the files contradict) and fixed after it, since the string alone no longer makes the group OpenJ9 and judgeAll skipped every OpenJ9-marked library. Without the string it was fixed all along. - A VM library the scan met and did not read: over --max-file-size, unreadable, or at a path an image's layers do not settle. Beside a fixed lib/server the runtime was fixed, exit 0; as the runtime's only library there was no finding at all, only the skip record. - A Red Hat row applied to the finding judgeAll returned. With the row's build in lib/server and a 17.0.20 or GraalVM library in lib/client, the server library's verdict was kept as the worst (both vulnerable) and the row then cleared the runtime. Latent: the table is empty. Now judgeAll applies the Red Hat row to each library's verdict before it takes the worst, and a library it cannot judge on its own (in a runtime that is not OpenJ9) makes a runtime that would be cleared unknown. The scan keeps the VM library names VisitOverLimit and VisitUnread tell it about; assess treats them as it treats linked libraries: unknown for a runtime with nothing else, unknown instead of a clear, a note beside a verdict that is not a clear. A Semeru runtime (redirector and libj9vm, one VM) is not affected as before. Co-Authored-By: Claude Fable 5.2 --- detectors/java4shell/FACTS.md | 3 + .../java4shell/internal/assess/assess.go | 96 +++++++++++++-- .../internal/assess/libraries_test.go | 110 ++++++++++++++++++ detectors/java4shell/java4shell.go | 57 ++++++--- detectors/java4shell/unread_internal_test.go | 80 +++++++++++++ 5 files changed, 318 insertions(+), 28 deletions(-) create mode 100644 detectors/java4shell/unread_internal_test.go diff --git a/detectors/java4shell/FACTS.md b/detectors/java4shell/FACTS.md index c0276f3..3f095c9 100644 --- a/detectors/java4shell/FACTS.md +++ b/detectors/java4shell/FACTS.md @@ -123,6 +123,9 @@ OpenJDK fix commit and Amazon Corretto's changelog. - A runtime directory that holds several VM libraries (server and client or minimal VMs, a Java 8 `lib/amd64/server` left by an upgrade in place) is judged by every library that states a version or carries the decoder, and the worst verdict is the runtime's. A VM library that is a symbolic or hard link to a file with another name is never read under its own name, so that runtime is unknown. + The same holds for a VM library the scan met and did not read (over `--max-file-size`, unreadable, at a path an image's layers do not + settle) and for one that states no version and carries no decoder stubs in a runtime that is not OpenJ9: a runtime the other libraries + would clear is unknown. A Red Hat row is applied to each library's verdict before the worst is taken. - OpenJ9 is taken from an OpenJ9 VM library by name (`libj9vm29.so`). The `lib/server/libjvm.so` redirector's string (`OPENJ9_JAVA_OPTIONS`) counts only with such a library in the runtime or a release file that names OpenJ9. - A packaged JDK (apk, dpkg, rpm) is judged by the same upstream version: no distribution has published a fixed package or a backport diff --git a/detectors/java4shell/internal/assess/assess.go b/detectors/java4shell/internal/assess/assess.go index d3f1445..63d7a7c 100644 --- a/detectors/java4shell/internal/assess/assess.go +++ b/detectors/java4shell/internal/assess/assess.go @@ -96,6 +96,10 @@ type Input struct { // Linked are VM library names that are links to a file the scan did // not read as a VM library: the runtime there was not judged. Linked []LinkedLibrary + // UnreadLibraries are VM libraries the scan met and did not read (over + // a size limit, unreadable, at a path an image's layers do not + // settle): the runtime there was not judged by them. + UnreadLibraries []string // OSID is the target's os-release ID (rhel, rocky, debian), "" when // it has none. OSID string @@ -127,13 +131,30 @@ func Run(in Input) []Finding { } linked[root] = append(linked[root], l) } + unread := map[string][]string{} + for _, p := range in.UnreadLibraries { + root, ok := jvm.Root(p) + if !ok { + root = path.Dir(p) + } + unread[root] = append(unread[root], p) + } roots := make([]string, 0, len(byRoot)) + seen := map[string]bool{} for r := range byRoot { - roots = append(roots, r) + roots, seen[r] = append(roots, r), true } for r := range linked { - if _, ok := byRoot[r]; !ok { - roots = append(roots, r) + if !seen[r] { + roots, seen[r] = append(roots, r), true + } + } + for _, l := range loose { + seen[path.Dir(l.Path)] = true // judged below, where it lies + } + for r := range unread { + if !seen[r] { + roots, seen[r] = append(roots, r), true } } sort.Strings(roots) @@ -142,14 +163,19 @@ func Run(in Input) []Finding { for _, r := range roots { f := Finding{Kind: KindRuntime, Path: r} if libs := byRoot[r]; len(libs) > 0 { - f = redHat(in, judgeAll(in, env, r, libs)) + f = judgeAll(in, env, r, libs) } else if name, dir, ok := Product(r); ok { f.Kind, f.Product, f.ProductDir = KindBundled, name, dir } - out = append(out, withFix(notFollowed(f, linked[r]))) + out = append(out, withFix(notRead(notFollowed(f, linked[r]), unread[r]))) } for _, l := range loose { - out = append(out, withFix(redHat(in, judge(in, env, path.Dir(l.Path), []*jvm.Library{l})))) + f := redHat(in, judge(in, env, path.Dir(l.Path), []*jvm.Library{l})) + if _, ok := byRoot[path.Dir(l.Path)]; ok { + out = append(out, withFix(f)) // that directory's unread libraries are told there + continue + } + out = append(out, withFix(notRead(f, unread[path.Dir(l.Path)]))) } return out } @@ -162,23 +188,75 @@ func Run(in Input) []Finding { // put in bin/server. Each other library that states a version or carries // the decoder is judged on its own, and the worst verdict is the // runtime's: a library that clears never hides one that does not. +// +// A Red Hat row speaks for one build, so it is applied to each library's +// verdict before the worst is taken, never to the runtime's afterwards. +// And a library that cannot be judged on its own (no HotSpot version line +// and no decoder stubs, in a runtime that is not OpenJ9: the redirector's +// string alone, a stripped or packed file) was not judged at all: a +// runtime the others would clear is unknown. func judgeAll(in Input, env map[string]string, root string, libs []*jvm.Library) Finding { - f := judge(in, env, root, libs) + group := judge(in, env, root, libs) + f := redHat(in, group) worst := f + var unjudged []*jvm.Library for _, l := range libs { - if l == f.Library || l.OpenJ9 || !l.HotSpot() && !l.VBMIStubs { + switch { + case l == f.Library: + continue + case l.OpenJ9 && group.VM == "OpenJ9": + continue // the redirector and the VM of one OpenJ9 runtime + case !l.HotSpot() && !l.VBMIStubs: + unjudged = append(unjudged, l) continue } - if x := judge(in, env, root, []*jvm.Library{l}); rank(x.Status) > rank(worst.Status) { + if x := redHat(in, judge(in, env, root, []*jvm.Library{l})); rank(x.Status) > rank(worst.Status) { worst = x } } if worst.Library != f.Library { worst.Reason += fmt.Sprintf("; this runtime holds %d VM libraries and the worst decides (%s alone: %s)", len(libs), f.Library.Path, f.Status) } + if len(unjudged) > 0 && rank(worst.Status) == 0 { + sort.Slice(unjudged, func(i, j int) bool { return unjudged[i].Path < unjudged[j].Path }) + why := fmt.Sprintf("its VM library %s states no version (no HotSpot version line, no decoder stubs) and is not shown to be OpenJ9, so that library was not judged", unjudged[0].Path) + if len(unjudged) > 1 { + why += fmt.Sprintf(", nor were %d more", len(unjudged)-1) + } + v, vok := knowledge.Parse(worst.Version) + worst.Release = knowledge.Unknown + return worst.set(Unknown, worst.Reason+"; but "+why, describe(worst, v, vok)+": one of its VM libraries could not be judged") + } return worst } +// notRead applies what a runtime's unread VM libraries leave open, as +// notFollowed does for links: a runtime with nothing else to judge is +// unknown, and so is one its other libraries would clear. +func notRead(f Finding, unread []string) Finding { + if len(unread) == 0 { + return f + } + sort.Strings(unread) + why := fmt.Sprintf("its VM library %s was not read (over a size limit, unreadable, or at a path the image's layers do not settle)", unread[0]) + if len(unread) > 1 { + why += fmt.Sprintf(", nor were %d more", len(unread)-1) + } + v, vok := knowledge.Parse(f.Version) + switch { + case f.Library == nil && f.Status == "": + return f.set(Unknown, why+": the runtime was not checked", "Java runtime: its VM library was not read") + case f.Library == nil: + f.Reason += "; " + why + return f + case rank(f.Status) == 0: + f.Release = knowledge.Unknown + return f.set(Unknown, f.Reason+"; but "+why+": that library was not checked", describe(f, v, vok)+": one of its VM libraries was not read") + } + f.Reason += "; " + why + return f +} + // notFollowed applies what a runtime's linked VM libraries leave open: a // library that is a link to a file with another name was never read, so a // runtime with nothing else to judge is unknown, and so is one its other diff --git a/detectors/java4shell/internal/assess/libraries_test.go b/detectors/java4shell/internal/assess/libraries_test.go index ce717ee..2a65689 100644 --- a/detectors/java4shell/internal/assess/libraries_test.go +++ b/detectors/java4shell/internal/assess/libraries_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/DefectDojo/earlylight/detectors/java4shell/internal/jvm" + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" ) @@ -103,3 +104,112 @@ func TestOpenJ9NeedsTwoWitnesses(t *testing.T) { } } } + +// Second final review: a VM library the scan cannot judge on its own (no +// HotSpot version line and no decoder stubs, with or without OpenJ9's +// string, in a runtime that is not OpenJ9) never lets the libraries beside +// it clear the runtime. Before, a fixed lib/server cleared a runtime whose +// lib/client carried only OPENJ9_JAVA_OPTIONS (unknown before the +// two-witness rule), or no version at all. +func TestUnjudgedLibraryNeverCleared(t *testing.T) { + const root = "/opt/jdk" + fixed := testlib.Lib{Version: "21.0.13.1+2-LTS", VBMI: true} + vuln := testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true} + for _, c := range []struct { + name string + libs map[string]testlib.Lib + release []string + want Status + }{ + {"fixed server, client with only OpenJ9's string", map[string]testlib.Lib{"lib/server/libjvm.so": fixed, "lib/client/libjvm.so": {Extra: "OPENJ9_JAVA_OPTIONS"}}, nil, Unknown}, + {"fixed server, client with no version line", map[string]testlib.Lib{"lib/server/libjvm.so": fixed, "lib/client/libjvm.so": {}}, []string{"JAVA_VERSION", "21.0.13"}, Unknown}, + {"fixed server, client with no version line, fixed release file", map[string]testlib.Lib{"lib/server/libjvm.so": fixed, "lib/client/libjvm.so": {}}, []string{"JAVA_VERSION", "21.0.13.1"}, Unknown}, + {"Java 8 server, minimal with no version line", map[string]testlib.Lib{"lib/amd64/server/libjvm.so": {Version: "1.8.0_452-b09"}, "lib/amd64/minimal/libjvm.so": {}}, nil, Unknown}, + {"aarch64 server, x86-64 client with no version line", map[string]testlib.Lib{"lib/server/libjvm.so": {Machine: "aarch64", Version: "21.0.13+9-LTS"}, "lib/client/libjvm.so": {}}, nil, Unknown}, + // A verdict that is not a clear stands. + {"vulnerable server, client with only OpenJ9's string", map[string]testlib.Lib{"lib/server/libjvm.so": vuln, "lib/client/libjvm.so": {Extra: "OPENJ9_JAVA_OPTIONS"}}, nil, Vulnerable}, + {"vulnerable server, client with no version line", map[string]testlib.Lib{"lib/server/libjvm.so": vuln, "lib/client/libjvm.so": {}}, nil, Vulnerable}, + } { + in := Input{Releases: map[string]jvm.Release{}} + for p, l := range c.libs { + in.Libraries = append(in.Libraries, lib(t, root+"/"+p, l)) + } + if c.release != nil { + in.Releases[root] = rel(t, c.release...) + } + if f := one(t, in); f.Status != c.want { + t.Errorf("%s: %s, want %s (%s)", c.name, f.Status, c.want, f.Reason) + } + } +} + +// A VM library the scan met and did not read (over a size limit, +// unreadable, a path an image's layers do not settle) is a library that was +// not judged: its runtime is unknown when nothing else was read there, and +// when what was read would clear it. +func TestUnreadLibraryNeverCleared(t *testing.T) { + const root = "/opt/jdk" + fixed := lib(t, root+"/lib/server/libjvm.so", testlib.Lib{Version: "21.0.13.1+2-LTS", VBMI: true}) + vuln := lib(t, root+"/lib/server/libjvm.so", testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true}) + for _, c := range []struct { + name string + libs []*jvm.Library + unread []string + want Status + }{ + {"the only library", nil, []string{root + "/lib/server/libjvm.so"}, Unknown}, + {"beside a fixed library", []*jvm.Library{fixed}, []string{root + "/lib/client/libjvm.so"}, Unknown}, + {"beside a vulnerable library", []*jvm.Library{vuln}, []string{root + "/lib/client/libjvm.so"}, Vulnerable}, + {"in another runtime", []*jvm.Library{fixed}, []string{"/opt/other/lib/server/libjvm.so"}, Fixed}, + } { + fs := Run(Input{Libraries: c.libs, UnreadLibraries: c.unread, Releases: map[string]jvm.Release{}}) + var got *Finding + for i := range fs { + if fs[i].Path == root { + got = &fs[i] + } + } + if got == nil || got.Status != c.want { + t.Errorf("%s: %+v, want %s", c.name, fs, c.want) + continue + } + if len(c.unread) > 0 && strings.HasPrefix(c.unread[0], root) && !strings.Contains(got.Reason, "not read") { + t.Errorf("%s: the reason does not name the unread library: %s", c.name, got.Reason) + } + } + // The other runtime's unread library is its own unknown finding. + fs := Run(Input{Libraries: []*jvm.Library{fixed}, UnreadLibraries: []string{"/opt/other/lib/server/libjvm.so"}, Releases: map[string]jvm.Release{}}) + if len(fs) != 2 || fs[0].Path != root || fs[1].Path != "/opt/other" || fs[1].Status != Unknown { + t.Errorf("an unread library in a second runtime: %+v", fs) + } +} + +// A Red Hat row speaks for one build. With several VM libraries in the +// runtime it is applied to each, not to the one the worst verdict names: a +// library that is another update, or a GraalVM build, keeps its verdict. +func TestRedHatRowEveryLibrary(t *testing.T) { + saved := knowledge.RedHatFixed + t.Cleanup(func() { knowledge.RedHatFixed = saved }) + knowledge.RedHatFixed = []knowledge.RedHatFix{{Package: "java-17-openjdk", Dist: "el9_6", EVR: "1:17.0.21.0.9-2.el9_6", Advisory: "RHSA-2026:0000"}} + const root = "/usr/lib/jvm/java-17-openjdk-17.0.21.0.9-2.el9_6.x86_64" + row := testlib.Lib{Version: "17.0.21+9-LTS", VBMI: true} + for _, c := range []struct { + name string + libs map[string]testlib.Lib + want Status + }{ + {"the row's build alone", map[string]testlib.Lib{"lib/server/libjvm.so": row}, Fixed}, + {"the row's build twice", map[string]testlib.Lib{"lib/server/libjvm.so": row, "lib/client/libjvm.so": row}, Fixed}, + {"a client library of an older update", map[string]testlib.Lib{"lib/server/libjvm.so": row, "lib/client/libjvm.so": {Version: "17.0.20+8", VBMI: true}}, Vulnerable}, + {"a minimal library that is a GraalVM build", map[string]testlib.Lib{"lib/server/libjvm.so": row, "lib/minimal/libjvm.so": {Version: "17.0.21+9-jvmci-23.0-b12", VBMI: true}}, Vulnerable}, + {"a client library with no version line", map[string]testlib.Lib{"lib/server/libjvm.so": row, "lib/client/libjvm.so": {}}, Unknown}, + } { + in := Input{OSID: "rhel", Releases: map[string]jvm.Release{root: rel(t, "IMPLEMENTOR", "Red Hat, Inc.", "JAVA_VERSION", "17.0.21")}} + for p, l := range c.libs { + in.Libraries = append(in.Libraries, lib(t, root+"/"+p, l)) + } + if f := one(t, in); f.Status != c.want { + t.Errorf("%s: %s, want %s (%s)", c.name, f.Status, c.want, f.Reason) + } + } +} diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 138df82..0b4e2b4 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -144,8 +144,9 @@ func (d *Detector) Limit(p string, head []byte, _ bool) int64 { // mitigation the scan would report. A start script not read keeps a // mitigation from being reported when the container's command runs it. An // /etc/os-release not read keeps a Red Hat row from clearing a runtime -// (osID). The other files with a limit are deliberate exclusions: no -// verdict is cleared on them. +// (osID). A VM library not read leaves its runtime unknown (assess). The +// other files with a limit are deliberate exclusions: no verdict is +// cleared on them. func (s *scan) VisitOverLimit(p string, _ int64) []engine.Skip { s.notRead(p) return nil @@ -170,6 +171,15 @@ func (s *scan) notRead(p string) { if p == "/etc/os-release" { s.osUnread = true } + if jvm.IsLibraryName(path.Base(p)) { + // The file a runtime's verdict is made of: its runtime was not + // judged by it, and is not cleared without it. + if len(s.unreadLibs) >= maxLibs { + s.limit(fmt.Sprintf("more than %d Java VM libraries", maxLibs)) + } else { + s.unreadLibs[p] = true + } + } if hsErr.MatchString(path.Base(p)) || p == "/etc/os-release" || p == "/usr/lib/os-release" { return } @@ -185,7 +195,7 @@ func (s *scan) notRead(p string) { // FinishSkips reports the JVM settings files not read as coverage gaps // when the target holds a runtime. func (s *scan) FinishSkips() []engine.Skip { - if s.libs.len() == 0 { + if s.libs.len() == 0 && len(s.unreadLibs) == 0 { return nil } var out []engine.Skip @@ -214,6 +224,7 @@ func (s *scan) Forget(p string) { delete(s.scriptWords, p) delete(s.undoScripts, p) delete(s.unreadScripts, p) + delete(s.unreadLibs, p) delete(s.overSettings, p) if path.Base(p) == "release" { delete(s.releases, path.Dir(p)) @@ -301,7 +312,7 @@ const ( func (d *Detector) NewScan(kind engine.TargetKind) engine.Scan { return &scan{kind: kind, releases: map[string]jvm.Release{}, badReleases: map[string]string{}, kept: map[string][]byte{}, lists: map[string][]byte{}, scripts: map[string]map[string]bool{}, unreadScripts: map[string]bool{}, overSettings: map[string]bool{}, - scriptWords: map[string]assess.WordSet{}, undoScripts: map[string]string{}} + scriptWords: map[string]assess.WordSet{}, undoScripts: map[string]string{}, unreadLibs: map[string]bool{}} } type scan struct { @@ -328,6 +339,8 @@ type scan struct { scriptWords map[string]assess.WordSet undoScripts map[string]string scriptsOver bool + // unreadLibs are VM libraries the scan met and did not read. + unreadLibs map[string]bool // overSettings are JVM settings files not read. overSettings map[string]bool // osUnread is set when /etc/os-release was met and not read. @@ -491,7 +504,12 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { links, hardlinks := ctx.Links() res := resolver{links: links} linked := s.linkedLibraries(ctx, res, links, hardlinks) - if s.libs.len() == 0 && len(linked) == 0 { + unreadLibs := make([]string, 0, len(s.unreadLibs)) + for p := range s.unreadLibs { + unreadLibs = append(unreadLibs, p) + } + sort.Strings(unreadLibs) + if s.libs.len() == 0 && len(linked) == 0 && len(unreadLibs) == 0 { if len(s.limits) > 0 { ctx.Problem("java4shell: the scan reached its limit on " + strings.Join(s.limits, " and ") + " for one target") } @@ -511,20 +529,21 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { } } in := assess.Input{ - Libraries: s.libs.list(), - Releases: s.releases, - BadReleases: s.badReleases, - Settings: s.settings.list(), - Owners: owners, - Resolve: res.resolve, - Scripts: s.scripts, - UnreadScripts: s.unreadScripts, - UnreadDirs: s.unreadDirs, - UnreadAll: s.unreadAll, - ScriptWords: s.scriptWords, - UndoScripts: s.undoScripts, - ScriptsOver: s.scriptsOver, - Linked: linked, + Libraries: s.libs.list(), + Releases: s.releases, + BadReleases: s.badReleases, + Settings: s.settings.list(), + Owners: owners, + Resolve: res.resolve, + Scripts: s.scripts, + UnreadScripts: s.unreadScripts, + UnreadDirs: s.unreadDirs, + UnreadAll: s.unreadAll, + ScriptWords: s.scriptWords, + UndoScripts: s.undoScripts, + ScriptsOver: s.scriptsOver, + Linked: linked, + UnreadLibraries: unreadLibs, } in.OSID = s.osID(ctx.Exists, res, hardlinks) if s.kind == engine.Image { diff --git a/detectors/java4shell/unread_internal_test.go b/detectors/java4shell/unread_internal_test.go new file mode 100644 index 0000000..31597e8 --- /dev/null +++ b/detectors/java4shell/unread_internal_test.go @@ -0,0 +1,80 @@ +package java4shell + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/testlib" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// Second final review: the VM library is the file a runtime's verdict is +// made of. One the scan met and did not read (over --max-file-size, +// unreadable, named twice in one image layer) makes its runtime unknown: +// never nothing, and never fixed on the word of a library beside it. +func TestUnreadLibraryMakesTheRuntimeUnknown(t *testing.T) { + fixed := testlib.Build(testlib.Lib{Version: "21.0.13.1+2-LTS", VBMI: true}) + vuln := testlib.Build(testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true}) + big := testlib.Build(testlib.Lib{Version: "21.0.13+9-LTS", VBMI: true, Extra: strings.Repeat("x", 8192)}) + tree := func(files map[string][]byte) string { + root := t.TempDir() + for rel, data := range files { + p := filepath.Join(root, rel) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, data, 0o755); err != nil { + t.Fatal(err) + } + } + return root + } + scan := func(root string, max int64) engine.Target { + return *engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true, MaxFileSize: max}) + } + verdicts := func(tg engine.Target) string { + var out []string + for _, f := range tg.Findings { + out = append(out, f.Path+" "+string(f.Verdict)) + } + return strings.Join(out, ", ") + } + + // Over --max-file-size beside a fixed library. + root := tree(map[string][]byte{"opt/jdk/lib/server/libjvm.so": fixed, "opt/jdk/lib/client/libjvm.so": big}) + if got := verdicts(scan(root, 4096)); got != "/opt/jdk unknown" { + t.Errorf("an over-limit client library beside a fixed server library: %q, want /opt/jdk unknown", got) + } + if got := verdicts(scan(root, 0)); got != "/opt/jdk vulnerable" { + t.Errorf("the same read in full: %q, want /opt/jdk vulnerable", got) + } + // Beside a vulnerable library the verdict stands. + root = tree(map[string][]byte{"opt/jdk/lib/server/libjvm.so": vuln, "opt/jdk/lib/client/libjvm.so": big}) + if got := verdicts(scan(root, 4096)); got != "/opt/jdk vulnerable" { + t.Errorf("an over-limit client library beside a vulnerable server library: %q", got) + } + // The only library of the runtime, and another runtime read in full. + root = tree(map[string][]byte{"opt/jdk/lib/server/libjvm.so": big, "opt/jdk/release": testlib.Release("JAVA_VERSION", "21.0.13.1"), "opt/other/lib/server/libjvm.so": fixed}) + if got := verdicts(scan(root, 4096)); got != "/opt/jdk unknown, /opt/other fixed" { + t.Errorf("the only library over the limit: %q, want /opt/jdk unknown, /opt/other fixed", got) + } + // Unreadable (not as root, which can read it). + if os.Geteuid() != 0 { + root = tree(map[string][]byte{"opt/jdk/lib/server/libjvm.so": fixed, "opt/jdk/lib/client/libjvm.so": vuln}) + if err := os.Chmod(filepath.Join(root, "opt/jdk/lib/client/libjvm.so"), 0); err != nil { + t.Fatal(err) + } + if got := verdicts(scan(root, 0)); got != "/opt/jdk unknown" { + t.Errorf("an unreadable client library beside a fixed server library: %q, want /opt/jdk unknown", got) + } + } + // A docker export that names the library again, read: the last entry + // is the file and nothing is left unread. + exp := exportOf(t, tarEntry{name: "opt/jdk/lib/server/libjvm.so", data: fixed}, tarEntry{name: "opt/jdk/lib/client/libjvm.so", data: big}, tarEntry{name: "opt/jdk/lib/client/libjvm.so", data: fixed}) + tg := engine.ScanImage([]engine.Detector{&Detector{}}, exp, engine.Options{MaxFileSize: 4096}) + if got := verdicts(*tg); got != "/opt/jdk fixed" { + t.Errorf("an over-limit library named again and read: %q, want /opt/jdk fixed", got) + } +} From a83f30a9a9a2e21cf8fee38fd9170fe02fb1b1a8 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 14:03:00 +0000 Subject: [PATCH 113/119] java4shell: a Compose build argument is judged, not marked on every Dockerfile that uses its name Second final review, finding 5. 37dd76b recorded "not checked" for every Dockerfile whose FROM uses an ARG that any Compose file in the tree sets as a build argument. A tree with no Java (ARG NGINX=1.27, FROM nginx:${NGINX}, build.args NGINX: 1.28) got a coverage gap, and "earlylight fix --dry-run" went from "nothing to change", exit 0 on main to exit 1. The value is a literal in the Compose file, so the FROM is now read with it and judged like any other reference: eclipse-temurin:${TAG} with build.args TAG: 21.0.13_9-jre over a fixed default is a vulnerable finding that names the Compose file (and is not one fix edits). It is a gap only when the value cannot be read (taken from the environment, or another variable of the reference stays open) and the image could be a Java one, and only for the Dockerfile the service's context and dockerfile name; a service whose Dockerfile the tree cannot place still goes by the ARG's name. An unresolved reference is likewise a java4shell gap only when its name looks like Java or a variable stands where the name is: a variable in the tag of registry.example.com/acme/web is the image reference scan's gap, not this detector's. Co-Authored-By: Claude Fable 5.2 --- .../java4shell/internal/repo/final_test.go | 9 +- detectors/java4shell/internal/repo/refscan.go | 115 ++++++++++++++++-- detectors/java4shell/internal/repo/repo.go | 61 +++++++--- .../java4shell/internal/repo/second_test.go | 76 ++++++++++++ 4 files changed, 233 insertions(+), 28 deletions(-) create mode 100644 detectors/java4shell/internal/repo/second_test.go diff --git a/detectors/java4shell/internal/repo/final_test.go b/detectors/java4shell/internal/repo/final_test.go index fa9aead..d178915 100644 --- a/detectors/java4shell/internal/repo/final_test.go +++ b/detectors/java4shell/internal/repo/final_test.go @@ -256,13 +256,14 @@ func TestBuildSettingsForms(t *testing.T) { } // Final review B6: a Compose file that sets a build argument overrides the -// ARG default a FROM is read with: the image that build uses is not -// checked. +// ARG default a FROM is read with: the image that build uses is judged +// with the argument's value (TestComposeBuildArgsAreJudged has the cases +// where it cannot be). func TestComposeBuildArgs(t *testing.T) { const df = "ARG TAG=21.0.13.1_2-jre\nFROM eclipse-temurin:${TAG}\n" for name, c := range map[string]struct{ compose, want string }{ - "a map": {"services:\n app:\n build:\n context: .\n args:\n TAG: 21.0.13_9-jre\n", "skip Dockerfile:2"}, - "a list": {"services:\n app:\n build:\n context: .\n args:\n - TAG=21.0.13_9-jre\n", "skip Dockerfile:2"}, + "a map": {"services:\n app:\n build:\n context: .\n args:\n TAG: 21.0.13_9-jre\n", "Dockerfile:2 image-pin vulnerable"}, + "a list": {"services:\n app:\n build:\n context: .\n args:\n - TAG=21.0.13_9-jre\n", "Dockerfile:2 image-pin vulnerable"}, "another argument": {"services:\n app:\n build:\n context: .\n args:\n HTTP_PROXY: http://proxy\n", ""}, "no arguments": {"services:\n app:\n build: .\n", ""}, } { diff --git a/detectors/java4shell/internal/repo/refscan.go b/detectors/java4shell/internal/repo/refscan.go index 601c00d..8b43698 100644 --- a/detectors/java4shell/internal/repo/refscan.go +++ b/detectors/java4shell/internal/repo/refscan.go @@ -21,27 +21,124 @@ func (s *scanner) images(opts Options) { for _, sk := range skips { // An unresolved reference that does not look like Java is left // out, unless a variable hides its name: FROM ${BASE}:${VER} can be - // a Java image. - if sk.Text != "" && !Javaish(sk.Text) && !strings.Contains(sk.Text, "$") { + // a Java image, FROM nginx:${VER} cannot. + if sk.Text != "" && !couldBeJava(sk.Text) { continue } s.skips = append(s.skips, Skip{File: sk.File, Line: sk.Line, Reason: sk.Reason}) } for i := range rs { s.judgeRef(rs[i], opts) - // A Compose file that sets one of the FROM's ARGs as a build - // argument builds on another image than the default read here. - if rs[i].Kind == refs.KindDockerfile { - for _, v := range rs[i].Vars { - if f, ok := s.buildArgs[v.Name]; ok { - s.skips = append(s.skips, Skip{File: rs[i].File, Line: rs[i].Line, Reason: fmt.Sprintf("the FROM is read with the default of ARG %s, which %s sets as a build argument: the image that build uses is not checked", refs.CleanText(v.Name, 60), refs.CleanText(f, 120))}) - break + if rs[i].Kind == refs.KindDockerfile && len(rs[i].Vars) > 0 { + s.composeBuilds(rs[i], opts) + } + } +} + +// composeBuilds judges a FROM again as each Compose service builds it: a +// build argument replaces the ARG default the reference was read with. +// The value is a literal in the Compose file, so the image it gives is +// judged like any other (not one fix edits: the argument is the Compose +// file's). When the value cannot be read (it comes from the environment), +// or another variable of the reference stays open, the image that build +// uses is not checked, and that is recorded only when it could be a Java +// image. +func (s *scanner) composeBuilds(r refs.Ref, opts Options) { + uses := map[string]bool{} + for _, v := range r.Vars { + uses[v.Name] = true + } + // Each Compose file's arguments for this Dockerfile: the services that + // build it, or, when a service's Dockerfile cannot be placed, any that + // set an ARG the FROM uses. + type build struct { + values map[string]string + opaque string // an argument whose value the file does not give + } + builds := map[string]*build{} + var order []string + for _, a := range s.buildArgs { + if !uses[a.name] || a.dockerfile != "" && a.dockerfile != r.File { + continue + } + b := builds[a.compose] + if b == nil { + b = &build{values: map[string]string{}} + builds[a.compose] = b + order = append(order, a.compose) + } + if !a.literal { + b.opaque = a.name + } else if _, ok := b.values[a.name]; !ok { + b.values[a.name] = a.value + } + } + done := map[string]bool{} + for _, file := range order { + b := builds[file] + img := varRef.ReplaceAllStringFunc(r.Text, func(m string) string { + g := varRef.FindStringSubmatch(m) + if v, ok := b.values[g[1]+g[3]]; ok && v != "" { + return v + } + return m + }) + if b.opaque != "" || strings.Contains(img, "$") { + if couldBeJava(img) || couldBeJava(r.Text) || Javaish(r.Image) { + name := b.opaque + if name == "" { + for n := range b.values { + name = n + } } + s.skips = append(s.skips, Skip{File: r.File, Line: r.Line, Reason: fmt.Sprintf("the FROM is read with the default of ARG %s, which %s sets as a build argument this scan cannot resolve: the image that build uses is not checked", refs.CleanText(name, 60), refs.CleanText(file, 120))}) + } + continue + } + if img == r.Image || done[img] { + continue + } + done[img] = true + alt := r + alt.Image, alt.Context = img, "FROM (build arguments of "+file+")" + before := len(s.findings) + s.judgeRef(alt, opts) + for k := before; k < len(s.findings); k++ { + f := &s.findings[k] + f.Reason += "; the image is the one " + refs.CleanText(file, 120) + " builds, by its build arguments" + if f.Fixable { + f.Fixable, f.edit = false, nil + f.Fix = "Change the build argument in " + refs.CleanText(file, 120) + " by hand. " + f.Fix } } } } +// couldBeJava reports whether an image reference with variables in it +// could name a Java image: what is written looks like one, or a variable +// stands where the name is (a variable in the tag alone does not hide the +// name). +func couldBeJava(text string) bool { + if Javaish(text) { + return true + } + // The name is what comes before the tag: the last ":" outside ${...} + // that no "/" follows. + name, depth := text, 0 + for i := 0; i < len(text); i++ { + switch c := text[i]; { + case c == '{': + depth++ + case c == '}' && depth > 0: + depth-- + case c == ':' && depth == 0 && !strings.Contains(text[i:], "/"): + name = text[:i] + i = len(text) + } + } + return strings.Contains(name, "$") +} + // amd64 reports whether the tree builds for x86-64 (or does not say). func amd64(opts Options) bool { if len(opts.Platforms) == 0 { diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index 72fd4a1..7cff8fa 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -184,7 +184,7 @@ func scanList(ctx context.Context, root string, list []string, opts Options, res } } sort.Strings(list) - s := &scanner{root: root, opts: opts, mitigated: map[string]string{}, buildArgs: map[string]string{}} + s := &scanner{root: root, opts: opts, mitigated: map[string]string{}} for _, rel := range list { if ctx.Err() != nil { return res, ctx.Err() @@ -329,13 +329,24 @@ type scanner struct { mitigated map[string]string // unparsed are Dockerfiles the instruction parser refused. unparsed []Skip - // buildArgs maps a build argument a Compose file sets to that file. - buildArgs map[string]string + // buildArgs are the build arguments Compose files set. + buildArgs []buildArg +} + +// buildArg is one build argument a Compose service sets: the value, when +// the file gives it as a literal, and the Dockerfile the service builds, +// "" when the tree cannot place it (a context in a variable or outside). +type buildArg struct { + name, value string + literal bool + compose string // the Compose file + dockerfile string } // composeArgs records the build arguments a Compose file sets -// (services.*.build.args, as a map or a list of NAME=value): they replace -// the ARG defaults a Dockerfile's FROM is read with. +// (services.*.build.args, as a map or a list of NAME=value) and the +// Dockerfile each service builds: they replace the ARG defaults that +// Dockerfile's FROM is read with. func (s *scanner) composeArgs(rel string, b []byte) { if !bytes.Contains(b, []byte("args")) || !bytes.Contains(b, []byte("build")) { return @@ -345,25 +356,45 @@ func (s *scanner) composeArgs(rel string, b []byte) { return // the image reference scan records a file it cannot parse } walkYAML(&doc, 0, func(m *yaml.Node) { - args := deref(mapGet(deref(mapGet(m, "build")), "args")) + build := deref(mapGet(m, "build")) + args := deref(mapGet(build, "args")) if args == nil { return } - var names []string + // The Dockerfile: build.dockerfile inside build.context, both + // relative to the Compose file. + dockerfile := "" + ctx, df := ".", "Dockerfile" + if n := deref(mapGet(build, "context")); n != nil && n.Kind == yaml.ScalarNode { + ctx = n.Value + } + if n := deref(mapGet(build, "dockerfile")); n != nil && n.Kind == yaml.ScalarNode { + df = n.Value + } + if !strings.ContainsAny(ctx+df, "$:") && !path.IsAbs(ctx) && !path.IsAbs(df) { + if p := path.Join(path.Dir(rel), ctx, df); p != ".." && !strings.HasPrefix(p, "../") { + dockerfile = p + } else { + return // a Dockerfile outside the tree + } + } + add := func(name, value string, set bool) { + if name == "" || len(s.buildArgs) >= 4096 { + return + } + s.buildArgs = append(s.buildArgs, buildArg{name: name, value: value, literal: set && !strings.Contains(value, "$"), compose: rel, dockerfile: dockerfile}) + } switch args.Kind { case yaml.MappingNode: for i := 0; i+1 < len(args.Content); i += 2 { - names = append(names, args.Content[i].Value) + v := deref(args.Content[i+1]) + // A null value takes the variable from the environment. + add(args.Content[i].Value, v.Value, v.Kind == yaml.ScalarNode && v.Tag != "!!null") } case yaml.SequenceNode: for _, a := range args.Content { - n, _, _ := strings.Cut(a.Value, "=") - names = append(names, n) - } - } - for _, n := range names { - if _, ok := s.buildArgs[n]; !ok && n != "" && len(s.buildArgs) < 4096 { - s.buildArgs[n] = rel + n, v, ok := strings.Cut(a.Value, "=") + add(n, v, ok) } } }) diff --git a/detectors/java4shell/internal/repo/second_test.go b/detectors/java4shell/internal/repo/second_test.go new file mode 100644 index 0000000..2e47cf1 --- /dev/null +++ b/detectors/java4shell/internal/repo/second_test.go @@ -0,0 +1,76 @@ +package repo + +import ( + "context" + "strings" + "testing" +) + +// Second final review: a Compose build argument is a literal in the tree, +// so the FROM is judged with it. It is a gap only when the value cannot be +// read and the image could be a Java one, and only for the Dockerfile the +// service builds. Before, any Dockerfile that used an ARG of that name +// was marked not checked: a tree with no Java in it made fix exit 1. +func TestComposeBuildArgsAreJudged(t *testing.T) { + const fixedDefault = "ARG TAG=21.0.13.1_2-jre\nFROM eclipse-temurin:${TAG}\n" + compose := func(context, args string) string { + return "services:\n app:\n build:\n context: " + context + "\n args:\n" + args + } + for name, c := range map[string]struct { + files map[string]string + want string + }{ + "no Java: nginx with a literal": {map[string]string{"Dockerfile": "ARG NGINX=1.27\nFROM nginx:${NGINX}\n", "docker-compose.yml": compose(".", " NGINX: 1.28\n")}, ""}, + "no Java: nginx with a variable": {map[string]string{"Dockerfile": "ARG NGINX=1.27\nFROM nginx:${NGINX}\n", "docker-compose.yml": compose(".", " NGINX: ${NGINX_VERSION}\n")}, ""}, + "a vulnerable tag over a fixed default": {map[string]string{"Dockerfile": fixedDefault, "docker-compose.yml": compose(".", " TAG: 21.0.13_9-jre\n")}, "Dockerfile:2 image-pin vulnerable"}, + "the same as a list": {map[string]string{"Dockerfile": fixedDefault, "docker-compose.yml": compose(".", " - TAG=21.0.13_9-jre\n")}, "Dockerfile:2 image-pin vulnerable"}, + "a fixed tag over a fixed default": {map[string]string{"Dockerfile": fixedDefault, "docker-compose.yml": compose(".", " TAG: 21.0.13.1_2-jdk\n")}, ""}, + "the default again": {map[string]string{"Dockerfile": fixedDefault, "docker-compose.yml": compose(".", " TAG: 21.0.13.1_2-jre\n")}, ""}, + "a fixed tag over a vulnerable default: the default still builds": {map[string]string{"Dockerfile": "ARG TAG=21.0.13_9-jre\nFROM eclipse-temurin:${TAG}\n", "docker-compose.yml": compose(".", " TAG: 21.0.13.1_2-jre\n")}, "Dockerfile:2 image-pin vulnerable"}, + "a value from the environment": {map[string]string{"Dockerfile": fixedDefault, "docker-compose.yml": compose(".", " TAG: ${JAVA_TAG}\n")}, "skip Dockerfile:2"}, + "a name with no value (taken from the environment)": {map[string]string{"Dockerfile": fixedDefault, "docker-compose.yml": compose(".", " - TAG\n")}, "skip Dockerfile:2"}, + "the whole image in the argument": {map[string]string{"Dockerfile": "ARG BASE=debian:12\nFROM ${BASE}\n", "docker-compose.yml": compose(".", " BASE: eclipse-temurin:21.0.13_9-jre\n")}, "Dockerfile:2 image-pin vulnerable"}, + "the whole image, not Java": {map[string]string{"Dockerfile": "ARG BASE=debian:12\nFROM ${BASE}\n", "docker-compose.yml": compose(".", " BASE: debian:13\n")}, ""}, + "the whole image from the environment": {map[string]string{"Dockerfile": "ARG BASE=debian:12\nFROM ${BASE}\n", "docker-compose.yml": compose(".", " BASE: ${BASE_IMAGE}\n")}, "skip Dockerfile:2"}, + "two arguments, one set": {map[string]string{"Dockerfile": "ARG REPO=eclipse-temurin\nARG TAG=21.0.13.1_2-jre\nFROM ${REPO}:${TAG}\n", "docker-compose.yml": compose(".", " TAG: 21.0.13_9-jre\n")}, "skip Dockerfile:3"}, + "another service's Dockerfile is not marked": {map[string]string{"Dockerfile": fixedDefault, "svc/Dockerfile": "ARG TAG=3\nFROM alpine:3\n", "docker-compose.yml": compose("./svc", " TAG: 21.0.13_9-jre\n")}, ""}, + "a Dockerfile named in a sub-directory": {map[string]string{"app/Dockerfile.prod": fixedDefault, "docker-compose.yml": "services:\n a:\n build:\n context: ./app\n dockerfile: Dockerfile.prod\n args:\n TAG: 21.0.13_9-jre\n"}, "app/Dockerfile.prod:2 image-pin vulnerable"}, + "a context the tree cannot place": {map[string]string{"Dockerfile": fixedDefault, "docker-compose.yml": compose("${APP_DIR}", " TAG: 21.0.13_9-jre\n")}, "Dockerfile:2 image-pin vulnerable"}, + "a Compose file in a sub-directory": {map[string]string{"deploy/Dockerfile": fixedDefault, "deploy/compose.yaml": compose(".", " TAG: 21.0.13_9-jre\n")}, "deploy/Dockerfile:2 image-pin vulnerable"}, + } { + if g := strings.Join(got(t, tree(t, c.files)), ", "); g != c.want { + t.Errorf("%s: [%s], want [%s]", name, g, c.want) + } + } + // The finding names the Compose file and is not one fix edits. + res := scanTree(t, map[string]string{"Dockerfile": fixedDefault, "docker-compose.yml": compose(".", " TAG: 21.0.13_9-jre\n")}) + if len(res.Findings) != 1 || res.Findings[0].Fixable || !strings.Contains(res.Findings[0].Reason, "docker-compose.yml") { + t.Errorf("the finding from a Compose build argument: %+v", res.Findings) + } +} + +// An unresolved reference is a java4shell gap only when it could be a +// Java image: its name says so, or a variable hides the name. A variable +// in the tag of an image that is plainly something else is not. +func TestUnresolvedReferenceThatIsNotJava(t *testing.T) { + for name, c := range map[string]struct{ df, want string }{ + "a variable tag of another image": {"FROM registry.example.com/acme/web:${VERSION}\n", ""}, + "a variable tag with a default-less brace form": {"FROM nginx:$NGINX\n", ""}, + "a variable tag of a Java image": {"FROM eclipse-temurin:${VERSION}\n", "skip Dockerfile:1"}, + "a variable name": {"FROM ${BASE}:${VERSION}\n", "skip Dockerfile:1"}, + "a variable registry path": {"FROM registry.example.com/${TEAM}/app:1\n", "skip Dockerfile:1"}, + } { + if g := strings.Join(got(t, tree(t, map[string]string{"Dockerfile": c.df})), ", "); g != c.want { + t.Errorf("%s: [%s], want [%s]", name, g, c.want) + } + } +} + +func scanTree(t *testing.T, files map[string]string) Result { + t.Helper() + res, err := Scan(context.Background(), tree(t, files), Options{}) + if err != nil { + t.Fatal(err) + } + return res +} From edb2f904ea853d17dbbfc1154b759022e9f926c6 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 14:09:08 +0000 Subject: [PATCH 114/119] refs, java4shell: a Dockerfile the parser refuses is still read, and the install forms that gave nothing Second final review, findings 3 and 8 and the silent RUN forms. A Dockerfile refs.Instructions refused (an unterminated heredoc, a directive given twice, an escape character it does not accept) became one skip record: "FROM debian:12 / RUN apt-get install -y openjdk-17-jdk / RUN cat < --- .../internal/repo/dockerfile_fix_test.go | 175 +++++++ .../java4shell/internal/repo/final_test.go | 2 +- detectors/java4shell/internal/repo/repo.go | 482 ++++++++++++++++-- internal/refs/instructions.go | 19 +- internal/refs/instructions_test.go | 11 +- 5 files changed, 651 insertions(+), 38 deletions(-) create mode 100644 detectors/java4shell/internal/repo/dockerfile_fix_test.go diff --git a/detectors/java4shell/internal/repo/dockerfile_fix_test.go b/detectors/java4shell/internal/repo/dockerfile_fix_test.go new file mode 100644 index 0000000..f56ecc1 --- /dev/null +++ b/detectors/java4shell/internal/repo/dockerfile_fix_test.go @@ -0,0 +1,175 @@ +package repo + +import ( + "runtime" + "strings" + "testing" +) + +// one scans a tree that holds one Dockerfile. +func one(t *testing.T, df string) string { + t.Helper() + return strings.Join(got(t, tree(t, map[string]string{"Dockerfile": df})), ", ") +} + +// Second final review, finding 1: a Dockerfile the instruction parser +// refuses keeps its skip record, and its RUN lines are still read line by +// line: a finding is never traded for a gap. Nothing in such a file is +// reported as mitigated. +func TestUnparsedDockerfileIsStillRead(t *testing.T) { + const skip = ", skip Dockerfile:0" + for name, c := range map[string]struct{ df, want string }{ + "an unterminated heredoc": {"FROM debian:12\nRUN apt-get install -y openjdk-17-jdk\nRUN cat < /x\nhello\n", "Dockerfile:2 os-package vulnerable" + skip}, + "its body": {"FROM debian:12\nRUN < /x\nhello\nRUN apt-get install -y openjdk-17-jdk\n", "Dockerfile:4 os-package vulnerable" + skip}, + "a heredoc on a descriptor": {"FROM debian:12\nRUN test 1 -lt 2 && cat 3< /x\nhello\n", "skip Dockerfile:0"}, + "a file larger than the parser's": {"FROM debian:12\nRUN apt-get install -y openjdk-17-jdk\n" + strings.Repeat("# "+strings.Repeat("x", 78)+"\n", 13200), "Dockerfile:2 os-package vulnerable" + skip}, + } { + if g := one(t, c.df); g != c.want { + t.Errorf("%s: [%s], want [%s]", name, g, c.want) + } + } +} + +// Finding 8: the instruction parser keeps the position of every byte, and +// the image reference scan caps it at refs.MaxDockerfileSize. A larger +// Dockerfile is read line by line here, in memory of the file's own order. +func TestLargeDockerfileMemory(t *testing.T) { + var b strings.Builder + b.WriteString("FROM debian:12\nRUN apt-get update \\\n") + for b.Len() < maxFileSize-256 { + b.WriteString(" && echo 0123456789012345678901234567890123456789012345678901234567890123456789 \\\n") + } + b.WriteString(" && apt-get install -y openjdk-17-jdk\n") + dir := tree(t, map[string]string{"Dockerfile": b.String()}) + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + g := strings.Join(got(t, dir), ", ") + runtime.ReadMemStats(&after) + if want := "Dockerfile:2 os-package vulnerable, skip Dockerfile:0"; g != want { + t.Errorf("[%s], want [%s]", g, want) + } + if mb := (after.TotalAlloc - before.TotalAlloc) >> 20; mb > 160 { + t.Errorf("scanning a %d MiB Dockerfile allocated %d MiB", b.Len()>>20, mb) + } +} + +// Finding 3: a RUN whose install is the text of a shell's -c, whatever +// stands before the shell or between it and -c. +func TestRunShellTexts(t *testing.T) { + const vuln = "Dockerfile:2 os-package vulnerable" + for name, c := range map[string]struct{ run, want string }{ + "exec form, sh -c, one command": {`RUN ["sh", "-c", "apt-get install -y openjdk-17-jdk"]`, vuln}, + "exec form, bash -c": {`RUN ["bash", "-c", "apt-get install -y openjdk-17-jdk"]`, vuln}, + "exec form, bash -lc": {`RUN ["/bin/bash", "-lc", "apt-get install -y openjdk-17-jdk"]`, vuln}, + "exec form, -o pipefail -c": {`RUN ["/bin/bash", "-o", "pipefail", "-c", "apt-get install -y openjdk-17-jdk"]`, vuln}, + "exec form, two commands": {`RUN ["/bin/sh", "-c", "apt-get update; apt-get install -y openjdk-17-jdk"]`, vuln}, + "exec form, two lines": {`RUN ["sh", "-c", "apt-get update\napt-get install -y openjdk-17-jdk"]`, vuln}, + "exec form, no shell": {`RUN ["apt-get", "install", "-y", "openjdk-17-jdk"]`, vuln}, + "exec form, a word with &&": {`RUN ["apt-get", "install", "-y", "curl", "&&", "openjdk-17-jdk"]`, vuln}, + "exec form, two names in a word": {`RUN ["apt-get", "install", "-y", "curl openjdk-17-jdk"]`, vuln}, + "exec form, a quote in the text": {`RUN ["sh", "-c", "echo 'it''s' && apt-get install -y 'openjdk-17-jdk'"]`, vuln}, + "bash -o pipefail -c": {`RUN bash -o pipefail -c "apt-get install -y openjdk-17-jdk"`, vuln}, + "bash -euo pipefail -c": {`RUN bash -euo pipefail -c "apt-get install -y openjdk-17-jdk"`, vuln}, + "bash --login -c": {`RUN bash --login -c "apt-get install -y openjdk-17-jdk"`, vuln}, + "bash -c -x": {`RUN bash -c -x "apt-get install -y openjdk-17-jdk"`, vuln}, + "su -c": {`RUN su -c "apt-get install -y openjdk-17-jdk" root`, vuln}, + "su user -c": {`RUN su - root -c "apt-get install -y openjdk-17-jdk"`, vuln}, + "sudo sh -c": {`RUN sudo -E sh -c "apt-get install -y openjdk-17-jdk"`, vuln}, + "chroot sh -c": {`RUN chroot /mnt /bin/sh -c "apt-get install -y openjdk-17-jdk"`, vuln}, + "eval": {`RUN eval "apt-get install -y openjdk-17-jdk"`, vuln}, + "a nested text": {`RUN sh -c 'sh -c "apt-get install -y openjdk-17-jdk"'`, vuln}, + "a text that is only printed": {`RUN echo "run apt-get install -y openjdk-17-jdk to get Java"`, ""}, + "a text that is only written out": {`RUN printf '%s\n' "apt-get install -y openjdk-17-jdk" > /usr/local/bin/get-java`, ""}, + "a script file, not a text": {`RUN bash /tmp/setup.sh apt-get`, ""}, + } { + if g := one(t, "FROM debian:12\n"+c.run+"\n"); g != c.want { + t.Errorf("%s: [%s], want [%s]", name, g, c.want) + } + } +} + +// Finding 4: installs that named a Java package, or took their package +// list from somewhere this file does not show, and gave nothing. +func TestRunInstallForms(t *testing.T) { + const vuln, skip = "Dockerfile:2 os-package vulnerable", "skip Dockerfile:2" + for name, c := range map[string]struct{ df, want string }{ + "xargs from a file": {"FROM debian:12\nRUN xargs apt-get install -y < packages.txt\n", skip}, + "xargs -a": {"FROM debian:12\nRUN xargs -a packages.txt apt-get install -y\n", skip}, + "xargs after cat": {"FROM debian:12\nRUN cat packages.txt | xargs -r apt-get install -y --no-install-recommends\n", skip}, + "xargs after echo": {"FROM debian:12\nRUN echo openjdk-17-jdk | xargs apt-get install -y\n", vuln}, + "xargs after echo, no Java": {"FROM debian:12\nRUN echo curl git | xargs apt-get install -y\n", ""}, + "xargs with a name of its own": {"FROM debian:12\nRUN xargs apt-get install -y openjdk-17-jdk < more.txt\n", vuln + ", " + skip}, + "Bitnami install_packages": {"FROM bitnami/minideb:bookworm\nRUN install_packages openjdk-17-jdk\n", vuln}, + "install_packages, no Java": {"FROM bitnami/minideb:bookworm\nRUN install_packages curl ca-certificates\n", ""}, + "nala": {"FROM debian:12\nRUN nala install -y openjdk-17-jdk\n", vuln}, + "apt-fast": {"FROM debian:12\nRUN apt-fast install -y openjdk-17-jdk\n", vuln}, + "apt-get satisfy": {"FROM debian:12\nRUN apt-get satisfy -y \"openjdk-17-jdk (>= 17)\"\n", vuln}, + "dnf upgrade": {"FROM rockylinux:9\nRUN dnf upgrade -y java-21-openjdk-headless\n", vuln}, + "yum update": {"FROM rockylinux:9\nRUN yum update -y java-21-openjdk-headless\n", vuln}, + "dnf downgrade": {"FROM rockylinux:9\nRUN dnf downgrade -y java-21-openjdk-headless\n", vuln}, + "apk upgrade": {"FROM alpine:3.22\nRUN apk upgrade --no-cache openjdk21-jre-headless\n", vuln}, + "apt-get update, no package": {"FROM debian:12\nRUN apt-get update && apt-get upgrade -y\n", ""}, + "the tool in an ARG": {"FROM debian:12\nARG APT=\"apt-get install -y\"\nRUN $APT openjdk-17-jdk\n", "Dockerfile:3 os-package vulnerable"}, + "the tool in a variable unset": {"FROM debian:12\nARG INSTALL\nRUN $INSTALL openjdk-17-jdk\n", "Dockerfile:3 os-package vulnerable"}, + "a variable tool, no Java": {"FROM debian:12\nARG INSTALL\nRUN $INSTALL curl && $JAVA_HOME/bin/java -version\n", ""}, + "a shell variable over an ARG": {"FROM debian:12\nARG PKG=curl\nRUN PKG=openjdk-17-jdk && apt-get install -y $PKG\n", "Dockerfile:3 os-package vulnerable"}, + "an exported one": {"FROM debian:12\nARG PKG=curl\nRUN export PKG=openjdk-17-jdk; apt-get install -y \"$PKG\"\n", "Dockerfile:3 os-package vulnerable"}, + "one from a command": {"FROM debian:12\nARG PKG=curl\nRUN PKG=$(cat /pkg) && apt-get install -y $PKG\n", "skip Dockerfile:3"}, + "one that is read": {"FROM debian:12\nARG PKG=curl\nRUN cat /pkgs | while read PKG; do apt-get install -y $PKG; done\n", "skip Dockerfile:3"}, + "a prefix assignment is not it": {"FROM debian:12\nARG PKG=openjdk-17-jdk\nRUN PKG=curl apt-get install -y $PKG\n", "Dockerfile:3 os-package vulnerable"}, + "a for loop": {"FROM debian:12\nRUN for p in curl openjdk-17-jdk; do apt-get install -y $p; done\n", vuln}, + "a later stage's ARG, unset": {"FROM debian:12 AS a\nARG PKG=curl\nRUN apt-get install -y $PKG\nFROM debian:12\nARG PKG\nRUN apt-get install -y $PKG\n", "skip Dockerfile:6"}, + "a later stage's ARG, global": {"ARG PKG=openjdk-17-jdk\nFROM debian:12 AS a\nARG PKG=curl\nRUN apt-get install -y $PKG\nFROM debian:12\nARG PKG\nRUN apt-get install -y $PKG\n", "Dockerfile:7 os-package vulnerable"}, + "an ENV of the name stays": {"FROM debian:12\nENV PKG=openjdk-17-jdk\nARG PKG\nRUN apt-get install -y $PKG\n", "Dockerfile:4 os-package vulnerable"}, + "a comment after the install": {"FROM debian:12\nRUN apt-get install -y openjdk-17-jdk # java\n", vuln}, + "a comment that hides it": {"FROM debian:12\nRUN apt-get install -y curl # openjdk-17-jdk\n", ""}, + "a # inside a word": {"FROM debian:12\nRUN apt-get install -y curl#x openjdk-17-jdk\n", vuln}, + "a heredoc with a comment": {"FROM debian:12\nRUN <<]+)([^\s;&|]+))?`) rpmJava = regexp.MustCompile(`\b(java-(\d{1,2})-(openjdk|amazon-corretto)(?:-headless|-devel|-jdk)?)(?:-(\d[\w.:*?+~-]*))?`) @@ -1202,8 +1202,10 @@ func (s *scanner) dockerfile(rel, text string) { ins, err := refs.Instructions([]byte(text)) if err != nil { // The image reference scan records the same file when it cannot - // parse it: one record (scanList). - s.unparsed = append(s.unparsed, Skip{File: rel, Reason: "the Dockerfile could not be parsed (" + refs.CleanText(err.Error(), 120) + "): the packages it installs are not checked"}) + // parse it: one record (scanList). What the lines say is still + // read: a finding is not traded for the gap. + s.unparsed = append(s.unparsed, Skip{File: rel, Reason: "the Dockerfile could not be parsed (" + refs.CleanText(err.Error(), 120) + "): it was read line by line, and what a line alone does not show is not checked"}) + s.dockerfileLines(rel, text) return } from := 0 @@ -1212,7 +1214,8 @@ func (s *scanner) dockerfile(rel, text string) { // stage sets the mitigation (before or after the install: ENV applies // to the image the stage makes). stageEnv := map[string]string{} - var stageCmd []string // ENTRYPOINT and CMD words of the stage + stageEnvAll := map[string]bool{} // the names ENV sets in the stage, its base's included + var stageCmd []string // ENTRYPOINT and CMD words of the stage endStage := func() { o := undo(jvm.FromEnv(withoutJavaOptions(stageEnv), nil, 17, nil), stageCmd, stageEnv) ok, how := o.Mitigates() @@ -1232,11 +1235,36 @@ func (s *scanner) dockerfile(rel, text string) { } } defer endStage() - // vars are the ARG defaults and ENV values the file sets, for package - // names a RUN takes from a variable. + // vars are the ARG and ENV values in force in the stage, for package + // names a RUN takes from a variable. An ARG before the first FROM is + // global: a stage has it once it declares it (ARG NAME). A stage + // built on an earlier one starts with that stage's ENV values; + // nothing else carries over. vars := map[string]string{} + globals := map[string]string{} + envOf := map[string]map[string]string{} // stage name or index -> its ENV values + stageName, stageIndex := "", -1 + closeStage := func() { + if stageIndex < 0 { + return + } + env := map[string]string{} + for k := range stageEnvAll { + if v, ok := vars[k]; ok { + env[k] = v + } + } + envOf[fmt.Sprint(stageIndex)] = env + if stageName != "" { + envOf[stageName] = env + } + } stages := map[string]bool{} for _, in := range ins { + if in.Onbuild && in.Cmd != "run" && in.Cmd != "copy" && in.Cmd != "add" { + // It runs in another image's build: it sets nothing here. + continue + } // COPY --from=image and RUN --mount=...,from=image bring files of // another image into the stage: the image is judged like a FROM. for _, fl := range in.Flags { @@ -1268,16 +1296,37 @@ func (s *scanner) dockerfile(rel, text string) { switch in.Cmd { case "from": endStage() + closeStage() from, stageStart, stageEnv, stageCmd = in.Line, len(s.findings), map[string]string{}, nil - if w := strings.Fields(in.Args); len(w) >= 3 && strings.EqualFold(w[len(w)-2], "as") { - stages[strings.ToLower(w[len(w)-1])] = true + stageIndex, stageName, stageEnvAll = stageIndex+1, "", map[string]bool{} + w := strings.Fields(in.Args) + vars = map[string]string{} + if len(w) > 0 { + for k, v := range envOf[strings.ToLower(w[0])] { + vars[k], stageEnvAll[k] = v, true + } + } + if len(w) >= 3 && strings.EqualFold(w[len(w)-2], "as") { + stageName = strings.ToLower(w[len(w)-1]) + stages[stageName] = true } case "cmd", "entrypoint": stageCmd = append(stageCmd, commandWords(in.Args)...) case "arg": for _, kv := range jvm.Words(in.Args) { - if k, v, ok := strings.Cut(kv, "="); ok { - vars[k] = v + k, v, ok := strings.Cut(kv, "=") + switch { + case from == 0 && ok: + globals[k] = v + case from == 0: + case ok: + if !stageEnvAll[k] { + vars[k] = v // an ENV of the name wins over the ARG + } + default: + if g, set := globals[k]; set && !stageEnvAll[k] { + vars[k] = g + } } } case "env": @@ -1285,13 +1334,13 @@ func (s *scanner) dockerfile(rel, text string) { // image keeps; the mitigation is decided when the stage ends. for _, kv := range jvm.Words(in.Args) { if k, v, ok := strings.Cut(kv, "="); ok { - stageEnv[k], vars[k] = v, v + stageEnv[k], vars[k], stageEnvAll[k] = v, v, true } } case "run": run := in.Args if in.JSON != nil { - run = strings.Join(jvm.CommandWords(in.JSON), " ") + run = execForm(in.JSON) } s.packages(rel, in.Line, run, vars) for _, body := range in.Heredocs { @@ -1324,16 +1373,258 @@ func heredocCommands(body string) string { return strings.Join(out, " ; ") } +// execForm turns the words of an exec-form RUN into a command line: the +// script itself when the words run a shell's -c text, the words quoted +// one by one otherwise (no shell reads them, so "&&" is an argument). +func execForm(words []string) string { + if text, ok := shellText(words); ok { + return text + } + var b strings.Builder + for i, w := range words { + if i > 0 { + b.WriteByte(' ') + } + b.WriteByte('"') + b.WriteString(strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(w)) + b.WriteByte('"') + } + return b.String() +} + +// dockerInstructions are the instruction words; in a file the parser +// refused, a line that starts with none of them is taken as shell text +// (the body of a heredoc). +var dockerInstructions = map[string]bool{"from": true, "run": true, "cmd": true, "label": true, "maintainer": true, "expose": true, "env": true, + "add": true, "copy": true, "entrypoint": true, "volume": true, "user": true, "workdir": true, "arg": true, "onbuild": true, + "stopsignal": true, "healthcheck": true, "shell": true} + +var escapeDirective = regexp.MustCompile("(?i)^#\\s*escape\\s*=\\s*([\\\\`])\\s*$") + +// dockerfileLines reads a Dockerfile the instruction parser refused (an +// unterminated heredoc, a directive it does not accept, a file over its +// size limit) line by line: continuation lines joined, comment lines +// dropped. RUN lines and what follows them as shell text are read for +// installs, FROM and COPY --from images are judged. ARG and ENV values are +// taken for the whole file, and no mitigation is read from it: a line +// alone does not show what a stage ends with. +func (s *scanner) dockerfileLines(rel, text string) { + ls := lines(text) + escape := byte('\\') + for _, l := range ls { + t := strings.TrimSpace(l) + if t == "" { + continue + } + if !strings.HasPrefix(t, "#") { + break + } + if m := escapeDirective.FindStringSubmatch(t); m != nil { + escape = m[1][0] + break + } + } + vars := map[string]string{} + stages := map[string]bool{} + runLine := 0 + for i := 0; i < len(ls); i++ { + start := i + 1 + var b strings.Builder + for ; i < len(ls); i++ { + t := strings.TrimRight(ls[i], " \t") + if b.Len() > 0 && strings.HasPrefix(strings.TrimSpace(t), "#") { + continue // a comment line inside a continuation + } + if strings.HasSuffix(t, string(escape)) { + b.WriteString(strings.TrimSuffix(t, string(escape))) + b.WriteByte(' ') + continue + } + b.WriteString(t) + break + } + full := strings.TrimSpace(b.String()) + if full == "" || strings.HasPrefix(full, "#") { + continue + } + word, rest := full, "" + if k := strings.IndexAny(full, " \t"); k >= 0 { + word, rest = full[:k], strings.TrimSpace(full[k+1:]) + } + cmd := strings.ToLower(word) + if cmd == "onbuild" { + word, rest2, _ := strings.Cut(rest, " ") + if k := strings.IndexAny(rest, " \t"); k >= 0 { + word, rest2 = rest[:k], strings.TrimSpace(rest[k+1:]) + } + if c := strings.ToLower(word); c == "run" || c == "copy" || c == "add" { + cmd, rest = c, rest2 + } else { + continue + } + } + if !dockerInstructions[cmd] { + // Shell text: the body of a heredoc the RUN above opened. + line := start + if runLine > 0 { + line = runLine + } + s.packages(rel, line, full, vars) + continue + } + if cmd != "run" { + runLine = 0 + } + words := strings.Fields(rest) + image := func(img, context, platform string) { + if img == "" || stages[strings.ToLower(img)] || atoi(img) > 0 || img == "0" || strings.Contains(img, "$") { + return + } + before := len(s.findings) + s.judgeRef(refs.Ref{File: rel, Line: start, Kind: refs.KindDockerfile, Context: context, Text: img, Image: img, Platform: platform}, s.opts) + for k := before; k < len(s.findings); k++ { + if f := &s.findings[k]; f.Fixable { + f.Fixable, f.edit = false, nil + f.Fix = "Change the image by hand: this Dockerfile could not be parsed. " + f.Fix + } + } + } + switch cmd { + case "from": + platform := "" + for len(words) > 0 && strings.HasPrefix(words[0], "--") { + if v, ok := strings.CutPrefix(words[0], "--platform="); ok { + platform = v + } + words = words[1:] + } + if len(words) > 0 { + image(expandVars(strings.Trim(words[0], `"'`), vars), "FROM", platform) + } + if len(words) >= 3 && strings.EqualFold(words[len(words)-2], "as") { + stages[strings.ToLower(words[len(words)-1])] = true + } + case "arg", "env": + for _, kv := range jvm.Words(rest) { + if k, v, ok := strings.Cut(kv, "="); ok { + vars[k] = v + } + } + case "copy", "add", "run": + for len(words) > 0 && strings.HasPrefix(words[0], "--") { + fl := strings.Trim(words[0], `"'`) + if v, ok := strings.CutPrefix(fl, "--from="); ok { + image(v, strings.ToUpper(cmd)+" from", "") + } + if v, ok := strings.CutPrefix(fl, "--mount="); ok { + for _, kv := range strings.Split(v, ",") { + if img, ok := strings.CutPrefix(kv, "from="); ok { + image(img, "RUN from", "") + } + } + } + words = words[1:] + rest = strings.TrimSpace(strings.TrimPrefix(rest, strings.Fields(rest)[0])) + } + if cmd != "run" { + continue + } + runLine = start + var arr []string + if strings.HasPrefix(rest, "[") && json.Unmarshal([]byte(rest), &arr) == nil { + rest = execForm(arr) + } + s.packages(rel, start, rest, vars) + } + } +} + +// lineVars returns the variables in force for a RUN line: the stage's, +// changed by what the line itself assigns before it uses them. A shell +// variable set on the line (PKG=x && ..., export PKG=x; ...) has that +// value, a for loop's variable has its list, and one set from a command, +// from another variable or by read has none this file gives. +func lineVars(run string, vars map[string]string) map[string]string { + if !strings.Contains(run, "$") { + return vars + } + var out map[string]string + set := func(k, v string, known bool) { + if out == nil { + out = make(map[string]string, len(vars)+2) + for a, b := range vars { + out[a] = b + } + } + if known { + out[k] = v + } else { + delete(out, k) + } + } + for _, cmd := range jvm.SplitCommands(run) { + words := jvm.Words(cmd) + for len(words) > 0 && shellLead[strings.TrimLeft(words[0], "({")] { + words = words[1:] + } + if len(words) == 0 { + continue + } + switch { + case words[0] == "for" && len(words) >= 3 && words[2] == "in": + list := strings.Join(words[3:], " ") + set(words[1], list, !strings.ContainsAny(list, "$`*")) + case words[0] == "read": + for _, w := range words[1:] { + if !strings.HasPrefix(w, "-") { + set(w, "", false) + } + } + case assignment.MatchString(words[0]): + all := true + for _, w := range words { + all = all && assignment.MatchString(w) + } + k, v, _ := strings.Cut(words[0], "=") + if !all { + // NAME=$(command ...) spans words; NAME=x command is a + // prefix for that command alone. + if strings.HasPrefix(v, "$(") || strings.HasPrefix(v, "`") { + set(k, "", false) + } + continue + } + for _, w := range words { + k, v, _ := strings.Cut(w, "=") + set(k, v, !strings.ContainsAny(v, "$`")) + } + } + } + if out == nil { + return vars + } + return out +} + +var ( + assignment = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*=`) + // shellLead are words that stand before a command without changing + // what it is. + shellLead = map[string]bool{"do": true, "then": true, "else": true, "export": true, "declare": true, "local": true, "readonly": true, "while": true, "until": true, "if": true, "!": true} +) + // packages finds the OpenJDK packages a RUN line installs: distribution // packages and the vendors' own (Temurin, Corretto, Zulu, Microsoft, // SapMachine), with or without a version. func (s *scanner) packages(rel string, line int, run string, vars map[string]string) { - if !installRE.MatchString(run) { + // The tool can come from a variable (ARG APT="apt-get install -y"). + run = expandVars(run, lineVars(run, vars)) + if !installRE.MatchString(run) && !strings.Contains(run, "$") { return } var hits []pkgHit var opaque []string - for _, arg := range installArgs(expandVars(run, vars), 0) { + for _, arg := range installArgs(run, 0) { if strings.HasPrefix(arg, opaqueArg) { opaque = append(opaque, strings.TrimPrefix(arg, opaqueArg)) continue @@ -1342,8 +1633,17 @@ func (s *scanner) packages(rel string, line int, run string, vars map[string]str arg = strings.TrimPrefix(arg, fileArg) // A version range in one quoted word ('java-17-openjdk >= 17.0.21.1'): // the package is judged without the range. + // A word that holds several names (an exec-form argument with a + // space in it) is judged by the Java package among them. if name, _, ok := strings.Cut(arg, " "); ok && !fromFile { + whole := arg arg = name + for _, w := range strings.Fields(whole)[1:] { + if !javaPackage(name) && javaPackage(w) { + arg = w + break + } + } } before := len(hits) switch { @@ -1461,8 +1761,11 @@ var ( ) var ( - pkgTools = map[string]bool{"apt-get": true, "aptitude": true, "apt": true, "apk": true, "dnf": true, "dnf5": true, "yum": true, "microdnf": true, "tdnf": true, "zypper": true, "rpm": true, "dpkg": true} - pkgVerbs = map[string]bool{"install": true, "add": true, "in": true, "reinstall": true, "localinstall": true} + pkgTools = map[string]bool{"apt-get": true, "aptitude": true, "apt": true, "apt-fast": true, "nala": true, "install_packages": true, "apk": true, "dnf": true, "dnf5": true, "yum": true, "microdnf": true, "tdnf": true, "zypper": true, "rpm": true, "dpkg": true} + // pkgVerbs install the packages named after them. An upgrade or a + // downgrade that names a package installs a release of it too. + pkgVerbs = map[string]bool{"install": true, "add": true, "in": true, "reinstall": true, "localinstall": true, "satisfy": true, + "upgrade": true, "update": true, "up": true, "downgrade": true, "dist-upgrade": true, "full-upgrade": true} // pkgValueFlags are package-manager options followed by a separate value. pkgValueFlags = map[string]bool{"-t": true, "-o": true, "-X": true, "--repository": true, "--virtual": true, "-c": true, "--root": true, "-p": true, "--target-release": true, "--option": true, "--repo": true, "--setopt": true, "--enablerepo": true, "--disablerepo": true, @@ -1602,8 +1905,20 @@ func vendorFileVersion(name string) string { // their values, paths and URLs. func installArgs(run string, depth int) []string { var out []string + var prev []string // the words of the command before + at := 0 // where the search for the next command starts in run for _, cmd := range jvm.SplitCommands(run) { + // Whether a pipe leads into this command (xargs reads the one + // before it). + piped := false + if k := strings.Index(run[at:], cmd); k >= 0 && cmd != "" { + before := strings.TrimRight(run[:at+k], " \t\n") + piped = strings.HasSuffix(before, "|") && !strings.HasSuffix(before, "||") + at += k + len(cmd) + } words := jvm.Words(cmd) + last := prev + prev = words // A group or subshell: ( apt-get install x ), { ...; }. for k, w := range words { if t := strings.TrimLeft(w, "({"); t != "" { @@ -1627,11 +1942,48 @@ func installArgs(run string, depth int) []string { i++ } if i == len(words) { + // A tool this file names by a variable it does not set + // ($INSTALL openjdk-17-jdk): the words after it are read as + // packages, since a Java package name there is an install. + if k := leadWords(words); k < len(words) && bareVar.MatchString(words[k]) { + for _, w := range words[k+1:] { + if strings.HasPrefix(w, "#") { + break + } + if !strings.HasPrefix(w, "-") && !strings.HasPrefix(w, "$") && javaPackage(w) { + out = append(out, packageName(w)) + } + } + } continue } + // xargs gives the tool its package names: those of an echo or + // printf piped into it are read, anything else (a file, another + // command's output) is a list this file does not show. + for _, w := range words[:i] { + if path.Base(w) != "xargs" { + continue + } + lead := leadWords(last) + if piped && lead < len(last) && (last[lead] == "echo" || last[lead] == "printf") { + for _, a := range last[lead+1:] { + if a = redirect.ReplaceAllString(a, ""); a == "" || strings.HasPrefix(a, "-") || strings.Contains(a, "%") || strings.Contains(a, "\\") { + continue + } + if strings.HasPrefix(a, "$") || strings.HasPrefix(a, "`") { + out = append(out, opaqueArg+a) + } else if n := packageName(a); n != "" { + out = append(out, n) + } + } + } else { + out = append(out, opaqueArg+"xargs") + } + break + } tool := path.Base(words[i]) i++ - installs := false + installs := tool == "install_packages" // Bitnami's wrapper: the packages follow it for i < len(words) && strings.HasPrefix(words[i], "-") { if tool == "rpm" && rpmInstallFlag.MatchString(words[i]) || tool == "dpkg" && dpkgInstallFlag.MatchString(words[i]) { installs = true @@ -1641,7 +1993,7 @@ func installArgs(run string, depth int) []string { } i++ } - if tool == "rpm" || tool == "dpkg" { + if tool == "rpm" || tool == "dpkg" || tool == "install_packages" { // rpm -ivh file.rpm, dpkg -i file.deb: the package files follow // the flags. if !installs { @@ -1652,6 +2004,9 @@ func installArgs(run string, depth int) []string { continue } for j := i + 1; j < len(words); j++ { + if strings.HasPrefix(words[j], "#") { + break // a shell comment: the rest of the line + } w := redirect.ReplaceAllString(words[j], "") if w == "" { continue @@ -1692,25 +2047,88 @@ func installArgs(run string, depth int) []string { // a version, not by a path or a descriptor.) var redirect = regexp.MustCompile(`(?:>>?|<)[/&].*$|(?:>>?|<)$`) -// shellText returns the script of a "sh -c TEXT" command (also -ec, -lc -// and the like, behind env or a path). +// bareVar is a word that is one variable and nothing else. +var bareVar = regexp.MustCompile(`^\$\{?[A-Za-z_][A-Za-z0-9_]*\}?$`) + +// javaPackage reports whether a word names a Java package any reader here +// knows. +func javaPackage(w string) bool { + n := packageName(w) + if n == "" { + return false + } + base, _, _ := strings.Cut(n, "=") + return aptArg.MatchString(n) || apkArg.MatchString(n) || rpmArg.MatchString(n) || vendorArg.MatchString(n) || defaultArg.MatchString(n) || + rpmVirtual.MatchString(base) || rpmLatest.MatchString(base) || zypperArg.MatchString(n) || varJavaArg.MatchString(n) +} + +// leadWords returns the index of a command's own word: after assignments +// and the words that run another command (env, exec, sudo, nice, time, +// chroot DIR) with their options. +func leadWords(words []string) int { + i := 0 + for i < len(words) && i < 12 { + w := words[i] + switch b := path.Base(w); { + case b == "chroot" && i+1 < len(words): + i++ + case strings.HasPrefix(w, "-"), assignment.MatchString(w), b == "env", b == "exec", b == "sudo", b == "nice", b == "time", b == "nohup", b == "command": + default: + return i + } + i++ + } + return i +} + +// shellOptionWithValue are the shell options that take the next word. +var shellOptionWithValue = map[string]bool{"-o": true, "+o": true, "-O": true, "+O": true, "--rcfile": true, "--init-file": true} + +// shellText returns the script of a "sh -c TEXT" command: also -ec, -lc, +// -o pipefail -c, --login -c and the like, behind env, sudo or a path, +// the text of su -c, and what eval is given. func shellText(words []string) (string, bool) { - for i := 0; i < len(words) && i < 4; i++ { - switch path.Base(words[i]) { - case "sh", "bash", "ash", "dash", "zsh", "ksh": - for j := i + 1; j < len(words); j++ { - w := words[j] - if !strings.HasPrefix(w, "-") || strings.HasPrefix(w, "--") { - return "", false + i := leadWords(words) + if i >= len(words) { + return "", false + } + script := func(text string) (string, bool) { + // Lines of a script are commands of their own. + return strings.ReplaceAll(text, "\n", " ; "), true + } + switch path.Base(words[i]) { + case "sh", "bash", "ash", "dash", "zsh", "ksh": + c := false + for j := i + 1; j < len(words); j++ { + w := words[j] + switch { + case shellOptionWithValue[w]: + j++ + case strings.HasPrefix(w, "--"): + case strings.HasPrefix(w, "-") || strings.HasPrefix(w, "+"): + // A cluster: -ec has -c; one that ends in o (-euo) + // takes the next word as the option's name. + if strings.HasPrefix(w, "-") && strings.Contains(w, "c") { + c = true } - if strings.HasSuffix(w, "c") && j+1 < len(words) { - return words[j+1], true + if strings.HasSuffix(w, "o") { + j++ } + case c: + return script(w) + default: + return "", false // a script file, not a text + } + } + case "su": + for j := i + 1; j+1 < len(words); j++ { + if words[j] == "-c" || words[j] == "--command" { + return script(words[j+1]) } - return "", false } - if !strings.Contains(words[i], "=") && path.Base(words[i]) != "env" && path.Base(words[i]) != "exec" { - return "", false + case "eval": + if i+1 < len(words) { + return script(strings.Join(words[i+1:], " ")) } } return "", false diff --git a/internal/refs/instructions.go b/internal/refs/instructions.go index ceb1b6c..25de80f 100644 --- a/internal/refs/instructions.go +++ b/internal/refs/instructions.go @@ -2,9 +2,15 @@ package refs import ( "encoding/json" + "fmt" "strings" ) +// MaxDockerfileSize is the largest Dockerfile the instruction parser +// reads: it keeps the source position of every byte, and no real +// Dockerfile comes near this. +const MaxDockerfileSize = maxDockerfileSize + // Instruction is one Dockerfile instruction as BuildKit reads it: the // "# escape=" directive honoured, continuation lines joined, comment and // blank lines inside a continuation dropped, and the bodies of the @@ -15,6 +21,9 @@ type Instruction struct { // Cmd is the instruction word in lower case; for ONBUILD, the // instruction it wraps. Cmd string + // Onbuild is set for an instruction ONBUILD wraps: it runs in the build + // of an image made from this one, not in this build. + Onbuild bool // Line is the 1-based line the instruction starts on. Line int // Flags are the leading --flags of the arguments, quotes removed @@ -30,8 +39,11 @@ type Instruction struct { } // Instructions parses a Dockerfile. The error is the parser's: a file the -// builder would refuse. +// builder would refuse, or one larger than MaxDockerfileSize. func Instructions(b []byte) ([]Instruction, error) { + if len(b) > MaxDockerfileSize { + return nil, fmt.Errorf("larger than the %d bytes the instruction parser reads", MaxDockerfileSize) + } p, err := parseDockerfile("", b) if err != nil { return nil, err @@ -39,7 +51,8 @@ func Instructions(b []byte) ([]Instruction, error) { out := make([]Instruction, 0, len(p.instrs)) for _, in := range p.instrs { cmd, rest := in.cmd, in.rest.String() - if cmd == "onbuild" { + onbuild := cmd == "onbuild" + if onbuild { rest = strings.TrimSpace(rest) word, after, _ := strings.Cut(rest, " ") if i := strings.IndexAny(rest, " \t"); i >= 0 { @@ -47,7 +60,7 @@ func Instructions(b []byte) ([]Instruction, error) { } cmd, rest = strings.ToLower(word), strings.TrimSpace(after) } - x := Instruction{Cmd: cmd, Line: in.line, Args: rest, Heredocs: in.heredocs} + x := Instruction{Cmd: cmd, Onbuild: onbuild, Line: in.line, Args: rest, Heredocs: in.heredocs} if args, flags, err := extractBuilderFlags(rest); err == nil { x.Args, x.Flags = args, flags } diff --git a/internal/refs/instructions_test.go b/internal/refs/instructions_test.go index 13b0b9f..7ebb379 100644 --- a/internal/refs/instructions_test.go +++ b/internal/refs/instructions_test.go @@ -19,7 +19,11 @@ func TestInstructions(t *testing.T) { } var got []string for _, in := range ins { - got = append(got, fmt.Sprintf("%d %s %q %q %q %q", in.Line, in.Cmd, in.Flags, in.Args, in.JSON, in.Heredocs)) + cmd := in.Cmd + if in.Onbuild { + cmd = "onbuild:" + cmd + } + got = append(got, fmt.Sprintf("%d %s %q %q %q %q", in.Line, cmd, in.Flags, in.Args, in.JSON, in.Heredocs)) } want := []string{ `2 from [] "debian:12 AS base" [] []`, @@ -27,7 +31,7 @@ func TestInstructions(t *testing.T) { `7 run [] "[\"apt-get\", \"install\", \"-y\", \"x\"]" ["apt-get" "install" "-y" "x"] []`, `8 run ["--mount=type=bind,from=eclipse-temurin:21,target=/j"] "cp -r /j /opt" [] []`, `9 run [] "< Date: Wed, 18 Nov 2026 14:16:08 +0000 Subject: [PATCH 115/119] image, engine: writes through a link are settled by following the links and by layer order; a file named twice in a layer is read twice Second final review, finding 2. A path the flattener could not settle is forgotten and left as a coverage gap, which does not change the exit code. 2c2d19b kept the one file written through a single link; six other layouts still gave "OK", exit 0, where main reports the vulnerable library and docker export shows the container has it: - a link chain (lib -> usr/lib -> ../opt/real) and a link to the root; - ".." in a link's target after another link, where the landing path was worked out as text and an unrelated file was forgotten instead; - the same file written through the link and by its real path in one layer, and through two links to one directory; - one path twice in one layer. The flattener now knows each entry's place in its layer as well as its layer, and places an entry written under a link by following the stream's links one path component at a time, as the runtime did. All the entries that land on one path are one file, and the one the runtime applied last (a higher layer's, or a later entry of the same layer) is it: it stays read under the name it was written with, and the others are unresolved. It is not kept when a layer above the write took away a directory above the landing path (a whiteout, an opaque marker, a file in the directory's place): 2c2d19b had given back an emudhra clear on a certifi bundle whose directory a higher layer removed. An entry stays unresolved when a link on its way is of its own layer or a higher one, for a loop, and when the last entry through a link is a whiteout. A path a layer names twice as a regular file is written to the stream twice, the second entry marked with a PAX record (image.ReplacesRecord). The tar reader, which takes the first entry for a path in a flattened image, takes a marked entry as a docker export's repeat: the scans forget the first and read the second. Two entries of other kinds for one path stay unresolved. java4shell does not count a VM library as unread at a path where one written through a link landed and was read under its own name. On the review's fixtures all six are exit 1 with main's finding again; the same path twice, clean then vulnerable, is vulnerable (nothing on main). Co-Authored-By: Claude Fable 5.2 --- detectors/brotli/layers_internal_test.go | 63 ++++- detectors/java4shell/java4shell.go | 11 +- internal/engine/run.go | 4 +- internal/image/flatten.go | 279 +++++++++++++++++------ internal/image/flatten_test.go | 86 ++++++- internal/source/source.go | 7 +- 6 files changed, 360 insertions(+), 90 deletions(-) diff --git a/detectors/brotli/layers_internal_test.go b/detectors/brotli/layers_internal_test.go index 5ad38c9..15fe8ac 100644 --- a/detectors/brotli/layers_internal_test.go +++ b/detectors/brotli/layers_internal_test.go @@ -99,16 +99,75 @@ func TestWrittenThroughALink(t *testing.T) { if len(tg.Findings) != 1 || tg.Findings[0].Verdict != engine.Vulnerable || tg.Findings[0].Path != "/usr/lib/libbrotlidec.so.1" || tg.Gaps() != 1 { t.Errorf("the real path written afterwards: findings %+v skipped %+v", tg.Findings, tg.Skipped) } - // Written both ways in one layer, whose order decides: neither is kept. + // Written both ways in one layer: the layer's order decides, and the + // later entry is the file. p = archiveOf(t, []entry{{name: "usr/lib", dir: true}, {name: "lib", link: "usr/lib"}}, []entry{{name: "lib/libbrotlidec.so.1", data: fixed}, {name: "usr/lib/libbrotlidec.so.1", data: vulnerable}}) tg = engine.ScanImage([]engine.Detector{&Detector{}}, "docker-archive:"+p, engine.Options{}) - if len(tg.Findings) != 0 || tg.Gaps() != 2 { + if len(tg.Findings) != 1 || tg.Findings[0].Verdict != engine.Vulnerable || tg.Findings[0].Path != "/usr/lib/libbrotlidec.so.1" || tg.Gaps() != 1 { t.Errorf("written both ways: findings %+v skipped %+v", tg.Findings, tg.Skipped) } } +// Second final review, finding 2: layer layouts where the container has +// the vulnerable library (checked with docker load and docker export) and +// the scan reported only a coverage gap, exit 0, where main reports the +// library. Each is settled now: by following the links as the runtime did, +// by the order of a layer's entries, or by reading both entries a layer +// has for one path. +func TestLayersThatDroppedAFinding(t *testing.T) { + fixed := testbinFixed() + const lib = "libbrotlidec.so.1" + for name, c := range map[string]struct { + layers [][]entry + want string // the path of the one vulnerable finding + }{ + "a link chain": {[][]entry{ + {{name: "opt/real", dir: true}, {name: "usr", dir: true}, {name: "usr/lib", link: "../opt/real"}, {name: "lib", link: "usr/lib"}}, + {{name: "lib/" + lib, data: vulnerable}}}, "/lib/" + lib}, + "a link to the root, over a clean file": {[][]entry{ + {{name: "r", link: "/"}, {name: "usr/lib", dir: true}, {name: "usr/lib/" + lib, data: fixed}}, + {{name: "r/usr/lib/" + lib, data: vulnerable}}}, "/r/usr/lib/" + lib}, + ".. across a link: the clean file lands elsewhere": {[][]entry{ + {{name: "opt/real", dir: true}, {name: "opt/lib64", dir: true}, {name: "usr/lib", link: "/opt/real"}, {name: "lib", link: "usr/lib/../lib64"}, + {name: "usr/lib64", dir: true}, {name: "usr/lib64/" + lib, data: vulnerable}}, + {{name: "lib/" + lib, data: fixed}}}, "/usr/lib64/" + lib}, + "both names in one layer, the real path last": {[][]entry{ + {{name: "usr/lib", dir: true}, {name: "lib", link: "usr/lib"}}, + {{name: "lib/" + lib, data: vulnerable}, {name: "usr/lib/" + lib, data: vulnerable}}}, "/usr/lib/" + lib}, + "both names in one layer, the link's last": {[][]entry{ + {{name: "usr/lib", dir: true}, {name: "lib", link: "usr/lib"}}, + {{name: "usr/lib/" + lib, data: vulnerable}, {name: "lib/" + lib, data: vulnerable}}}, "/lib/" + lib}, + "two links to one directory": {[][]entry{ + {{name: "usr/lib", dir: true}, {name: "lib", link: "usr/lib"}, {name: "lib64", link: "usr/lib"}}, + {{name: "lib/" + lib, data: vulnerable}}, + {{name: "lib64/" + lib, data: vulnerable}}}, "/lib64/" + lib}, + "one path twice in one layer": {[][]entry{ + {{name: "usr/lib", dir: true}, {name: "usr/lib/" + lib, data: vulnerable}, {name: "usr/lib/" + lib, data: vulnerable}}}, "/usr/lib/" + lib}, + "one path twice in one layer, clean then vulnerable": {[][]entry{ + {{name: "usr/lib", dir: true}, {name: "usr/lib/" + lib, data: fixed}, {name: "usr/lib/" + lib, data: vulnerable}}}, "/usr/lib/" + lib}, + } { + tg := engine.ScanImage([]engine.Detector{&Detector{}}, "docker-archive:"+archiveOf(t, c.layers...), engine.Options{}) + var got []string + for _, f := range tg.Findings { + if f.Verdict == engine.Vulnerable { + got = append(got, f.Path) + } + } + if tg.Error != "" || len(got) != 1 || got[0] != c.want { + t.Errorf("%s: error %q, vulnerable at %v, want %s (findings %+v, skipped %+v)", name, tg.Error, got, c.want, tg.Findings, tg.Skipped) + } + } + // The last entry is the file the other way round too: vulnerable then + // clean in one layer is clean. + tg := engine.ScanImage([]engine.Detector{&Detector{}}, "docker-archive:"+archiveOf(t, + []entry{{name: "usr/lib", dir: true}, {name: "usr/lib/" + lib, data: vulnerable}, {name: "usr/lib/" + lib, data: fixed}}), engine.Options{}) + if tg.Error != "" || tg.Count(engine.Vulnerable) != 0 || tg.Gaps() != 0 { + t.Errorf("vulnerable then clean in one layer: findings %+v skipped %+v", tg.Findings, tg.Skipped) + } +} + // Final review A5: a docker export names d/lib twice, and d is a link that // points somewhere else by the second time: the two entries are two files // (e/lib and o/lib), so the first is not forgotten. diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 0b4e2b4..87b36e6 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -506,7 +506,16 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { linked := s.linkedLibraries(ctx, res, links, hardlinks) unreadLibs := make([]string, 0, len(s.unreadLibs)) for p := range s.unreadLibs { - unreadLibs = append(unreadLibs, p) + // A path the layers do not settle can be where a library written + // through a link landed: that library was read, under the name it + // was written with. + read := false + for _, a := range ctx.Aliases(p) { + read = read || a != p && s.libs.has(a) + } + if !read { + unreadLibs = append(unreadLibs, p) + } } sort.Strings(unreadLibs) if s.libs.len() == 0 && len(linked) == 0 && len(unreadLibs) == 0 { diff --git a/internal/engine/run.go b/internal/engine/run.go index d961acd..6a244c6 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -331,7 +331,8 @@ func (w *walker) sourceOptions(opts Options) source.Options { abs := w.abs(p) if w.ctx.seen[abs] { // The path comes round again in a docker export: this entry - // is the file (a flattened image never repeats a path). + // is the file (a flattened image repeats a path only for a + // layer that named it twice, where the last entry is the file). w.replaced(abs) } // A path that was a link is a file now. @@ -785,6 +786,7 @@ func ScanImage(dets []Detector, ref string, opts Options) *Target { // first entry for a path is the file. A docker export (rootfs:) is // one filesystem, where the last entry is. so.FirstWins = !strings.HasPrefix(ref, "rootfs:") + so.Replaces = image.ReplacesRecord skips, n, err := source.Tar(rc, so, w.visit) t.Skipped, t.Files = append(t.Skipped, skips...), n if err != nil { diff --git a/internal/image/flatten.go b/internal/image/flatten.go index 661746c..7f42f40 100644 --- a/internal/image/flatten.go +++ b/internal/image/flatten.go @@ -17,13 +17,15 @@ package image // hidden by an upper layer (RUN ln /a /b; RUN rm /a): the layer is read // again for it. // -// What the layers do not settle cheaply (two entries for one path in one -// layer, a hard link to a file not in its layer, a write or whiteout +// A path one layer names twice as a regular file is written twice, the +// second entry marked as the one the runtime keeps (ReplacesRecord). +// +// What the layers do not settle cheaply (two entries of other kinds for one +// path in one layer, a hard link to a file not in its layer, a whiteout // through a directory that is a symbolic link) is listed as unresolved: -// the scan treats those paths as not read. A file an upper layer wrote -// through a lower layer's link is the exception when nothing else claims -// the path it landed on: the container has that file, so it stays read -// under the name it was written with (throughLinks). +// the scan treats those paths as not read. Files written through a link +// are settled where the layers allow it: the one the runtime applied last +// stays read under the name it was written with (throughLinks). import ( "archive/tar" @@ -47,8 +49,8 @@ const ( // function returns the paths left unresolved, once the stream has ended. func flatten(img v1.Image) (io.ReadCloser, func() []string) { pr, pw := io.Pipe() - f := &flattener{fileMap: map[string]bool{}, opaqueDirs: map[string]bool{}, written: map[string]int{}, - tombs: map[string]bool{}, links: map[string]flatLink{}, unresolved: map[string]bool{}} + f := &flattener{fileMap: map[string]bool{}, opaqueDirs: map[string]bool{}, opaqueAt: map[string]int{}, written: map[string]flatWrite{}, + links: map[string]flatLink{}, unresolved: map[string]bool{}} done := make(chan struct{}) var out []string go func() { @@ -73,13 +75,33 @@ type flattener struct { tw *tar.Writer fileMap map[string]bool // path -> hides what is below it (non-directory or whiteout) opaqueDirs map[string]bool - cur int // the layer being read (0 is the lowest) - written map[string]int // non-directories written, and whiteouts: path -> layer - tombs map[string]bool // of those, the whiteouts - links map[string]flatLink // symbolic links written + opaqueAt map[string]int // the highest layer with an opaque marker in each directory + cur int // the layer being read (0 is the lowest) + seq int // the entry being read, counted through the layer + written map[string]flatWrite // non-directories written, and whiteouts + links map[string]flatLink // symbolic links written unresolved map[string]bool } +// flatWrite is where an entry that was written (or a whiteout) comes from: +// its layer and its place in the layer, which is the order the runtime +// applies entries in. +type flatWrite struct { + layer, seq int + tomb bool +} + +// later reports whether w is applied after o. +func (w flatWrite) later(o flatWrite) bool { + return w.layer > o.layer || w.layer == o.layer && w.seq > o.seq +} + +// ReplacesRecord marks, in the flattened stream, a second entry for a +// path: one layer named the path twice as a regular file, and the later +// entry is the file the runtime keeps. A reader that takes the first entry +// for a path takes this one instead. +const ReplacesRecord = "EARLYLIGHT.replaces" + // flatLink is a symbolic link written to the stream: its target and layer. type flatLink struct { to string @@ -112,9 +134,11 @@ func rootName(name string) string { func (f *flattener) layer(layer v1.Layer) error { layerOpaque := map[string]bool{} - inLayer := map[string]bool{} // names this layer has (value: a directory) - hidden := map[string]bool{} // regular files of this layer not written - here := map[string]bool{} // regular files of this layer written + inLayer := map[string]bool{} // names this layer has (value: a directory) + hidden := map[string]bool{} // regular files of this layer not written + here := map[string]bool{} // regular files of this layer written + plain := map[string]bool{} // of those, the ones named only as regular files so far + f.seq = 0 pending := map[string][]string{} // hidden file -> hard links to fill from it rc, err := layer.Uncompressed() if err != nil { @@ -145,8 +169,12 @@ func (f *flattener) layer(layer v1.Layer) error { if dir == "." { dir = "" } + f.seq++ if base == opaqueWhiteout { layerOpaque[dir] = true + if _, ok := f.opaqueAt[dir]; !ok { + f.opaqueAt[dir] = f.cur + } continue } tombstone := strings.HasPrefix(base, whiteoutPrefix) @@ -158,13 +186,30 @@ func (f *flattener) layer(layer v1.Layer) error { name = path.Join(dir, base) } isDir := h.Typeflag == tar.TypeDir && !tombstone + regular := (h.Typeflag == tar.TypeReg || h.Typeflag == tar.TypeRegA) && !tombstone //nolint:staticcheck if prev, ok := inLayer[name]; ok && !(prev && isDir) { - // Two entries for one path in one layer: the runtime keeps the - // last, this stream the first. + if regular && plain[name] { + // The path again as a regular file: the runtime keeps this + // entry. It is written too, marked as the one that replaces + // the first. + h.PAXRecords = map[string]string{ReplacesRecord: "1"} + if err := f.tw.WriteHeader(h); err != nil { + return err + } + if h.Size > 0 { + if _, err := io.CopyN(f.tw, tr, h.Size); err != nil { + return err + } + } + f.written[name] = flatWrite{layer: f.cur, seq: f.seq} + continue + } + // Two entries of other kinds for one path in one layer: the + // runtime keeps the last, this stream the first. f.unresolved[name] = true + plain[name] = false } inLayer[name] = isDir - regular := h.Typeflag == tar.TypeReg || h.Typeflag == tar.TypeRegA //nolint:staticcheck if hides, ok := f.fileMap[name]; ok && !tombstone { if !hides && !isDir { // An upper layer has a directory where this layer has a @@ -184,7 +229,7 @@ func (f *flattener) layer(layer v1.Layer) error { } f.fileMap[name] = tombstone || !isDir if tombstone { - f.written[name], f.tombs[name] = f.cur, true + f.written[name] = flatWrite{layer: f.cur, seq: f.seq, tomb: true} continue } if h.Typeflag == tar.TypeLink { @@ -193,7 +238,7 @@ func (f *flattener) layer(layer v1.Layer) error { // It names a file an upper layer hides: it keeps that file's // content, written once the layer is read again. pending[h.Linkname] = append(pending[h.Linkname], name) - f.written[name] = f.cur + f.written[name] = flatWrite{layer: f.cur, seq: f.seq} continue case !here[h.Linkname]: f.unresolved[name] = true // not a file of its own layer @@ -208,10 +253,10 @@ func (f *flattener) layer(layer v1.Layer) error { } } if regular { - here[name] = true + here[name], plain[name] = true, true } if !isDir { - f.written[name] = f.cur + f.written[name] = flatWrite{layer: f.cur, seq: f.seq} } if h.Typeflag == tar.TypeSymlink { f.links[name] = flatLink{h.Linkname, f.cur} @@ -276,79 +321,86 @@ func (f *flattener) fillLinks(layer v1.Layer, pending map[string][]string) error return nil } -// throughLinks finds the entries an upper layer wrote, or whited out, -// under a directory that is a symbolic link in the final filesystem: the -// runtime wrote through the link, to the path it names. +// throughLinks finds the entries a layer wrote, or whited out, under a +// directory that is a symbolic link in the final filesystem: the runtime +// wrote through the link, to the path it names. // -// The path it names is unresolved: a lower layer's file there was replaced -// or removed, and the stream names the new one elsewhere. The entry itself -// is unresolved too. Two cases are certain, and keep what was read: +// Each such entry is placed where it landed, by following the links one +// path component at a time as the runtime did (a chain of links, a link to +// the root, ".." in a target). Everything that landed on one path, and the +// entry that names the path itself, is then one file, and the entry the +// runtime applied last is it: a higher layer's, or a later one of the same +// layer. That entry stays read under the name it was written with; the +// others are stale and unresolved. Losing them all would lose what an image +// built with paths written as they are (lib/libx.so under a lib -> usr/lib +// link) holds. // -// - The entry is the file: a file (not a whiteout) written by a layer -// above the link's, landing on a path that no link leads on from, that -// no other such write lands on, and that no layer at or above the -// write's names directly. It stays read under the name it was written -// with; dropping it would lose what an image built with paths written -// as they are (lib/libx.so under a lib -> usr/lib link) holds. -// - A layer above every such write names the path itself: that entry is -// the file, and only the writes through the link are unresolved. +// What stays unresolved, every name and the landing path with it: +// +// - an entry that cannot be placed: a link of its own layer or a higher +// one on the way (the link may not have been there yet), a loop; +// - a landing path whose last entry through a link is a whiteout; +// - a landing path under a directory that a layer above the write +// removed, replaced or made opaque: the file is gone with it. +// +// The landing path of an entry that stays read is listed too: what the +// stream holds there, if anything, is an older file. func (f *flattener) throughLinks() { if len(f.links) == 0 { return } - type write struct { - name string - layer int - sure bool // above the link's layer, and not a whiteout + type member struct { + name string + w flatWrite } - lands := map[string][]write{} - for name, layer := range f.written { - for a := path.Dir(name); a != "." && a != "/" && a != ""; a = path.Dir(a) { - l, ok := f.links[a] - if !ok { - continue - } - to := l.to - if !path.IsAbs(to) { - to = path.Join(path.Dir(a), to) - } - at := "" - if r := rootName(to); r != "" { - at = path.Join(r, strings.TrimPrefix(name, a+"/")) + groups := map[string][]member{} + for name, w := range f.written { + if !f.underLink(name) { + continue + } + at, ok := f.land(name, w.layer) + if !ok { + f.unresolved[name] = true + if t := f.textual(name); t != "" { + f.unresolved[t] = true } - lands[at] = append(lands[at], write{name, layer, l.layer < layer && !f.tombs[name]}) - break + continue } + groups[at] = append(groups[at], member{name, w}) } - for at, ws := range lands { - // through: the one write through a link is the file. direct: a - // layer above every such write named the path itself afterwards, - // and that entry is the file. - through, direct := false, false - if at != "" && !f.linked(at) { - top := -1 - for _, w := range ws { - top = max(top, w.layer) + for at, ms := range groups { + if w, ok := f.written[at]; ok && !f.underLink(at) { + ms = append(ms, member{at, w}) + } + win := ms[0] + for _, m := range ms[1:] { + if m.w.later(win.w) { + win = m } - d, ok := f.written[at] - through = len(ws) == 1 && ws[0].sure && (!ok || d < top) - direct = ok && d > top } - if at != "" && !direct { + if win.name != at && (win.w.tomb || f.removedAbove(at, win.w.layer)) { + // Nothing certain is left of what landed here. + for _, m := range ms { + f.unresolved[m.name] = true + } f.unresolved[at] = true + continue } - if !through { - for _, w := range ws { - f.unresolved[w.name] = true + for _, m := range ms { + if m.name != win.name { + f.unresolved[m.name] = true } } + if win.name != at { + f.unresolved[at] = true + } } } -// linked reports whether name, or a directory above it, is a symbolic -// link in the stream. -func (f *flattener) linked(name string) bool { - for a := name; a != "." && a != "/" && a != ""; a = path.Dir(a) { +// underLink reports whether a directory above name is a symbolic link in +// the stream. +func (f *flattener) underLink(name string) bool { + for a := path.Dir(name); a != "." && a != "/" && a != ""; a = path.Dir(a) { if _, ok := f.links[a]; ok { return true } @@ -356,6 +408,81 @@ func (f *flattener) linked(name string) bool { return false } +// textual is where name would land by joining the first link above it with +// the rest of the name, without following anything further: the path the +// stream is told not to trust when name cannot be placed. +func (f *flattener) textual(name string) string { + for a := path.Dir(name); a != "." && a != "/" && a != ""; a = path.Dir(a) { + l, ok := f.links[a] + if !ok { + continue + } + to := l.to + if !path.IsAbs(to) { + to = path.Join(path.Dir(a), to) + } + return path.Join(rootName(to), strings.TrimPrefix(name, a+"/")) + } + return "" +} + +// land returns the path an entry named name, written by layer, landed on: +// the directories above it resolved through the stream's links, one +// component at a time. ok is false when a link on the way is not from a +// layer below (it may not have been there when the entry was written), and +// for a loop. +func (f *flattener) land(name string, layer int) (string, bool) { + rest := strings.Split(path.Dir(name), "/") + cur := "" + for hops := 0; len(rest) > 0; { + c := rest[0] + rest = rest[1:] + switch c { + case "", ".": + continue + case "..": + if cur = path.Dir(cur); cur == "." { + cur = "" + } + continue + } + next := path.Join(cur, c) + l, ok := f.links[next] + if !ok { + cur = next + continue + } + if hops++; hops > 40 || l.layer >= layer { + return "", false + } + if path.IsAbs(l.to) { + cur = "" + } + rest = append(strings.Split(l.to, "/"), rest...) + } + return path.Join(cur, path.Base(name)), true +} + +// removedAbove reports whether a layer above layer took away a directory +// above at: named it as a file, a link or a whiteout, or put an opaque +// marker in it. +func (f *flattener) removedAbove(at string, layer int) bool { + for a := path.Dir(at); ; a = path.Dir(a) { + if a == "." || a == "/" { + a = "" + } + if o, ok := f.opaqueAt[a]; ok && o > layer { + return true + } + if a == "" { + return false + } + if w, ok := f.written[a]; ok && w.layer > layer { + return true + } + } +} + func inOpaqueDir(opaqueDirs map[string]bool, file string) bool { for file != "" && file != "." { dir := path.Dir(file) diff --git a/internal/image/flatten_test.go b/internal/image/flatten_test.go index b2c7f6c..7b0a4ac 100644 --- a/internal/image/flatten_test.go +++ b/internal/image/flatten_test.go @@ -219,7 +219,10 @@ func TestFlattenUnresolved(t *testing.T) { layers [][]ent want string }{ - {"two entries in one layer", [][]ent{{f("a", "1"), f("a", "2")}}, "[/a]"}, + {"two files in one layer: both written, the second marked", [][]ent{{f("a", "1"), f("a", "2")}}, "[]"}, + {"a file then a link in one layer", [][]ent{{f("a", "1"), sl("a", "b")}}, "[/a]"}, + {"a link then a file in one layer", [][]ent{{sl("a", "b"), f("a", "1")}}, "[/a]"}, + {"a file, a whiteout and a file in one layer", [][]ent{{f("a", "1"), f(".wh.a", ""), f("a", "2")}}, "[/a]"}, {"whiteout then file", [][]ent{{f("a", "lower")}, {f(".wh.a", ""), f("a", "new")}}, "[/a]"}, {"file then whiteout", [][]ent{{f("a", "lower")}, {f("a", "new"), f(".wh.a", "")}}, "[/a]"}, {"a directory twice", [][]ent{{d("d"), d("d"), f("d/x", "1")}}, "[]"}, @@ -237,15 +240,48 @@ func TestFlattenUnresolved(t *testing.T) { "[/lib/x]"}, {"a higher layer removes the real path", [][]ent{{sl("lib", "usr/lib")}, {f("lib/x", "mid")}, {f("usr/lib/.wh.x", "")}}, "[/lib/x]"}, - // Which of the two the container has is not settled: both. - {"the same layer writes the real path too", [][]ent{{sl("lib", "usr/lib")}, {f("lib/x", "a"), f("usr/lib/x", "b")}}, - "[/lib/x /usr/lib/x]"}, - {"the link is of the same layer", [][]ent{{f("lib/x", "a"), sl("lib", "usr/lib")}}, - "[/lib/x /usr/lib/x]"}, + // Second final review: one layer writes both names. The runtime + // applies a layer's entries in order, so the later one is the file. + {"the same layer writes the real path afterwards", [][]ent{{sl("lib", "usr/lib")}, {f("lib/x", "a"), f("usr/lib/x", "b")}}, + "[/lib/x]"}, + {"the same layer writes the real path first", [][]ent{{sl("lib", "usr/lib")}, {f("usr/lib/x", "b"), f("lib/x", "a")}}, + "[/usr/lib/x]"}, + // Two links to one directory: the higher layer's write is the file. {"two links to one directory", [][]ent{{sl("a", "c"), sl("b", "c")}, {f("a/x", "1")}, {f("b/x", "2")}}, - "[/a/x /b/x /c/x]"}, + "[/a/x /c/x]"}, + {"two links to one directory, the lower link written last", [][]ent{{sl("a", "c"), sl("b", "c")}, {f("b/x", "2")}, {f("a/x", "1")}}, + "[/b/x /c/x]"}, + // The landing path is found by following the links as the runtime + // did: a chain, a link to the root, ".." in a target (after the + // link before it, not instead of it). {"a link to a link", [][]ent{{sl("a", "b"), sl("b", "c")}, {f("a/x", "1")}}, + "[/c/x]"}, + {"a usr-merge link to a link elsewhere", [][]ent{{sl("lib", "usr/lib"), sl("usr/lib", "../opt/real"), f("opt/real/x", "old")}, {f("lib/x", "new")}}, + "[/opt/real/x]"}, + {"a link to the root", [][]ent{{sl("r", "/"), f("usr/lib/x", "old")}, {f("r/usr/lib/x", "new")}}, + "[/usr/lib/x]"}, + {"a link to .", [][]ent{{sl("r", "."), f("x", "old")}, {f("r/x", "new")}}, + "[/x]"}, + {".. across a link", [][]ent{{sl("usr/lib", "/opt/real"), sl("lib", "usr/lib/../lib64"), f("usr/lib64/x", "other")}, {f("lib/x", "new")}}, + "[/opt/lib64/x]"}, + {"a loop", [][]ent{{sl("a", "b"), sl("b", "a")}, {f("a/x", "1")}}, + "[/a/x /b/x]"}, + // A link that may not have been there when the entry was written. + {"the link is of the same layer", [][]ent{{f("lib/x", "a"), sl("lib", "usr/lib")}}, + "[/lib/x /usr/lib/x]"}, + {"a link on the way is of a higher layer", [][]ent{{sl("a", "b")}, {f("a/x", "1")}, {sl("b", "c")}}, "[/a/x /b/x]"}, + // A layer above the write took away the directory it landed in: + // the file is gone with it (emudhra cleared a bundle on a certifi + // that was no longer there). + {"the landing directory whited out above", [][]ent{{d("opt"), d("opt/certifi"), sl("sp/certifi", "/opt/certifi")}, {f("sp/certifi/cacert.pem", "x")}, {f("opt/.wh.certifi", "")}}, + "[/opt/certifi/cacert.pem /sp/certifi/cacert.pem]"}, + {"the landing directory made opaque above", [][]ent{{d("opt"), d("opt/certifi"), sl("sp/certifi", "/opt/certifi")}, {f("sp/certifi/cacert.pem", "x")}, {f("opt/certifi/.wh..wh..opq", "")}}, + "[/opt/certifi/cacert.pem /sp/certifi/cacert.pem]"}, + {"the landing directory replaced by a file above", [][]ent{{d("opt"), d("opt/certifi"), sl("sp/certifi", "/opt/certifi")}, {f("sp/certifi/cacert.pem", "x")}, {f("opt/certifi", "now a file")}}, + "[/opt/certifi/cacert.pem /sp/certifi/cacert.pem]"}, + {"the landing directory whited out below the write", [][]ent{{d("opt"), d("opt/certifi"), sl("sp/certifi", "/opt/certifi")}, {f("opt/.wh.certifi", "")}, {d("opt/certifi"), f("sp/certifi/cacert.pem", "x")}}, + "[/opt/certifi/cacert.pem]"}, {"a whiteout through a symlinked directory", [][]ent{{sl("etc/ssh", "/opt/ssh"), f("opt/ssh/sshd_config", "old")}, {f("etc/ssh/.wh.sshd_config", "")}}, "[/etc/ssh/sshd_config /opt/ssh/sshd_config]"}, } { @@ -338,10 +374,14 @@ func FuzzFlatten(fz *testing.F) { t.Fatalf("layers %v:\nflatten %s\nExtract %s", layers, a, b) } } + // A name is written once, or again only as the regular file one + // layer named twice. got, _ := flat(t, wild...) for name, v := range got { - if len(v) != 1 { - t.Fatalf("%s written %d times: %v (layers %v)", name, len(v), v, wild) + for _, e := range v { + if len(v) != 1 && !strings.HasPrefix(e, "f:") { + t.Fatalf("%s written %d times: %v (layers %v)", name, len(v), v, wild) + } } } }) @@ -355,3 +395,31 @@ func dump(m map[string][]string) string { sort.Strings(out) return strings.Join(out, " ") } + +// Second final review: a path one layer names twice as a regular file is +// in the stream twice, in the layer's order, and the second entry carries +// the record that tells the reader it replaces the first. A lower layer's +// entry for the path stays hidden. +func TestFlattenFileTwiceInOneLayer(t *testing.T) { + rc, unresolved := flatten(imageOf(t, []ent{f("a", "lower")}, []ent{f("a", "1"), f("b", "x"), f("a", "2"), f("a", "3")})) + defer rc.Close() + var got []string + tr := tar.NewReader(rc) + for { + h, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(tr) + got = append(got, fmt.Sprintf("%s=%s%s", h.Name, b, map[bool]string{true: "*"}[h.PAXRecords[ReplacesRecord] != ""])) + } + if want := "[a=1 b=x a=2* a=3*]"; fmt.Sprint(got) != want { + t.Errorf("stream %v, want %s", got, want) + } + if u := unresolved(); len(u) != 0 { + t.Errorf("unresolved %v", u) + } +} diff --git a/internal/source/source.go b/internal/source/source.go index 5667e8e..53452e4 100644 --- a/internal/source/source.go +++ b/internal/source/source.go @@ -67,6 +67,11 @@ type Options struct { // the first entry for a path is the file and later ones are ignored. // Otherwise (a docker export) the last entry is the file. FirstWins bool + // Replaces (Tar, with FirstWins) names a PAX record that marks a later + // entry for a path as the file after all: the layer named the path + // twice, and the runtime keeps the last. Such an entry is read as a + // docker export's repeat is. + Replaces string // Other (Tar) receives each entry that is not a regular file (a // directory, symbolic link or hard link), before Symlink or Hardlink: // a path that was a file earlier in the stream is one no longer. @@ -296,7 +301,7 @@ func Tar(r io.Reader, opts Options, visit Visitor) ([]Skip, int, error) { continue } if opts.FirstWins { - if met[abs] { + if met[abs] && (opts.Replaces == "" || h.PAXRecords[opts.Replaces] == "") { continue } met[abs] = true From f914c977feb11910694365c5fe8add6653285c33 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 14:27:32 +0000 Subject: [PATCH 116/119] java4shell: Jib's base image wherever the from block has it, BP_JVM_VERSION by line, Zulu's own numbers Second final review: source-tree forms that passed in silence, or were read from a comment. - Jib. The from block was read with one expression that stopped at the first "}" and wanted "image =" first: from { platforms { ... } image = "eclipse-temurin:21.0.13_9-jre" } and from { auth { ... } image = ... } gave nothing, as did ..., the call forms image "x" and image("x"), and ${base.image} with the property in the same pom. A commented "image =" line above the real one was the image that was judged. The block is now matched by its braces (the element by its closing tag), nested blocks are left out, and comments are blanked first. A from block whose image this scan cannot read (a variable, a property set elsewhere, none) is not checked. - BP_JVM_VERSION = 21, 21.0 or 21.* gave nothing: only a line without a fix or a three-number version was judged. It is the newest BellSoft Liberica release of the line at build time, a moving pin whose status is not checked, as .java-version 21 is. Lines 8 to 16 stay silent. A commented BP_JVM_VERSION is not a setting, and a pom's closing is no longer counted as a second, unread one (a fixed pin exited 3 over it). - Zulu. FACTS.md says Azul Zulu's own numbers start with the Java line and a line without a fix is vulnerable from that number alone. That held in .tool-versions and mise files; azul/zulu-openjdk:22.32.15, the jenv name zulu64-22.32.15 and setup-java's zulu distribution said "not a Java version" (vulnerable on 62f3d8b). They follow the rule again; a bare 22.32.15 and other vendors' tags stay not checked. On the review's 125 probes of these readers 28 differ from 8dbc868: 24 are a finding or a note where there was nothing or less, one names another line, two lose only the spurious closing-tag note, and the fixed pom pin 21.0.13.1 is clean. Co-Authored-By: Claude Fable 5.2 --- detectors/java4shell/internal/repo/refscan.go | 4 + detectors/java4shell/internal/repo/repo.go | 213 +++++++++++++++++- .../java4shell/internal/repo/second_test.go | 87 +++++++ 3 files changed, 298 insertions(+), 6 deletions(-) diff --git a/detectors/java4shell/internal/repo/refscan.go b/detectors/java4shell/internal/repo/refscan.go index 8b43698..2854d8b 100644 --- a/detectors/java4shell/internal/repo/refscan.go +++ b/detectors/java4shell/internal/repo/refscan.go @@ -207,6 +207,10 @@ func (s *scanner) judgeRef(r refs.Ref, opts Options) { if fam.GraalVM { st, why = graalTag(tv, st, why, graalDist(fam.Vendor)) } + if st == knowledge.Unknown && fam.Vendor == "Azul Zulu" && knowledge.NotJava(tv.Nums) && zuluNoFix(tv.Nums[0]) { + // Zulu's own number in the tag (22.32.15 is JDK 22). + st, why = knowledge.Vulnerable, fmt.Sprintf("the tag names Azul Zulu %s, whose first number is the Java line: Java %d received no Java4Shell fix", tv.Text, tv.Nums[0]) + } switch st { case knowledge.Unknown: s.add(Finding{Rule: RuleNotChecked, File: r.File, Line: r.Line, Level: "note", Status: StatusUnknown, Pull: img, ref: &r, diff --git a/detectors/java4shell/internal/repo/repo.go b/detectors/java4shell/internal/repo/repo.go index b92fbf1..126c70b 100644 --- a/detectors/java4shell/internal/repo/repo.go +++ b/detectors/java4shell/internal/repo/repo.go @@ -457,6 +457,12 @@ func (s *scanner) judgeVersion(rel string, line int, ga bool, verText, source, v if vendor != "" { props["vendor"] = vendor } + if knowledge.NotJava(tv.Nums) && strings.Contains(strings.ToLower(vendor), "zulu") && zuluNoFix(tv.Nums[0]) { + // Zulu's own numbers start with the Java line: a line that + // received no fix is vulnerable whatever the rest says. + s.lineToolchain(rel, line, tv.Nums[0], source+" ("+refs.CleanText(verText, 60)+", Azul Zulu)") + return + } if knowledge.NotJava(tv.Nums) && !isGraal(vendor) { s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, Reason: knowledge.NotJavaWhy(verText), Message: fmt.Sprintf("%s selects %s, which is not a Java version: not checked for the Java4Shell fix", source, verText), @@ -1031,13 +1037,29 @@ var ( // environment("BP_JVM_VERSION", "21"), environment["BP_JVM_VERSION"] = "21" // and project.toml's name = "BP_JVM_VERSION" with value = "21" after it. bpJVM = regexp.MustCompile(`BP_JVM_VERSION["']?\s*\]?\s*(?:[:=,]|to\b|>|value\s*=)\s*["']?(\d{1,2}(?:\.\d+)*)`) - // jibFrom reads a Jib base image across lines: from { image = "..." }, - // jib.from.image = "...", ..., . - jibFrom = regexp.MustCompile(`(?:\bfrom\s*\{[^}]*?\bimage\s*=\s*|jib\.from\.image\s*=\s*|\s*\s*|\s*)["']?([A-Za-z0-9][\w./:@-]*)`) + // jibFrom reads a Jib base image written in one piece: jib.from.image = + // "..." and . The from { } block and element are + // read by jibBlocks. + jibFrom = regexp.MustCompile(`(?:jib\.from\.image\s*=\s*|\s*)["']?([A-Za-z0-9][\w./:@-]*)`) + // jibBlock opens Jib's from block; jibImage is the image set directly + // in it: image = "x", image "x", image("x"). + jibBlock = regexp.MustCompile(`\bfrom\s*\{`) + jibImage = regexp.MustCompile(`\bimage\s*(?:=\s*|\(\s*|\s)["']([^"'\s]+)["']`) + jibElement = regexp.MustCompile(`(?s)(.*?)`) + jibTag = regexp.MustCompile(`\s*([^<\s]*)\s*`) + pomRef = regexp.MustCompile(`^\$\{([\w.-]+)\}$`) mavenToolchain = regexp.MustCompile(`\s*\[?(\d{1,2})(?:,\))?\s*`) enforcerJava = regexp.MustCompile(`(?s)\s*\s*([^<]{1,60})`) ) +// zuluNoFix reports whether the first number of one of Azul Zulu's own +// version numbers (22.32.15 is JDK 22) names a Java line that received no +// fix: the number alone then says vulnerable. +func zuluNoFix(feature int) bool { + l, ok := knowledge.LineOf(feature) + return feature > 17 && ok && l.Fixed == nil +} + // lineToolchain reports a toolchain or release setting that selects a Java // line with no fix. Lines with a fix are not reported: the toolchain picks // whichever release of that line is installed. @@ -1063,10 +1085,74 @@ func (s *scanner) gradle(rel, text string) { s.settings(rel, text) } +// uncomment blanks out a build file's comments, keeping every offset and +// line: // and /* */ in Gradle files, in XML, # in TOML and +// properties files. What a comment says is not a setting. +func uncomment(rel, text string) string { + b := []byte(text) + blank := func(from, to int) { + for k := from; k < to && k < len(b); k++ { + if b[k] != '\n' { + b[k] = ' ' + } + } + } + base := strings.ToLower(path.Base(rel)) + switch { + case strings.HasSuffix(base, ".xml"): + for off := 0; ; { + i := strings.Index(text[off:], "") + if end < 0 { + blank(off+i, len(b)) + break + } + blank(off+i, off+i+end+3) + off += i + end + 3 + } + default: + hash := strings.HasSuffix(base, ".toml") || strings.HasSuffix(base, ".properties") || strings.HasSuffix(base, ".yaml") || strings.HasSuffix(base, ".yml") + var q byte + for i := 0; i < len(text); i++ { + c := text[i] + switch { + case q != 0: + if c == '\\' { + i++ + } else if c == q || c == '\n' { + q = 0 + } + case c == '"' || c == '\'': + q = c + case hash && c == '#', !hash && c == '/' && i+1 < len(text) && text[i+1] == '/': + end := strings.IndexByte(text[i:], '\n') + if end < 0 { + end = len(text) - i + } + blank(i, i+end) + i += end - 1 + case !hash && c == '/' && i+1 < len(text) && text[i+1] == '*': + end := strings.Index(text[i+2:], "*/") + if end < 0 { + blank(i, len(b)) + return string(b) + } + blank(i, i+end+4) + i += end + 3 + } + } + } + return string(b) +} + // settings reads what a build file sets across lines: the buildpack's -// BP_JVM_VERSION and a Jib base image. A BP_JVM_VERSION written in a form -// that is not read is not checked. +// BP_JVM_VERSION and a Jib base image, never from a comment. A +// BP_JVM_VERSION written in a form that is not read is not checked. func (s *scanner) settings(rel, text string) { + text = uncomment(rel, text) lineOf := func(off int) (int, int) { return strings.Count(text[:off], "\n") + 1, off - (strings.LastIndex(text[:off], "\n") + 1) } @@ -1081,7 +1167,8 @@ func (s *scanner) settings(rel, text string) { if i < 0 { break } - if at := off + i; !read[at] { + // closes the element that set it. + if at := off + i; !read[at] && !(at >= 2 && text[at-2:at] == " +// element (Maven) wherever it stands in it: after platforms { }, auth { } +// or their elements, as image = "x", image "x" or image("x"), or as a +// property of the same pom. A block whose image this scan cannot read (a +// variable, a property set elsewhere, none: Jib then picks a base image of +// its own) is not checked. +func (s *scanner) jibBlocks(rel, text string, lineOf func(int) (int, int)) { + notRead := func(off int, what string) { + line, _ := lineOf(off) + s.add(Finding{Rule: RuleNotChecked, File: rel, Line: line, Level: "note", Status: StatusUnknown, + Reason: "Jib's base image is " + what + ": only the image that is built on can show which Java release it holds", + Message: "Jib's from block names no base image this scan can read: not checked for the Java4Shell fix", + Fix: "Check the base image Jib builds on: 17.0.21.1, 21.0.13.1, 25.0.5.1 or 27.0.1.1 and later of the same update have the fix.", + Props: map[string]string{"source": "jib"}}) + } + if strings.HasSuffix(strings.ToLower(rel), ".xml") { + for n, m := range jibElement.FindAllStringSubmatchIndex(text, 64) { + body := text[m[2]:m[3]] + im := jibTag.FindStringSubmatchIndex(body) + if im == nil { + if n < 64 && !strings.Contains(body, "<") { + continue // text: another plugin's element + } + notRead(m[0], "not set in the from element (Jib picks one by the project's Java version)") + continue + } + img, at := body[im[2]:im[3]], m[2]+im[2] + if ref := pomRef.FindStringSubmatch(img); ref != nil { + p := regexp.MustCompile(`<` + regexp.QuoteMeta(ref[1]) + `>\s*([^<\s]+)\s*`).FindStringSubmatchIndex(text) + if p == nil { + notRead(at, "the property "+refs.CleanText(ref[1], 60)+", which this file does not set") + continue + } + img, at = text[p[2]:p[3]], p[2] + line, col := lineOf(at) + first, _ := lineOf(m[2] + im[2]) + // Reported where the from element uses it; fix edits the + // property's own line. + before := len(s.findings) + s.jibRef(rel, line, col, img) + for k := before; k < len(s.findings); k++ { + s.findings[k].Line = first + } + continue + } + if img == "" || strings.Contains(img, "$") { + notRead(at, "written with a value this file does not give") + continue + } + line, col := lineOf(at) + s.jibRef(rel, line, col, img) + } + return + } + for _, m := range jibBlock.FindAllStringIndex(text, 64) { + // The block's own text: what nested blocks hold is blanked out. + depth, end := 1, -1 + own := []byte(text[m[1]:]) + var q byte + for i := 0; i < len(own) && end < 0; i++ { + c := own[i] + switch { + case q != 0: + if c == '\\' { + if depth > 1 { + own[i] = ' ' + } + i++ + } else if c == q || c == '\n' { + q = 0 + } + case c == '"' || c == '\'': + q = c + case c == '{': + depth++ + case c == '}': + if depth--; depth == 0 { + end = i + } + } + if depth > 1 && i < len(own) && own[i] != '\n' { + own[i] = ' ' + } + } + if end < 0 { + continue // not a block that closes: not Jib's + } + body := string(own[:end]) + im := jibImage.FindStringSubmatchIndex(body) + switch { + case im != nil && !strings.Contains(body[im[2]:im[3]], "$"): + line, col := lineOf(m[1] + im[2]) + s.jibRef(rel, line, col, body[im[2]:im[3]]) + case regexp.MustCompile(`\bimage\b`).MatchString(body): + notRead(m[0], "set from a value this file does not give") + case jibInFile(text[:m[0]]): + notRead(m[0], "not set in the from block (Jib picks one by the project's Java version)") + } + } +} + +// jibInFile reports whether the text before a from block opens Jib's +// configuration: a from { } elsewhere (a copy spec, a Docker task) is not +// Jib's. +func jibInFile(before string) bool { + i := strings.LastIndex(before, "jib") + return i >= 0 && strings.Count(before[i:], "{") > strings.Count(before[i:], "}") } func (s *scanner) maven(rel, text string) { @@ -1158,7 +1355,11 @@ func (s *scanner) buildpack(rel string, line int, ver string) { } if strings.Count(ver, ".") >= 2 { s.judgeVersion(rel, line, false, ver, "BP_JVM_VERSION (Cloud Native Buildpacks)", "") + return } + // 21, 21.0, 21.*: the newest release of the line at build time, of + // BellSoft Liberica, whose fixed releases are not known here. + s.movingPin(rel, line, n, "liberica", ver, "BP_JVM_VERSION (Cloud Native Buildpacks)") } // jibRef judges a Jib base image like an image reference. diff --git a/detectors/java4shell/internal/repo/second_test.go b/detectors/java4shell/internal/repo/second_test.go index 2e47cf1..744f1d5 100644 --- a/detectors/java4shell/internal/repo/second_test.go +++ b/detectors/java4shell/internal/repo/second_test.go @@ -2,6 +2,7 @@ package repo import ( "context" + "fmt" "strings" "testing" ) @@ -74,3 +75,89 @@ func scanTree(t *testing.T, files map[string]string) Result { } return res } + +// Second final review: Jib's base image wherever it stands in the from +// block, and never from a comment. A from block whose image this scan +// cannot read is not checked. +func TestJibFromBlock(t *testing.T) { + const vuln, fixed = "eclipse-temurin:21.0.13_9-jre", "eclipse-temurin:21.0.13.1_2-jre" + for name, c := range map[string]struct{ file, body, want string }{ + "image first": {"build.gradle", "jib {\n from {\n image = \"" + vuln + "\"\n }\n}\n", "build.gradle:3 image-pin vulnerable"}, + "platforms first": {"build.gradle", "jib {\n from {\n platforms {\n platform {\n architecture = \"amd64\"\n os = \"linux\"\n }\n }\n image = \"" + vuln + "\"\n }\n}\n", "build.gradle:9 image-pin vulnerable"}, + "auth first": {"build.gradle", "jib {\n from {\n auth {\n username = \"u\"\n }\n image = \"" + vuln + "\"\n }\n}\n", "build.gradle:6 image-pin vulnerable"}, + "a commented fixed image first": {"build.gradle", "jib {\n from {\n // image = \"" + fixed + "\"\n image = \"" + vuln + "\"\n }\n}\n", "build.gradle:4 image-pin vulnerable"}, + "a block comment first": {"build.gradle", "jib {\n from {\n /* image = \"" + fixed + "\"\n */\n image = \"" + vuln + "\"\n }\n}\n", "build.gradle:5 image-pin vulnerable"}, + "only a commented image": {"build.gradle", "jib {\n from {\n // image = \"" + vuln + "\"\n }\n}\n", "build.gradle:2 not-checked unknown"}, + "the call form": {"build.gradle", "jib {\n from {\n image \"" + vuln + "\"\n }\n}\n", "build.gradle:3 image-pin vulnerable"}, + "Kotlin, with parentheses": {"build.gradle.kts", "jib {\n from {\n image(\"" + vuln + "\")\n }\n}\n", "build.gradle.kts:3 image-pin vulnerable"}, + "an image from a variable": {"build.gradle", "jib {\n from {\n image = baseImage\n }\n}\n", "build.gradle:2 not-checked unknown"}, + "platforms only": {"build.gradle", "jib {\n from {\n platforms {\n platform {\n os = \"linux\"\n }\n }\n }\n}\n", "build.gradle:2 not-checked unknown"}, + "the to block's image is not it": {"build.gradle", "jib {\n from {\n image = \"" + fixed + "\"\n }\n to {\n image = \"registry.example.com/app:" + "21.0.13_9-jre\"\n }\n}\n", ""}, + "a URL in a string is no comment": {"build.gradle", "jib {\n from {\n auth { helper = \"https://x\" }\n image = \"" + vuln + "\"\n }\n}\n", "build.gradle:4 image-pin vulnerable"}, + "pom, image first": {"pom.xml", "\n\n" + vuln + "\n\n\n", "pom.xml:3 image-pin vulnerable"}, + "pom, platforms first": {"pom.xml", "\n\namd64linux\n" + vuln + "\n\n\n", "pom.xml:4 image-pin vulnerable"}, + "pom, auth first": {"pom.xml", "\n\nu\n" + vuln + "\n\n\n", "pom.xml:4 image-pin vulnerable"}, + "pom, a commented fixed image": {"pom.xml", "\n\n\n" + vuln + "\n\n\n", "pom.xml:4 image-pin vulnerable"}, + "pom, a property of the file": {"pom.xml", "\n\n" + vuln + "\n\n\n${base.image}\n\n\n", "pom.xml:6 image-pin vulnerable"}, + "pom, a property from elsewhere": {"pom.xml", "\n\n${base.image}\n\n\n", "pom.xml:3 not-checked unknown"}, + "pom, a fixed image": {"pom.xml", "\n\n" + fixed + "\n\n\n", ""}, + } { + if g := strings.Join(got(t, tree(t, map[string]string{c.file: c.body})), ", "); g != c.want { + t.Errorf("%s: [%s], want [%s]", name, g, c.want) + } + } +} + +// BP_JVM_VERSION with a line and no update installs the newest BellSoft +// Liberica release of the line when the image is built: a moving pin, +// whose status FACTS.md gives as not checked. It was passed in silence. +// The closing tag of a pom property is not a second, unread setting, and a +// commented setting is not one. +func TestBuildpackShortVersion(t *testing.T) { + const notChecked, noFix = "not-checked unknown", "java-line vulnerable" + for name, c := range map[string]struct{ file, body, want string }{ + "gradle 21": {"build.gradle", "bootBuildImage {\n environment = [\"BP_JVM_VERSION\": \"21\"]\n}\n", "build.gradle:2 " + notChecked}, + "gradle 17": {"build.gradle", "bootBuildImage {\n environment = [\"BP_JVM_VERSION\": \"17\"]\n}\n", "build.gradle:2 " + notChecked}, + "gradle 21.*": {"build.gradle", "bootBuildImage {\n environment = [\"BP_JVM_VERSION\": \"21.*\"]\n}\n", "build.gradle:2 " + notChecked}, + "gradle 21.0": {"build.gradle", "bootBuildImage {\n environment = [\"BP_JVM_VERSION\": \"21.0\"]\n}\n", "build.gradle:2 " + notChecked}, + "gradle 11": {"build.gradle", "bootBuildImage {\n environment = [\"BP_JVM_VERSION\": \"11\"]\n}\n", ""}, + "gradle 22": {"build.gradle", "bootBuildImage {\n environment = [\"BP_JVM_VERSION\": \"22\"]\n}\n", "build.gradle:2 " + noFix}, + "project.toml 21": {"project.toml", "[[build.env]]\nname = \"BP_JVM_VERSION\"\nvalue = \"21\"\n", "project.toml:2 " + notChecked}, + "pom 21": {"pom.xml", "21\n", "pom.xml:1 " + notChecked}, + "pom 22": {"pom.xml", "22\n", "pom.xml:1 " + noFix}, + "pom 21.0.13": {"pom.xml", "21.0.13\n", "pom.xml:1 java-pin vulnerable"}, + "pom 21.0.13.1": {"pom.xml", "21.0.13.1\n", ""}, + "a commented setting": {"build.gradle", "bootBuildImage {\n // environment = [\"BP_JVM_VERSION\": \"21.0.13\"]\n environment = [\"BP_JVM_VERSION\": \"21.0.13.1\"]\n}\n", ""}, + "a commented fixed pin": {"build.gradle", "bootBuildImage {\n // environment = [\"BP_JVM_VERSION\": \"21.0.13.1\"]\n environment = [\"BP_JVM_VERSION\": \"21.0.13\"]\n}\n", "build.gradle:3 java-pin vulnerable"}, + } { + if g := strings.Join(got(t, tree(t, map[string]string{c.file: c.body})), ", "); g != c.want { + t.Errorf("%s: [%s], want [%s]", name, g, c.want) + } + } +} + +// FACTS.md, "Version-manager names in vendors' own numbers": Azul Zulu's +// own numbers start with the Java line, and a line that received no fix is +// vulnerable from that number alone. That held for .tool-versions and +// mise; an image tag, a jenv name and setup-java's zulu distribution said +// "not a Java version" (they were vulnerable before the rule that X.Y with +// Y not 0 is no Java version). +func TestZuluOwnNumbers(t *testing.T) { + const sj = "on: push\njobs:\n b:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/setup-java@v4\n with:\n distribution: %s\n java-version: %s\n" + for name, c := range map[string]struct{ file, body, want string }{ + "image tag, 22": {"Dockerfile", "FROM azul/zulu-openjdk:22.32.15\n", "Dockerfile:1 image-pin vulnerable"}, + "image tag, alpine 20": {"Dockerfile", "FROM azul/zulu-openjdk-alpine:20.32.11\n", "Dockerfile:1 image-pin vulnerable"}, + "image tag, 21: a fixed line": {"Dockerfile", "FROM azul/zulu-openjdk:21.38.21\n", "Dockerfile:1 not-checked unknown"}, + "image tag of another vendor": {"Dockerfile", "FROM eclipse-temurin:22.32.15\n", "Dockerfile:1 not-checked unknown"}, + "jenv name": {".java-version", "zulu64-22.32.15\n", ".java-version:1 java-line vulnerable"}, + "jenv name, a fixed line": {".java-version", "zulu64-21.38.21\n", ".java-version:1 not-checked unknown"}, + "a bare number": {".java-version", "22.32.15\n", ".java-version:1 not-checked unknown"}, + "setup-java zulu": {".github/workflows/ci.yml", fmt.Sprintf(sj, "zulu", "22.32.15"), ".github/workflows/ci.yml:9 java-line vulnerable"}, + "setup-java temurin": {".github/workflows/ci.yml", fmt.Sprintf(sj, "temurin", "22.32.15"), ".github/workflows/ci.yml:9 not-checked unknown"}, + ".tool-versions, as before": {".tool-versions", "java zulu-22.32.15\n", ".tool-versions:1 java-line vulnerable"}, + } { + if g := strings.Join(got(t, tree(t, map[string]string{c.file: c.body})), ", "); g != c.want { + t.Errorf("%s: [%s], want [%s]", name, g, c.want) + } + } +} From 74bac0e10361730eea0a60fda73692caae60c20e Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 14:31:03 +0000 Subject: [PATCH 117/119] java4shell: the large-Dockerfile test does not bound allocations under the race detector go test -race, which the release workflow runs, allocates several times more in the same scan (985 MiB against under 160 MiB), so the bound on a 4 MiB Dockerfile failed there. The finding and the skip are still asserted under -race; the bound is checked in a plain run. Co-Authored-By: Claude Fable 5.2 --- detectors/java4shell/internal/repo/dockerfile_fix_test.go | 2 +- detectors/java4shell/internal/repo/race_off_test.go | 5 +++++ detectors/java4shell/internal/repo/race_on_test.go | 7 +++++++ 3 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 detectors/java4shell/internal/repo/race_off_test.go create mode 100644 detectors/java4shell/internal/repo/race_on_test.go diff --git a/detectors/java4shell/internal/repo/dockerfile_fix_test.go b/detectors/java4shell/internal/repo/dockerfile_fix_test.go index f56ecc1..5f727cd 100644 --- a/detectors/java4shell/internal/repo/dockerfile_fix_test.go +++ b/detectors/java4shell/internal/repo/dockerfile_fix_test.go @@ -61,7 +61,7 @@ func TestLargeDockerfileMemory(t *testing.T) { if want := "Dockerfile:2 os-package vulnerable, skip Dockerfile:0"; g != want { t.Errorf("[%s], want [%s]", g, want) } - if mb := (after.TotalAlloc - before.TotalAlloc) >> 20; mb > 160 { + if mb := (after.TotalAlloc - before.TotalAlloc) >> 20; mb > 160 && !raceDetector { t.Errorf("scanning a %d MiB Dockerfile allocated %d MiB", b.Len()>>20, mb) } } diff --git a/detectors/java4shell/internal/repo/race_off_test.go b/detectors/java4shell/internal/repo/race_off_test.go new file mode 100644 index 0000000..f501e9d --- /dev/null +++ b/detectors/java4shell/internal/repo/race_off_test.go @@ -0,0 +1,5 @@ +//go:build !race + +package repo + +const raceDetector = false diff --git a/detectors/java4shell/internal/repo/race_on_test.go b/detectors/java4shell/internal/repo/race_on_test.go new file mode 100644 index 0000000..d73c313 --- /dev/null +++ b/detectors/java4shell/internal/repo/race_on_test.go @@ -0,0 +1,7 @@ +//go:build race + +package repo + +// raceDetector is true when the tests run under the race detector, which +// changes how much a run allocates (sync.Pool gives nothing back). +const raceDetector = true From 0196e2b0e0b942f51713fd108244f7d54fb94671 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 18:36:32 +0000 Subject: [PATCH 118/119] README: a VM library that was not read or cannot be judged makes the runtime unknown, as FACTS.md says 18539ac changed the rule and FACTS.md; the README row still said only a linked VM library makes a runtime unknown. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fe91db2..900b6b4 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ One engine for DefectDojo's emerging-vulnerability scanners. Each new vulnerabil | `php2shell` | PHP runtimes vulnerable to CVE-2026-109618 and CVE-2026-109619 ("PHP2Shell"), fixed in PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12 ([GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w), [GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp)). A packaged PHP is judged by its vendor's backport data, never by the version it reports. Also checks the images a source tree builds on and deploys, and can rewrite them to fixed images | `fs`, `image`, `repo`, `fix` | | `brotli` | Brotli decoders vulnerable to CVE-2026-111497 ("Node2Shell", "Broccoli2Shell"), Brotli 1.0.3 through 1.2.0, fixed in 1.0.10, 1.1.1 and 1.2.1 ([GHSA-9v8h-qqgm-4m35](https://github.com/advisories/GHSA-9v8h-qqgm-4m35)): system `libbrotlidec` and every copy bundled into other software (Node.js, .NET, Bun, Electron, Envoy and Istio, Python wheels such as Pillow, pyarrow, duckdb, pycurl and PyMuPDF, brotli4j, and more), on Linux, Windows and macOS. A decoder is judged first by the error code the fix added, so vendor backports are recognised without distribution data; a build that strips it by its own version stamp or by its code, which returns that error code only once fixed. In a source tree it finds the Node.js, .NET and Bun releases and the bundling packages a project pins, and `fix` moves each to the fixed release | `fs`, `image`, `repo`, `fix` | | `sshole` | \*sshole, the OpenSSH password authentication bypass on musl libc fixed in OpenSSH 10.6p2 and in Alpine's openssh packages of November 5, 2026 ([release notes](https://www.openssh.org/releasenotes.html#10.6p2), [writeup](https://sshhole.com)). On musl, sshd from 7.3p1 to 10.6p1 compares an account's password field of `*` with the `*` that crypt returns when it fails, so a crafted password logs in to that account. It judges each installed sshd by its C library, its release and the apk database (Alpine backports keep the release number), then checks what the target's `sshd_config` (Include, Match, PasswordAuthentication, AuthenticationMethods, PermitRootLogin, AllowUsers and the rest) and account files make reachable, and reports the accounts. In an image it also reads the command (`sshd -o` and `-f`) and the startup scripts it runs (entrypoints, s6, cont-init.d), and reports a server as exposed when a startup script turns password logins on, sets a `*` field or sets passwords. OpenWrt's opkg database and its backports (23.05, 24.10, 25.12) count like Alpine's. PAM-checked builds (`UsePAM yes`) are not affected. On a live server it reads the banner and the offered methods and never sends a password. In a source tree it finds Dockerfiles that install an OpenSSH server on Alpine without the fix (package lists in `ARG` and `ENV` too), Ansible apk tasks, Buildroot, OpenWrt and Yocto configurations that build one on musl, and anything that sets a password field to `*`. It also pulls the images the tree references (through the guarded transport, with the command a Compose service or Kubernetes container sets) and judges them like `scan image`. `fix` adds the fixed release floor (in the variable when the list is one), moves an end-of-life Alpine base to a tag on the nearest fixed Alpine release (`alpine:3.14` to `3.16`, `python:3.9-alpine3.14` to `3.9-alpine3.16` after checking that image) as a labelled upgrade, adds upstream commit 4353fdc43 as a patch scoped to the OpenSSH versions it applies to (Buildroot `BR2_GLOBAL_PATCH_DIR`, a version-specific Yocto bbappend), sets Ansible tasks to `state: latest`, and changes `*` to `*NP*` | `fs`, `image`, `host`, `repo`, `fix` | -| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64, fixed in OpenJDK 17.0.21.1, 21.0.13.1 and 25.0.5.1 (tagged November 15, 2026) and 27.0.1.1 (tagged November 17) by JDK-8393212 ([commit](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b); that this change is the CVE's fix is inferred: the [OpenJDK advisory](https://openjdk.org/groups/vulnerability/advisories/2026-11-17) confirms the component (hotspot/compiler), the lines (17, 21, 25, 27) and the last affected releases (17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3) but names no JDK bug: see the [knowledge table](detectors/java4shell/FACTS.md)). CVSS 8.1 (OpenJDK and Oracle). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (going by GCC's CPU tables: Intel Xeon from Ice Lake on except the E-core Xeon 6, and the client Cannon Lake, Ice Lake, Tiger Lake and Rocket Lake, not Alder Lake or later; AMD Zen 4 and Zen 5; the detector reads the flags, not the model); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds Java runtimes by their VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others); a JDK download sitting in the target (OpenJDK21U-jre_…tar.gz and the like) is recorded by name as context, not read or unpacked. Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; each platform of a multi-arch image is judged on its own with `--platform all`), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness: when the library's version line can be read, the library decides and a different release-file version is only noted; a release file naming OpenJ9 next to HotSpot evidence makes the verdict unknown; and a release file alone does not clear a runtime. A runtime directory with several VM libraries (server, client, minimal, a Java 8 `lib/amd64/server` left by an upgrade in place) is judged by every library that states a version or carries the decoder, and the worst verdict is the runtime's; a VM library that is a link to a file with another name cannot be read under its own name, so that runtime is unknown. OpenJ9 is recognised from its own VM library (`libj9vm29.so`), or from the `libjvm.so` redirector only when a release file also names OpenJ9. Past 4096 VM libraries the scan is capped: no runtime is cleared and the target reports the cap as a problem. No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version and build (the first fixed build of each release, such as 21.0.13.1+2; pre-release builds are not judged fixed, and a self-built JDK at a build boundary is unknown). A GraalVM JDK (a `-jvmci-` version line; Oracle lists GraalVM for JDK 17 and 21 and GraalVM Enterprise 21.3 as affected) is vulnerable where its OpenJDK version is and fixed only at a published fixed GraalVM build (none yet). A Red Hat rpm build is judged by its VM library unless Red Hat's backport table, keyed on the rpm release's stream (el9_6) and upstream build, lists a fixed build and the runtime confirms it (its VM library is that exact update and build, its release file names Red Hat and the target's os-release says `ID=rhel`, so Rocky, AlmaLinux and CentOS Stream are not cleared by it); the table is empty: Red Hat had published none. OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is recorded as a mitigation on a finding that stays vulnerable (status `mitigated`, counted in the exit status): the options can be overridden where the runtime is deployed, and the runtime still needs the update; `_JAVA_OPTIONS` turning the intrinsic back on undoes it, and no mitigation is recorded when the command reaches a start script that was not read or one that turns the intrinsic back on. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context; neither clears a runtime. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft, Oracle, GraalVM and Red Hat UBI `openjdk-NN` images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | +| `java4shell` | Java4Shell (CVE-2026-114938), an out-of-bounds write in HotSpot's AVX-512 VBMI Base64 decoder on x86-64, fixed in OpenJDK 17.0.21.1, 21.0.13.1 and 25.0.5.1 (tagged November 15, 2026) and 27.0.1.1 (tagged November 17) by JDK-8393212 ([commit](https://github.com/openjdk/jdk/commit/5177a70b385c16f26ede191fdac7aaba0bed0f8b); that this change is the CVE's fix is inferred: the [OpenJDK advisory](https://openjdk.org/groups/vulnerability/advisories/2026-11-17) confirms the component (hotspot/compiler), the lines (17, 21, 25, 27) and the last affected releases (17.0.21.0.3, 21.0.13.0.3, 25.0.5.0.3, 27.0.1.0.3) but names no JDK bug: see the [knowledge table](detectors/java4shell/FACTS.md)). CVSS 8.1 (OpenJDK and Oracle). Decoding a malformed Base64 input that ends in a padded fragment of one to three characters (64 `A` then `=`) writes up to 64 bytes past the output once the decoder is compiled, on CPUs with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (going by GCC's CPU tables: Intel Xeon from Ice Lake on except the E-core Xeon 6, and the client Cannon Lake, Ice Lake, Tiger Lake and Rocket Lake, not Alder Lake or later; AMD Zen 4 and Zen 5; the detector reads the flags, not the model); [Calif](https://calif.io/java4shell/) showed pre-authentication code execution on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. The decoder came with JDK 18 and 17.0.6; OpenJDK 8, 11 and 17.0.0 to 17.0.5 do not have it (Oracle's Java 8 Performance Pack carries it and is reported vulnerable up to 8u511), and Java 18 to 20, 22 to 24 and 26 received no fix. It finds Java runtimes by their VM library (`libjvm.so`, `jvm.dll`, `libjvm.dylib`): installed JDKs and JREs, jlink images, distribution packages (apk, dpkg, and rpm by install path) and runtimes bundled in products (Atlassian, Elasticsearch, Artifactory, JetBrains IDEs and others); a JDK download sitting in the target (OpenJDK21U-jre_…tar.gz and the like) is recorded by name as context, not read or unpacked. Each is judged by what the library proves: its CPU architecture (only x86-64 is affected; each platform of a multi-arch image is judged on its own with `--platform all`), the version compiled into it, and whether it carries the decoder's stubs, which catches a vendor backport into an older line; the `release` file is a second witness: when the library's version line can be read, the library decides and a different release-file version is only noted; a release file naming OpenJ9 next to HotSpot evidence makes the verdict unknown; and a release file alone does not clear a runtime. A runtime directory with several VM libraries (server, client, minimal, a Java 8 `lib/amd64/server` left by an upgrade in place) is judged by every library that states a version or carries the decoder, and the worst verdict is the runtime's; a VM library that is a link to a file with another name cannot be read under its own name, so that runtime is unknown, and so is a runtime the other libraries would clear beside a VM library the scan met and did not read (over `--max-file-size`, unreadable, or at a path an image's layers do not settle) or one that states no version and carries no stubs. OpenJ9 is recognised from its own VM library (`libj9vm29.so`), or from the `libjvm.so` redirector only when a release file also names OpenJ9. Past 4096 VM libraries the scan is capped: no runtime is cleared and the target reports the cap as a problem. No marker in the binary separates fixed from unfixed code, so the fix itself is judged by version and build (the first fixed build of each release, such as 21.0.13.1+2; pre-release builds are not judged fixed, and a self-built JDK at a build boundary is unknown). A GraalVM JDK (a `-jvmci-` version line; Oracle lists GraalVM for JDK 17 and 21 and GraalVM Enterprise 21.3 as affected) is vulnerable where its OpenJDK version is and fixed only at a published fixed GraalVM build (none yet). A Red Hat rpm build is judged by its VM library unless Red Hat's backport table, keyed on the rpm release's stream (el9_6) and upstream build, lists a fixed build and the runtime confirms it (its VM library is that exact update and build, its release file names Red Hat and the target's os-release says `ID=rhel`, so Rocky, AlmaLinux and CentOS Stream are not cleared by it); the table is empty: Red Hat had published none. OpenJ9 (IBM Semeru) is not HotSpot and is not affected. `-XX:-UseBASE64Intrinsics` or, on x86-64 only (an ARM JVM refuses it), `-XX:UseAVX=2` or lower in the image's `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` or `_JAVA_OPTIONS`, the container's java command, `CATALINA_OPTS` or `JAVA_OPTS` passed on by catalina.sh or the start script, a product's `setenv.sh`, `jvm.options` or `.vmoptions`, or the systemd unit that starts a product, is recorded as a mitigation on a finding that stays vulnerable (status `mitigated`, counted in the exit status): the options can be overridden where the runtime is deployed, and the runtime still needs the update; `_JAVA_OPTIONS` turning the intrinsic back on undoes it, and no mitigation is recorded when the command reaches a start script that was not read or one that turns the intrinsic back on. A filesystem scan records the scanning CPU's AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 flags and any `hs_err_pid*.log` as context; neither clears a runtime. In a source tree it judges Java images by their tags (eclipse-temurin, amazoncorretto, azul/zulu-openjdk, bellsoft/liberica, sapmachine, openjdk, Microsoft, Oracle, GraalVM and Red Hat UBI `openjdk-NN` images) in Dockerfiles, Compose, Kubernetes, Helm values, CI files and Jib configuration, reads moving tags and product images (Jira, Elasticsearch, Jenkins, Tomcat...) from the registry for linux/amd64, and checks setup-java, `.java-version`, `.sdkmanrc`, `.tool-versions`, mise, Gradle and Maven toolchains, the Maven Enforcer floor, `BP_JVM_VERSION` and the OpenJDK packages a Dockerfile installs, with the mitigation a stage, Compose service or Kubernetes container sets. `fix` moves an image tag to the first published fixed tag of the same variant (`21.0.13_9-jre-alpine` to `21.0.13.1_2-jre-alpine`, or for Corretto, which republishes the update's tag, `21.0.12-al2023` to `21.0.13-al2023`) after reading it and finding the fixed runtime, and a setup-java pin to the major version when the distribution's newest release is fixed (Corretto, SapMachine); everything else gets the exact manual step, and a product image gets the interim `ENV JAVA_TOOL_OPTIONS` line as an optional edit it does not apply | `fs`, `image`, `repo`, `fix` | The detectors ported from standalone scanners also build as standalone binaries under the names people search for: `emudhra-scan` and `php2shell-scan`. They keep their original commands, flags and exit status rules. `brotli`, `sshole` and `java4shell` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`, `--detector java4shell`). From d465d6cbeecd252600dff82bd6e020d77aa6a6e4 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 18:51:52 +0000 Subject: [PATCH 119/119] java4shell: the catalog names the CPUs as README and FACTS.md do The finding description (and so detectors.json) still said "Intel server CPUs from Ice Lake on ... AMD Zen 4 and later; common on cloud instances": that takes in the E-core Xeon 6, which has no AVX-512, and states as fact what FACTS.md marks inferred. It now gives GCC's CPU tables as README does. Co-Authored-By: Claude Opus 5.5 --- detectors/java4shell/java4shell.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/detectors/java4shell/java4shell.go b/detectors/java4shell/java4shell.go index 87b36e6..c0ef745 100644 --- a/detectors/java4shell/java4shell.go +++ b/detectors/java4shell/java4shell.go @@ -53,10 +53,10 @@ const about = " HotSpot's AVX-512 VBMI Base64 decoder (x86-64, JDK 18 and later, " characters (64 'A' then '=' is enough), so a Java program that decodes untrusted Base64 (tokens, headers," + " certificates, JSON) can have its heap corrupted once the decoder is compiled: pre-authentication remote code" + " execution was shown on default Keycloak, Jira, Confluence, Artifactory, Jenkins and PingFederate. It runs on CPUs" + - " with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (Intel server CPUs from Ice Lake on and some client CPUs, not Alder" + - " Lake or Raptor Lake; AMD Zen 4 and later; common on cloud instances). Fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1" + - " and 27.0.1.1 (by JDK-8393212, the change the public descriptions of the CVE match); Java 18 to 20, 22 to 24" + - " and 26 received no fix. Oracle GraalVM for JDK 17 and 21 and GraalVM Enterprise Edition 21.3 are affected too, with no" + + " with AVX-512F, AVX-512BW, AVX-512 VBMI and BMI2 (going by GCC's CPU tables: Intel Xeon from Ice Lake on except the" + + " E-core Xeon 6, and the client Cannon Lake, Ice Lake, Tiger Lake and Rocket Lake, not Alder Lake or later; AMD Zen 4" + + " and Zen 5). Fixed in OpenJDK 17.0.21.1, 21.0.13.1, 25.0.5.1 and 27.0.1.1 (by JDK-8393212, the change the public" + + " descriptions of the CVE match); Java 18 to 20, 22 to 24 and 26 received no fix. Oracle GraalVM for JDK 17 and 21 and GraalVM Enterprise Edition 21.3 are affected too, with no" + " fixed GraalVM build known yet. -XX:-UseBASE64Intrinsics (or, on x86-64 only, -XX:UseAVX=2) keeps the decoder from being" + " generated until the runtime is updated."