diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 15bcb44..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 @@ -33,6 +35,16 @@ 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/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 + 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/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 diff --git a/README.md b/README.md index 6f9ea5a..900b6b4 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, 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` 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 / # 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 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 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 @@ -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/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/brotli/brotli.go b/detectors/brotli/brotli.go index 433f2c0..560923f 100644 --- a/detectors/brotli/brotli.go +++ b/detectors/brotli/brotli.go @@ -78,21 +78,52 @@ 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{} } +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 +} -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. "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) { + for _, i := range s.foundIn[p] { + s.gone[i] = true + } + delete(s.foundIn, p) +} func (s *scan) Visit(f engine.File) []engine.Skip { if !archive.IsExecutable(f.Data) && !fingerprint.IsWasm(f.Data) { 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 new file mode 100644 index 0000000..b741ee5 --- /dev/null +++ b/detectors/brotli/forget_internal_test.go @@ -0,0 +1,68 @@ +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 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 { + 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. 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 := (&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") + 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/brotli/layers_internal_test.go b/detectors/brotli/layers_internal_test.go new file mode 100644 index 0000000..15fe8ac --- /dev/null +++ b/detectors/brotli/layers_internal_test.go @@ -0,0 +1,217 @@ +package brotli + +import ( + "archive/tar" + "bytes" + "io" + "os" + "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: 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) != 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. +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/detectors/emudhra/emudhra.go b/detectors/emudhra/emudhra.go index 13a6d46..8754c48 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{}, foundIn: map[string][]int{}} } // Probe checks the certificate chain a TLS server presents. @@ -92,6 +92,11 @@ type scan struct { findings []detect.Finding 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 @@ -101,10 +106,27 @@ 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. 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) + 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 { 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 @@ -114,7 +136,15 @@ func (s *scan) Visit(f engine.File) []engine.Skip { continue } s.dedupe[k] = true + // 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) } var out []engine.Skip for _, sk := range skips { @@ -124,10 +154,16 @@ 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(), + 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(), }) 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..fa9c4de --- /dev/null +++ b/detectors/emudhra/limit_test.go @@ -0,0 +1,162 @@ +package emudhra_test + +import ( + "archive/tar" + "bytes" + "encoding/json" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "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()) + } + } +} + +// 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()) + } +} + +// 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) { + 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/FACTS.md b/detectors/java4shell/FACTS.md new file mode 100644 index 0000000..439e77f --- /dev/null +++ b/detectors/java4shell/FACTS.md @@ -0,0 +1,139 @@ +# Java4Shell (CVE-2026-114938): what is known, and from where + +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 | +| --- | --- | +| 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. 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. 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 | +| 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. 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 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 | +| 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 | +| --- | --- | --- | +| 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 | 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 + +| Line | Fixed in | Source | +| --- | --- | --- | +| 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). 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 | + +## 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). **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. 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 (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 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) | +| 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 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; 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) 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** | + +## Advisory links + +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 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 + 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 + 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/context.go b/detectors/java4shell/context.go new file mode 100644 index 0000000..a0d5041 --- /dev/null +++ b/detectors/java4shell/context.go @@ -0,0 +1,87 @@ +package java4shell + +import ( + "regexp" + "runtime" + "strings" + "unicode/utf8" + + "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 = clip(string(m[1]), 61) + } + if m := frameLine.FindSubmatch(b); m != nil { + c.Frame = clip(strings.TrimSpace(string(m[1])), 300) + 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 +} + +// 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/coverage_test.go b/detectors/java4shell/coverage_test.go new file mode 100644 index 0000000..8b8ea21 --- /dev/null +++ b/detectors/java4shell/coverage_test.go @@ -0,0 +1,138 @@ +package java4shell_test + +import ( + "bytes" + "github.com/DefectDojo/earlylight/detectors/java4shell" + "os" + "path/filepath" + "strings" + "testing" + + "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" +) + +// 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) + } +} + +// 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") + } +} + +// 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) + } + } +} + +// 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/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/assess.go b/detectors/java4shell/internal/assess/assess.go new file mode 100644 index 0000000..63d7a7c --- /dev/null +++ b/detectors/java4shell/internal/assess/assess.go @@ -0,0 +1,841 @@ +// 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"` + // 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. +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 + // 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 + // 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 + // 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 + // Resolve follows symbolic links within the target. + 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{} + 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) + } + 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) + } + 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, seen[r] = append(roots, r), true + } + for r := range linked { + 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) + env := jvm.EnvMap(in.Env) + var out []Finding + for _, r := range roots { + f := Finding{Kind: KindRuntime, Path: r} + if libs := byRoot[r]; len(libs) > 0 { + 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(notRead(notFollowed(f, linked[r]), unread[r]))) + } + for _, l := range loose { + 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 +} + +// 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. +// +// 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 { + group := judge(in, env, root, libs) + f := redHat(in, group) + worst := f + var unjudged []*jvm.Library + for _, l := range libs { + 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 := 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 +// 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 { + 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) + 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 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() + named, redirector, stubs := false, false, false + for _, l := range libs { + 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 := "", "" + 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 + f.GraalVM = knowledge.IsGraalVM(lib.JREVersion) || knowledge.IsGraalVM(lib.VMVersion) || + hasRel && (rel["GRAALVM_VERSION"] != "" || knowledge.IsGraalVM(rel.Version())) + if openj9 { + f.VM = "OpenJ9" + } + what := describe(f, v, vok) + + hotspot := false + for _, l := range libs { + if l.HotSpot() { + hotspot = true + } + } + switch { + 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", + 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): + 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") + } + judgeVersion, judgeBackport := knowledge.Judge, knowledge.JudgeBackport + if f.GraalVM { + 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 + 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 { + bs, bwhy := judgeBackport(v) + f.Release = bs + if bs == knowledge.Vulnerable { + 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") + } + 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") + } + 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+" 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 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 { + 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 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") + } + 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. 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, 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 + } + st, why, known := knowledge.JudgeRedHat(f.Package.Name, f.Package.Version) + if !known || st != knowledge.Fixed { + return f + } + 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.Vendor != redHatVendor: + 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+"; 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, 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)") +} + +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 + 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") + } + 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. + // 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] && javaHomeIs(in, env, root) { + 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") + } + } + // 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 == "" || 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) { + 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") + } + } + 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 jvm.MergeUnits(in.Settings) { + 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 +} + +// 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 +} + +// 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) + } + 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 "" +} + +// 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 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 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 { + if fx := knowledge.FixedVersion(v.Feature()); fx != "" { + target = "Java " + fx + " or later of the same update" + } else if v.Feature() >= 17 { + 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 %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) + } + return fmt.Sprintf("Update this runtime to %s (%s: check your vendor).%s", target, knowledge.VendorStatus(), interim) +} diff --git a/detectors/java4shell/internal/assess/assess_test.go b/detectors/java4shell/internal/assess/assess_test.go new file mode 100644 index 0000000..31dd375 --- /dev/null +++ b/detectors/java4shell/internal/assess/assess_test.go @@ -0,0 +1,318 @@ +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}, + {"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}, + {"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{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 { + 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", "JAVA_HOME=/opt/java/openjdk"} + 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) + } + } + + // 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")) + 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) +} + +// 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) + } + // 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/internal/assess/coverage_test.go b/detectors/java4shell/internal/assess/coverage_test.go new file mode 100644 index 0000000..ce87098 --- /dev/null +++ b/detectors/java4shell/internal/assess/coverage_test.go @@ -0,0 +1,206 @@ +package assess + +import ( + "strings" + "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" +) + +// 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) + } + } +} + +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) + } + } +} + +// 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 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 + os string + noStubs bool + } + const rh, rhel = "Red Hat, Inc.", "rhel" + run := func(c rt) Finding { + l := testlib.Lib{Version: c.lib, VBMI: !c.noStubs} + 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, + OSID: c.os, + } + return one(t, in) + } + 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) + } + 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", Dist: "el9_6", EVR: "1:17.0.21.0.9-2.el9_6", Advisory: "RHSA-2026:0000"}} + 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) + } + 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 + }{ + {"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}, + } { + 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) + } + } +} + +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/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/assess/libraries_test.go b/detectors/java4shell/internal/assess/libraries_test.go new file mode 100644 index 0000000..2a65689 --- /dev/null +++ b/detectors/java4shell/internal/assess/libraries_test.go @@ -0,0 +1,215 @@ +package assess + +import ( + "strings" + "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" +) + +// 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) + } +} + +// 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) + } + } +} + +// 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/internal/assess/packages.go b/detectors/java4shell/internal/assess/packages.go new file mode 100644 index 0000000..fb7b370 --- /dev/null +++ b/detectors/java4shell/internal/assess/packages.go @@ -0,0 +1,144 @@ +package assess + +import ( + "fmt" + "path" + "regexp" + "strings" + + "github.com/DefectDojo/earlylight/detectors/java4shell/internal/knowledge" +) + +// 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 " + knowledge.AsOf() + 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 %s 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/assess/product.go b/detectors/java4shell/internal/assess/product.go new file mode 100644 index 0000000..b3db62a --- /dev/null +++ b/detectors/java4shell/internal/assess/product.go @@ -0,0 +1,96 @@ +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"}, + {"/pingfederate", "PingFederate"}, {"/pingaccess", "PingAccess"}, {"/spinnaker", "Spinnaker"}, {"/gerrit", "Gerrit"}, + {"/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 { + 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. + 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) + // 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 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 { + if strings.Contains(dir, p.part) { + return p.name, dir, true + } + } + return path.Base(dir), dir, true +} diff --git a/detectors/java4shell/internal/assess/review2_test.go b/detectors/java4shell/internal/assess/review2_test.go new file mode 100644 index 0000000..67ebcd1 --- /dev/null +++ b/detectors/java4shell/internal/assess/review2_test.go @@ -0,0 +1,114 @@ +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) + } +} + +// 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) + } +} + +// 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) + } +} + +// 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) + } +} 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/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/internal/jvm/jvm.go b/detectors/java4shell/internal/jvm/jvm.go new file mode 100644 index 0000000..aafa610 --- /dev/null +++ b/detectors/java4shell/internal/jvm/jvm.go @@ -0,0 +1,333 @@ +// 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"` + // 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"` +} + +// 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)"), 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. +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 := 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]) + } + l.VBMIStubs = bytes.Contains(b, []byte("lookup_lo_base64\x00")) && bytes.Contains(b, []byte("pack_vec_base64\x00")) + // 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. + 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 +} + +// 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 { + 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"] +} + +// 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/jvm_test.go b/detectors/java4shell/internal/jvm/jvm_test.go new file mode 100644 index 0000000..1c92d27 --- /dev/null +++ b/detectors/java4shell/internal/jvm/jvm_test.go @@ -0,0 +1,251 @@ +package jvm + +import ( + "bytes" + "strings" + "testing" + "time" + + "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.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" { + 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))) + }) +} + +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/options.go b/detectors/java4shell/internal/jvm/options.go new file mode 100644 index 0000000..f3d114b --- /dev/null +++ b/detectors/java4shell/internal/jvm/options.go @@ -0,0 +1,243 @@ +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, "" +} + +// 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") +} + +// 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" || strings.HasSuffix(w, "/bin/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/jvm/review2_test.go b/detectors/java4shell/internal/jvm/review2_test.go new file mode 100644 index 0000000..b511c6d --- /dev/null +++ b/detectors/java4shell/internal/jvm/review2_test.go @@ -0,0 +1,150 @@ +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") + } +} + +// 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") + } +} + +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() + }) +} + +// 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 || 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. +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 + } + o.ApplyWord(l.word, s.File) + } +} + +// 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})?)?:`) + 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 +// 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 = scopeOrNone(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 = scopeOrNone(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{} + } + 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 ") { + 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 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 "systemd": + s.systemdLine(line) + } + } + 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 { + return + } + 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 EnvVars { + if name == n { + s.Env[name] = val + } + } + } + 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 // "ExecStart=" resets the command + } + s.Exec = ws[0] + if opts, ok := JavaOptions(ws); ok { + for _, w := range opts { + if xxRE.MatchString(w) { + s.ExecOpts = append(s.ExecOpts, w) + } + } + } + } +} + +// 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} + +// setenvVars are the variables a setenv file's launcher passes to java, +// in the order the JVM sees them: the JVM's own JAVA_TOOL_OPTIONS and +// JDK_JAVA_OPTIONS first, then catalina.sh's command line ($JAVA_OPTS then +// $CATALINA_OPTS; Atlassian's setenv.sh puts JVM_SUPPORT_RECOMMENDED_ARGS +// into CATALINA_OPTS), then _JAVA_OPTIONS, which overrides everything. +func setenvVars(scope string) []string { + vars := []string{"JAVA_TOOL_OPTIONS", "JDK_JAVA_OPTIONS", "JAVA_OPTS"} + if strings.Contains(scope, "/atlassian/") { + vars = append(vars, "JVM_SUPPORT_RECOMMENDED_ARGS") + } + return append(vars, "CATALINA_OPTS", "_JAVA_OPTIONS") +} + +// jvmEnvVar reports the variables the JVM reads itself: a shell script +// must export them for java to see them. +func jvmEnvVar(name string) bool { + return name == "JAVA_TOOL_OPTIONS" || name == "JDK_JAVA_OPTIONS" || name == "_JAVA_OPTIONS" +} + +// readSetenv reads a start script's settings file the way the launcher +// uses it: only the variables that launcher passes to java count (the +// JVM's own variables only when exported), the last assignment wins +// ("$VAR ..." appends, unset clears), and a file that sets, unsets or +// exports one of them under a condition, in a loop, in a function or a +// { } group counts for nothing, since which value java gets cannot be +// known without running it. Heredoc text is skipped. What it does not +// model (multi-line values, helper variables, sourced files) is not +// counted, which leaves the runtime vulnerable. Batch files +// (setenv.bat) are read with "set NAME=value" and %NAME%. +func readSetenv(s *Setting, text string) { + wanted := map[string]bool{} + order := setenvVars(s.Scope) + for _, n := range order { + wanted[n] = true + } + var vals map[string]string + var ok bool + if s.WindowsOnly { + vals, ok = readBatch(text, wanted) + } else { + vals, ok = readShell(text, wanted) + } + if !ok { + return + } + for _, n := range order { + for _, w := range xxRE.FindAllString(vals[n], -1) { + s.lines = append(s.lines, optLine{0, 0, w}) + } + } +} + +func readBatch(text string, wanted map[string]bool) (map[string]string, bool) { + vals := map[string]string{} + for _, raw := range strings.Split(text, "\n") { + line := strings.TrimSpace(strings.TrimSuffix(raw, "\r")) + low := strings.ToLower(line) + if line == "" || strings.HasPrefix(low, "rem") && (len(low) == 3 || low[3] == ' ') || strings.HasPrefix(line, "::") || strings.HasPrefix(low, "@rem") { + continue + } + if strings.HasPrefix(low, "if ") || strings.HasPrefix(low, "for ") || strings.HasPrefix(low, "goto") || strings.HasPrefix(line, ":") || strings.ContainsAny(line, "()") { + for n := range wanted { + if strings.Contains(line, n) { + return nil, false + } + } + continue + } + m := batSetRE.FindStringSubmatch(line) + if m == nil || !wanted[m[1]] { + continue + } + vals[m[1]] = batVarRE.ReplaceAllStringFunc(m[2], func(v string) string { return vals[strings.Trim(v, "%")] }) + } + return vals, true +} + +var heredocRE = regexp.MustCompile(`<<(-?)\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?`) + +// shellCmd is one simple command of a line and whether it runs only +// depending on another (after && or ||, or in a pipeline). +type shellCmd struct { + text string + 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 + var q byte + start, cond := 0, false + add := func(end int, next bool) { + out = append(out, shellCmd{strings.TrimSpace(line[start:end]), cond}) + cond = next + } + for i := 0; i < len(line); i++ { + c := line[i] + switch { + case q != 0: + if c == q { + q = 0 + } else if c == '\\' && q == '"' { + i++ + } + case c == '"' || c == '\'': + q = c + case c == '\\': + i++ + case c == ';': + add(i, false) + start = i + 1 + case c == '&' || c == '|': + two := i+1 < len(line) && line[i+1] == c + add(i, true) + if two { + i++ + } + start = i + 1 + } + } + add(len(line), false) + return out +} + +func readShell(text string, wanted map[string]bool) (map[string]string, bool) { + vals := map[string]string{} + exported := map[string]bool{} + depth := 0 + heredoc, dashed := "", false +lines: + for _, raw := range strings.Split(text, "\n") { + line := strings.TrimSuffix(raw, "\r") + if heredoc != "" { + end := line + if dashed { + end = strings.TrimLeft(end, "\t") + } + if end == heredoc { + heredoc = "" + } + continue + } + line = strings.TrimSpace(stripComment(line)) + if line == "" { + continue + } + if m := heredocRE.FindStringSubmatch(line); m != nil { + heredoc, dashed = m[2], m[1] == "-" + } + for _, c := range splitCommands(line) { + words := Words(c.text) + if len(words) == 0 { + continue + } + // 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++ + 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 + } + 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 + } + 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, "=") + 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 + } + 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) + } + } + 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, "${}")] }) +} diff --git a/detectors/java4shell/internal/knowledge/coverage_test.go b/detectors/java4shell/internal/knowledge/coverage_test.go new file mode 100644 index 0000000..29172c9 --- /dev/null +++ b/detectors/java4shell/internal/knowledge/coverage_test.go @@ -0,0 +1,252 @@ +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) + } + } +} + +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, 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[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, GraalVMOracle); 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, 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, 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[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, + "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, GraalVMOracle); st != want { + t.Errorf("row 17.0.21.1+2: JudgeGraalVM(%s) = %s (%s), want %s", v, st, why, want) + } + } +} + +// 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[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, GraalVMOracle); 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) { + 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) + } + } +} + +// 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) + } + } +} + +// 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/graalvm.go b/detectors/java4shell/internal/knowledge/graalvm.go new file mode 100644 index 0000000..7d728c8 --- /dev/null +++ b/detectors/java4shell/internal/knowledge/graalvm.go @@ -0,0 +1,173 @@ +package knowledge + +import ( + "fmt" + "regexp" + "strconv" + "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 +} + +// 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" + +// 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 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: + return st, why + case Vulnerable: + return st, "GraalVM: " + why + "; " + graalVMAffected + } + // 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[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 { + 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} +) + +// 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 && 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 +// 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. 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 + // 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 && 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) + 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 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 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/knowledge.go b/detectors/java4shell/internal/knowledge/knowledge.go new file mode 100644 index 0000000..b6c9657 --- /dev/null +++ b/detectors/java4shell/internal/knowledge/knowledge.go @@ -0,0 +1,422 @@ +// 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 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" + +// 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: every "as of" +// statement (a vendor or distribution had not published a fix) is as of +// this date. +const Checked = "2026-11-18" + +// 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" +) + +// 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" } + +// 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 // a pre-release or self-built JDK: -ea, -beta, -internal, adhoc + // 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...). +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:] + } + 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 { + v.Build = b + } + // A self-built JDK ("+0-adhoc.root.jdk17u") is not a release. + if strings.Contains(r, "adhoc") { + v.EA, v.SelfBuilt = true, true + } + } + 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), 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}, 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}, 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}, 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}, FixedBuild: 4}, +} + +// 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 +) + +// maxPatch is the largest fourth version number taken as an OpenJDK patch +// 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 { + 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 && 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 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 %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) + } + l, ok := LineOf(f) + 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 { + // 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] + } + v.Nums = v.Nums[:4] + } + 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) + } + } + if l.Fixed == nil { + return Vulnerable, fmt.Sprintf("Java %s has the AVX-512 VBMI Base64 decoder without the fix: %s", ver, l.Note) + } + // 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, 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, 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 it has the fix (%s)", 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, 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) + } + if v.EA { + 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, BugRef) +} + +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..d45927f --- /dev/null +++ b/detectors/java4shell/internal/knowledge/knowledge_test.go @@ -0,0 +1,125 @@ +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}, + {"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}, + {"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, true}, + } { + 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}, + {"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}, + {"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/knowledge/redhat.go b/detectors/java4shell/internal/knowledge/redhat.go new file mode 100644 index 0000000..65a7324 --- /dev/null +++ b/detectors/java4shell/internal/knowledge/redhat.go @@ -0,0 +1,257 @@ +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 +// 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 + 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-... +} + +// 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 for %s (%s)", f.Package, f.EVR, f.Dist, f.Advisory)) + } + return "Red Hat's fixed builds: " + strings.Join(parts, ", ") +} + +var ( + // 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 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 "", "", false + } + v := rpmVersion.FindStringSubmatch(evr) + if v == nil || v[3] == "" { + return "", "", false + } + d := rhRelease.FindStringSubmatch(v[3]) + if d == nil { + return "", "", false + } + return m[1], d[1], true +} + +// 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.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 { + 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 +// [epoch:]version-release) by the backport table. known is false when the +// 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, dist, ok := RedHatPackage(name, evr) + if !ok { + return Unknown, "", false + } + fx, ok := RedHatFixFor(pkg, dist) + if !ok || !sameUpstream(evr, fx.EVR) { + 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 %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 %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 { + 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..326a5dc --- /dev/null +++ b/detectors/java4shell/internal/knowledge/redhat_test.go @@ -0,0 +1,117 @@ +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", 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_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_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 + // 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) + 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) + } + } +} + +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, len(a)%2 == 0); st == "" || why == "" { + t.Fatalf("JudgeGraalVMRelease(%q) gave no verdict or reason", a) + } + }) +} diff --git a/detectors/java4shell/internal/knowledge/review2_test.go b/detectors/java4shell/internal/knowledge/review2_test.go new file mode 100644 index 0000000..d10ff42 --- /dev/null +++ b/detectors/java4shell/internal/knowledge/review2_test.go @@ -0,0 +1,79 @@ +package knowledge + +import ( + "strings" + "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", 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. + {"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) + } + } +} + +// 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) + } + } +} + +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/coverage_test.go b/detectors/java4shell/internal/repo/coverage_test.go new file mode 100644 index 0000000..5bb9f8a --- /dev/null +++ b/detectors/java4shell/internal/repo/coverage_test.go @@ -0,0 +1,783 @@ +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 +// (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) + } +} + +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) + } + } +} + +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", + "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", + "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", 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}, + {"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", 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}, + {"Dockerfile", 3, RuleNotChecked, StatusUnknown}, + {"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) + } +} + +// 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) + } + } + } +} + +// 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) + } + } +} + +// 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) + } +} + +// 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) + } + } +} + +// 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) + } + } +} + +// 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}, + }) +} + +// 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) + } + } +} + +// 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}, + }) +} + +// 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}, + }) +} + +// 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) + } + } +} + +// 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) + } +} + +// 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) + } +} + +// 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/dockerfile_fix_test.go b/detectors/java4shell/internal/repo/dockerfile_fix_test.go new file mode 100644 index 0000000..5f727cd --- /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 && !raceDetector { + 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 </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 <= 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) + } + } +} + +// 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) + } +} + +// 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 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", "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", ""}, + } { + 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) + } + } +} + +// 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/graalvm.go b/detectors/java4shell/internal/repo/graalvm.go new file mode 100644 index 0000000..20c7e56 --- /dev/null +++ b/detectors/java4shell/internal/repo/graalvm.go @@ -0,0 +1,178 @@ +package repo + +import ( + "fmt" + "regexp" + "strings" + + "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] } + +// 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([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, dist string) (knowledge.Status, string) { + if knowledge.GraalVMOwnNumber(tv.Text) { + return knowledge.Unknown, ownNumberWhy(tv.Text) + } + 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}, dist) + return gs, "the tag names Java " + tv.Text + ": " + gwhy + } + 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 { + 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. +// 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: + 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 (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), + 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 + } + 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" + 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: gwhy, Message: msg, + Fix: graalFix(tv.Nums[0], source), Props: props}) + return + } + 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 + } + // 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 + } + before := strings.TrimRight(value[:j[0]], "+-_") + i := strings.IndexAny(before, "0123456789") + if i < 0 { + return "", 0, false + } + return strings.TrimSuffix(before[i:], "-Final"), atoi(value[j[2]:j[3]]), true +} diff --git a/detectors/java4shell/internal/repo/images.go b/detectors/java4shell/internal/repo/images.go new file mode 100644 index 0000000..0910b09 --- /dev/null +++ b/detectors/java4shell/internal/repo/images.go @@ -0,0 +1,238 @@ +package repo + +import ( + "fmt" + "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 + // 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. + 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, OpenJDKBuild: true}, + {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"}, + // 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-"}, +} + +// 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 + // 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 +// 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, OpenJDKBuild: -1} + 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.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, "-") + 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 +} + +// 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 + 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 { + 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, EA: tv.EA}) + 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", "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 { + 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..0c51c11 --- /dev/null +++ b/detectors/java4shell/internal/repo/plan.go @@ -0,0 +1,405 @@ +package repo + +import ( + "context" + "errors" + "fmt" + "os" + "path" + "path/filepath" + "regexp" + "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. 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") +} + +// 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 + 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 + } + 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 + // which release it holds, and Verify does. + cs = append(cs, cand{t, tv, true}) + } + } + 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 + } + 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 { + 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 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) + } + // 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 { + 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) + } + 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 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)) +} + +// 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 { + 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) +} + +// 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 +} + +// 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"} + +// 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 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. 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, " ") + 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 { + case current == "" || target == "": + 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/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 diff --git a/detectors/java4shell/internal/repo/redhat.go b/detectors/java4shell/internal/repo/redhat.go new file mode 100644 index 0000000..c1c7f68 --- /dev/null +++ b/detectors/java4shell/internal/repo/redhat.go @@ -0,0 +1,121 @@ +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]), 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) + 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 !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 + } + 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 +} + +// 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. +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 for %s (%s)", f.EVR, f.Dist, 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 new file mode 100644 index 0000000..2854d8b --- /dev/null +++ b/detectors/java4shell/internal/repo/refscan.go @@ -0,0 +1,359 @@ +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 { + // 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, 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) + 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 { + 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 + } + // 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} + if mit != "" { + props["mitigation"] = mit + } + if s.redHatRef(r, img, props, mit) { + return + } + 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 + } + // 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, + 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) + 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, + Reason: why, Message: fmt.Sprintf("image %s: %s", img, why), Props: props}) + return + case knowledge.Vulnerable: + default: + if pinned { + byDigest() + } + 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 != "" { + 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 = StatusMitigated + 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 + } + } + } + // 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) + } + 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..126c70b --- /dev/null +++ b/detectors/java4shell/internal/repo/repo.go @@ -0,0 +1,2683 @@ +// 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 ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io/fs" + "os" + "path" + "path/filepath" + "regexp" + "sort" + "strconv" + "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"` + 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 +) + +// 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) + 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 + } + 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 + } + 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) + case "yaml": + s.composeArgs(rel, b) + } + } + s.images(opts) + for _, u := range s.unparsed { + dup := false + for _, sk := range s.skips { + dup = dup || sk.File == u.File && sk.Line == 0 + } + if !dup { + s.skips = append(s.skips, u) + } + } + 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 == ".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")), + lower == "action.yml" || lower == "action.yaml": // a composite action's steps + return "workflow" + 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" + 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 + // unparsed are Dockerfiles the instruction parser refused. + unparsed []Skip + // 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) 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 + } + 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) { + build := deref(mapGet(m, "build")) + args := deref(mapGet(build, "args")) + if args == nil { + return + } + // 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 { + 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, v, ok := strings.Cut(a.Value, "=") + add(n, v, ok) + } + } + }) +} + +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. +// +// 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. + nums = base + if n, err := strconv.Atoi(b); err == nil && n >= 0 { + 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) + 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 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), + 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 + } + 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" + } + 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: msg, + 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}) + } else if tv.Exact || tv.EA { + // A pinned release the data does not settle (17.0.22, a later + // 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}) + } + } +} + +// preReleaseSuffix is a pre-release marker in a version name: 21-ea, +// 17.0.21.1-ea, 22-beta. +var preReleaseSuffix = regexp.MustCompile(`(?i)-(?:ea|beta|rc).*$`) + +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()) + } + 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(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, rest := m[2], l[idx[5]:] + if strings.HasPrefix(strings.ToLower(m[1]), "corretto") { + ver = CorrettoJava(ver) + } + 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 + } +} + +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", + "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) { + // 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]] + if vendor == "" { + vendor = m[2] + } + if isGraal(m[2]) { + if g, java, ok := graalNamed(m[1]); ok { + s.graalOwn(rel, i+1, g, java, m[2] == "grl", 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 + } + s.judgeVersion(rel, i+1, true, 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, 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|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). +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] { + case "graalvm", "mandrel": + if g, java, ok := graalNamed(value); ok { + s.graalOwn(rel, line, g, java, m[1] == "graalvm", value, source) + 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 + // 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 + } + ver := strings.TrimSuffix(m[2], ".") + if m[1] == "corretto" { + ver = CorrettoJava(ver) + } + 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 asdfPreRelease.MatchString(rest) { + ver += "-ea" + } + if b := anyBuildRE.FindStringSubmatch(rest); b != nil { + ver += "+" + b[1] + } + } + 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 { + if m := plusBuildRE.FindStringSubmatch(rest); m != nil { + return "+" + m[1] + } + return "" +} + +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(`(?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 +// (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 { + n := 0 + fmt.Sscanf(parts[3], "%d", &n) + if n > 3 { + return strings.Join(parts[:3], ".") + } + } + return ver +} + +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", false) + } + } +} + +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) { + 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) + } + } +} + +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} + +// 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 { + s.skips = append(s.skips, Skip{File: rel, Reason: "not valid YAML: " + refs.CleanText(err.Error(), 200)}) + 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) { + // 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 := 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} + 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 { + 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, "${{") { + 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) + 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" { + return + } + before := len(s.findings) + 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, false, judged, "actions/setup-java", dist) + if len(s.findings) == before { + s.movingSetupJava(rel, v, m, dist) + 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 && 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)) + } + } + 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) + } +} + +// 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 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), + 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, + 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" + } + return d +} + +// ---- Gradle, Maven, buildpacks + +var ( + 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 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 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. +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") + } + } + 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, 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) + } + 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 + } + // 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) { + 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 + } + } + 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 + 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) { + s.settings(rel, text) + for i, l := range lines(text) { + 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, 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. +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 ( + // installRE finds a package tool on a RUN line; installArgs decides + // whether it installs. + installRE = regexp.MustCompile(`\b(?:apt-get|aptitude|apt|apt-fast|nala|install_packages|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.:*?+~-]*))?`) + // 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). + 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`) +) + +func (s *scanner) dockerfile(rel, text string) { + // 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). 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 + 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). + stageEnv := map[string]string{} + 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() + 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 { + f.Status = StatusMitigated + f.Props["mitigation"] = how + f.Reason += "; " + how + f.Message += ", mitigated by the stage's JVM options until it is updated" + } + } + } + defer endStage() + // 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 { + 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() + closeStage() + from, stageStart, stageEnv, stageCmd = in.Line, len(s.findings), map[string]string{}, nil + 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) { + 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": + // The last ENV of each variable in the stage is what the + // 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], stageEnvAll[k] = v, v, true + } + } + case "run": + run := in.Args + if in.JSON != nil { + run = execForm(in.JSON) + } + s.packages(rel, in.Line, run, vars) + for _, body := range in.Heredocs { + s.packages(rel, in.Line, heredocCommands(body), vars) + } + } + } +} + +// 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, " ; ") +} + +// 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) { + // 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(run, 0) { + if strings.HasPrefix(arg, opaqueArg) { + opaque = append(opaque, strings.TrimPrefix(arg, opaqueArg)) + continue + } + 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. + // 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 { + 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): + 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"}) + 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"}) + 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): + // 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}) + } + 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 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) { + hits = append(hits, pkgHit{name: arg, mgr: "rpm", vendor: "distribution", unreadable: true}) + } + } + 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. +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) + rpmArg = anchored(rpmJava) + vendorArg = anchored(vendorJava) + defaultArg = anchored(defaultJava) +) + +var ( + 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, + "--installroot": true, "--releasever": true, "--dbpath": true, "--prefix": 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, "=") + // 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 + } + name = name[:i] + } + name = debArchRE.ReplaceAllString(name, "") + if pinned { + return name + "=" + ver + } + return rpmArchRE.ReplaceAllString(name, "") +} + +// unreadableArg marks a package file installArgs found but could not +// 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+)$`) + +// 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", "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 +// 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 + url := strings.Contains(w, "://") + if i := strings.IndexAny(u, "?#"); url && i >= 0 { + u = u[:i] + } + base := path.Base(u) + 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, "*?[") { + // 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 "", strings.HasSuffix(strings.ToLower(base), ".rpm") || strings.Contains(w, "/") + } + 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:" + +// 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. +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 != "" { + 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])]) { + 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 := 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 + } + if pkgValueFlags[words[i]] { + i++ + } + i++ + } + if tool == "rpm" || tool == "dpkg" || tool == "install_packages" { + // rpm -ivh file.rpm, dpkg -i file.deb: 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++ { + if strings.HasPrefix(words[j], "#") { + break // a shell comment: the rest of the line + } + 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 != "" { + out = append(out, a) + } + continue + } + } + switch { + case tool == "rpm" || tool == "dpkg": + if pkgValueFlags[w] { + j++ + } + case pkgValueFlags[w]: + j++ + case strings.HasPrefix(w, "-"), strings.Contains(w, "://"), strings.HasPrefix(w, "/"), strings.HasPrefix(w, "$"): + default: + if a := packageName(w); a != "" { + out = append(out, a) + } + } + } + } + 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(`(?:>>?|<)[/&].*$|(?:>>?|<)$`) + +// 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) { + 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, "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]) + } + } + case "eval": + if i+1 < len(words) { + return script(strings.Join(words[i+1:], " ")) + } + } + return "", false +} + +// 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) + 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 { + if v != "" { + return "=" + } + return "" +} + +func atoi(s string) int { + n := 0 + fmt.Sscanf(s, "%d", &n) + 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"} + +// 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 { + if h.ver == "" || strings.Contains(h.ver, "$") || strings.ContainsAny(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", "+") + switch { + case h.vendor == "corretto": + // 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) + } + 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.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.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}, + 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 + } + 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}, + 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 { + 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}) + return + } + props["fixed_in"] = knowledge.FixedVersion(h.feature) + } + fx := props["fixed_in"] + 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 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 + // (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, + 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() + 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: fix, Props: props}) + } + return + } + 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", + 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 + ")" + } + 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, + 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": + 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, 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" || 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) + } + s.add(Finding{Rule: RulePackage, File: rel, Line: line, Level: "warning", Status: StatusVulnerable, Reason: reason, Message: msg, Props: props, Fix: fix}) + } +} + +// ---- 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 + } + 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 +} + +// 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/repo_test.go b/detectors/java4shell/internal/repo/repo_test.go new file mode 100644 index 0000000..b35aef1 --- /dev/null +++ b/detectors/java4shell/internal/repo/repo_test.go @@ -0,0 +1,272 @@ +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" + + "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", + ".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) + 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) + } + 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) + // 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) + 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(".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 { + 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) + } + } + }) +} diff --git a/detectors/java4shell/internal/repo/review3_test.go b/detectors/java4shell/internal/repo/review3_test.go new file mode 100644 index 0000000..a15cb77 --- /dev/null +++ b/detectors/java4shell/internal/repo/review3_test.go @@ -0,0 +1,128 @@ +package repo + +import ( + "strings" + "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) + } +} + +// 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) + } +} + +// 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) + } + } +} + +// 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) + } + } +} diff --git a/detectors/java4shell/internal/repo/review4_test.go b/detectors/java4shell/internal/repo/review4_test.go new file mode 100644 index 0000000..83f5285 --- /dev/null +++ b/detectors/java4shell/internal/repo/review4_test.go @@ -0,0 +1,95 @@ +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") + } +} + +// 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())) + } +} + +// 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) + } +} diff --git a/detectors/java4shell/internal/repo/review_test.go b/detectors/java4shell/internal/repo/review_test.go new file mode 100644 index 0000000..7748a0b --- /dev/null +++ b/detectors/java4shell/internal/repo/review_test.go @@ -0,0 +1,106 @@ +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.2" || CorrettoJava("21.0.13.0.11") != "21.0.13.0.11" { + t.Error("CorrettoJava") + } + + // 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) != 1 || res.Findings[0].Rule != RuleNotChecked || res.Findings[0].Fixable { + 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) + } + + // 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) + } +} + +// 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) + } +} + +// 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) + } + } +} diff --git a/detectors/java4shell/internal/repo/second_test.go b/detectors/java4shell/internal/repo/second_test.go new file mode 100644 index 0000000..744f1d5 --- /dev/null +++ b/detectors/java4shell/internal/repo/second_test.go @@ -0,0 +1,163 @@ +package repo + +import ( + "context" + "fmt" + "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 +} + +// 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) + } + } +} diff --git a/detectors/java4shell/internal/testlib/testlib.go b/detectors/java4shell/internal/testlib/testlib.go new file mode 100644 index 0000000..34c9473 --- /dev/null +++ b/detectors/java4shell/internal/testlib/testlib.go @@ -0,0 +1,82 @@ +// 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 + Musl bool // the platform is --musl, as on Alpine +} + +// 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.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)...) + 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.go b/detectors/java4shell/java4shell.go new file mode 100644 index 0000000..c0ef745 --- /dev/null +++ b/detectors/java4shell/java4shell.go @@ -0,0 +1,892 @@ +// 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 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. +// +// 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, 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 (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." + +// 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{ + knowledge.OpenJDKAdvisory, + knowledge.OracleAdvisory, + "https://calif.io/java4shell/", + "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", + }, + 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: 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: 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"}, + 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 || l.FixedBuild < 1) { + 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) +} + +// 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 +} + +// 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. An +// /etc/os-release not read keeps a Red Hat row from clearing a runtime +// (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 +} + +// 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 + } +} + +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 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 + } + 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 s.libs.len() == 0 && len(s.unreadLibs) == 0 { + return nil + } + 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) + } + if p == "/etc/os-release" { + s.osUnread = false + } + delete(s.scripts, p) + 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)) + delete(s.badReleases, path.Dir(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$`) + +// 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 s.archives.len() < maxArchivesNoted && jdkArchive.MatchString(path.Base(p)) && archive.IsArchive(head) { + s.archives.add(p, p) + } +} + +// 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. +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) +} + +// 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 + 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 + 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. +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{}, unreadLibs: map[string]bool{}} +} + +type scan struct { + kind engine.TargetKind + libs pathList[*jvm.Library] + releases map[string]jvm.Release + badReleases map[string]string + settings pathList[jvm.Setting] + kept map[string][]byte + lists map[string][]byte + scripts map[string]map[string]bool + crashes pathList[crash] + dropped int + keptBytes int + 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 + 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 + // 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. + 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 +} + +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 { + 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 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) + } + 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")) { + 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 s.crashes.len() < maxHsErrs && len(f.Data) <= maxHsErr { + s.crashes.add(f.Path, readCrash(f.Path, f.Data)) + } + return nil + } + if k := jvm.SettingKind(f.Path); k != "" && len(f.Data) <= maxSetting { + // 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.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.add(f.Path, st) + s.plainUnits++ + } + } + } + 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. + var b []byte + 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') + } + } + 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 { + // 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 { + // 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)) { + vars[n] = true + } + } + if len(vars) > 0 { + 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 +} + +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 s.crashes.len() > 0 { + ctx.Annotate("java4shell_crash_logs", s.crashes.list()) + } + 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) + } + links, hardlinks := ctx.Links() + res := resolver{links: links} + linked := s.linkedLibraries(ctx, res, links, hardlinks) + unreadLibs := make([]string, 0, len(s.unreadLibs)) + for p := range s.unreadLibs { + // 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 { + if len(s.limits) > 0 { + ctx.Problem("java4shell: the scan reached its limit on " + strings.Join(s.limits, " and ") + " for one target") + } + return nil + } + 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.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 { + in.Env = ctx.Env() + if in.Env == nil { + in.Env = []string{} + } + 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 runtimes, 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) + } + out = append(out, f) + } + 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 +// /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 "" + } + 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[file]), " ") + 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, + assess.NotAffected: engine.Fixed, + // 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 { + 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 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" + 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 +} + +// 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) > maxOSRelease { + 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 = osToken(strings.Trim(v, "\"'")) + switch k { + case "ID": + id = v + case "VERSION_ID": + ver = v + } + } + if id != "" { + return strings.TrimSpace(id + " " + ver) + } + } + 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) 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) <= maxOSRelease { + 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 +} + +// 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 } + +// 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) + for i, v := range l.items { + if !l.gone[i] { + out = append(out, v) + } + } + return out +} diff --git a/detectors/java4shell/java4shell_test.go b/detectors/java4shell/java4shell_test.go new file mode 100644 index 0000000..1944905 --- /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.Vulnerable || 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) + } + } +} diff --git a/detectors/java4shell/limit_internal_test.go b/detectors/java4shell/limit_internal_test.go new file mode 100644 index 0000000..4f3c5b7 --- /dev/null +++ b/detectors/java4shell/limit_internal_test.go @@ -0,0 +1,342 @@ +package java4shell + +import ( + "archive/tar" + "bytes" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" + "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" +) + +// 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) + } +} + +// 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) { + 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) + } + } + 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) + } + } + 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) + } + settings := "[true]" + if runtime { + settings = "[false]" // one record: the gap replaces the exclusion + } + 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, 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) + s.VisitOverLimit("/etc/os-release", 300<<10) + 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 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 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) + } +} + +// 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) + } +} + +// 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) + } +} + +// 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/java4shell/links_internal_test.go b/detectors/java4shell/links_internal_test.go new file mode 100644 index 0000000..236beba --- /dev/null +++ b/detectors/java4shell/links_internal_test.go @@ -0,0 +1,130 @@ +package java4shell + +import ( + "archive/tar" + "bytes" + "fmt" + "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) + } +} + +// 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()) + } +} diff --git a/detectors/java4shell/osrelease_internal_test.go b/detectors/java4shell/osrelease_internal_test.go new file mode 100644 index 0000000..0c074d8 --- /dev/null +++ b/detectors/java4shell/osrelease_internal_test.go @@ -0,0 +1,164 @@ +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 + hard bool // link is a hard link + } + 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", 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, "", 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) + } + 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. + 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 := osID(s); id != "" { + t.Errorf("unreadable /etc/os-release: os ID %q, want none", id) + } + s.Forget("/etc/os-release") + 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. + 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 := osID(u); 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") + s.VisitOverLimit("/usr/lib/os-release", maxOSRelease+1) + if id := osID(s); id != "rocky" { + t.Errorf("os ID %q, want rocky", id) + } +} 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/registry_internal_test.go b/detectors/java4shell/registry_internal_test.go new file mode 100644 index 0000000..825df26 --- /dev/null +++ b/detectors/java4shell/registry_internal_test.go @@ -0,0 +1,172 @@ +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 +} + +// 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)) + } +} + +// 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 new file mode 100644 index 0000000..c6db9ea --- /dev/null +++ b/detectors/java4shell/repo.go @@ -0,0 +1,426 @@ +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/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: 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: 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: 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: 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."}, + } +} + +// 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 + } + if reason == "" && v != engine.Vulnerable { + reason = "not decided" + } + facts := map[string]string{} + 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" { + 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 + } + 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)) + g.Reason = "the image could not be pulled" + g.CVEs[0].Reason = g.Reason + return []engine.Finding{g} + } + 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 + } + 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 { + // 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) + } + 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 +// 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) { + 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 + } + // A mitigated pin still needs the update, so fix moves it too. + // 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 || f.Status == repo.StatusUnknown { + 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 + } + 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 + } + 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) + } + // 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 := 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 { + 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)} + } + 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 + } +} + +func annotation(t *engine.Target, key string) string { + if t == nil || t.Error != "" { + return "" + } + 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}) +} diff --git a/detectors/java4shell/review2_test.go b/detectors/java4shell/review2_test.go new file mode 100644 index 0000000..c706df8 --- /dev/null +++ b/detectors/java4shell/review2_test.go @@ -0,0 +1,114 @@ +package java4shell_test + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/java4shell" + "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) + } +} + +// 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) + } +} + +// 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")) + 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) + } +} + +// 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) + } +} 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) + } + } +} 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") 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) + } +} diff --git a/detectors/php2shell/forget_internal_test.go b/detectors/php2shell/forget_internal_test.go new file mode 100644 index 0000000..7821098 --- /dev/null +++ b/detectors/php2shell/forget_internal_test.go @@ -0,0 +1,46 @@ +package php2shell + +import ( + "fmt" + "testing" + "time" + + "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")}} + 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 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 383ff3f..ca9fbb0 100644 --- a/detectors/php2shell/php2shell.go +++ b/detectors/php2shell/php2shell.go @@ -123,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 @@ -160,6 +162,36 @@ 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. It costs what p held, not every binary kept. +func (c *collector) Forget(p string) { + delete(c.dbFiles, 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 { if f.Member || excluded(f.Path, c.exclude) { return nil // installed files only, not archive members or excluded paths @@ -177,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 @@ -208,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/detectors/sshole/internal/assess/argument_test.go b/detectors/sshole/internal/assess/argument_test.go new file mode 100644 index 0000000..6887959 --- /dev/null +++ b/detectors/sshole/internal/assess/argument_test.go @@ -0,0 +1,99 @@ +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) + } + } +} + +// 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/assess.go b/detectors/sshole/internal/assess/assess.go index 1be61e5..74f9829 100644 --- a/detectors/sshole/internal/assess/assess.go +++ b/detectors/sshole/internal/assess/assess.go @@ -75,10 +75,17 @@ 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. 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 @@ -204,12 +211,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 } @@ -235,6 +292,16 @@ func assessUnit(in Input, u []*Binary) (Finding, bool) { return f, true } f.UsePAM = strings.ToLower(cfg.Global("usepam", "no")) + 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.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 + } 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" @@ -245,9 +312,16 @@ func assessUnit(in Input, u []*Binary) (Finding, bool) { 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 { @@ -280,7 +354,7 @@ func assessUnit(in Input, u []*Binary) (Finding, bool) { 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 @@ -338,11 +412,13 @@ 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, 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 { for _, b := range u { @@ -353,19 +429,30 @@ 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 + // 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 } } - for _, inv := range mine[1:] { - if inv.config != mine[0].config || !sameOpts(inv.opts, mine[0].opts) { - return invocation{}, false + 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) + } + if !dup { + out = append(out, inv) } } - return mine[0], true + // 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/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/runtime.go b/detectors/sshole/internal/assess/runtime.go index 92e2790..5b836c3 100644 --- a/detectors/sshole/internal/assess/runtime.go +++ b/detectors/sshole/internal/assess/runtime.go @@ -14,6 +14,93 @@ 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 (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 s.UnreadAll { + return []string{"more files than the scan records"} + } + if len(s.Unread) == 0 && len(s.UnreadDirs) == 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 !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) + } + } + for _, w := range s.Command { + 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) + } + } + } + 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 } // initDirs hold scripts an init system runs at start whatever the command @@ -54,28 +141,62 @@ 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. + // 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 - 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 + program, operand := false, 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) { + 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 + } } } - } else { - add(c[0]) + // 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 || 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 + // 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 + } } } } @@ -94,18 +215,48 @@ func (s Startup) startScripts(resolve func(string) (string, bool)) []script { return out } -type script struct{ where, text string } - -var absPathRE = regexp.MustCompile(`/[A-Za-z0-9_./-]+`) +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 +} -func isWrapper(b string) 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", "s6-svscan": + case "tini", "dumb-init", "su-exec", "gosu", "env", "exec", "catatonit": return true } + if isShell(b) || strings.HasPrefix(w, "-") || assignmentRE.MatchString(w) && !strings.Contains(w, "/") { + return true + } + if i > 0 { + switch path.Base(c[i-1]) { + case "su-exec", "gosu": + return true + } + } 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 { switch b { case "sh", "bash", "ash", "dash", "busybox": @@ -120,6 +271,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 @@ -133,6 +287,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) } } @@ -278,7 +433,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 { diff --git a/detectors/sshole/internal/assess/unread_test.go b/detectors/sshole/internal/assess/unread_test.go new file mode 100644 index 0000000..94f4b8d --- /dev/null +++ b/detectors/sshole/internal/assess/unread_test.go @@ -0,0 +1,221 @@ +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) + } + // 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) + } +} + +// 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) + } + } +} + +// 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) + } + } +} + +// 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) + } + } +} diff --git a/detectors/sshole/limit_internal_test.go b/detectors/sshole/limit_internal_test.go new file mode 100644 index 0000000..91c7097 --- /dev/null +++ b/detectors/sshole/limit_internal_test.go @@ -0,0 +1,90 @@ +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) + } + // 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) + } +} + +// 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) + } + } +} + +// 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("#!/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.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 new file mode 100644 index 0000000..f4f022c --- /dev/null +++ b/detectors/sshole/limit_test.go @@ -0,0 +1,647 @@ +package sshole_test + +import ( + "archive/tar" + "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" + "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) + 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) + } +} + +// 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) + } +} + +// 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) + } +} + +// 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) + } +} + +// 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/detectors/sshole/sshole.go b/detectors/sshole/sshole.go index d91286e..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" @@ -83,6 +85,34 @@ 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, 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] == '!' } @@ -112,11 +142,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{}} + 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 { @@ -125,17 +158,113 @@ 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 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; 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 +// 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 { + 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) + 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.binaries = bs +} + +// 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: "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 } 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) + 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.unread(f.Path) + delete(s.over, f.Path) // read as a file the verdict reads + } } - 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 } @@ -149,13 +278,15 @@ 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, unreadDirs: s.unreadDirs, root: ctx.SystemRoot()} links, _ := ctx.Links() res := resolver{links: links, exists: func(p string) bool { 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{} @@ -180,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, @@ -187,10 +319,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}, + 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 @@ -260,14 +397,105 @@ func yes(b bool) string { // root's own files from disk. type files struct { kept map[string][]byte - 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 +} + +// 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 { + 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 == "" { + if f.root == "" || f.over[p] || f.inUnreadDir(p) { return nil } return f.disk(p) @@ -306,12 +534,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 @@ -319,11 +548,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() > keptLimit(p) { return nil } b, err := os.ReadFile(full) @@ -336,12 +576,24 @@ 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.mayHide(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) @@ -351,7 +603,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) } diff --git a/go.mod b/go.mod index 635bc81..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 @@ -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 diff --git a/internal/engine/engine.go b/internal/engine/engine.go index c05a48b..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. @@ -138,7 +143,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 @@ -186,6 +192,72 @@ 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, 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 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 +} + +// 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 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) +} + +// 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..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. @@ -226,3 +231,68 @@ 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) + } +} + +// 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/limit_test.go b/internal/engine/limit_test.go new file mode 100644 index 0000000..3f5e745 --- /dev/null +++ b/internal/engine/limit_test.go @@ -0,0 +1,669 @@ +package engine + +import ( + "archive/tar" + "bytes" + "fmt" + "os" + "path/filepath" + "runtime" + "sort" + "strconv" + "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) + } +} + +// 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 }) + _, db := capped("t-two64k", osRelease, limit64K) + tg := ScanFS([]Detector{ds, db}, root, Options{AsRoot: true}) + var got []string + for _, s := range tg.Skipped { + got = append(got, s.Reason) + } + // 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) + } +} + +// 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() +} + +// 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}, {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) { + 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) + } + } + // 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) + } + for i := range lims { + 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 !exists { + t.Fatalf("Exists false for a file the walk met") + } + }) +} + +// 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) + } + // 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) + } +} + +// 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) + } +} + +// 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 02d6e3b..6a244c6 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 @@ -187,6 +199,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 @@ -197,6 +210,25 @@ 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 + // 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 + // 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 +// for the file. +type fileLimit struct { + bytes int64 + wants bool } // abs turns a walked path into its path inside the system root. @@ -220,6 +252,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 @@ -234,28 +267,264 @@ 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.ctx.hardlinks[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)) }, } - var readers []Reader - for _, d := range w.dets { - r, ok := d.(Reader) - if !ok { - return so // this detector wants everything + 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, headScan{w.dets[i].Manifest().ID, h}) } - readers = append(readers, r) } - so.Read = func(p string, head []byte, exe bool) bool { - for _, r := range readers { - if r.Wants(w.abs(p), head, exe) { - return true + visitHead := func(p string, head []byte) { + for _, h := range heads { + w.visitHeadSafely(h.id, h.h, w.abs(p), head) + } + } + 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 _, 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 { + case limited: + w.limits = make([]fileLimit, len(w.dets)) + 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, 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: + 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 + } + } + 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 in a docker export: this entry + // 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. + delete(w.ctx.symlinks, 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 + 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 { + 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 false } 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. 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) +} + +// 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 { + 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 +// is kept for handing the file out. +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 + 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) + } + } + if unlimited { + return read, 0 + } + return read, most +} + +// 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 { + 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 +} + +// 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)" + } + 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 +// 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. +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 @@ -270,18 +539,29 @@ 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}) }) 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 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) { continue } + if w.over(i, f) { + if w.limits[i].wants { + w.t.Skipped = append(w.t.Skipped, w.overLimit(i, f.Path, int64(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}) } @@ -299,7 +579,20 @@ 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() { + defer func() { w.t.Skipped = oneRecordPerPath(w.t.Skipped) }() for i, s := range w.scans { fs, err := finishSafely(s, w.ctx) if err != nil { @@ -307,7 +600,70 @@ 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.dropExclusion(i, sk.Path) + w.t.Skipped = append(w.t.Skipped, source.Skip{Path: sk.Path, Reason: sk.Reason}) + } + } + } +} + +// 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) { + 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 { + err = fmt.Errorf("%v", r) + } + }() + return s.FinishSkips(), nil } func finishSafely(s Scan, ctx TargetContext) (fs []Finding, err error) { @@ -392,6 +748,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 @@ -419,11 +776,17 @@ 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() 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:") + 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 { @@ -434,6 +797,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/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') diff --git a/internal/image/flatten.go b/internal/image/flatten.go new file mode 100644 index 0000000..7f42f40 --- /dev/null +++ b/internal/image/flatten.go @@ -0,0 +1,531 @@ +package image + +// Flattening follows go-containerregistry's mutate.Extract (Apache-2.0, +// 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. +// +// 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. 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" + "errors" + "fmt" + "io" + "path" + "sort" + "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. 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() + 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() { + 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 + } +} + +type flattener struct { + tw *tar.Writer + fileMap map[string]bool // path -> hides what is below it (non-directory or whiteout) + opaqueDirs map[string]bool + 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 + layer int +} + +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-- { + f.cur = i + 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. +// 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("/"+name), "/") +} + +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 + 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 { + 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.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 = "" + } + 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) + if tombstone { + base = base[len(whiteoutPrefix):] + } + name := h.Name + if h.Typeflag != tar.TypeDir { + 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) { + 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 + 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(f.fileMap, name) || inOpaqueDir(f.opaqueDirs, name) { + if regular { + hidden[name] = true + } + continue + } + f.fileMap[name] = tombstone || !isDir + if tombstone { + f.written[name] = flatWrite{layer: f.cur, seq: f.seq, tomb: true} + continue + } + 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] = flatWrite{layer: f.cur, seq: f.seq} + 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(f.tw, tr, h.Size); err != nil { + return err + } + } + if regular { + here[name], plain[name] = true, true + } + if !isDir { + f.written[name] = flatWrite{layer: f.cur, seq: f.seq} + } + if h.Typeflag == tar.TypeSymlink { + f.links[name] = flatLink{h.Linkname, f.cur} + } + } + for d := range layerOpaque { + 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 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. +// +// 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. +// +// 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 member struct { + name string + w flatWrite + } + 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 + } + continue + } + groups[at] = append(groups[at], member{name, w}) + } + 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 + } + } + 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 + } + for _, m := range ms { + if m.name != win.name { + f.unresolved[m.name] = true + } + } + if win.name != at { + f.unresolved[at] = true + } + } +} + +// 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 + } + } + 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) + if dir == "." { + dir = "" + } + if opaqueDirs[dir] { + return true + } + if file == dir { + break + } + file = dir + } + return false +} + +func inWhiteoutDir(fileMap map[string]bool, file string) bool { + for file != "" { + dir := path.Dir(file) + if file == dir || 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 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..7b0a4ac --- /dev/null +++ b/internal/image/flatten_test.go @@ -0,0 +1,425 @@ +package image + +import ( + "archive/tar" + "bytes" + "fmt" + "io" + "sort" + "strings" + "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" +) + +// 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 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.body)) + } + } + 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 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() + 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) + 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) + } +} + +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]) + } + 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") + } + if _, ok := got["etc/gone2"]; ok { + t.Error("a whiteout spelled etc/.wh.gone2 did not hide /etc/gone2") + } + for name := range got { + if strings.HasPrefix(name, "/") { + t.Errorf("entry %q is not relative to the root", name) + } + } +} + +// 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")})) + 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 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")}}, "[]"}, + // 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")}}, + "[/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]"}, + // 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 /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]"}, + } { + _, 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) + } + } + // 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 { + 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) + } + } + } + }) +} + +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, " ") +} + +// 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/image/image.go b/internal/image/image.go index c7bfce3..40986db 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" ) @@ -20,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. @@ -62,7 +64,7 @@ func opened(img v1.Image) (*Opened, error) { } } } - o.FS = mutate.Extract(img) + o.FS, o.Unresolved = flatten(img) return o, nil } 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..25de80f --- /dev/null +++ b/internal/refs/instructions.go @@ -0,0 +1,76 @@ +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 +// 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 + // 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 + // (--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 < 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 + } + out := make([]Instruction, 0, len(p.instrs)) + for _, in := range p.instrs { + cmd, rest := in.cmd, in.rest.String() + onbuild := cmd == "onbuild" + if onbuild { + rest = strings.TrimSpace(rest) + word, after, _ := strings.Cut(rest, " ") + if i := strings.IndexAny(rest, " \t"); i >= 0 { + word, after = rest[:i], rest[i+1:] + } + cmd, rest = strings.ToLower(word), strings.TrimSpace(after) + } + 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 + } + 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..7ebb379 --- /dev/null +++ b/internal/refs/instructions_test.go @@ -0,0 +1,55 @@ +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) + } + if _, err := Instructions(make([]byte, MaxDockerfileSize+1)); err == nil { + t.Error("a Dockerfile over MaxDockerfileSize was parsed") + } +} 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 39b7ce2..53452e4 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,35 @@ 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 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 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 + // 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 + // 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. + 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 + // 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). @@ -70,6 +99,45 @@ 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/"} +// 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 +} + +// 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 { + var told []Skip + switch { + case own && o.Over != nil: + 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 append([]Skip{{Path: abs, Reason: fmt.Sprintf("larger than --max-file-size (%d bytes) while reading", most)}}, told...) + } + 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. type Visitor func(File) error @@ -111,7 +179,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 } @@ -141,7 +209,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++ @@ -165,43 +233,48 @@ 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] exe := opts.IsExecutable != nil && opts.IsExecutable(head) - if opts.Read != nil && !opts.Read(abs, head, exe) { - return nil + var lim int64 + 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, opts.tooLarge(abs, fi.Size(), most, own)...) 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 { - *skips = append(*skips, Skip{Path: abs, Reason: err.Error()}) + *skips = append(*skips, opts.unread(abs, err.Error(), false)) 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, opts.tooLarge(abs, -1, most, own)...) return nil } return visit(File{Path: abs, Data: data, Executable: exe}) @@ -214,6 +287,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) { @@ -226,6 +300,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] && (opts.Replaces == "" || h.PAXRecords[opts.Replaces] == "") { + 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 { @@ -251,24 +334,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 int64 + 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, opts.tooLarge(abs, h.Size, most, own)...) 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, 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 f596585..ee2b976 100644 --- a/internal/source/source_test.go +++ b/internal/source/source_test.go @@ -3,6 +3,11 @@ package source import ( "archive/tar" "bytes" + "io" + "os" + "path/filepath" + "runtime" + "strings" "testing" ) @@ -24,8 +29,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, 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 }, Hardlink: func(p, to string) { links[p] = to }, @@ -55,7 +62,143 @@ 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, + // 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, 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}) + 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, _ bool) []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) { + 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, int64) { + if p == "/big" { + return true, 100 // above MaxFileSize: MaxFileSize applies + } + return true, 4 + }, + } + 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 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)" { + 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, 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 set 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, 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 { + 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 } diff --git a/parity/JAVA4SHELL-RESULTS.md b/parity/JAVA4SHELL-RESULTS.md new file mode 100644 index 0000000..acdd8a8 --- /dev/null +++ b/parity/JAVA4SHELL-RESULTS.md @@ -0,0 +1,51 @@ +# 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, 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 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 | +| 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 | +| 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 | +| 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 | +| 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 (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 | + +43/43 cases match. diff --git a/parity/java4shell.py b/parity/java4shell.py new file mode 100644 index 0000000..df1e882 --- /dev/null +++ b/parity/java4shell.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Check the java4shell detector against Java runtimes whose status is known. + +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` +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, 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. +""" +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: + 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 + + +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) + # 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, version from) |\n| --- | --- | --- | --- |\n") + 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) + + +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/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/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..69f72c1 --- /dev/null +++ b/parity/java4shell/cases.json @@ -0,0 +1,850 @@ +[ + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "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" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ], + "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", + "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" + ] + ], + "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", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "name": "corretto-21-al2023", + "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": [ + [ + "linux/amd64", + "/usr/lib/jvm/java-21-amazon-corretto.x86_64", + "runtime", + "fixed", + "fixed", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "name": "corretto-17-alpine", + "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": [ + [ + "linux/amd64", + "/usr/lib/jvm/java-17-amazon-corretto", + "runtime", + "fixed", + "fixed", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "release-file" + ] + ] + }, + { + "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", + "mode": "registry", + "ref": "elasticsearch:9.5.5", + "expected": [ + [ + "linux/amd64", + "/usr/share/elasticsearch/jdk", + "bundled-runtime", + "vulnerable", + "vulnerable", + "vm-library" + ] + ] + }, + { + "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", + "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" + ] + ] + }, + { + "name": "jlink", + "what": "jlink runtime made from Temurin 21.0.13", + "mode": "build", + "dockerfile": "jlink.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/app/runtime", + "runtime", + "vulnerable", + "vulnerable", + "vm-library" + ] + ] + }, + { + "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", + "vulnerable", + "mitigated", + "vm-library" + ], + [ + "linux/amd64", + "/opt/atlassian/confluence/jre", + "bundled-runtime", + "vulnerable", + "vulnerable", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "mode": "build", + "dockerfile": "mitigated-env.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/opt/java/openjdk", + "runtime", + "vulnerable", + "mitigated", + "vm-library" + ] + ] + }, + { + "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", + "vulnerable", + "mitigated", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "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", + "vulnerable", + "mitigated", + "vm-library" + ] + ] + }, + { + "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", + "vulnerable", + "mitigated", + "vm-library" + ] + ] + }, + { + "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", + "vm-library" + ], + [ + "linux/amd64", + "/opt/huge", + "runtime", + "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" + ] + ] + }, + { + "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", + "vm-library" + ] + ] + }, + { + "name": "repo", + "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": [ + [ + ".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", + "vulnerable" + ], + [ + "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", + "vulnerable" + ], + [ + "compose.yaml:13", + "not-checked", + "unknown" + ], + [ + "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" + ], + [ + "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" + ] + ] + } +] 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/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/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/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 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.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 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/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/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/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 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-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 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/*