diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c2bf1a7..29c348f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,6 +45,13 @@ jobs: 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 + go test ./detectors/nginxh2 -run '^$' -fuzz '^FuzzSource$' -fuzztime 30s + go test ./detectors/nginxh2/internal/assess -run '^$' -fuzz '^FuzzStart$' -fuzztime 20s + go test ./detectors/nginxh2/internal/conf -run '^$' -fuzz '^FuzzParse$' -fuzztime 30s + go test ./detectors/nginxh2/internal/ngx -run '^$' -fuzz '^FuzzInspect$' -fuzztime 20s + go test ./detectors/nginxh2/internal/ngx -run '^$' -fuzz '^FuzzVersions$' -fuzztime 15s + go test ./detectors/nginxh2/internal/pkgdb -run '^$' -fuzz '^FuzzDatabases$' -fuzztime 15s + go test ./detectors/nginxh2/internal/repo -run '^$' -fuzz '^FuzzScanText$' -fuzztime 20s 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/README.md b/README.md index 900b6b4..f015cec 100644 --- a/README.md +++ b/README.md @@ -16,8 +16,9 @@ One engine for DefectDojo's emerging-vulnerability scanners. Each new vulnerabil | `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` | +| `nginxh2` | The nginx HTTP/2 remote code execution pair disclosed on November 18, 2026: CVE-2026-123007, memory corruption in HTTP/2 flow control (nginx 1.9.5 to 1.31.8), and CVE-2026-123633, a use-after-free in HTTP/2 connection reuse (1.19.7 to 1.31.8), both fixed in nginx 1.31.9 and 1.30.7 ([fix](https://github.com/nginx/nginx/commit/e27f5fa84fe6e98505e70bc543b748747dad0a3b), [fix](https://github.com/nginx/nginx/commit/2df48a501d0fb8212b7d39dffeeff5876332ba59), [Wiz](https://www.wiz.io/blog/nginx-http2-rce-vulnerabilities), [knowledge table](detectors/nginxh2/FACTS.md)). CVSS 9.2 (Wiz). It finds nginx, OpenResty, Tengine, Angie and NGINX Plus binaries by what the binary carries (its version line, configure arguments and module list), and judges each CVE on each binary on its own: a build without HTTP/2 is not affected, a build whose version line is missing, renamed or disagrees with its other version strings is unknown and never cleared, and the fix leaves no marker in the binary, so the fix itself is judged by version. OpenResty is judged by its nginx core and its own release (it backports as patches), Tengine and Angie by their own releases (no fixed release yet), NGINX Plus by its release (fixed 37.0.8.1 and 37.3.0.1; 37.0.7.1 and 37.2.0.1 fix CVE-2026-123633 only). A distribution build is read through the package database (dpkg, apk) with a backport table that is empty today: Debian and Ubuntu had published no fixed package; Alpine 3.24 and edge have 1.30.7-r0. It then reads the configuration the binary loads (its compiled-in path or the image command's `-c`, includes at any level with globs and symbolic links, the official image's templates, `-g`) and reports exposure as a fact on a finding that stays vulnerable: HTTP/2 over TLS (CVE-2026-123007), HTTP/2 in front of `proxy_pass`, `grpc_pass` and the other proxies (CVE-2026-123633), `worker_connections`; HTTP/2 off everywhere is "not exposed", and "not exposed" needs the start read exactly (the nginx word resolved to that very binary, or the official entrypoint by hash with only its own scripts in `/docker-entrypoint.d`, or a systemd unit whose settings it applies) and every included file read, so a wrapper or custom script, a unit setting it does not apply, an include it cannot read, a configuration the ingress-nginx or F5 controller writes at start, or none at all leaves exposure unknown, never off. In a source tree it judges nginx image tags (official image and variants, nginx-unprivileged, OpenResty, Bitnami, ingress-nginx and its Helm chart, the F5 NGINX Ingress Controller, Angie) in Dockerfiles, Compose, Kubernetes, Helm values and CI files, reads moving tags and digests from the registry on linux/amd64 and linux/arm64, judges the nginx packages a Dockerfile installs (apt, apk, dnf and yum, dnf module streams, through `sh -c`, subshells, xargs, heredocs, ARG and ENV) against each distribution's status, and reports the configurations that turn HTTP/2 on. `fix` moves a tag to the first fixed release of its line and variant (`1.31.8-alpine3.24-perl` to `1.31.9-alpine3.24-perl`, `1.30.6` to `1.30.7`) after reading the new image on each platform judged, checking that it is published for every platform the tree builds and stays on the same base OS, moves an Alpine 3.24 pin to 1.30.7-r0, declines everything without a published fix with the reason, and prints the `http2 off;` edit as an optional interim step it never applies | `fs`, `image`, `repo`, `fix` | -The detectors ported from standalone scanners also build as standalone binaries under the names people search for: `emudhra-scan` and `php2shell-scan`. They keep their original commands, flags and exit status rules. `brotli`, `sshole` and `java4shell` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`, `--detector java4shell`). +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`, `java4shell` and `nginxh2` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`, `--detector java4shell`, `--detector nginxh2`). ## Install @@ -55,6 +56,10 @@ earlylight scan image --detector java4shell --platform all eclipse-temurin:21-jr 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 --detector nginxh2 --platform all nginx:1.31.8 # nginx binaries and the HTTP/2 their configuration turns on +sudo earlylight scan fs --detector nginxh2 / # this machine's nginx, OpenResty, Angie +earlylight scan repo --detector nginxh2 . # nginx images, packages and configurations a tree uses +earlylight fix --detector nginxh2 --dry-run --platform linux/amd64,linux/arm64 . # verified moves to 1.31.9 / 1.30.7 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 @@ -119,6 +124,7 @@ The engine enforces one rule for every detector: a finding can only be `fixed`, | `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 | +| `detectors/nginxh2` | Adapter, plus `internal/knowledge` (the release data and version judgement, sourced in `FACTS.md`), `internal/ngx` (what an nginx binary proves: product, version line, configure arguments, modules, word size), `internal/conf` (nginx's configuration grammar, includes and globs, and what it says about HTTP/2, TLS and proxying), `internal/pkgdb` (dpkg and apk owners and version order), `internal/assess` (each CVE's verdict on each binary, with its exposure) and `internal/repo` (nginx images, packages and configurations 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 | @@ -134,6 +140,7 @@ Every port must give exactly the verdicts of the scanner it came from before it - `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/nginxh2.py` checks 39 cases against verdicts taken from [FACTS.md](detectors/nginxh2/FACTS.md): official images before and after the fix on both lines (Debian, Alpine, perl, otel; arm64 and 386), the 1.19.6 / 1.19.7 boundary, 1.18.0 and 1.10.3, nginx-unprivileged, OpenResty, Bitnami, ingress-nginx and the F5 NGINX Ingress Controller before and after 5.8.0, Debian, Ubuntu and Alpine packages (a filesystem export too), configurations that turn HTTP/2 on over TLS, without TLS, without a proxy, in a template, through `-c` and through a symbolic link, that turn it off, or that cannot be read in full (unreadable includes, loops, a 5 MB file), synthetic binaries without a version line, renamed, with only the version line edited to claim the fix, and without HTTP/2, a source tree, and `fix` offline and against the registry ([NGINXH2-RESULTS.md](parity/NGINXH2-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 @@ -155,9 +162,17 @@ go test ./detectors/sshole/internal/assess -run '^$' -fuzz '^FuzzConfig$' -fuzzt 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 +go test ./detectors/nginxh2/internal/conf -run '^$' -fuzz '^FuzzParse$' -fuzztime 60s +go test ./detectors/nginxh2/internal/ngx -run '^$' -fuzz '^FuzzInspect$' -fuzztime 60s +go test ./detectors/nginxh2/internal/ngx -run '^$' -fuzz '^FuzzVersions$' -fuzztime 60s +go test ./detectors/nginxh2/internal/repo -run '^$' -fuzz '^FuzzScanText$' -fuzztime 60s +go test ./detectors/nginxh2 -run '^$' -fuzz '^FuzzSource$' -fuzztime 60s +go test ./detectors/nginxh2/internal/assess -run '^$' -fuzz '^FuzzStart$' -fuzztime 60s +go test ./detectors/nginxh2/internal/pkgdb -run '^$' -fuzz '^FuzzDatabases$' -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 +python3 parity/nginxh2.py ./earlylight ``` ## Privacy diff --git a/detectors/all/all.go b/detectors/all/all.go index 7549169..a9f08ad 100644 --- a/detectors/all/all.go +++ b/detectors/all/all.go @@ -5,6 +5,7 @@ import ( _ "github.com/DefectDojo/earlylight/detectors/brotli" _ "github.com/DefectDojo/earlylight/detectors/emudhra" _ "github.com/DefectDojo/earlylight/detectors/java4shell" + _ "github.com/DefectDojo/earlylight/detectors/nginxh2" _ "github.com/DefectDojo/earlylight/detectors/php2shell" _ "github.com/DefectDojo/earlylight/detectors/sshole" ) diff --git a/detectors/nginxh2/FACTS.md b/detectors/nginxh2/FACTS.md new file mode 100644 index 0000000..6693393 --- /dev/null +++ b/detectors/nginxh2/FACTS.md @@ -0,0 +1,163 @@ +# nginx HTTP/2 RCE pair (CVE-2026-123007, CVE-2026-123633): what is known, and from where + +Checked 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. Rows marked **lead** were read by the lead in a browser and relayed: the research host +cannot reach nginx.org, wiz.io, my.f5.com, access.redhat.com, ubuntu.com, openresty.org, angie.software, +registry.k8s.io, ghcr.io or quay.io. + +## The advisories (lead, 2026-11-18) + +| Fact | Source | +| --- | --- | +| Coordinated disclosure on 2026-11-18 with the F5 release. Wiz scores both CVEs CVSS 4.0 **9.2**; the detector reports 9.2 | [Wiz, "Unauthenticated Remote Code Execution in NGINX: CVE-2026-123633 and CVE-2026-123007"](https://www.wiz.io/blog/nginx-http2-rce-vulnerabilities) (lead) | +| **CVE-2026-123007**, "Memory corruption in HTTP/2 flow control", nginx.org severity major. Vulnerable **1.9.5 to 1.31.8**; not vulnerable **1.31.9+, 1.30.7+**. Credit Xint.io | [nginx.org security advisories](https://nginx.org/en/security_advisories.html), [F5 K000163926](https://my.f5.com/manage/s/article/K000163926) (lead) | +| nginx CHANGES for 1.31.9 is dated 18 Nov 2026 and credits Xint.io (CVE-2026-123007) and Albert of Vexera AI (CVE-2026-123633) | [nginx CHANGES](https://nginx.org/en/CHANGES) (lead, 2026-11-18) | +| **CVE-2026-123633**, "Use-after-free in HTTP/2", nginx.org severity medium. Vulnerable **1.19.7 to 1.31.8**; not vulnerable **1.31.9+, 1.30.7+**. Credit Albert of Vexera AI | nginx.org security advisories, [F5 K000163928](https://my.f5.com/manage/s/article/K000163928) (lead) | +| Red Hat scores CVE-2026-123007 CVSS 3.1 **8.1** (AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H), CWE-787, Bugzilla 2575895, and lists no fixed products, NVRs or errata. Red Hat's page for CVE-2026-123633 returned 404 | [access.redhat.com CVE-2026-123007](https://access.redhat.com/security/cve/CVE-2026-123007), [CVE-2026-123633](https://access.redhat.com/security/cve/CVE-2026-123633) (lead, 2026-11-18) | +| Ubuntu gives CVE-2026-123007 priority **High**: vulnerable on 26.10, 26.04 LTS, 24.04 LTS, 22.04 LTS, 20.04 LTS, 18.04 LTS and 16.04 LTS, not affected on 14.04 (nginx 1.4.6, no HTTP/2); no fixed versions | [ubuntu.com/security CVE-2026-123007](https://ubuntu.com/security/CVE-2026-123007) (lead, 2026-11-18) | +| NGINX Plus: affected from R33 and 37.0.0; fixed **37.0.7.1 and 37.2.0.1** (CVE-2026-123633), **37.0.8.1 and 37.3.0.1** (CVE-2026-123007) | F5 K000163926, K000163928 (lead) | +| CVE-2026-123007 preconditions: HTTP/2 on, over TLS, a 64-bit build; plain static files reach it, no proxy or module needed. Wiz showed pre-authentication RCE with an ASLR bypass on the official 1.31.7 and 1.31.8 builds. No PoC released | Wiz (lead) | +| CVE-2026-123633 preconditions: HTTP/2 on, a reverse-proxy configuration, worker_connections nearly exhausted | Wiz (lead) | +| Interim mitigation, not a fix: turn HTTP/2 off (`http2 off;` from 1.25.1, and remove `http2` from every `listen`) | nginx.org, Wiz (lead) | +| Wiz detection hints: version check, HTTP/2 on in the config, worker crashes, long-lived HTTP/2 connections with many WINDOW_UPDATE frames. **No binary indicator or IOC** was published | Wiz (lead) | +| The same 1.31.9 / 1.30.7 releases also fix CVE-2026-121810 (HTTP/3), CVE-2026-123634 (resolver), CVE-2026-113425 (mail), CVE-2026-118899, CVE-2026-125283, CVE-2026-120967, CVE-2026-120993 and CVE-2026-123640. They are not this detector's | nginx.org (lead) | + +## The fixes in the nginx source (github.com/nginx/nginx, read here) + +| Fact | Source | +| --- | --- | +| CVE-2026-123007 fix: "HTTP/2: account for queued frames when validating WINDOW_UPDATE" (Roman Arutyunyan, 2026-10-29, "Reported by Xint.io"). Adds `h2c->send_queued`, counts queued DATA frames in it, and checks `window > NGX_HTTP_V2_MAX_WINDOW - h2c->send_window - h2c->send_queued` | [`e27f5fa84`](https://github.com/nginx/nginx/commit/e27f5fa84fe6e98505e70bc543b748747dad0a3b) on 1.31 (`release-1.31.9`), [`b89c4100b`](https://github.com/nginx/nginx/commit/b89c4100bf6762a45e4a6463eaf4b70368277c94) on `stable-1.30` (`release-1.30.7`) | +| CVE-2026-123633 fix: "HTTP/2: reset reusable connection status on stream creation" (Roman Arutyunyan, 2026-09-17, "Reported by Albert @ Vexera AI"): `ngx_reusable_connection(h2c->connection, 0)` in `ngx_http_v2_create_stream()`. The commit names the cause as 76672e650 ("HTTP/2: reuse of connections with incomplete frames", 2021-02-11), first released in **1.19.7** | [`2df48a501`](https://github.com/nginx/nginx/commit/2df48a501d0fb8212b7d39dffeeff5876332ba59) (1.31), [`0c87dd1db`](https://github.com/nginx/nginx/commit/0c87dd1db413e440a4e3ef7ee8acc518509e8809) (`stable-1.30`); `git tag --contains 76672e650` starts at `release-1.19.7` | +| HTTP/2 came in **1.9.5** ("The HTTP/2 implementation", ee37ff613, 2015-09-11; first tag `release-1.9.5`) | nginx/nginx history | +| Tags: `release-1.31.9` (c2c44702c, tagged 2026-11-06), `release-1.30.7` (2df4366ef, tagged 2026-11-11). The mainline branch was bumped to 1.31.10 on 2026-11-18 | nginx/nginx tags | +| **No binary marker.** The 123633 fix adds one call and no string; the 123007 fix changes a comparison and the arguments of an existing log message whose format string stays the same. A fixed build differs from an unfixed one of the same version in code only | the two diffs above | +| A build from the source tree between the "Version bump" to 1.31.9 (2026-10-22) and the fix commits also reports 1.31.9 without the fixes; release tarballs and packages do not. The detector takes a version string as the release's | nginx/nginx history; **inferred** | +| HTTP/2 is compiled in only with `./configure --with-http_v2_module` (it cannot be a dynamic module); a build that has it lists `ngx_http_v2_module` in its module names and in its configure arguments | `auto/options`, `auto/modules` | +| HTTP/2 is on for a connection when the listening socket has the `http2` parameter (deprecated, still honoured) or the server's `http2` directive is on (from **1.25.1**, aefd862ab). With TLS it is chosen by ALPN; without TLS by the client's HTTP/2 preface (prior knowledge) | `ngx_http_init_connection()` and `ngx_http_ssl_handshake_handler()` in `src/http/ngx_http_request.c` at `release-1.31.9` | +| The `ssl on;` directive (TLS on every listener of the server) was removed in **1.25.1** (d32f66f1e); before, it made a server's plain `listen` lines TLS | nginx/nginx history | + +## How a binary says what it is (read from real binaries here) + +| Build | What the binary carries | Source | +| --- | --- | --- | +| nginx (official image, nginx.org package) | `nginx version: nginx/1.31.8`, `nginx/1.31.8`, `configure arguments: --prefix=/etc/nginx ... --with-http_v2_module ...`, `ngx_http_v2_module`, help text `set configuration file (default: /etc/nginx/nginx.conf)` | `nginx:1.31.8` (index sha256:165ddde8751e…6aff76d82), `nginx:1.31.9` (index sha256:a7087e95bd21…8fb3581c), linux/amd64 | +| Debian | `nginx version: nginx/1.22.1`, prefix `/usr/share/nginx/`, conf `/etc/nginx/nginx.conf`; dpkg `nginx 1.22.1-9+deb12u10` owns `/usr/sbin/nginx` | `debian:12` + `apt-get install nginx`, 2026-11-18 | +| Ubuntu | `nginx version: nginx/1.24.0 (Ubuntu)` (built with `--build=Ubuntu`); dpkg `nginx 1.24.0-2ubuntu7.19` | `ubuntu:24.04` + `apt-get install nginx` | +| Alpine | `nginx version: nginx/1.30.6`, prefix `/var/lib/nginx/`; apk `nginx 1.30.6-r0` | `alpine:3.24` + `apk add nginx` | +| OpenResty | `nginx version: openresty/1.31.8.1`, `openresty/1.31.8.1`, the core `1.31.8` as its own string, prefix `/usr/local/openresty/nginx/` | `openresty/openresty:1.31.8.1-alpine` (sha256:fec9da11e7a9…4959b943) | +| Tengine | `Tengine version: Tengine/3.2.0` and `nginx version: nginx/1.31.5` (`TENGINE_VER_BUILD`, `NGINX_VER_BUILD`) | alibaba/tengine `src/core/nginx.c`, `nginx.h` (master, 2026-09-07) | +| Angie | `Angie version: Angie/1.13.0` and, for `-V`, `nginx version: nginx/1.31.3`: a compatibility number, not the code Angie carries | webserver-llc/angie `src/core/nginx.c`, `angie.h`, `nginx.h` (master, 2026-11-13) | +| NGINX Plus | `nginx version: nginx/1.x.y (nginx-plus-rNN)`, with `-pN` for a patch release. **Unverified here**: no Plus binary could be read, and how the 37.x.y.z numbers appear in a binary is not known | F5 naming convention; **unverified** | + +## Fixed releases and downstream status (2026-11-18) + +| Vendor / package | Status | Source | +| --- | --- | --- | +| nginx (upstream) | fixed in **1.31.9** (mainline) and **1.30.7** (stable). Lines 1.29 and older received no fix | tags above; nginx.org (lead) | +| nginx.org packages | `1.31.9-1~trixie` and `1.30.7-1~trixie` (Debian), `1.31.9-r1` / `1.30.7-r1` (Alpine) are what the official images install. nginx.org's package pages could not be read here | [nginx/docker-nginx](https://github.com/nginx/docker-nginx) `mainline/debian/Dockerfile`, `stable/alpine-slim/Dockerfile` at `a2a986d19a` (2026-11-18 16:17 UTC) | +| Docker official `nginx` | **fixed**: tags **1.31.9** and **1.30.7** exist with every variant of the line: (none), `-perl`, `-otel`, `-trixie`, `-trixie-perl`, `-trixie-otel`, `-alpine`, `-alpine-slim`, `-alpine-perl`, `-alpine-otel`, `-alpine3.24`, `-alpine3.24-slim`, `-alpine3.24-perl`, `-alpine3.24-otel`. The 1.30 and 1.31 lines have no `-bookworm` tags (1.29 and older do; they received no fix). **Observed 17:04 UTC:** `1.31.9` and `1.30.7` held linux/amd64 and linux/arm64 only (mainline, still 1.31.8-era, holds eight platforms), and `1.31.9-alpine`, `1.30.7-alpine` were empty indexes: the images were still being published. **17:40 UTC:** `1.31.9` and `1.30.7` had seven platforms but no linux/riscv64 (which `1.31.8` has); `1.30.7-alpine` had amd64, arm, arm64 and s390x but no linux/386. `fix` therefore checks that the target tag has every platform the tree builds (`--platform`), or else every platform the current tag has | registry-1.docker.io tag list and manifests, 2026-11-18 | +| nginxinc/nginx-unprivileged | **not fixed on Docker Hub** at 16:50 UTC (newest tag 1.31.7); the GitHub repository moved to 1.31.9 / 1.30.7 at 16:37 UTC, so the tags are expected (expected, not a fact) | registry tag list; [nginx/docker-nginx-unprivileged](https://github.com/nginx/docker-nginx-unprivileged) `bef9cb1f0c` | +| bitnami/nginx | only `latest` is public (Bitnami moved versioned tags out in 2025); `bitnamilegacy/nginx` stops at **1.29.1** and will receive no fix | registry tag lists | +| Debian | **not fixed** (rechecked 17:47 UTC): the tracker lists nginx vulnerable and unfixed in bookworm (1.22.1-9+deb12u9, security 1.22.1-9+deb12u10), trixie (1.26.3-3+deb13u7, security 1.26.3-3+deb13u10), forky and sid (1.30.6-3), for both CVEs. bullseye (1.18.0-6.1+deb11u3) is not listed. No DSA or DLA (lead, CVE-2026-123007 page, 2026-11-18) | [security-tracker.debian.org CVE-2026-123007](https://security-tracker.debian.org/tracker/CVE-2026-123007), [CVE-2026-123633](https://security-tracker.debian.org/tracker/CVE-2026-123633); deb.debian.org and security.debian.org pools | +| Ubuntu | **not fixed** (rechecked 17:47 UTC): the newest sources are jammy 1.18.0-6ubuntu14.22, noble 1.24.0-2ubuntu7.19, questing 1.28.0-6ubuntu1.8, resolute 1.28.3-2ubuntu1.12, stonking 1.30.4-7ubuntu1.1 (security uploads of 2026-10-24 and 2026-06-19) and the development release 1.30.6-3ubuntu1 (2026-11-06); no changelog names either CVE. Ubuntu's CVE-2026-123007 page lists 26.10, 26.04 LTS, 24.04 LTS, 22.04 LTS, 20.04 LTS, 18.04 LTS and 16.04 LTS as vulnerable with no fixed versions, and 14.04 (nginx 1.4.6) as not affected (lead) | archive.ubuntu.com pool, `debian/changelog` of each; [ubuntu.com/security CVE-2026-123007](https://ubuntu.com/security/CVE-2026-123007) (lead, 2026-11-18) | +| Alpine | **fixed on 3.24 and edge**: main/nginx **1.30.7-r0**, published 2026-11-18 17:06 UTC (v3.24) and 17:11 UTC (edge), an upgrade to the fixed upstream release (aports master and 3.24-stable `pkgver=1.30.7`). **Not fixed** on 3.23 and 3.22 (1.28.3-r7) or 3.21 (1.26.3-r3) at 17:47 UTC; their APKBUILD `secfixes` name neither CVE. (At 16:50 UTC every branch was still unfixed: 3.24 1.30.6-r0, edge 1.30.6-r1.) | dl-cdn.alpinelinux.org APKINDEX (rechecked 17:47 UTC); alpinelinux/aports `main/nginx/APKBUILD` (GitHub mirror) | +| Red Hat (RHEL nginx module streams, UBI) | **not fixed**: Red Hat's CVE-2026-123007 page lists no fixed products, NVRs or errata (CVSS 3.1 8.1, Bugzilla 2575895); its CVE-2026-123633 page returned 404. The detector judges a Red Hat build by its version: vulnerable in range until a fixed build is known | [access.redhat.com CVE-2026-123007](https://access.redhat.com/security/cve/CVE-2026-123007) (lead, 2026-11-18) | +| OpenResty | **not fixed**: newest release 1.31.8.1 bundles nginx 1.31.8; its master (2026-11-07) carries `nginx-1.31.8-*.patch` files and none for these CVEs. OpenResty does backport nginx CVE fixes as patches without a new core (`nginx-1.31.8-CVE-2026-9256.patch`) | [openresty/openresty](https://github.com/openresty/openresty) `util/ver`, `patches/nginx/1.31.8`; Docker Hub `openresty/openresty` tags (newest 1.31.8.1) | +| Tengine | **not fixed**: newest 3.2.0-rc5 (2026-09-04), nginx core 1.31.5; master's `ngx_http_v2.c` has the unfixed WINDOW_UPDATE check and the `ngx_reusable_connection(c, 1)` with `h2c->state.incomplete` that 76672e650 added | [alibaba/tengine](https://github.com/alibaba/tengine) master; **inferred** affected from the source | +| Angie | **not fixed**: newest 1.12.4 (2026-10-16); master (2026-11-13, 1.13.0) has the same unfixed code | [webserver-llc/angie](https://github.com/webserver-llc/angie) master; **inferred** affected from the source | +| Kubernetes ingress-nginx | **no fix, ever**: the project was archived on 2026-03-23; last releases controller v1.15.1, v1.14.5, v1.13.9 (2026-03-19). Their build scripts use nginx **1.27.1**; v1.11 and v1.12 used 1.25.5, v1.5 to v1.10 1.21.6, v1.0.0 1.20.1 (all in both ranges). The chart turns HTTP/2 on by default (`use-http2: true`) and always proxies | kubernetes/ingress-nginx `images/nginx/rootfs/build.sh` and `NGINX_BASE` at each tag, `internal/ingress/controller/config/config.go` (`UseHTTP2: true`, `MaxWorkerConnections: 16384`) at v1.15.1. Built image versions **inferred** from the build scripts | +| F5 NGINX Ingress Controller (`nginx/nginx-ingress`) | **5.8.0** (2026-11-18) builds on nginx **1.31.9** and Plus R37.3; 5.7.1 used 1.31.8. The images' binaries read 1.31.9 and 1.31.8 (parity cases f5-ingress-5.8.0, f5-ingress-5.7.1). The controller writes nginx.conf at start; its ConfigMap key `http2` decides HTTP/2 | nginx/kubernetes-ingress `build/Dockerfile` (`ARG NGINX_OSS_VERSION`) at v5.8.0 and v5.7.1; `nginx/nginx-ingress:5.8.0` sha256:57705208dfa8…6fec37aa, `5.7.1` sha256:b6a970b8fccb…80bb6b480 | +| Traefik, Caddy, Envoy, HAProxy | not nginx: out of scope | n/a | + +## Backports (a fixed package that keeps the nginx version) + +| Downstream | Backports nginx security fixes without a new nginx version? | Source | +| --- | --- | --- | +| Debian | yes (`+debNNuN` releases carry patches) | Debian changelogs | +| Ubuntu | yes (`debian/patches/CVE-*.patch`, `ubuntuN.M` releases) | Ubuntu changelogs above | +| Alpine | yes (`secfixes` on `-rN` releases of the same version, such as 1.28.3-r6) | APKBUILD above | +| Red Hat | yes for other CVEs (module stream builds keep their upstream version); no fix listed for CVE-2026-123007 on 2026-11-18, and no page for CVE-2026-123633 | Red Hat convention, **not verified here**; Red Hat CVE page (lead) | +| OpenResty | yes (`nginx--CVE-*.patch`) | openresty/openresty patches | +| nginx.org, the Docker official image | no: they ship the fixed upstream release | docker-nginx | + +The detector keeps a backport table (`knowledge.Backports`): distribution, release, source package, fixed version, +advisory. It is **empty**: no distribution had published a backported fix on 2026-11-18 (Alpine's fix is the new +upstream release, which the binary's own version shows; `knowledge.AlpineFixed` lists it for the source-tree scan). A row clears a binary only +when the binary's own version is the upstream version of that package and the package database names it the owner +of the binary. + +## How the detector uses this + +- The version that decides is the one in the binary's `nginx version:` line (or `Angie version:`, `Tengine version:`); + every other `nginx/x.y.z` string in it must agree, or the binary is unknown. A version from a package database, a + file name or an image tag never clears a binary on its own. A version on a line newer than any known on the check + date (above 1.31; above 37.3 for NGINX Plus's numbered releases) is unknown, never fixed: NGINX Plus now numbers + its releases 37.x, and how they appear in a binary is not verified. +- A build without a readable version (renamed, `server_tokens`-patched or stripped of the line) is unknown, never + cleared. A build is not affected for lack of HTTP/2 only when its configure arguments were read to their end and its + module list (1.9.11 and later) is present, and neither has HTTP/2; a cut or missing witness leaves it unknown. + HTTP/2 compiled into a core older than nginx's own (1.9.5) is a vendor backport: unknown (also when the witness of + HTTP/2 is cut or missing on a Tengine or NGINX Plus build on such a core), except Tengine 2.1.2 to + 2.2.x (cores 1.6.2 and 1.8.1), whose source carries nginx's unfixed flow-control code and predates the reuse change + (alibaba/tengine `src/http/v2` at `tengine-2.1.2` and `tengine-2.2.2`; the change reached Tengine in 2.4.0). +- Each CVE is judged on its own: a binary below 1.19.7 can be vulnerable to CVE-2026-123007 and not affected by + CVE-2026-123633. +- OpenResty is judged by its nginx core (the first three numbers of its version): a core at or past a fixed release + is fixed; an OpenResty release newer than the newest known one (1.31.8.1) on an unfixed core is unknown, since + OpenResty backports as patches. Tengine and Angie: releases up to the newest known (3.2.0-rc5, 1.12.4) are + vulnerable, later ones unknown; Angie's `nginx/` compatibility number is never used. NGINX Plus is judged by its own + release. +- The configuration decides **exposure**, never the verdict: HTTP/2 off everywhere is reported as "not exposed" on a + finding that stays vulnerable, because the binary still needs the update. +- Exposure reads "not exposed" only when all of this holds; anything else is unknown: + - the command that starts nginx was read, and its nginx word resolves, by path and content the scan read, to the + very binary judged (a relative path against the image's working directory, a bare name through its `PATH`, a + `PATH` search stopping at a link as the runtime does); a base name alone is never trusted, and a binary the + command does not start (`nginx-debug` in the official images) is unknown, or exposed when what it would load + turns HTTP/2 on. Any word before nginx + other than the official entrypoint is unknown: `tini`, `dumb-init`, `env` (with its `PATH` or `--chdir`), `exec`, + `sh -c` and custom scripts included; + - the official entrypoint is recognised by SHA-256 (every version in nginx/docker-nginx and + docker-nginx-unprivileged), is given `nginx` or `nginx-debug` as its first argument, and every file reachable in + `/docker-entrypoint.d` (any name, extension or size, with or without `#!`, through any link) was read and is that + name's official script; a link out of the directory, or a file not read, is unknown. The templates are applied + only then, as `20-envsubst-on-templates.sh` applies them, and only from a template directory the scan reads + whole; `NGINX_ENVSUBST_FILTER` is unknown; + - on a host, the command is the `ExecStart` of the systemd unit that runs that binary: the unit of the first + directory that has it (`/etc`, `/run`, `/lib`, `/usr/lib`), links followed, every drop-in applied, read from disk + below a system root. Its `Environment=` and `EnvironmentFile=` are read for the plain forms only (nginx.org's + pkg-oss unit starts `nginx -c ${conffile} $cmdopts`): a specifier (`%`), a glob in an `EnvironmentFile=` path, a + continued line, an environment file line with `export`, an escape, a variable or an inner quote, an environment + file that is there but not read, more than one `ExecStart=`, an `@`, `|` or `:` prefix, and `PassEnvironment=`, + `UnsetEnvironment=`, `RootDirectory=`, `RootImage=`, `MountImages=`, `ExtensionImages=`, + `ExtensionDirectories=`, `BindPaths=`, `BindReadOnlyPaths=` or `TemporaryFileSystem=` are unknown. A variable + the unit does not set is empty only when the manager's `system.conf` and its drop-ins were read and set no + `DefaultEnvironment=` or `ManagerEnvironment=`, and no environment generator is installed; the kernel command + line (`systemd.setenv=`) is not read. A unit, drop-in, unit directory or environment file not read is unknown. + `ExecStartPre`, `ExecStartPost` and `ExecCondition` (each its own list) may only run `/bin/rm` or `/usr/bin/rm -f` + of the pid file, or a test by the very binary `ExecStart` runs; + - nginx's own option parsing is followed (`-qc file`, `-p`, `-g` whose includes are loaded); a command that only + tests, shows or signals (`-t`, `-T`, `-v`, `-V`, `-s`, `-h`) serves nothing; + - an include the walk could not read (the engine's not-scanned records), one that is not kept, a glob the scan does + not read whole, a configuration generated at start (ingress-nginx, the F5 controller), a template variable left + unset in `listen`, in `http2` or standing for a whole directive (not inside `map`, `geo`, `split_clients`, + `types` or `charset_map`, whose keys may hold `$`), or more than the loader's budget across all includes + (2 Mi tokens, 16 MiB; reading stops there) is unknown; + - in a source tree, an image read from its registry under a deployment that sets its command, arguments, + environment or mounts is unknown: a Compose service (with its override files, `extends` and `volumes_from`), a + Kubernetes container, a GitLab CI service, Helm values whose chart templates (in any subdirectory) set them or are + not in the tree, and a Dockerfile that builds on the image through any chain of stage aliases. What the tree + cannot show is not checked either way: a Compose file merged only with `-f` (`docker-compose.prod.yml`) is not + known to apply to a service, and a GitHub Actions service's `volumes` are not read, so an image read under those + reports its own exposure. +- The configuration read is the one nginx loads: the compiled-in path (a relative one moved by `-p`), or the command's + `-c`; the official image's templates with the image's environment put in as its entrypoint does, when it runs + them. Globs follow glob(3) (`[!x]`, `[[:digit:]]`, no leading dots); symbolic and hard links are followed inside the + target. Below a system root a glob is read from disk: a link that is matched is kept and followed, a linked + directory on the way, or a directory that cannot be listed (`EACCES`), leaves it incomplete, so exposure unknown. nginx keeps + one socket per port: `ssl` and `http2` on any `listen` of it, and the default server's `http2 on`, count for every + server on it. Anything that opens upstream connections while a request is served (`*_pass`, Lua handlers, njs, + `auth_request`, `mirror`, `perl`) counts as a proxy for CVE-2026-123633. +- Findings carry CVSS 9.2 (Wiz). A 32-bit build, HTTP/2 without TLS (CVE-2026-123007) and HTTP/2 without a proxy + directive (CVE-2026-123633) are reported as facts that weaken the published exploit path; none clears a finding. diff --git a/detectors/nginxh2/apkindex.go b/detectors/nginxh2/apkindex.go new file mode 100644 index 0000000..eae81bc --- /dev/null +++ b/detectors/nginxh2/apkindex.go @@ -0,0 +1,101 @@ +package nginxh2 + +import ( + "archive/tar" + "bufio" + "compress/gzip" + "context" + "errors" + "fmt" + "io" + "net/http" + "regexp" + "strings" + "time" + + "github.com/DefectDojo/earlylight/internal/engine" + "github.com/DefectDojo/earlylight/internal/netguard" +) + +// apkMirror is where fix reads an Alpine branch's package index. +const apkMirror = "https://dl-cdn.alpinelinux.org/alpine" + +// maxAPKIndex bounds the index fix reads (main/x86_64 is a few MiB). +const maxAPKIndex = 32 << 20 + +var apkBranch = regexp.MustCompile(`^(?:edge|3\.\d{1,2})$`) + +// apkIndex returns the nginx version in an Alpine branch's main index, +// read through the guarded transport within the timeout. +func apkIndex(o engine.Options) func(context.Context, string) (string, error) { + return func(ctx context.Context, branch string) (string, error) { + if !apkBranch.MatchString(branch) { + return "", fmt.Errorf("%q is not an Alpine branch", branch) + } + dir := branch + if branch != "edge" { + dir = "v" + branch + } + timeout := o.Timeout + if timeout <= 0 { + timeout = 60 * time.Second + } + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, apkMirror+"/"+dir+"/main/x86_64/APKINDEX.tar.gz", nil) + if err != nil { + return "", err + } + resp, err := (&http.Client{Transport: netguard.Transport(o.PublicOnly)}).Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("%s: HTTP %d", req.URL, resp.StatusCode) + } + return nginxInIndex(io.LimitReader(resp.Body, maxAPKIndex)) + } +} + +// nginxInIndex reads the nginx package's version from an APKINDEX.tar.gz. +func nginxInIndex(r io.Reader) (string, error) { + gz, err := gzip.NewReader(r) + if err != nil { + return "", err + } + // The index is a gzip stream of signature then index; read on + // through every member. + gz.Multistream(true) + tr := tar.NewReader(gz) + for { + h, err := tr.Next() + if err != nil { + if errors.Is(err, io.EOF) { + return "", errors.New("the index has no APKINDEX file") + } + return "", err + } + if h.Name != "APKINDEX" { + continue + } + sc := bufio.NewScanner(io.LimitReader(tr, maxAPKIndex)) + sc.Buffer(make([]byte, 64<<10), 1<<20) + pkg := "" + for sc.Scan() { + l := sc.Text() + switch { + case l == "": + pkg = "" + case strings.HasPrefix(l, "P:"): + pkg = l[2:] + case strings.HasPrefix(l, "V:") && pkg == "nginx": + return l[2:], nil + } + } + if err := sc.Err(); err != nil { + return "", err + } + return "", errors.New("the index lists no nginx package") + } +} diff --git a/detectors/nginxh2/entrypoints.go b/detectors/nginxh2/entrypoints.go new file mode 100644 index 0000000..94dac53 --- /dev/null +++ b/detectors/nginxh2/entrypoints.go @@ -0,0 +1,84 @@ +package nginxh2 + +// officialScripts are the SHA-256 of every version of the official nginx +// image's entrypoint and /docker-entrypoint.d scripts, by file name, in +// the history of github.com/nginx/docker-nginx and +// github.com/nginx/docker-nginx-unprivileged (read 2026-11-18). A script +// is trusted only by its content. +var officialScripts = map[string]map[string]bool{ + "10-listen-on-ipv6-by-default.sh": { + "049df3929188dcce3f370da602ada4dbcde7e80b774d3f340f5994cc077e53de": true, + "1431651f608f7e4b33215dec67a1c623cd47a43ab1e783fdcdb5f6ff6e55f7dd": true, + "1ccc7715f8f454b0a1fa43a2b8f3d53778bbadaa3f60662f13f23cc664381cde": true, + "1decbf35705a305ffd6ba18164f7c9af8ee7d3fcf5cb36dd43ea3df58d6a743d": true, + "2f4b260a8a8320ba66d540798898771959de84f16f49f3df1ff22cefbeca8793": true, + "3b1efb4263e482d897d61024b6af352d7e20e950958b462275685161bf550a27": true, + "3e02c931b3adf55e3952e14bdd6cdf5af6341aed658cd5bad3185b47470dc590": true, + "5aeea461961fea4f6cefeca53c6b2cf80275f65fb9787af7e62ff47d7158c48b": true, + "6af73d816765f1a163eff548e120e9cfad5053776ca7c67d0966cdfaafc652dc": true, + "82d049f268c293e0cdbdfd6185683a21fc8f032a8c70aa32534c055f5b28e91c": true, + "8c5d2c912416126c7d65651600b166c00ad9ca3e3af82487ddd5a5da94fb8fb5": true, + "91c84252278f74e5b22f9c573464994691bd4e0b2b7196315342979d49722f79": true, + "95ac0282b4f4841d47f57d1cf8c81334e3d143ff6f8a5df7ca8be5d6e100377c": true, + "9d36e71af5e9adcbf7e4f92835eef678b4b475dfe0838d48ece4445641452c26": true, + "a04b7d0da99a1fc75abfbba9ea9ca371283bd63ed4c242b87705409e8557a591": true, + "a0cd7b5f4f2eca6c416c5f3e64af9b4bedcad1145a61a940159ef2e08a92cc67": true, + "a267cc710deae9a11278c784655c31b6e375fd8c55f1b79c6de948a35280bfe8": true, + "a493f7d754e12a5e8e9c5174c4caa9289296c56b5215be747965a34cbee8b818": true, + "b18798299833e0089b06ad6af65ed23547a922cbe6bbd2358b88a9e8b92fa682": true, + "c4b740384b88b86bc84ecf4237167b16d09d6e35cf9564b676ba1fd0249f6fcc": true, + "c6b6a5501e6fcf309d26a2bf584df9a3b42c626447b417d2d002d2227a9208a4": true, + "d09a9874ae89162d72b53b541eeca42c0f74fc0e881da516f1eb226c460319de": true, + "d2a29aae11e6684ef917182bff5a306cbcf5debc872645d4c35b8b457d364e69": true, + "db9d8be6f3ea527a22c22bdf7fff1f3bcdb3be61a75e5d3e84d128665af33cc4": true, + "dbc37e03540c6641ec3e006a95586ca0da61368659d92546faee54509bd6ad19": true, + "dd39eedf150f68f5e7a4fb9f1637faa7ae26bc56daf97cb90b0c429a4cfedb87": true, + "e296e115fc8e0865145f304db80b773da456692df1fdb4c5fdd435f20a213533": true, + "fe712628e80fc0a52c0bede8071d872a8d5401cee8592bfb58e76e3232baa1fd": true, + }, + "15-local-resolvers.envsh": { + "18cb166b07aac0992725ca6eace13f2386f4f8eda16fece504303d4acc258cbf": true, + "329a1e89cc898599338874f679e22711c4c2d69f65f98b64a72d8b708e69ee44": true, + "3659a4a271496f6a8f0785a1d7e57a9348803e90c08fe57431fe3ee19b010644": true, + "93078c67574883131f8afdbb27c20173674358ca63e4ef67c0fee10429d64c1a": true, + "ac3cca51e959ed97b20ca10a38a24b8404e52f7de50d414a96118902c7858a33": true, + }, + "20-envsubst-on-templates.sh": { + "00d6d14424342d6a3439f4d7af190bfc33b96f40221946b174a6c7385ee3b98c": true, + "253c8724acff9f5c0d0e8938e71fe7c33097d40031a5bc9c7f59dfd2ba5f1377": true, + "372dc96ddf9b2d7c8a974f43c61e77efef539d5f6f8903197987523bc4b31000": true, + "37eb458e54b5c3defd6cb62d15456ba961f5e322c6c50662b81f366a743614e9": true, + "3a2ac24c7e19fe0ab81a7f2ef469cf01a2e86f85802d2e6cbc5d9579cad8ea88": true, + "54ccb0807c9fbde4b23614da27d5071c5a49a2c0c3be419e3f5c2d6c46acc140": true, + "7740f9a27ae6ce89b7c0dc0e8224bc0b9ed364e2440604356468fd8d2c50cc59": true, + "97a871eb3192f4913a9bedd5f4597552f053319a0a54cc65146da27b675b4a53": true, + "ac517b7fe85e59c26241469c89e825305b007566f2dd9b7238fcc3bc36089209": true, + "c62d8bd0c11f43942253ec2e75b9727b69c6cbf598be6517d39ec63fa086b2bf": true, + "ce71637f0fb7a4c2c363f901226af65655e448070ed43a5d43d56449a74d9e75": true, + "d019545eecafccc67a62aba7b351fc83e20f7220a404ba0fb9f02c4e409698f1": true, + "d88f37ff868d0e47c90feaead5f1138a5e6b8a046440e5a8399e091e3e94e239": true, + "e9c68630816e6b8f58a4993b4c43be80c230f44260bb33d3b26738a99e43512c": true, + "f2dd783ed775bc923fe79dd0568c18670d74b0fdc462ff7f3c6343e676f5f671": true, + "fe5c125274976088179762f7918b1a02a1aa1eb5ccad8fd1b46d7d46287410f2": true, + }, + "30-tune-worker-processes.sh": { + "1b99cae15627930024f6f942f0f1744671814de5398ebe9cb65c6ceb9d0a18cf": true, + "1f068aa49da8df46bfd5a917debf110af9b115370739e3be34af83ebf583fbce": true, + "77cf5b2f9a80f0ecf860a6c0f69efa5879b8afdadef24e15cf14d32bde463fcd": true, + "a0f53c5bf9b043b6d14f0643965dabd19059f25ef2cba34b3da53a1cb2dd782c": true, + "b8f0d3f5b52987b19c4875789999372ef45ba1dc9a1849a8737268e7812e5d5e": true, + }, + "docker-entrypoint.sh": { + "026ebfe1f5b9a951c519f040dbcf3f7274e49bfc9eaadb449a9d6f80beed4939": true, + "220b6ae8317ca4c7326158e8246e5f9f45c2bfe3c8792423ba8d6ad61bfa77b6": true, + "324df58250bdb0b35678bcba147282736e2511c46fa1487f48dd394250c91cd3": true, + "3372fd90162da30d09f62c245e9c6bfd620fb0bb5b48ab54b16e804c2b9e8aae": true, + "50a4ca27f8f73ba446478d44b7e0734003c717164b6b7f49077dba708cf8543b": true, + "698acdc803486bbe6a9ab9951e353467584acaade53b112aef2274da3060c598": true, + "81cdfd1ebdd7717981e2a92f563350a7ce012bdcb8a5a62e6521caa6ce600b67": true, + "b288af423e84fd92b50ec944e593ef2505c831a43c639163dadc9db2b4105f1b": true, + "c14d3511ddb4d34fbe3a377a87f70efbd68831bf3f3ad28f67594fe32e0361b6": true, + "caa180b65c1957815db934968c1ee079771fa64f52dae45cc0778015f7cfdc22": true, + "fbb111dbfd1efb9f34e485ba5b1ba243c60561d8d43e64c803ea6ae3b55bcb51": true, + }, +} diff --git a/detectors/nginxh2/fuzz_test.go b/detectors/nginxh2/fuzz_test.go new file mode 100644 index 0000000..229b9c7 --- /dev/null +++ b/detectors/nginxh2/fuzz_test.go @@ -0,0 +1,56 @@ +package nginxh2 + +import ( + "path" + "strings" + "testing" +) + +// FuzzSource: the glob matcher, the symbolic link resolver, template +// substitution and the systemd unit reader take any input without a panic +// or an unbounded loop. +func FuzzSource(f *testing.F) { + f.Add("/etc/nginx/conf.d/[[:digit:]]*.conf", "/etc/nginx/conf.d/10-a.conf", "/etc/nginx/conf.d=../x;/x=/etc", "listen ${A} $B;", "A=1", "ExecStart=-/usr/sbin/nginx -g 'daemon on;'") + f.Add("/a/[!_]*", "/a/.b", "/a=/a", "${", "=", "ExecStart=\nExecStart=nginx \\") + f.Add("/usr/sbin/nginx", "/docker-entrypoint.d/40-x.sh", "/docker-entrypoint.d/sub=/etc;/usr/bin/nginx=../sbin/nginx", "", "PATH=/usr/bin", "#!/bin/sh\n") + // The launcher is the official entrypoint, so the fuzzed file in + // /docker-entrypoint.d and the links reach the directory walk. + ep := official(f, "docker-entrypoint.sh") + tpl := official(f, "20-envsubst-on-templates.sh") + f.Fuzz(func(t *testing.T, pattern, p, links, tmpl, env, unit string) { + globMatch(pattern, p) + posixClasses(pattern) + lm := map[string]string{} + for _, kv := range strings.Split(links, ";") { + if k, v, ok := strings.Cut(kv, "="); ok && len(lm) < 32 { + lm[path.Clean("/"+k)] = v + } + } + s := &confSource{kept: map[string][]byte{p: []byte(tmpl)}, links: lm, hardlinks: map[string]string{p: pattern}} + s.resolve(p) + s.Read(p) + s.Glob(pattern) + envsubst([]byte(tmpl), strings.Split(env, ",")) + unitWords(unit) + us := &scan{db: map[string][]byte{"/lib/systemd/system/nginx.service": []byte(unit), "/etc/systemd/system/nginx.service.d/a.conf": []byte(tmpl)}} + us.systemdStarts(&confSource{links: lm}) + nginxTest(unitWords(unit)) + vars, _ := envFile([]byte(tmpl)) + expandUnit(unit, vars) + unsetVar(unit, vars) + execPrefix(unit) + harmless(unitWords(unit), "/run/nginx.pid", "/usr/sbin/nginx") + resolveCommand(p, pattern, strings.Split(env, ","), func(q string) bool { return q == pattern }) + fuzzed := "/docker-entrypoint.d/" + path.Base(p) + ls := &scan{db: map[string][]byte{"/docker-entrypoint.d/20-envsubst-on-templates.sh": tpl}, + scripts: map[string][]byte{"/docker-entrypoint.sh": ep, fuzzed: []byte(unit)}, + epSeen: map[string]bool{fuzzed: true, "/docker-entrypoint.d/" + path.Base(pattern): true}} + cmds := ls.commands(lm, nil, pattern, strings.Split(env, ","), nil) + ok, _ := cmds.launcher("/docker-entrypoint.sh") + cmds.launcher(p) + cmds.starts(p, pattern) + if b := path.Base(p); ok && b != "." && b != "/" && !strings.Contains(b, "/") && !officialScripts[b][sha([]byte(unit))] && len(lm) == 0 { + t.Fatalf("the entrypoint passed with %s not official", fuzzed) + } + }) +} diff --git a/detectors/nginxh2/internal/assess/assess.go b/detectors/nginxh2/internal/assess/assess.go new file mode 100644 index 0000000..2146fbd --- /dev/null +++ b/detectors/nginxh2/internal/assess/assess.go @@ -0,0 +1,438 @@ +// Package assess decides, for each nginx binary and each CVE of the pair, +// what the binary proves (vulnerable, fixed, not affected, unknown) and +// what the configuration it loads says about exposure. Exposure never +// changes a verdict: a server with HTTP/2 off still needs the update. It +// knows nothing about the engine. +package assess + +import ( + "fmt" + "sort" + "strings" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/conf" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/knowledge" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngx" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/pkgdb" +) + +// Kind IDs, one per CVE. +const ( + KindFlow = "flow-control" + KindReuse = "connection-reuse" +) + +// KindOf is the kind for a CVE. +func KindOf(cve string) string { + if cve == knowledge.Reuse { + return KindReuse + } + return KindFlow +} + +// Input is one target. +type Input struct { + Binaries []*ngx.Binary + // Source serves configuration files. + Source conf.Source + // Owner returns the package that owns a binary, nil when none does or + // the database was not read. + Owner func(p string) *pkgdb.Package + // Distro is the os-release family (debian, ubuntu, alpine, rhel) and + // Release its VERSION_ID (Alpine: the branch). + Distro, Release string + // Command is what starts nginx: an image's container command, or the + // ExecStart of a host's service unit; nil when none was found. + Command []string + // CommandFrom says where Command came from ("the image's command"). + CommandFrom string + // CommandFor, when set, gives the start command of one binary (a + // host's service unit), where it came from, and why there is none. + CommandFor func(binary string) (cmd []string, from, none string) + // Launcher, when set, says whether a word that runs before nginx in + // the command can be passed over: the official image's entrypoint, + // recognised by its content and its scripts'. + Launcher func(word string) (bool, string) + // Starts says whether a command word that starts nginx resolves (as + // the runtime resolves it) to the binary judged. + Starts func(word, binary string) (bool, string) + // Ingress is set when the target holds the ingress-nginx controller, + // which writes nginx.conf at start with HTTP/2 on by default. + Ingress bool + // Generated says why the configuration on disk is not the one that + // runs (a controller writes it at start); exposure is then unknown. + Generated string +} + +// Finding is one CVE's verdict on one binary. +type Finding struct { + CVE string `json:"cve"` + Kind string `json:"kind"` + Path string `json:"path"` + Status knowledge.Status `json:"status"` + Reason string `json:"reason"` + Message string `json:"message"` + Fix string `json:"fix,omitempty"` + Severity string `json:"severity,omitempty"` + State conf.State `json:"exposure"` + Facts map[string]string `json:"facts"` + Binary *ngx.Binary `json:"binary"` + Package *pkgdb.Package `json:"package,omitempty"` + Config *conf.Exposure `json:"config,omitempty"` +} + +// Run judges every binary. +func Run(in Input) []Finding { + var out []Finding + cache := map[string]cached{} + for _, b := range in.Binaries { + main, extra, how, unsure := configFor(b, in) + exp, cfgFiles := exposure(in, main, extra, cache) + if unsure != "" && exp != nil && in.Generated == "" && !in.Ingress { + // The configuration read may not be the one that runs: a + // stronger answer from it stands, a weaker one is unknown. + x := *exp + x.Unread = append(append([]string(nil), x.Unread...), unsure) + if x.Flow != conf.Exposed { + x.Flow = conf.Unknown + } + if x.Reuse != conf.Exposed { + x.Reuse = conf.Unknown + } + if x.HTTP2 == "off" { + x.HTTP2 = "unknown" + } + exp = &x + } + var pkg *pkgdb.Package + if in.Owner != nil { + pkg = in.Owner(b.Path) + } + for _, c := range knowledge.CVEs { + st, why := judge(c, b) + st, why = backport(c, st, why, b, pkg, in) + f := Finding{CVE: c.ID, Kind: KindOf(c.ID), Path: b.Path, Status: st, Reason: why, Binary: b, Package: pkg, Config: exp} + f.State = stateFor(c.ID, exp) + f.Facts = facts(b, pkg, exp, f.State, main, how, cfgFiles, in) + f.Message = message(c, b, f) + f.Fix = fixText(f, pkg, in.Distro, in.Release) + if st == knowledge.Vulnerable { + f.Severity = severity(f.State) + } + out = append(out, f) + } + } + sort.SliceStable(out, func(i, j int) bool { + if out[i].Path != out[j].Path { + return out[i].Path < out[j].Path + } + return out[i].CVE < out[j].CVE + }) + return out +} + +func stateFor(cve string, e *conf.Exposure) conf.State { + if e == nil { + return conf.Unknown + } + if cve == knowledge.Reuse { + return e.Reuse + } + return e.Flow +} + +// judge decides from the binary alone. +func judge(c knowledge.CVE, b *ngx.Binary) (knowledge.Status, string) { + if b.Conflict != "" { + return knowledge.Unknown, b.Conflict + ": not judged by either" + } + var st knowledge.Status + var why string + switch b.Product { + case ngx.Hidden: + st, why = knowledge.Unknown, "an nginx binary without a readable version line (renamed, patched or stripped of it): it is never cleared" + if b.HTTP2 == ngx.No { + why += "; its configure arguments do not include HTTP/2, which would make it not affected if they are the build's own" + } + return st, why + case ngx.Other: + return knowledge.Unknown, fmt.Sprintf("an nginx build that names itself %q in its version line: what it is based on is not known", b.Name+"/"+b.Version) + case ngx.Nginx: + v, err := knowledge.ParseV(b.Version) + if err != nil { + return knowledge.Unknown, "its version could not be read: " + err.Error() + } + st, why = knowledge.Nginx(c, v) + case ngx.OpenResty: + v, err := knowledge.ParseV(b.Version) + if err != nil { + return knowledge.Unknown, "its OpenResty version could not be read: " + err.Error() + } + st, why = knowledge.OpenResty(c, v) + case ngx.Tengine: + v, err := knowledge.ParseV(b.Version) + if err != nil { + return knowledge.Unknown, "its Tengine version could not be read: " + err.Error() + } + core, _ := knowledge.ParseV(b.Core) + st, why = knowledge.Tengine(c, v, core, b.HTTP2 == ngx.Yes) + case ngx.Angie: + v, err := knowledge.ParseV(b.Version) + if err != nil { + return knowledge.Unknown, "its Angie version could not be read: " + err.Error() + } + st, why = knowledge.Angie(c, v) + case ngx.Plus: + core, _ := knowledge.ParseV(b.Core) + st, why = knowledge.Plus(c, b.PlusRelease, core) + default: + return knowledge.Unknown, "not an nginx build the detector knows" + } + if b.HTTP2 == ngx.Unknown && st == knowledge.NotAffected && (b.Product == ngx.Tengine || b.Product == ngx.Plus) { + if core, err := knowledge.ParseV(b.Core); err == nil && knowledge.Cmp(core, knowledge.MustV("1.9.5")) < 0 { + // A fork may carry HTTP/2 on a core that predates nginx's + // (Tengine 2.1.2 to 2.2.x do): without a whole witness of what + // is compiled in, the core's age clears nothing. + return knowledge.Unknown, fmt.Sprintf("%s is built on nginx %s, older than nginx's own HTTP/2, and whether HTTP/2 is compiled in could not be read (its configure arguments were cut or it has no module list)", b.Name+"/"+b.Version, b.Core) + } + } + if b.HTTP2 == ngx.Yes && b.Product != ngx.Tengine && st == knowledge.NotAffected { + if core, err := knowledge.ParseV(b.Core); err == nil && knowledge.Cmp(core, knowledge.MustV("1.9.5")) < 0 { + // HTTP/2 compiled into a core that predates nginx's: a + // vendor's own backport, whose code is not known. + return knowledge.Unknown, fmt.Sprintf("HTTP/2 is compiled into a build on nginx %s, older than nginx's own HTTP/2 (1.9.5): a vendor backport, whose code is not known", b.Core) + } + } + if b.HTTP2 == ngx.No && (st == knowledge.Vulnerable || st == knowledge.Unknown) { + return knowledge.NotAffected, "built without HTTP/2: its configure arguments, read to their end, do not have --with-http_v2_module and its module list has no ngx_http_v2_module, so the flawed code is not in it" + } + return st, why +} + +// backport clears a vulnerable distribution build when the backport table +// lists a fixed package and the binary is that package's build: the +// package database names it the owner, and its version is the package's +// upstream version. No row exists yet (FACTS.md). +func backport(c knowledge.CVE, st knowledge.Status, why string, b *ngx.Binary, pkg *pkgdb.Package, in Input) (knowledge.Status, string) { + if st != knowledge.Vulnerable || pkg == nil || in.Distro == "" || knowledge.NginxOrgMaintainer(pkg.Maintainer) { + return st, why + } + up, err := knowledge.UpstreamOf(pkg.Version) + if err != nil || up.String() != b.Version { + return st, why + } + for _, r := range knowledge.Backports { + if r.Distro != in.Distro || r.Release != "" && r.Release != in.Release || r.Package != pkg.Source || !has(r.CVEs, c.ID) { + continue + } + cmp, ok := 0, true + switch pkg.Manager { + case "dpkg": + cmp = pkgdb.CompareDpkg(pkg.Version, r.Fixed) + case "apk": + cmp, ok = pkgdb.CompareAPK(pkg.Version, r.Fixed) + default: + ok = false + } + if !ok { + return knowledge.Unknown, why + fmt.Sprintf("; its package version %s could not be compared with the backport %s", pkg.Version, r.Fixed) + } + if cmp >= 0 { + return knowledge.Fixed, fmt.Sprintf("%s %s is at or past the build %s lists as fixed (%s; %s)", pkg.Name, pkg.Version, r.Distro, r.Fixed, r.Advisory) + } + } + return st, why +} + +func has(xs []string, s string) bool { + for _, x := range xs { + if x == s { + return true + } + } + return false +} + +type cached struct { + e *conf.Exposure + files int +} + +func exposure(in Input, main string, extra []conf.Directive, cache map[string]cached) (*conf.Exposure, int) { + if in.Ingress { + e := &conf.Exposure{HTTP2: "on", Flow: conf.Exposed, Reuse: conf.Exposed, + Where: []string{"ingress-nginx writes nginx.conf at start: HTTP/2 is on by default (ConfigMap use-http2, default true) on its TLS listeners, and every Ingress is proxied"}} + return e, 0 + } + if in.Generated != "" { + return &conf.Exposure{HTTP2: "unknown", Flow: conf.Unknown, Reuse: conf.Unknown, Unread: []string{in.Generated}}, 0 + } + if in.Source == nil { + return nil, 0 + } + key := main + "\x00" + fmt.Sprint(extra) + if c, ok := cache[key]; ok { + return c.e, c.files + } + c := conf.Load(in.Source, main, extra) + e := conf.Analyze(c) + cache[key] = cached{&e, len(c.Files)} + return &e, len(c.Files) +} + +func severity(s conf.State) string { + switch s { + case conf.Exposed: + return "critical" + case conf.Unknown: + return "high" + } + return "medium" +} + +func facts(b *ngx.Binary, pkg *pkgdb.Package, e *conf.Exposure, st conf.State, main, how string, files int, in Input) map[string]string { + f := map[string]string{"product": string(b.Product), "http2_module": string(b.HTTP2), "tls_module": string(b.TLS), "exposure": string(st), "config": main, "config_from": how} + if b.Version != "" { + f["version"] = b.Version + } + if b.Core != "" && b.Core != b.Version { + f["nginx_core"] = b.Core + } + if b.Build != "" { + f["build"] = b.Build + } + if b.Bits != 0 { + f["bits"] = fmt.Sprint(b.Bits) + } + if b.Arch != "" { + f["arch"] = b.Arch + } + if pkg != nil { + f["package"] = pkg.Name + " " + pkg.Version + } + if in.Distro != "" { + f["distro"] = in.Distro + if in.Release != "" { + f["distro"] += " " + in.Release + } + } + if e != nil { + f["http2"] = e.HTTP2 + if len(e.Where) > 0 { + f["http2_where"] = strings.Join(e.Where, ", ") + } + if len(e.Proxy) > 0 { + f["proxy_where"] = strings.Join(e.Proxy, ", ") + } + if e.WorkerConnections != "" { + f["worker_connections"] = e.WorkerConnections + } + if files > 0 { + f["config_files"] = fmt.Sprint(files) + } + } + return f +} + +func productName(b *ngx.Binary) string { + switch b.Product { + case ngx.Hidden: + return "nginx (version not readable)" + case ngx.Plus: + return "NGINX Plus " + b.PlusRelease + " (nginx " + b.Version + ")" + case ngx.OpenResty: + return "OpenResty " + b.Version + case ngx.Tengine: + return "Tengine " + b.Version + case ngx.Angie: + return "Angie " + b.Version + } + return b.Name + " " + b.Version +} + +func message(c knowledge.CVE, b *ngx.Binary, f Finding) string { + var verb string + switch f.Status { + case knowledge.Vulnerable: + verb = "is vulnerable to" + case knowledge.Fixed: + verb = "reports a version with the fix for" + case knowledge.NotAffected: + verb = "is not affected by" + default: + verb = "may be vulnerable to" + } + m := fmt.Sprintf("%s at %s %s %s (%s): %s.", productName(b), b.Path, verb, c.ID, c.Short, f.Reason) + if f.Status == knowledge.Vulnerable || f.Status == knowledge.Unknown { + m += " " + exposureText(c.ID, f) + if b.Bits == 32 && c.ID == knowledge.Flow { + m += " It is a 32-bit build; the published exploit needs a 64-bit one, but the memory corruption is the same." + } + if b.TLS == ngx.No && c.ID == knowledge.Flow { + m += " It is built without TLS; the published path is through TLS." + } + } + return m +} + +func exposureText(cve string, f Finding) string { + e := f.Config + where := "" + if e != nil && len(e.Where) > 0 { + where = " (" + strings.Join(e.Where, ", ") + ")" + } + switch f.State { + case conf.Exposed: + if cve == knowledge.Reuse { + return "HTTP/2 is on in front of a proxy" + where + ": the published preconditions hold, apart from worker_connections being nearly exhausted." + } + return "HTTP/2 is on over TLS" + where + ": the published preconditions hold." + case conf.Cleartext: + return "HTTP/2 is on only without TLS" + where + "; the published path is through TLS, so this configuration is reported as less exposed, not safe." + case conf.NoProxy: + return "HTTP/2 is on" + where + " but no server with it proxies to an upstream; the published path needs a reverse proxy, so this configuration is reported as less exposed, not safe." + case conf.NotExposed: + return fmt.Sprintf("HTTP/2 is off in every file of %s that was read: not exposed through this configuration, but the binary still needs the update.", f.Facts["config"]) + } + why := "the configuration was not found" + if e != nil && len(e.Unread) > 0 { + why = e.Unread[0] + } + return "Whether HTTP/2 is on is not known: " + why + "." +} + +func fixText(f Finding, pkg *pkgdb.Package, distro, release string) string { + switch f.Status { + case knowledge.Fixed, knowledge.NotAffected: + return "" + } + b := f.Binary + var s string + switch { + case b.Product == ngx.OpenResty: + s = "Update OpenResty to a release on nginx 1.31.9 or later, or one that carries the fix as a patch; none was published on " + knowledge.Checked + "." + case b.Product == ngx.Tengine: + s = "Tengine had published no fixed release on " + knowledge.Checked + "; apply upstream commits e27f5fa84 and 2df48a501 or move to nginx 1.31.9 / 1.30.7." + case b.Product == ngx.Angie: + s = "Angie had published no fixed release on " + knowledge.Checked + "; update Angie when it does." + case b.Product == ngx.Plus: + s = "Update NGINX Plus to 37.0.8.1 or 37.3.0.1 (both CVEs on 37.0 and 37.3; 37.2.0.1 fixes CVE-2026-123633 only)." + case pkg != nil && !knowledge.NginxOrgMaintainer(pkg.Maintainer) && distro == "alpine": + if v, ok := knowledge.AlpineFixed[release]; ok { + s = "Upgrade the package: apk upgrade " + pkg.Name + " (" + v + " on Alpine " + release + ", published " + knowledge.Checked + "), or rebuild the image." + } else { + s = knowledge.AlpineText(release) + ". Move to Alpine 3.24 (nginx 1.30.7-r0), or to nginx.org's 1.31.9 / 1.30.7 packages." + } + case pkg != nil && !knowledge.NginxOrgMaintainer(pkg.Maintainer) && distro != "" && knowledge.DistroStatus[distro] != "": + s = knowledge.DistroStatus[distro] + ". Update the " + pkg.Name + " package when a fixed one is published, or move to nginx.org's 1.31.9 / 1.30.7 packages." + default: + s = knowledge.UpdateText + } + if f.Status == knowledge.Vulnerable && f.State != conf.NotExposed { + s += " " + knowledge.Interim + } + if f.Status == knowledge.Unknown { + s = "Check which release this is (nginx -V) and update to a fixed one if it is not. " + s + } + return s +} diff --git a/detectors/nginxh2/internal/assess/assess_test.go b/detectors/nginxh2/internal/assess/assess_test.go new file mode 100644 index 0000000..482c7fc --- /dev/null +++ b/detectors/nginxh2/internal/assess/assess_test.go @@ -0,0 +1,393 @@ +package assess + +import ( + "path" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/conf" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/knowledge" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngx" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngxtest" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/pkgdb" +) + +type mem map[string]string + +func (m mem) Read(p string) ([]byte, bool, string) { + s, ok := m[p] + return []byte(s), ok, "missing" +} + +func (m mem) Glob(pattern string) ([]string, bool) { + var out []string + for p := range m { + if ok, _ := path.Match(pattern, p); ok { + out = append(out, p) + } + } + return out, true +} + +func bin(t *testing.T, b ngxtest.Build) *ngx.Binary { + t.Helper() + x, ok := ngx.Inspect("/usr/sbin/nginx", b.Bytes()) + if !ok { + t.Fatal("not an nginx binary") + } + return x +} + +func byCVE(fs []Finding) map[string]Finding { + out := map[string]Finding{} + for _, f := range fs { + out[f.CVE] = f + } + return out +} + +const h2conf = "http { server { listen 443 ssl http2; location / { proxy_pass http://u; } } }" + +func TestRunExposed(t *testing.T) { + fs := byCVE(Run(Input{Binaries: []*ngx.Binary{bin(t, ngxtest.Default("1.31.8"))}, Source: mem{"/etc/nginx/nginx.conf": h2conf}})) + for _, id := range []string{knowledge.Flow, knowledge.Reuse} { + f := fs[id] + if f.Status != knowledge.Vulnerable || f.State != conf.Exposed || f.Severity != "critical" || f.Facts["http2"] != "on" { + t.Errorf("%s: %+v", id, f) + } + if !strings.Contains(f.Fix, "1.31.9") || !strings.Contains(f.Fix, "it is not a fix") { + t.Errorf("%s fix: %s", id, f.Fix) + } + } + if fs[knowledge.Flow].Kind != KindFlow || fs[knowledge.Reuse].Kind != KindReuse { + t.Error("kinds") + } +} + +func TestRunNotExposedStaysVulnerable(t *testing.T) { + fs := byCVE(Run(Input{Binaries: []*ngx.Binary{bin(t, ngxtest.Default("1.30.6"))}, Source: mem{"/etc/nginx/nginx.conf": "http { server { listen 80; } }"}, + Command: []string{"nginx", "-g", "daemon off;"}, Starts: okStarts})) + f := fs[knowledge.Flow] + if f.Status != knowledge.Vulnerable || f.State != conf.NotExposed || f.Severity != "medium" || !strings.Contains(f.Message, "still needs the update") { + t.Errorf("%+v", f) + } + if strings.Contains(f.Fix, "it is not a fix") { + t.Error("the interim mitigation was offered where HTTP/2 is already off") + } + // No configuration at all: unknown exposure, still vulnerable. + fs = byCVE(Run(Input{Binaries: []*ngx.Binary{bin(t, ngxtest.Default("1.30.6"))}, Source: mem{}})) + if f := fs[knowledge.Flow]; f.Status != knowledge.Vulnerable || f.State != conf.Unknown || f.Severity != "high" { + t.Errorf("no config: %+v", f) + } +} + +func TestRunSplitsCVEs(t *testing.T) { + fs := byCVE(Run(Input{Binaries: []*ngx.Binary{bin(t, ngxtest.Default("1.18.0"))}, Source: mem{}})) + if fs[knowledge.Flow].Status != knowledge.Vulnerable || fs[knowledge.Reuse].Status != knowledge.NotAffected { + t.Errorf("1.18.0: flow %s reuse %s", fs[knowledge.Flow].Status, fs[knowledge.Reuse].Status) + } +} + +func TestRunNoHTTP2(t *testing.T) { + b := ngxtest.Default("1.31.8") + b.Configure, b.Modules = "--prefix=/etc/nginx --with-http_ssl_module", []string{"ngx_core_module"} + fs := Run(Input{Binaries: []*ngx.Binary{bin(t, b)}, Source: mem{}}) + for _, f := range fs { + if f.Status != knowledge.NotAffected || f.Fix != "" { + t.Errorf("%+v", f) + } + } + // A hidden version is never cleared, HTTP/2 or not. + b.Line, b.Extra = "", nil + for _, f := range Run(Input{Binaries: []*ngx.Binary{bin(t, b)}, Source: mem{}}) { + if f.Status != knowledge.Unknown { + t.Errorf("hidden: %+v", f) + } + } +} + +func TestRunConflictUnknown(t *testing.T) { + b := ngxtest.Default("1.31.9") + b.Extra = []string{"Server: nginx/1.31.8\r\n"} + for _, f := range Run(Input{Binaries: []*ngx.Binary{bin(t, b)}, Source: mem{}}) { + if f.Status != knowledge.Unknown { + t.Errorf("%+v", f) + } + } +} + +func TestRunCommandConfig(t *testing.T) { + src := mem{"/etc/nginx/nginx.conf": "http { server { listen 80; } }", "/app/nginx.conf": h2conf} + in := Input{Binaries: []*ngx.Binary{bin(t, ngxtest.Default("1.31.8"))}, Source: src, + Command: []string{"/docker-entrypoint.sh", "nginx", "-c", "/app/nginx.conf", "-g", "daemon off;"}, CommandFrom: "the container command", Starts: okStarts, + Launcher: func(w string) (bool, string) { return w == "/docker-entrypoint.sh", "" }} + f := byCVE(Run(in))[knowledge.Flow] + if f.State != conf.Exposed || f.Facts["config"] != "/app/nginx.conf" || f.Facts["config_from"] != "the container command's -c" { + t.Errorf("%+v", f.Facts) + } + in.Command = []string{"nginx", "-p", "/app/", "-cnginx.conf"} + if f := byCVE(Run(in))[knowledge.Flow]; f.Facts["config"] != "/app/nginx.conf" { + t.Errorf("-p/-c: %+v", f.Facts) + } +} + +func TestRunIngress(t *testing.T) { + b := ngxtest.Default("1.27.1") + fs := byCVE(Run(Input{Binaries: []*ngx.Binary{bin(t, b)}, Source: mem{"/etc/nginx/nginx.conf": "# placeholder"}, Ingress: true})) + if f := fs[knowledge.Reuse]; f.State != conf.Exposed || f.Status != knowledge.Vulnerable { + t.Errorf("%+v", f) + } +} + +func TestBackport(t *testing.T) { + saved := knowledge.Backports + defer func() { knowledge.Backports = saved }() + knowledge.Backports = []knowledge.Backport{{Distro: "debian", Release: "12", Package: "nginx", Fixed: "1.22.1-9+deb12u11", CVEs: []string{knowledge.Flow}, Advisory: "DSA-test"}} + b := ngxtest.Default("1.22.1") + owner := func(v, maint string) func(string) *pkgdb.Package { + return func(string) *pkgdb.Package { + return &pkgdb.Package{Manager: "dpkg", Name: "nginx", Source: "nginx", Version: v, Maintainer: maint} + } + } + run := func(v, maint, distro, rel string) map[string]Finding { + return byCVE(Run(Input{Binaries: []*ngx.Binary{bin(t, b)}, Source: mem{}, Owner: owner(v, maint), Distro: distro, Release: rel})) + } + fs := run("1.22.1-9+deb12u11", "Debian Nginx Maintainers", "debian", "12") + if fs[knowledge.Flow].Status != knowledge.Fixed || fs[knowledge.Reuse].Status != knowledge.Vulnerable { + t.Errorf("backport: flow %s reuse %s", fs[knowledge.Flow].Status, fs[knowledge.Reuse].Status) + } + for _, c := range []struct{ v, maint, distro, rel, why string }{ + {"1.22.1-9+deb12u10", "Debian", "debian", "12", "older package"}, + {"1.22.1-9+deb12u11", "Debian", "debian", "13", "other release"}, + {"1.22.1-9+deb12u11", "Debian", "ubuntu", "12", "other distro"}, + {"1.22.1-9+deb12u11", "NGINX Packaging ", "debian", "12", "nginx.org package"}, + {"1.24.0-9+deb12u11", "Debian", "debian", "12", "package not the binary's version"}, + } { + if st := run(c.v, c.maint, c.distro, c.rel)[knowledge.Flow].Status; st != knowledge.Vulnerable { + t.Errorf("%s: %s", c.why, st) + } + } + // No owner: the table cannot apply. + fs = byCVE(Run(Input{Binaries: []*ngx.Binary{bin(t, b)}, Source: mem{}, Distro: "debian", Release: "12"})) + if fs[knowledge.Flow].Status != knowledge.Vulnerable { + t.Error("cleared without a package owner") + } +} + +func TestDistroFixText(t *testing.T) { + b := ngxtest.Default("1.30.6") + fs := byCVE(Run(Input{Binaries: []*ngx.Binary{bin(t, b)}, Source: mem{}, Distro: "alpine", Release: "3.24", + Owner: func(string) *pkgdb.Package { + return &pkgdb.Package{Manager: "apk", Name: "nginx", Version: "1.30.6-r0", Maintainer: "Jakub Jirutka"} + }})) + if f := fs[knowledge.Flow]; !strings.Contains(f.Fix, "apk upgrade nginx (1.30.7-r0 on Alpine 3.24") || f.Facts["package"] != "nginx 1.30.6-r0" { + t.Errorf("%+v", f) + } + fs = byCVE(Run(Input{Binaries: []*ngx.Binary{bin(t, ngxtest.Default("1.28.3"))}, Source: mem{}, Distro: "alpine", Release: "3.23", + Owner: func(string) *pkgdb.Package { + return &pkgdb.Package{Manager: "apk", Name: "nginx", Version: "1.28.3-r7", Maintainer: "Jakub Jirutka"} + }})) + if f := fs[knowledge.Flow]; !strings.Contains(f.Fix, "Alpine 3.23 had no fixed nginx package") { + t.Errorf("3.23: %s", f.Fix) + } +} + +func TestConfigFor(t *testing.T) { + b := &ngx.Binary{ConfPath: "", Prefix: ""} + if m, _, how, _ := configFor(b, Input{}); m != "/usr/local/nginx/conf/nginx.conf" || how != "nginx's default" { + t.Errorf("%s %s", m, how) + } + if _, _, unsure := startArgs([]string{"sh", "-c", "echo"}, nil); unsure == "" { + t.Error("a command without nginx") + } +} + +func TestConfigForPrefixAndShell(t *testing.T) { + or := ngxtest.Default("x") + or.Line, or.ConfPath, or.Configure = "openresty/1.31.8.1", "conf/nginx.conf", "--prefix=/usr/local/openresty/nginx --with-http_v2_module" + or.Extra = []string{" -p prefix : set prefix path (default: /usr/local/openresty/nginx/)"} + b := bin(t, or) + if m, _, _, _ := configFor(b, Input{}); m != "/usr/local/openresty/nginx/conf/nginx.conf" { + t.Errorf("default: %s", m) + } + if m, _, how, _ := configFor(b, Input{Command: []string{"openresty", "-p", "/app/", "-g", "daemon off;"}}); m != "/app/conf/nginx.conf" || !strings.Contains(how, "-p") { + t.Errorf("-p: %s %s", m, how) + } + // An absolute compiled-in path does not move with -p. + if m, _, _, _ := configFor(bin(t, ngxtest.Default("1.31.8")), Input{Command: []string{"nginx", "-p", "/app/"}}); m != "/etc/nginx/nginx.conf" { + t.Errorf("absolute: %s", m) + } + // A shell start is not read (round 5): unsure. + if _, _, _, unsure := configFor(bin(t, ngxtest.Default("1.31.8")), Input{Command: []string{"/bin/sh", "-c", "exec nginx -c '/app/nginx.conf' -g 'daemon off;'"}, Starts: okStarts}); unsure == "" { + t.Error("sh -c was read") + } + m, _, how, unsure := configFor(bin(t, ngxtest.Default("1.31.8")), Input{Command: []string{"nginx", "-c", "/app/nginx.conf", "-g", "daemon off;"}, Starts: okStarts}) + if m != "/app/nginx.conf" || unsure != "" || !strings.Contains(how, "-c") { + t.Errorf("-c: %s %s %q", m, how, unsure) + } + // Something that writes the configuration first: unsure. + if _, _, _, unsure := configFor(bin(t, ngxtest.Default("1.31.8")), Input{Command: []string{"/bin/sh", "-c", "envsubst < /t > /etc/nginx/x.conf && exec nginx"}}); unsure == "" { + t.Error("envsubst before nginx was not noted") + } + if _, _, _, unsure := configFor(bin(t, ngxtest.Default("1.31.8")), Input{Command: []string{"sh", "-c", "nginx -c $CONF"}}); unsure == "" { + t.Error("a variable in the shell text was not noted") + } + // Unsure: a weaker answer becomes unknown. + fs := byCVE(Run(Input{Binaries: []*ngx.Binary{bin(t, ngxtest.Default("1.31.8"))}, Source: mem{"/etc/nginx/nginx.conf": "http { server { listen 80; } }"}, + Command: []string{"sh", "-c", "nginx -c $CONF"}})) + if f := fs[knowledge.Flow]; f.State != conf.Unknown { + t.Errorf("unsure: %+v", f.State) + } +} + +// Review 2, finding 2: exposure is "not exposed" only when the command +// that starts nginx, and everything it loads, were read. +func TestR2StartCommand(t *testing.T) { + off := mem{"/etc/nginx/nginx.conf": "http { server { listen 80; } }", "/x.conf": "http { server { listen 80; } }", + "/etc/nginx/h2.conf": "http { server { listen 443 ssl http2; } }"} + // The launcher stands for the adapter's content check: only + // /docker-entrypoint.sh is the official entrypoint here. + trusted := func(w string) (bool, string) { return w == "/docker-entrypoint.sh", "not the official entrypoint" } + run := func(cmd []string) conf.State { + return byCVE(Run(Input{Binaries: []*ngx.Binary{bin(t, ngxtest.Default("1.31.8"))}, Source: off, Command: cmd, Starts: okStarts, Launcher: trusted}))[knowledge.Flow].State + } + for _, c := range []struct { + name string + cmd []string + want conf.State + }{ + {"official", []string{"/docker-entrypoint.sh", "nginx", "-g", "daemon off;"}, conf.NotExposed}, + {"tini", []string{"/sbin/tini", "--", "nginx", "-g", "daemon off;"}, conf.Unknown}, + {"no command", nil, conf.Unknown}, + {"s6 init", []string{"/init"}, conf.Unknown}, + {"start script", []string{"/start.sh"}, conf.Unknown}, + {"forego", []string{"forego", "start", "-r"}, conf.Unknown}, + {"supervisord", []string{"supervisord", "-c", "/etc/supervisord.conf"}, conf.Unknown}, + {"wrapper then nginx", []string{"/usr/local/bin/wrap", "nginx"}, conf.Unknown}, + {"sed in sh -c", []string{"sh", "-c", "sed -i 's/listen 80;/listen 443 ssl http2;/' /etc/nginx/nginx.conf && nginx -g 'daemon off;'"}, conf.Unknown}, + {"exec in sh -c", []string{"sh", "-c", "exec nginx -g 'daemon off;'"}, conf.Unknown}, + {"continuation", []string{"sh", "-c", "exec nginx \\\n -c /etc/nginx/h2.conf"}, conf.Unknown}, + {"-qc", []string{"nginx", "-qc", "/etc/nginx/h2.conf"}, conf.Exposed}, + {"-g include", []string{"nginx", "-c", "/x.conf", "-g", "include /etc/nginx/h2.conf;"}, conf.Exposed}, + } { + if got := run(c.cmd); got != c.want { + t.Errorf("%s: %s, want %s", c.name, got, c.want) + } + } + // No launcher check at all: any wrapper is unknown. + if got := byCVE(Run(Input{Binaries: []*ngx.Binary{bin(t, ngxtest.Default("1.31.8"))}, Source: off, Command: []string{"/docker-entrypoint.sh", "nginx"}}))[knowledge.Flow].State; got != conf.Unknown { + t.Errorf("an entrypoint with no launcher check: %s", got) + } +} + +// Review 2, finding 6: a build is cleared as built without HTTP/2 only +// when its configure arguments were read whole and it has a module list; +// HTTP/2 on a core older than 1.9.5 is judged by the code where known. +func TestR6NoHTTP2Evidence(t *testing.T) { + statuses := func(b ngxtest.Build) map[string]knowledge.Status { + out := map[string]knowledge.Status{} + for _, f := range Run(Input{Binaries: []*ngx.Binary{bin(t, b)}, Source: mem{}}) { + out[f.CVE] = f.Status + } + return out + } + // 1.9.7: no module list; 4,451 bytes of configure arguments with the + // HTTP/2 flag last. + long := ngxtest.Build{Line: "nginx/1.9.7", Configure: "--prefix=/x " + strings.Repeat("--with-cc-opt=-Dx ", 246) + "--with-http_v2_module"} + if st := statuses(long)[knowledge.Flow]; st == knowledge.NotAffected { + t.Errorf("truncated configure arguments cleared 1.9.7: %s", st) + } + or := long + or.Line = "openresty/1.9.7.5" + if st := statuses(or)[knowledge.Flow]; st == knowledge.NotAffected { + t.Errorf("truncated configure arguments cleared OpenResty 1.9.7.5: %s", st) + } + // No module list, short configure arguments without the flag: not + // cleared either (the module list is the second witness). + if st := statuses(ngxtest.Build{Line: "nginx/1.9.7", Configure: "--prefix=/x"})[knowledge.Flow]; st == knowledge.NotAffected { + t.Errorf("no module list cleared 1.9.7: %s", st) + } + // Both witnesses read, neither has HTTP/2: not affected. + both := ngxtest.Default("1.31.8") + both.Configure, both.Modules = "--prefix=/etc/nginx", []string{"ngx_core_module", "ngx_http_module"} + if st := statuses(both)[knowledge.Flow]; st != knowledge.NotAffected { + t.Errorf("no HTTP/2 with both witnesses: %s", st) + } + // HTTP/2 on a core before 1.9.5: a vendor backport, not cleared. + plus := ngxtest.Default("1.9.4") + plus.Line = "nginx/1.9.4 (nginx-plus-r7)" + if st := statuses(plus); st[knowledge.Flow] != knowledge.Unknown || st[knowledge.Reuse] != knowledge.Unknown { + t.Errorf("Plus r7 with HTTP/2 on 1.9.4: %v", st) + } + // Tengine 2.2.2 in its old one-line form, on core 1.8.1, with HTTP/2: + // the unfixed flow-control code; not the 2021 reuse change. + te := ngxtest.Default("1.8.1") + te.Line, te.Tengine = "", "Tengine/2.2.2 (nginx/1.8.1)" + if st := statuses(te); st[knowledge.Flow] != knowledge.Vulnerable || st[knowledge.Reuse] != knowledge.NotAffected { + t.Errorf("Tengine 2.2.2: %v", st) + } + te.Tengine = "Tengine/2.0.3 (nginx/1.4.6)" + if st := statuses(te); st[knowledge.Flow] != knowledge.Unknown { + t.Errorf("Tengine 2.0.3 with HTTP/2: %v", st) + } +} + +// R16: a fixed verdict rests on the version; the message says so. +func TestR16FixedWording(t *testing.T) { + f := byCVE(Run(Input{Binaries: []*ngx.Binary{bin(t, ngxtest.Default("1.31.9"))}, Source: mem{}}))[knowledge.Flow] + if strings.Contains(f.Message, "has the fix for") || !strings.Contains(f.Message, "version") { + t.Errorf("%s", f.Message) + } +} + +// Verification 5: an older core whose HTTP/2 witness is cut or missing is +// unknown, never not affected. +func TestV5OldCoreWitness(t *testing.T) { + statuses := func(b ngxtest.Build) map[string]knowledge.Status { + out := map[string]knowledge.Status{} + for _, f := range Run(Input{Binaries: []*ngx.Binary{bin(t, b)}, Source: mem{}}) { + out[f.CVE] = f.Status + } + return out + } + cut := "--prefix=/x " + strings.Repeat("--with-cc-opt=-Dx ", 246) + "--with-http_v2_module" + for name, b := range map[string]ngxtest.Build{ + "Tengine 2.2.2, cut arguments": {Tengine: "Tengine/2.2.2 (nginx/1.8.1)", Configure: cut}, + "Tengine 2.2.2, no module list": {Tengine: "Tengine/2.2.2 (nginx/1.8.1)", Configure: "--prefix=/x"}, + "Plus R7, cut arguments": {Line: "nginx/1.9.4 (nginx-plus-r7)", Configure: cut}, + } { + for cve, st := range statuses(b) { + if st == knowledge.NotAffected { + t.Errorf("%s: %s not affected", name, cve) + } + } + } + // Plain nginx before 1.9.5 has no HTTP/2 in its source: not affected + // by its version. + if st := statuses(ngxtest.Build{Line: "nginx/1.8.1", Configure: cut}); st[knowledge.Flow] != knowledge.NotAffected { + t.Errorf("nginx 1.8.1: %v", st) + } +} + +// Verification 6, and round 5: a shell start is never read (it is trusted +// by nothing the scan can check); a command that only tests nginx is not +// the start. +func TestV6ShellTestCall(t *testing.T) { + off := mem{"/etc/nginx/nginx.conf": "http { server { listen 80; } }"} + run := func(cmd ...string) conf.State { + return byCVE(Run(Input{Binaries: []*ngx.Binary{bin(t, ngxtest.Default("1.31.8"))}, Source: off, Command: cmd, Starts: okStarts}))[knowledge.Flow].State + } + if got := run("sh", "-c", "nginx -t && exec nginx -g 'daemon off;'"); got != conf.Unknown { + t.Errorf("a shell start: %s", got) + } + if got := run("nginx", "-T"); got != conf.Unknown { + t.Errorf("a command that only tests: %s", got) + } + if got := run("nginx", "-g", "daemon off;"); got != conf.NotExposed { + t.Errorf("nginx itself: %s", got) + } +} + +// okStarts stands for the adapter's check that the word starts the binary +// judged. +func okStarts(string, string) (bool, string) { return true, "" } diff --git a/detectors/nginxh2/internal/assess/fuzz_test.go b/detectors/nginxh2/internal/assess/fuzz_test.go new file mode 100644 index 0000000..e399913 --- /dev/null +++ b/detectors/nginxh2/internal/assess/fuzz_test.go @@ -0,0 +1,25 @@ +package assess + +import ( + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngx" +) + +// FuzzStart: any start command reads without a panic, and the +// configuration path it gives is absolute. +func FuzzStart(f *testing.F) { + f.Add("sh -c", "exec nginx \\\n -qc /x.conf -g 'include /y;'", "40-x.sh") + f.Add("/docker-entrypoint.sh nginx", "-g daemon\\ off;", "") + f.Add("", "'unterminated", "10-listen-on-ipv6-by-default.sh") + f.Fuzz(func(t *testing.T, lead, rest, script string) { + cmd := append(strings.Fields(lead), rest) + nginxOptions(strings.Fields(rest)) + b := &ngx.Binary{ConfPath: "/etc/nginx/nginx.conf", ConfRaw: "/etc/nginx/nginx.conf"} + main, _, _, _ := configFor(b, Input{Command: cmd, Launcher: func(w string) (bool, string) { return w == script, "" }}) + if !strings.HasPrefix(main, "/") { + t.Fatalf("relative configuration path %q", main) + } + }) +} diff --git a/detectors/nginxh2/internal/assess/start.go b/detectors/nginxh2/internal/assess/start.go new file mode 100644 index 0000000..dd26cf9 --- /dev/null +++ b/detectors/nginxh2/internal/assess/start.go @@ -0,0 +1,215 @@ +package assess + +import ( + "fmt" + "path" + "strings" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/conf" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngx" +) + +// The configuration nginx loads depends on how it is started. Exposure can +// read as "not exposed" only when the command that starts nginx was read +// and nothing it runs first can change the configuration; otherwise the +// configuration read may not be the one that runs, and unsure says why. + +// nginxNames are the words that start an nginx build. +var nginxNames = map[string]bool{"nginx": true, "nginx-debug": true, "openresty": true, "angie": true, "tengine": true} + +// configFor returns the configuration file a binary loads, the -g +// directives, where the path came from, and why the answer is unsure ("" when +// the start command was read in full). +func configFor(b *ngx.Binary, in Input) (string, []conf.Directive, string, string) { + main, how := b.ConfPath, "the binary's default" + prefix := b.Prefix + var extra []conf.Directive + cmd, from := in.Command, in.CommandFrom + none := "" + if in.CommandFor != nil { + cmd, from, none = in.CommandFor(b.Path) + } + args, word, unsure := startArgs(cmd, in.Launcher) + if len(cmd) == 0 && none != "" { + unsure = none + } + if unsure == "" && word != "" { + // The word must start the very binary judged. + switch { + case in.Starts == nil: + unsure = "which binary " + word + " starts was not checked" + default: + if ok, why := in.Starts(word, b.Path); !ok { + unsure = why + } + } + } + if from == "" { + from = "the start command" + } + o, err := nginxOptions(args) + if err != "" && unsure == "" { + unsure = err + } + if o.conf != "" { + main, how = o.conf, from+"'s -c" + } + if o.prefix != "" { + prefix = o.prefix + if o.conf == "" && !strings.HasPrefix(b.ConfRaw, "/") { + // -p moves a relative compiled-in configuration path. + main, how = b.ConfRaw, "the binary's default under "+from+"'s -p" + if main == "" { + main = "conf/nginx.conf" + } + } + } + for _, g := range o.global { + ds, err := conf.Parse("-g", g) + if err != nil { + if unsure == "" { + unsure = from + "'s -g directives could not be read" + } + continue + } + extra = append(extra, ds...) + } + if main == "" { + main = "/usr/local/nginx/conf/nginx.conf" + how = "nginx's default" + } + if !strings.HasPrefix(main, "/") { + if prefix == "" { + prefix = "/usr/local/nginx/" + } + main = path.Join(prefix, main) + } + return path.Clean("/" + main), extra, how, unsure +} + +// startArgs returns nginx's arguments in a start command, the word that +// starts nginx, and why the configuration read may not be what runs. Only +// two starts are read: the nginx binary itself, and the official image's +// entrypoint (trusted by its content) given nginx or nginx-debug as its +// first argument. Anything else that runs first (tini, env, a shell, a +// wrapper) is trusted by nothing the scan can check, so it is unsure. +func startArgs(cmd []string, launcher func(string) (bool, string)) ([]string, string, string) { + if len(cmd) == 0 { + return nil, "", "no command that starts nginx was read (an image without one, or a host whose service unit was not found)" + } + i := 0 + if !nginxNames[path.Base(cmd[0])] { + ok, why := false, "" + if launcher != nil { + ok, why = launcher(cmd[0]) + } + if !ok { + if why == "" { + why = fmt.Sprintf("nginx is started through %s, which can change the configuration or the options it is given", cmd[0]) + } + return nil, "", why + } + i = 1 + if i >= len(cmd) || cmd[i] != "nginx" && cmd[i] != "nginx-debug" { + return nil, "", "the entrypoint is not given nginx as its first argument, so what it runs is not read" + } + } + w := cmd[i] + if !nginxNames[path.Base(w)] { + return nil, "", fmt.Sprintf("nginx is started through %s, which can change the configuration or the options it is given", w) + } + if noServe(cmd[i+1:]) { + return nil, "", "the command runs nginx only to test or show it, so what serves is started elsewhere" + } + args, unsure := varArgs(cmd[i+1:]) + return args, w, unsure +} + +// OfficialEntrypointRuns reports a command whose first word is the +// official entrypoint given nginx or nginx-debug: only then does it run +// /docker-entrypoint.d and write the templates. +func OfficialEntrypointRuns(cmd []string, launcher func(string) (bool, string)) bool { + if len(cmd) < 2 || launcher == nil || cmd[1] != "nginx" && cmd[1] != "nginx-debug" { + return false + } + ok, _ := launcher(cmd[0]) + return ok +} + +func varArgs(args []string) ([]string, string) { + for _, a := range args { + if strings.ContainsAny(a, "$`") { + return args, "nginx is started with arguments that use variables" + } + } + return args, "" +} + +// noServe reports nginx arguments with an option that makes nginx test, +// show its version or configuration, send a signal or print help, and +// exit without serving. +func noServe(args []string) bool { + for i := 0; i < len(args); i++ { + a := args[i] + if !strings.HasPrefix(a, "-") { + continue + } + for j := 1; j < len(a); j++ { + switch a[j] { + case 't', 'T', 'v', 'V', 's', 'h', '?': + return true + case 'p', 'c', 'e', 'g': + if j == len(a)-1 { + i++ + } + j = len(a) + } + } + } + return false +} + +type options struct { + conf, prefix string + global []string +} + +// nginxOptions reads nginx's command line as ngx_get_options does: each +// argument is a "-" and letters; ? h v V t T q take nothing, p c e g s +// take the rest of the argument or the next one ("-qc file"). +func nginxOptions(args []string) (options, string) { + var o options + for i := 0; i < len(args); i++ { + a := args[i] + if !strings.HasPrefix(a, "-") || len(a) < 2 { + return o, fmt.Sprintf("nginx is given %q, which it does not take as an option", a) + } + opts: + for j := 1; j < len(a); j++ { + switch a[j] { + case '?', 'h', 'v', 'V', 't', 'T', 'q': + case 'p', 'c', 'e', 'g', 's': + v := a[j+1:] + if v == "" { + if i+1 >= len(args) { + return o, fmt.Sprintf("nginx's option -%c has no value", a[j]) + } + i++ + v = args[i] + } + switch a[j] { + case 'p': + o.prefix = v + case 'c': + o.conf = v + case 'g': + o.global = append(o.global, v) + } + break opts + default: + return o, fmt.Sprintf("nginx is given the option -%c, which this scan does not know", a[j]) + } + } + } + return o, "" +} diff --git a/detectors/nginxh2/internal/conf/conf_test.go b/detectors/nginxh2/internal/conf/conf_test.go new file mode 100644 index 0000000..2d3d119 --- /dev/null +++ b/detectors/nginxh2/internal/conf/conf_test.go @@ -0,0 +1,290 @@ +package conf + +import ( + "path" + "sort" + "strings" + "testing" +) + +// mem is a Source over a map. incomplete lists glob patterns whose +// matches are not all known. +type mem struct { + files map[string]string + incomplete map[string]bool +} + +func (m mem) Read(p string) ([]byte, bool, string) { + s, ok := m.files[p] + if !ok { + return nil, false, "missing" + } + return []byte(s), true, "" +} + +func (m mem) Glob(pattern string) ([]string, bool) { + var out []string + for p := range m.files { + if ok, _ := path.Match(pattern, p); ok { + out = append(out, p) + } + } + sort.Strings(out) + return out, !m.incomplete[pattern] +} + +func analyze(t *testing.T, files map[string]string) Exposure { + t.Helper() + return Analyze(Load(mem{files: files}, "/etc/nginx/nginx.conf", nil)) +} + +func TestParse(t *testing.T) { + ds, err := Parse("f", `# comment +user nginx; +http { + log_format main '$remote_addr "$request"' ; + server { listen 443 ssl http2; server_name "a b" x\;y; + location / { return 200 "}{;"; } # trailing + set $x ${host}z; + } +}`) + if err != nil { + t.Fatal(err) + } + if len(ds) != 2 || ds[1].Name != "http" || len(ds[1].Block) != 2 { + t.Fatalf("got %+v", ds) + } + srv := ds[1].Block[1] + if srv.Name != "server" || srv.Block[0].Name != "listen" || strings.Join(srv.Block[0].Args, " ") != "443 ssl http2" { + t.Errorf("server %+v", srv) + } + if got := srv.Block[1].Args; len(got) != 2 || got[0] != "a b" || got[1] != `x\;y` { + t.Errorf("server_name args %q", got) + } + if got := srv.Block[3].Args; len(got) != 2 || got[1] != "${host}z" { + t.Errorf("set args %q", got) + } + if srv.Block[0].Line != 5 { + t.Errorf("line %d", srv.Block[0].Line) + } +} + +func TestParseErrors(t *testing.T) { + for _, bad := range []string{ + "http {", "}", "server ;;", "a \"b", "a 'b'c;", "a { b }", "{", "a ${b", strings.Repeat("a {", 100) + strings.Repeat("}", 100), + } { + if _, err := Parse("f", bad); err == nil { + t.Errorf("Parse(%q) accepted", bad) + } + } +} + +func TestLuaBlocks(t *testing.T) { + ds, err := Parse("f", `http { server { listen 443 ssl http2; + content_by_lua_block { + -- don't { count "this" + local s = "}" .. '{' .. [[ } ]] + --[==[ a } comment ]==] + if x then y() end + } + location / { proxy_pass http://u; } +} }`) + if err != nil { + t.Fatal(err) + } + srv := ds[0].Block[0] + if len(srv.Block) != 3 || srv.Block[2].Name != "location" { + t.Fatalf("lua block not skipped: %+v", srv.Block) + } +} + +func TestExposure(t *testing.T) { + cases := []struct { + name string + conf string + flow, reuse State + }{ + {"off", `http { server { listen 80; location / { proxy_pass http://u; } } }`, NotExposed, NotExposed}, + {"tls h2 proxy", `http { server { listen 443 ssl http2; location / { proxy_pass http://u; } } }`, Exposed, Exposed}, + {"tls h2 static", `http { server { listen 443 ssl http2; root /srv; } }`, Exposed, NoProxy}, + {"http2 on", `http { http2 on; server { listen 443 ssl; location / { grpc_pass grpc://u; } } }`, Exposed, Exposed}, + {"http2 on, server off", `http { http2 on; server { listen 443 ssl; http2 off; proxy_pass http://u; } }`, NotExposed, NotExposed}, + {"cleartext", `http { server { listen 80 http2; location / { proxy_pass http://u; } } }`, Cleartext, Exposed}, + {"old ssl on", `http { server { listen 443 http2; ssl on; } }`, Exposed, NoProxy}, + {"port shared", `http { server { listen 443 ssl http2; server_name a; } server { listen 443 ssl; server_name b; location / { proxy_pass http://u; } } }`, Exposed, Exposed}, + {"no http", `events {} stream { server { listen 443; proxy_pass x; } }`, NotExposed, NotExposed}, + {"quic only", `http { server { listen 443 quic; listen 443 ssl; location / { proxy_pass http://u; } } }`, NotExposed, NotExposed}, + {"ssl on another listen of the port", `http { server { listen 443 ssl default_server; return 444; } server { listen 443; http2 on; location / { proxy_pass http://u; } } }`, Exposed, Exposed}, + {"default server http2", `http { server { listen 80 default_server; http2 on; return 444; } server { listen 80; server_name a; location / { proxy_pass http://u; } } }`, Cleartext, Exposed}, + {"template variable in listen", `http { server { listen 443 ssl ${H2}; location / { proxy_pass http://u; } } }`, Unknown, Unknown}, + {"template variable in http2", `http { server { listen 443 ssl; http2 ${H2}; } }`, Unknown, Unknown}, + {"no listen, not root", `http { server { http2 on; location / { proxy_pass http://u; } } }`, Cleartext, Exposed}, + {"R4 variable listen address", `http { server { listen ${NGINX_LISTEN}; location / { proxy_pass http://u; } } }`, Unknown, Unknown}, + {"R4 variable glued to the port", `http { server { listen 443${H2OPTS}; location / { proxy_pass http://u; } } }`, Unknown, Unknown}, + {"R4 placeholder directive", `http { server { listen 443 ssl; ${EXTRA_SERVER_DIRECTIVES} } }`, Unknown, Unknown}, + {"R4 placeholder in http", `http { ${EXTRA_HTTP}; server { listen 443 ssl; } }`, Unknown, Unknown}, + {"R4 nginx variables elsewhere are fine", `http { server { listen 443 ssl; location / { proxy_pass http://$host; } } }`, NotExposed, NotExposed}, + {"R12 lua content", `http { server { listen 443 ssl http2; location / { content_by_lua_block { ngx.say(1) } } } }`, Exposed, Exposed}, + {"R12 njs", `http { server { listen 443 ssl http2; location / { js_content main.handler; } } }`, Exposed, Exposed}, + {"R12 redis2", `http { server { listen 443 ssl http2; location / { redis2_pass r:6379; } } }`, Exposed, Exposed}, + {"R12 auth_request", `http { server { listen 443 ssl http2; location / { auth_request /auth; root /srv; } } }`, Exposed, Exposed}, + {"V4 a map key ending in $", `http { map $http_user_agent $bot { default 0; ~*(bot|crawler)$ 1; } server { listen 443 ssl; } }`, NotExposed, NotExposed}, + {"V4 geo and split_clients", `http { geo $a { default 0; 10.0.0.0/8 $x; } split_clients $remote_addr $v { 50% $one; * $two; } types { text/$x foo; } server { listen 443 ssl; } }`, NotExposed, NotExposed}, + {"V4 a variable glued to text is not a placeholder", `http { server { listen 443 ssl; } } stream { foo$bar; }`, NotExposed, NotExposed}, + {"V4 a whole-token placeholder still counts", `http { $EXTRA; server { listen 443 ssl; } }`, Unknown, Unknown}, + {"nested if", `http { server { listen 443 ssl http2; location / { if ($x) { fastcgi_pass unix:/s; } } } }`, Exposed, Exposed}, + } + for _, c := range cases { + e := analyze(t, map[string]string{"/etc/nginx/nginx.conf": c.conf}) + if e.Flow != c.flow || e.Reuse != c.reuse { + t.Errorf("%s: flow %s reuse %s, want %s %s (%+v)", c.name, e.Flow, e.Reuse, c.flow, c.reuse, e) + } + } +} + +func TestIncludes(t *testing.T) { + files := map[string]string{ + "/etc/nginx/nginx.conf": "events { worker_connections 128; } http { include mime.types; include /etc/nginx/conf.d/*.conf; include sites-enabled/*; }", + "/etc/nginx/mime.types": "types { text/html html; }", + "/etc/nginx/conf.d/a.conf": "server { listen 80; }", + "/etc/nginx/sites-enabled/site": "server { listen 443 ssl; include snippets/h2.conf; location / { proxy_pass http://b; } }", + "/etc/nginx/snippets/h2.conf": "http2 on;", + } + e := analyze(t, files) + if e.Flow != Exposed || e.Reuse != Exposed || e.WorkerConnections != "128" { + t.Fatalf("%+v", e) + } + if len(e.Where) != 1 || e.Where[0] != "/etc/nginx/snippets/h2.conf:1" { + t.Errorf("where %v", e.Where) + } + // The include that turned it on cannot be read: unknown, not off. + delete(files, "/etc/nginx/snippets/h2.conf") + e = analyze(t, files) + if e.Flow != Unknown || e.Reuse != Unknown || e.HTTP2 != "unknown" || len(e.Unread) == 0 { + t.Errorf("unread include: %+v", e) + } + // A glob whose matches are not all known: unknown. + files["/etc/nginx/snippets/h2.conf"] = "http2 off;" + m := mem{files: files, incomplete: map[string]bool{"/etc/nginx/conf.d/*.conf": true}} + e = Analyze(Load(m, "/etc/nginx/nginx.conf", nil)) + if e.Flow != Unknown { + t.Errorf("incomplete glob: %+v", e) + } + // Everything read and off. + e = analyze(t, files) + if e.Flow != NotExposed || e.HTTP2 != "off" { + t.Errorf("off: %+v", e) + } + // Positive evidence wins over an unread file. + files["/etc/nginx/conf.d/a.conf"] = "server { listen 443 ssl http2; } include /missing.conf;" + e = analyze(t, files) + if e.Flow != Exposed || len(e.Unread) == 0 { + t.Errorf("exposed with unread: %+v", e) + } +} + +func TestIncludeHostile(t *testing.T) { + loop := map[string]string{ + "/etc/nginx/nginx.conf": "include a.conf;", + "/etc/nginx/a.conf": "include b.conf;", + "/etc/nginx/b.conf": "include a.conf;", + } + e := analyze(t, loop) + if e.Flow != Unknown || !strings.Contains(strings.Join(e.Unread, " "), "includes itself") { + t.Errorf("loop: %+v", e) + } + self := map[string]string{"/etc/nginx/nginx.conf": "http { include /etc/nginx/*.conf; }"} + if e := analyze(t, self); e.Flow != Unknown { + t.Errorf("self glob: %+v", e) + } + // A fan-out: each file includes the next level twice. + fan := map[string]string{"/etc/nginx/nginx.conf": "include l0.conf; include l0.conf;"} + for i := 0; i < 20; i++ { + fan["/etc/nginx/l"+string(rune('a'+i))+".conf"] = "" + } + for i := 0; i < 19; i++ { + fan["/etc/nginx/l"+itoa(i)+".conf"] = "include l" + itoa(i+1) + ".conf; include l" + itoa(i+1) + ".conf;" + } + fan["/etc/nginx/l19.conf"] = "http { server { listen 443 ssl http2; } }" + c := Load(mem{files: fan}, "/etc/nginx/nginx.conf", nil) + if len(c.Files) > MaxFiles || len(c.Unread) == 0 { + t.Errorf("fan-out read %d files, unread %v", len(c.Files), c.Unread) + } + vars := map[string]string{"/etc/nginx/nginx.conf": "include $x.conf;"} + if e := analyze(t, vars); e.Flow != Unknown { + t.Errorf("variable include: %+v", e) + } + if e := analyze(t, map[string]string{}); e.Flow != Unknown || e.Reuse != Unknown { + t.Errorf("no file: %+v", e) + } +} + +func itoa(i int) string { + if i < 10 { + return string(rune('0' + i)) + } + return string(rune('0'+i/10)) + string(rune('0'+i%10)) +} + +func TestCommandLineDirectives(t *testing.T) { + extra, err := Parse("-g", "daemon off; include /etc/nginx/h2.conf;") + if err != nil { + t.Fatal(err) + } + files := map[string]string{"/etc/nginx/nginx.conf": "http { server { listen 443 ssl; } }", "/etc/nginx/h2.conf": "http { http2 on; }"} + c := Load(mem{files: files}, "/etc/nginx/nginx.conf", extra) + if len(c.Root) != 3 { + t.Errorf("extra not added: %+v", c.Root) + } +} + +func TestPortOf(t *testing.T) { + for in, want := range map[string]string{"443": "443", "*:443": "443", "[::]:443": "443", "10.0.0.1:8443": "8443", "localhost": "80", "unix:/run/x": "unix:/run/x", "[::1]": "80"} { + if got := portOf(in); got != want { + t.Errorf("portOf(%q) = %q, want %q", in, got, want) + } + } +} + +// Review 2, finding 7: what all includes together make the loader parse +// is bounded; past the bound the answer is unknown. +func TestR7TotalBudget(t *testing.T) { + big := strings.Repeat("a;\n", 300000) // 900 KB, 600k tokens + main := "" + for i := 0; i < 62; i++ { + main += "include /etc/nginx/big.conf;\n" + } + c := Load(mem{files: map[string]string{"/etc/nginx/nginx.conf": "http { " + main + " server { listen 80; } }", "/etc/nginx/big.conf": big}}, "/etc/nginx/nginx.conf", nil) + if !strings.Contains(strings.Join(c.Unread, " "), "limit") { + t.Fatalf("no limit reached: %d files, unread %v", len(c.Files), c.Unread) + } + if e := Analyze(c); e.Flow != Unknown { + t.Errorf("over the budget: %s", e.Flow) + } +} + +// counting is a Source that counts reads. +type counting struct { + mem + reads int +} + +func (c *counting) Read(p string) ([]byte, bool, string) { + c.reads++ + return c.mem.Read(p) +} + +// Verification 7: once the loader's budget is spent, it reads no further +// includes. +func TestV7StopsReading(t *testing.T) { + big := strings.Repeat("# comment line to fill bytes\n", 150000) // ~4.3 MB + main := strings.Repeat("include /etc/nginx/big.conf;\n", 20000) + c := &counting{mem: mem{files: map[string]string{"/etc/nginx/nginx.conf": main, "/etc/nginx/big.conf": big}}} + cfg := Load(c, "/etc/nginx/nginx.conf", nil) + if c.reads > 10 { + t.Errorf("%d files read after the byte budget was spent", c.reads) + } + if e := Analyze(cfg); e.Flow != Unknown { + t.Errorf("over the budget: %s", e.Flow) + } +} diff --git a/detectors/nginxh2/internal/conf/exposure.go b/detectors/nginxh2/internal/conf/exposure.go new file mode 100644 index 0000000..9efa0a3 --- /dev/null +++ b/detectors/nginxh2/internal/conf/exposure.go @@ -0,0 +1,317 @@ +package conf + +import ( + "fmt" + "regexp" + "strings" +) + +// State is what a configuration says about one CVE's preconditions. +type State string + +const ( + // Exposed: HTTP/2 is on where the CVE's published path needs it (over + // TLS for CVE-2026-123007, with a proxy for CVE-2026-123633). + Exposed State = "exposed" + // Cleartext: HTTP/2 is on only without TLS (prior knowledge). The + // published path for CVE-2026-123007 is through TLS. + Cleartext State = "http2-cleartext-only" + // NoProxy: HTTP/2 is on, but no server that has it passes requests + // to an upstream (CVE-2026-123633 needs a reverse proxy). + NoProxy State = "http2-without-proxy" + // NotExposed: every file was read, and HTTP/2 is on nowhere. + NotExposed State = "not-exposed" + // Unknown: the configuration could not be read or settled. + Unknown State = "unknown" +) + +// Exposure is the configuration's answer. +type Exposure struct { + // HTTP2 is "on", "off" or "unknown". + HTTP2 string `json:"http2"` + Flow State `json:"flow"` + Reuse State `json:"reuse"` + // Where lists the directives that turn HTTP/2 on (file:line). + Where []string `json:"where,omitempty"` + // Proxy lists proxy directives in servers with HTTP/2 (file:line). + Proxy []string `json:"proxy,omitempty"` + // WorkerConnections is the events block's value, "" when unset + // (nginx's default is 512). + WorkerConnections string `json:"worker_connections,omitempty"` + Unread []string `json:"unread,omitempty"` +} + +// proxyDirectives open connections to an upstream while a request is +// served (the pressure CVE-2026-123633 needs): the *_pass directives, +// subrequests, and handlers that can open sockets of their own (Lua +// cosockets, njs fetch, Perl). +var proxyDirectives = map[string]bool{"proxy_pass": true, "grpc_pass": true, "fastcgi_pass": true, "uwsgi_pass": true, "scgi_pass": true, "memcached_pass": true, + "redis_pass": true, "redis2_pass": true, "postgres_pass": true, "drizzle_pass": true, "auth_request": true, "mirror": true, + "js_content": true, "js_access": true, "perl": true} + +// proxyHandler reports an OpenResty handler that can open its own +// connections (content_by_lua_block, access_by_lua_file, balancer_by_lua*). +func proxyHandler(name string) bool { + return strings.Contains(name, "_by_lua") +} + +type listen struct { + port string + ssl, http2 bool + dflt bool // default_server + where string +} + +type server struct { + listens []listen + h2 string // the http2 directive in force: on, off or "" + h2Where string + ssl bool // "ssl on;" (before 1.25.1) + proxy []string + where string +} + +// Analyze reads a loaded configuration. +func Analyze(c *Config) Exposure { + e := Exposure{Unread: append([]string(nil), c.Unread...)} + var servers []server + unsettled := func(msg string) { + if len(e.Unread) < 64 { + e.Unread = append(e.Unread, msg) + } + } + placeholders(c.Root, unsettled, 0) + for _, d := range c.Root { + switch d.Name { + case "events": + for _, x := range d.Block { + if x.Name == "worker_connections" && len(x.Args) == 1 { + e.WorkerConnections = x.Args[0] + } + } + case "http": + servers = append(servers, httpServers(d, unsettled)...) + } + } + // nginx keeps one socket per address and port: its ssl and http2 + // parameters, set on any listen of it, hold for every server on it, and + // the default server's "http2 on" holds for connections that do not + // select another server (no TLS, or no SNI). Ports are compared + // without their address, which can only count more servers as + // exposed, never fewer. + portH2, portSSL, dflt := map[string]string{}, map[string]bool{}, map[string]int{} + for i, s := range servers { + for _, l := range s.listens { + if l.http2 { + portH2[l.port] = l.where + } + if l.ssl || s.ssl { + portSSL[l.port] = true + } + if _, ok := dflt[l.port]; !ok || l.dflt { + dflt[l.port] = i + } + } + } + for port, i := range dflt { + if servers[i].h2 == "on" && portH2[port] == "" { + portH2[port] = servers[i].h2Where + " (the default server of port " + port + ")" + } + } + flow, clear, reuse, noProxy := false, false, false, false + add := func(list *[]string, w string) { + for _, x := range *list { + if x == w { + return + } + } + if len(*list) < 16 { + *list = append(*list, w) + } + } + for _, s := range servers { + for _, l := range s.listens { + on, why := false, "" + switch { + case l.http2: + on, why = true, l.where + case s.h2 == "on": + on, why = true, s.h2Where + case portH2[l.port] != "": + on, why = true, portH2[l.port] + } + if !on { + continue + } + add(&e.Where, why) + if l.ssl || s.ssl || portSSL[l.port] { + flow = true + } else { + clear = true + } + if len(s.proxy) > 0 { + reuse = true + for _, p := range s.proxy { + add(&e.Proxy, p) + } + } else { + noProxy = true + } + } + } + settled := len(e.Unread) == 0 && len(c.Files) > 0 + on := flow || clear + switch { + case on: + e.HTTP2 = "on" + case settled: + e.HTTP2 = "off" + default: + e.HTTP2 = "unknown" + } + e.Flow = decide(flow, clear, settled, Cleartext) + e.Reuse = decide(reuse, noProxy, settled, NoProxy) + return e +} + +// decide: positive evidence wins; a weaker state only when everything was +// read (an unread include could hold the stronger one). +func decide(full, partial, settled bool, partialState State) State { + switch { + case full: + return Exposed + case partial && settled: + return partialState + case settled: + return NotExposed + } + return Unknown +} + +func httpServers(h Directive, unsettled func(string)) []server { + h2, h2Where, ssl := "", "", false + h2Value := func(d Directive) string { + v := strings.ToLower(d.Args[0]) + if v != "on" && v != "off" { + // A template variable or anything else: decided where it + // runs, so not off. + unsettled(fmt.Sprintf("http2 at %s is %q, which is decided where it runs", loc(d), d.Args[0])) + } + return v + } + for _, d := range h.Block { + switch { + case d.Name == "http2" && len(d.Args) == 1: + h2, h2Where = h2Value(d), loc(d) + case d.Name == "ssl" && len(d.Args) == 1: + ssl = strings.EqualFold(d.Args[0], "on") + } + } + var out []server + for _, d := range h.Block { + if d.Name != "server" || !d.HasBlock { + continue + } + s := server{h2: h2, h2Where: h2Where, ssl: ssl, where: loc(d)} + for _, x := range d.Block { + switch { + case x.Name == "listen" && len(x.Args) > 0: + l := parseListen(x) + for _, a := range x.Args { + if strings.Contains(a, "$") { + unsettled(fmt.Sprintf("listen at %s has %q, which is decided where it runs", loc(x), a)) + } + } + s.listens = append(s.listens, l) + case x.Name == "http2" && len(x.Args) == 1: + s.h2, s.h2Where = h2Value(x), loc(x) + case x.Name == "ssl" && len(x.Args) == 1: + s.ssl = strings.EqualFold(x.Args[0], "on") + } + } + if len(s.listens) == 0 { + // *:80, or *:8000 when nginx does not run as root. + s.listens = []listen{{port: "80", where: s.where + " (no listen: *:80)"}, {port: "8000", where: s.where + " (no listen: *:8000 when not root)"}} + } + proxies(d.Block, &s.proxy, 0) + out = append(out, s) + } + return out +} + +// placeholders reports a directive whose name is a variable (a template's +// ${EXTRA_DIRECTIVES} left unset): what it stands for is decided where +// the configuration runs. +func placeholders(ds []Directive, unsettled func(string), depth int) { + if depth > maxDepth { + return + } + for _, d := range ds { + if placeholder.MatchString(d.Name) { + unsettled(fmt.Sprintf("%s at %s stands for directives decided where it runs", d.Name, loc(d))) + } + if d.HasBlock && !valueBlocks[d.Name] { + placeholders(d.Block, unsettled, depth+1) + } + } +} + +// placeholder is a directive name that is one variable and nothing else +// (${EXTRA_DIRECTIVES}, $EXTRA): what a template leaves unset. +var placeholder = regexp.MustCompile(`^(?:\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*)$`) + +// valueBlocks hold keys and values, not directives: a key there may be +// anything ("~*(bot|crawler)$" in a map). +var valueBlocks = map[string]bool{"map": true, "geo": true, "split_clients": true, "types": true, "charset_map": true} + +func proxies(ds []Directive, out *[]string, depth int) { + if depth > maxDepth { + return + } + for _, d := range ds { + if (proxyDirectives[d.Name] || proxyHandler(d.Name)) && len(*out) < 16 { + *out = append(*out, loc(d)) + } + if d.HasBlock { + proxies(d.Block, out, depth+1) + } + } +} + +func parseListen(d Directive) listen { + l := listen{port: portOf(d.Args[0]), where: loc(d)} + for _, a := range d.Args[1:] { + switch strings.ToLower(a) { + case "ssl": + l.ssl = true + case "http2": + l.http2 = true + case "default_server", "default": + l.dflt = true + } + } + return l +} + +// portOf reads the port of a listen address: "443", "*:443", +// "[::]:443", "10.0.0.1:443", "localhost:443", "unix:/path". +func portOf(a string) string { + if strings.HasPrefix(a, "unix:") { + return a + } + if i := strings.LastIndexByte(a, ']'); i >= 0 { + if p := strings.TrimPrefix(a[i+1:], ":"); p != "" { + return p + } + return "80" + } + if i := strings.LastIndexByte(a, ':'); i >= 0 { + return a[i+1:] + } + if a != "" && strings.Trim(a, "0123456789") == "" { + return a + } + return "80" // an address without a port listens on 80 +} + +func loc(d Directive) string { return fmt.Sprintf("%s:%d", d.File, d.Line) } diff --git a/detectors/nginxh2/internal/conf/fuzz_test.go b/detectors/nginxh2/internal/conf/fuzz_test.go new file mode 100644 index 0000000..da4055b --- /dev/null +++ b/detectors/nginxh2/internal/conf/fuzz_test.go @@ -0,0 +1,45 @@ +package conf + +import ( + "strings" + "testing" +) + +// FuzzParse: any input parses or fails with an error, within the limits, +// and the loader and analysis never panic on what it gives. +func FuzzParse(f *testing.F) { + for _, s := range []string{ + "http { server { listen 443 ssl http2; location / { proxy_pass http://u; } } }", + "events { worker_connections 1; } http { http2 on; include a/*.conf; }", + "a 'b\\'c' \"d\\\"\" ${x} e\\;f;", + "content_by_lua_block { -- } \n local s = [[ } ]] }", + "http { server { listen [::]:443 ssl; ssl on; } }", + "include include.conf;", + "#", + "}{;", + } { + f.Add(s) + } + f.Fuzz(func(t *testing.T, s string) { + ds, err := Parse("f", s) + if err != nil { + return + } + files := map[string]string{"/etc/nginx/nginx.conf": s, "/etc/nginx/include.conf": s} + c := Load(mem{files: files}, "/etc/nginx/nginx.conf", nil) + e := Analyze(c) + if e.Flow == "" || e.Reuse == "" || e.HTTP2 == "" { + t.Fatalf("empty state: %+v", e) + } + if e.HTTP2 == "off" && (e.Flow != NotExposed || e.Reuse != NotExposed) { + t.Fatalf("HTTP/2 off but %+v", e) + } + if e.HTTP2 == "off" && len(e.Unread) > 0 { + t.Fatalf("off with unread files: %+v", e) + } + _ = ds + if strings.Count(s, "{") > 10000 { + t.Skip() + } + }) +} diff --git a/detectors/nginxh2/internal/conf/load.go b/detectors/nginxh2/internal/conf/load.go new file mode 100644 index 0000000..61e7be1 --- /dev/null +++ b/detectors/nginxh2/internal/conf/load.go @@ -0,0 +1,167 @@ +package conf + +import ( + "fmt" + "path" + "sort" + "strings" +) + +// Source serves the files a configuration may read. +type Source interface { + // Read returns a file's content; ok is false when the file was not + // read (missing, unreadable, not kept). why says which, for the + // report. + Read(p string) (data []byte, ok bool, why string) + // Glob returns the files matching pattern, sorted, and whether that + // list is complete: false when files the pattern can match were not + // read, so the list may miss some. + Glob(pattern string) (matches []string, complete bool) +} + +// Limits on what one configuration can make the loader read. +const ( + MaxFiles = 4096 + MaxBytes = 16 << 20 + // MaxTotalTokens bounds what every file of one configuration, each + // time it is included, makes the loader parse: one file included many + // times is parsed each time. + MaxTotalTokens = 2 << 20 + maxNest = 32 +) + +// Config is a loaded configuration. +type Config struct { + Main string `json:"main"` + Root []Directive `json:"-"` + Files []string `json:"files"` + // Unread lists what could not be read or settled: each one makes a + // "not exposed" answer unknown. + Unread []string `json:"unread,omitempty"` +} + +type loader struct { + src Source + prefix string // the configuration prefix: the main file's directory + cfg *Config + bytes int + tokens int // left of MaxTotalTokens + spent bool // a limit was reached: no further file is read + stack []string +} + +// Load reads the main file and every file it includes, at any level, the +// way nginx does: a relative include is taken from the main file's +// directory; a pattern with *, ? or [ is a glob; a file included from +// itself, directly or not, is a loop nginx cannot load. extra are +// directives given on the command line (-g), added to the main context. +func Load(src Source, main string, extra []Directive) *Config { + l := &loader{src: src, prefix: path.Dir(main), cfg: &Config{Main: main}, tokens: MaxTotalTokens} + root, ok := l.file(main, 0) + if !ok { + return l.cfg + } + // -g directives are in the main context, and their includes are + // followed like any other. + l.cfg.Root = append(root, l.expand(extra, 0)...) + return l.cfg +} + +func (l *loader) unread(format string, a ...any) { + if len(l.cfg.Unread) < 64 { + l.cfg.Unread = append(l.cfg.Unread, fmt.Sprintf(format, a...)) + } +} + +func (l *loader) file(p string, nest int) ([]Directive, bool) { + for _, s := range l.stack { + if s == p { + l.unread("%s includes itself (through %s): nginx cannot load this configuration", p, strings.Join(l.stack, " -> ")) + return nil, false + } + } + if nest > maxNest { + l.unread("includes nested more than %d deep at %s", maxNest, p) + return nil, false + } + if l.spent { + return nil, false // recorded once, when the limit was reached + } + if len(l.cfg.Files) >= MaxFiles { + l.unread("more than %d configuration files; %s and later ones not read", MaxFiles, p) + l.spent = true + return nil, false + } + data, ok, why := l.src.Read(p) + if !ok { + l.unread("%s not read: %s", p, why) + return nil, false + } + l.bytes += len(data) + if l.bytes > MaxBytes { + l.unread("more than %d bytes of configuration; %s and later files not read", MaxBytes, p) + l.spent = true + return nil, false + } + l.cfg.Files = append(l.cfg.Files, p) + ds, err := parse(p, string(data), &l.tokens) + if err != nil { + l.unread("%s could not be parsed: %v", p, err) + if l.tokens <= 0 { + l.spent = true + } + return nil, false + } + l.stack = append(l.stack, p) + defer func() { l.stack = l.stack[:len(l.stack)-1] }() + return l.expand(ds, nest), true +} + +// expand replaces include directives, at every level, with what they +// include. +func (l *loader) expand(ds []Directive, nest int) []Directive { + out := make([]Directive, 0, len(ds)) + for _, d := range ds { + if d.Name == "include" && !d.HasBlock { + out = append(out, l.include(d, nest)...) + continue + } + if d.HasBlock { + d.Block = l.expand(d.Block, nest) + } + out = append(out, d) + } + return out +} + +func (l *loader) include(d Directive, nest int) []Directive { + where := fmt.Sprintf("%s:%d", d.File, d.Line) + if len(d.Args) != 1 { + l.unread("include at %s has %d arguments", where, len(d.Args)) + return nil + } + p := d.Args[0] + if strings.Contains(p, "$") { + l.unread("include at %s names a variable (%s), which nginx does not expand", where, p) + return nil + } + if !strings.HasPrefix(p, "/") { + p = path.Join(l.prefix, p) + } + p = path.Clean(p) + if !strings.ContainsAny(p, "*?[") { + ds, _ := l.file(p, nest+1) + return ds + } + matches, complete := l.src.Glob(p) + if !complete { + l.unread("include %s at %s: the files it matches were not all read", p, where) + } + sort.Strings(matches) + var out []Directive + for _, m := range matches { + ds, _ := l.file(m, nest+1) + out = append(out, ds...) + } + return out +} diff --git a/detectors/nginxh2/internal/conf/parse.go b/detectors/nginxh2/internal/conf/parse.go new file mode 100644 index 0000000..3f4ae91 --- /dev/null +++ b/detectors/nginxh2/internal/conf/parse.go @@ -0,0 +1,357 @@ +// Package conf reads an nginx configuration the way nginx does (tokens, +// blocks, includes with globs) and says whether it turns HTTP/2 on, over +// TLS, in front of a proxy. It reads only what it is given; anything it +// cannot read or settle makes the answer unknown, never off. It knows +// nothing about the engine. +package conf + +import ( + "fmt" + "strings" +) + +// Directive is one directive, with its block when it has one. +type Directive struct { + Name string `json:"name"` + Args []string `json:"args,omitempty"` + Block []Directive `json:"block,omitempty"` + // HasBlock is set for a directive with braces, even empty ones. + HasBlock bool `json:"-"` + File string `json:"file"` + Line int `json:"line"` +} + +// Limits on one file's parse. +const ( + maxDepth = 64 + maxTokens = 1 << 20 + maxArgs = 256 + maxToken = 64 << 10 +) + +// ParseError is a configuration nginx would refuse, or one past a limit. +type ParseError struct { + File string + Line int + Msg string +} + +func (e *ParseError) Error() string { return fmt.Sprintf("%s:%d: %s", e.File, e.Line, e.Msg) } + +type tokenizer struct { + file string + s string + i int + line int + tokens int + budget *int // tokens left across every file of one load; nil for none +} + +// tok kinds +const ( + tWord = iota + tSemi + tOpen + tClose + tEOF +) + +type token struct { + kind int + text string + line int + quoted bool +} + +func (t *tokenizer) errf(format string, a ...any) error { + return &ParseError{File: t.file, Line: t.line, Msg: fmt.Sprintf(format, a...)} +} + +// next reads one token as ngx_conf_read_token does: whitespace separates, +// ";", "{" and "}" end a word, "#" starts a comment at the start of a +// word, quotes group, and a backslash escapes the next character. +func (t *tokenizer) next() (token, error) { + t.tokens++ + if t.tokens > maxTokens { + return token{}, t.errf("more than %d tokens", maxTokens) + } + if t.budget != nil { + if *t.budget <= 0 { + return token{}, t.errf("over the limit of %d tokens across all included files", MaxTotalTokens) + } + *t.budget-- + } + for t.i < len(t.s) { + c := t.s[t.i] + switch { + case c == '\n': + t.line++ + t.i++ + case c == ' ' || c == '\t' || c == '\r': + t.i++ + case c == '#': + for t.i < len(t.s) && t.s[t.i] != '\n' { + t.i++ + } + case c == ';': + t.i++ + return token{kind: tSemi, line: t.line}, nil + case c == '{': + t.i++ + return token{kind: tOpen, line: t.line}, nil + case c == '}': + t.i++ + return token{kind: tClose, line: t.line}, nil + case c == '"' || c == '\'': + return t.quoted(c) + default: + return t.word() + } + } + return token{kind: tEOF, line: t.line}, nil +} + +func (t *tokenizer) quoted(q byte) (token, error) { + start := t.line + t.i++ + var b strings.Builder + for t.i < len(t.s) { + c := t.s[t.i] + switch { + case c == '\\' && t.i+1 < len(t.s): + n := t.s[t.i+1] + switch n { + case '"', '\'', '\\': + b.WriteByte(n) + case 't': + b.WriteByte('\t') + case 'r': + b.WriteByte('\r') + case 'n': + b.WriteByte('\n') + default: + b.WriteByte('\\') + b.WriteByte(n) + } + if n == '\n' { + t.line++ + } + t.i += 2 + case c == q: + t.i++ + // nginx wants whitespace or ; { } after a closing quote. + if t.i < len(t.s) && !strings.ContainsRune(" \t\r\n;{}", rune(t.s[t.i])) { + return token{}, t.errf("unexpected %q after a quoted string", t.s[t.i]) + } + return token{kind: tWord, text: b.String(), line: start, quoted: true}, nil + default: + if c == '\n' { + t.line++ + } + b.WriteByte(c) + t.i++ + } + if b.Len() > maxToken { + return token{}, t.errf("a quoted string longer than %d bytes", maxToken) + } + } + return token{}, &ParseError{File: t.file, Line: start, Msg: "unterminated quoted string"} +} + +func (t *tokenizer) word() (token, error) { + start := t.line + var b strings.Builder + for t.i < len(t.s) { + c := t.s[t.i] + switch { + case c == '\\' && t.i+1 < len(t.s): + b.WriteByte(c) + b.WriteByte(t.s[t.i+1]) + if t.s[t.i+1] == '\n' { + t.line++ + } + t.i += 2 + continue + case c == '$' && t.i+1 < len(t.s) && t.s[t.i+1] == '{': + // ${name}: the braces belong to the word. + j := strings.IndexByte(t.s[t.i:], '}') + if j < 0 || strings.ContainsAny(t.s[t.i:t.i+j], " \t\r\n;") { + return token{}, t.errf("unterminated ${...}") + } + b.WriteString(t.s[t.i : t.i+j+1]) + t.i += j + 1 + continue + case c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == ';' || c == '{' || c == '}': + return token{kind: tWord, text: b.String(), line: start}, nil + } + b.WriteByte(c) + t.i++ + if b.Len() > maxToken { + return token{}, t.errf("a word longer than %d bytes", maxToken) + } + } + return token{kind: tWord, text: b.String(), line: start}, nil +} + +// Parse reads one file's directives. Includes are left as directives; the +// loader expands them. +func Parse(file, text string) ([]Directive, error) { + return parse(file, text, nil) +} + +func parse(file, text string, budget *int) ([]Directive, error) { + t := &tokenizer{file: file, s: text, line: 1, budget: budget} + ds, end, err := parseBlock(t, 0) + if err != nil { + return nil, err + } + if end != tEOF { + return nil, t.errf("unexpected \"}\"") + } + return ds, nil +} + +func parseBlock(t *tokenizer, depth int) ([]Directive, int, error) { + if depth > maxDepth { + return nil, 0, t.errf("blocks nested more than %d deep", maxDepth) + } + var out []Directive + var cur *Directive + for { + tk, err := t.next() + if err != nil { + return nil, 0, err + } + switch tk.kind { + case tEOF, tClose: + if cur != nil { + return nil, 0, t.errf("unexpected end of block after %q", cur.Name) + } + if tk.kind == tEOF && depth > 0 { + return nil, 0, t.errf("unexpected end of file, expecting \"}\"") + } + return out, tk.kind, nil + case tWord: + if cur == nil { + cur = &Directive{Name: tk.text, File: t.file, Line: tk.line} + continue + } + if len(cur.Args) >= maxArgs { + return nil, 0, t.errf("more than %d arguments", maxArgs) + } + cur.Args = append(cur.Args, tk.text) + case tSemi: + if cur == nil { + return nil, 0, t.errf("unexpected \";\"") + } + out = append(out, *cur) + cur = nil + case tOpen: + if cur == nil { + return nil, 0, t.errf("unexpected \"{\"") + } + if strings.HasSuffix(cur.Name, "_by_lua_block") || cur.Name == "lua_block" { + // OpenResty: the block is Lua, not nginx syntax. + if err := skipLua(t); err != nil { + return nil, 0, err + } + cur.HasBlock = true + out = append(out, *cur) + cur = nil + continue + } + body, end, err := parseBlock(t, depth+1) + if err != nil { + return nil, 0, err + } + if end != tClose { + return nil, 0, t.errf("unexpected end of file, expecting \"}\"") + } + cur.Block, cur.HasBlock = body, true + out = append(out, *cur) + cur = nil + } + } +} + +// skipLua passes over a Lua block: braces counted outside Lua strings and +// comments, as OpenResty's own block reader does. +func skipLua(t *tokenizer) error { + depth := 1 + start := t.line + for t.i < len(t.s) { + c := t.s[t.i] + switch { + case c == '\n': + t.line++ + t.i++ + case c == '-' && strings.HasPrefix(t.s[t.i:], "--"): + t.i += 2 + if n, ok := longBracket(t.s[t.i:]); ok { + if !t.skipLong(n) { + return &ParseError{File: t.file, Line: start, Msg: "unterminated Lua comment"} + } + continue + } + for t.i < len(t.s) && t.s[t.i] != '\n' { + t.i++ + } + case c == '[': + if n, ok := longBracket(t.s[t.i:]); ok { + if !t.skipLong(n) { + return &ParseError{File: t.file, Line: start, Msg: "unterminated Lua long string"} + } + continue + } + t.i++ + case c == '"' || c == '\'': + t.i++ + for t.i < len(t.s) && t.s[t.i] != c && t.s[t.i] != '\n' { + if t.s[t.i] == '\\' { + t.i++ + } + t.i++ + } + t.i++ + case c == '{': + depth++ + t.i++ + case c == '}': + depth-- + t.i++ + if depth == 0 { + return nil + } + default: + t.i++ + } + } + return &ParseError{File: t.file, Line: start, Msg: "unterminated Lua block"} +} + +// longBracket reports a Lua long bracket "[[" or "[==[" at s and its level. +func longBracket(s string) (int, bool) { + if len(s) < 2 || s[0] != '[' { + return 0, false + } + n := 1 + for n < len(s) && s[n] == '=' { + n++ + } + if n < len(s) && s[n] == '[' { + return n - 1, true + } + return 0, false +} + +func (t *tokenizer) skipLong(level int) bool { + closer := "]" + strings.Repeat("=", level) + "]" + t.i += level + 2 + j := strings.Index(t.s[t.i:], closer) + if j < 0 { + return false + } + t.line += strings.Count(t.s[t.i:t.i+j], "\n") + t.i += j + len(closer) + return true +} diff --git a/detectors/nginxh2/internal/knowledge/knowledge.go b/detectors/nginxh2/internal/knowledge/knowledge.go new file mode 100644 index 0000000..29144ca --- /dev/null +++ b/detectors/nginxh2/internal/knowledge/knowledge.go @@ -0,0 +1,363 @@ +// Package knowledge holds what is known about the nginx HTTP/2 pair, +// CVE-2026-123007 and CVE-2026-123633, and judges a version against it. +// Every value is sourced in ../../FACTS.md. It knows nothing about files, +// images or the engine. +package knowledge + +import ( + "fmt" + "strconv" + "strings" +) + +// Dates. +const ( + Disclosed = "2026-11-18" + Checked = "2026-11-18" +) + +// CVSS is the score findings carry (Wiz, CVSS 4.0, both CVEs). +const CVSS = "9.2" + +// CVE IDs. +const ( + Flow = "CVE-2026-123007" + Reuse = "CVE-2026-123633" +) + +// CVE is one of the pair. +type CVE struct { + ID string + Short string // a few words, for messages + // Introduced is the first upstream release with the flaw. + Introduced V + // Fixed is the first fixed release of each line that received a fix. + // A line newer than every line here branched after the fix. + Fixed []V + // PlusFixed is the same for NGINX Plus's numbered releases. + PlusFixed []V + // PlusFrom is the first NGINX Plus R release F5 lists as affected. + PlusFrom int + Commits []string + Advisory string +} + +// CVEs are the pair, in report order. +var CVEs = []CVE{ + { + ID: Flow, Short: "memory corruption in HTTP/2 flow control", + Introduced: MustV("1.9.5"), Fixed: []V{MustV("1.30.7"), MustV("1.31.9")}, + PlusFixed: []V{MustV("37.0.8.1"), MustV("37.3.0.1")}, PlusFrom: 33, + Commits: []string{"e27f5fa84fe6e98505e70bc543b748747dad0a3b", "b89c4100bf6762a45e4a6463eaf4b70368277c94"}, + Advisory: "https://my.f5.com/manage/s/article/K000163926", + }, + { + ID: Reuse, Short: "use-after-free in HTTP/2 connection reuse", + Introduced: MustV("1.19.7"), Fixed: []V{MustV("1.30.7"), MustV("1.31.9")}, + PlusFixed: []V{MustV("37.0.7.1"), MustV("37.2.0.1")}, PlusFrom: 33, + Commits: []string{"2df48a501d0fb8212b7d39dffeeff5876332ba59", "0c87dd1db413e440a4e3ef7ee8acc518509e8809"}, + Advisory: "https://my.f5.com/manage/s/article/K000163928", + }, +} + +// ByID returns the CVE with that ID. +func ByID(id string) (CVE, bool) { + for _, c := range CVEs { + if c.ID == id { + return c, true + } + } + return CVE{}, false +} + +// FixedText is how a message names the fixed releases. +const FixedText = "1.31.9 (mainline) and 1.30.7 (stable)" + +// V is a version of dotted numbers, 2 to 4 of them. +type V []int + +// ParseV reads "1.31.8" or "37.0.7.1". Anything else (a letter, a +// suffix, a leading zero run longer than the number allows, more than +// four parts) is an error: a version the detector cannot read is never +// judged. +func ParseV(s string) (V, error) { + parts := strings.Split(s, ".") + if len(parts) < 2 || len(parts) > 4 { + return nil, fmt.Errorf("version %q: want 2 to 4 numbers", s) + } + out := make(V, len(parts)) + for i, p := range parts { + if p == "" || len(p) > 6 { + return nil, fmt.Errorf("version %q: bad number %q", s, p) + } + for _, r := range p { + if r < '0' || r > '9' { + return nil, fmt.Errorf("version %q: %q is not a number", s, p) + } + } + n, err := strconv.Atoi(p) + if err != nil { + return nil, err + } + out[i] = n + } + return out, nil +} + +// MustV is ParseV for constants. +func MustV(s string) V { + v, err := ParseV(s) + if err != nil { + panic(err) + } + return v +} + +func (v V) String() string { + s := make([]string, len(v)) + for i, n := range v { + s[i] = strconv.Itoa(n) + } + return strings.Join(s, ".") +} + +// Cmp compares two versions; a missing part counts as 0. +func Cmp(a, b V) 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 a version's first two numbers ("1.31"). +func (v V) Line() V { + if len(v) < 2 { + return v + } + return V{v[0], v[1]} +} + +// Status is a judgement. +type Status string + +const ( + Vulnerable Status = "vulnerable" + Fixed Status = "fixed" + NotAffected Status = "not-affected" + Unknown Status = "unknown" +) + +// lines judges v by per-line fixed releases: at or past the line's fix is +// fixed, before it vulnerable; a line newer than every known one is +// unknown; an older line, or one between, got no fix. +func lines(v V, fixed, others []V) (Status, string) { + newest := fixed[0] + known := fixed[0] + for _, f := range append(append([]V(nil), fixed...), others...) { + if Cmp(f.Line(), known.Line()) > 0 { + known = f + } + } + for _, f := range fixed { + if Cmp(f.Line(), v.Line()) == 0 { + if Cmp(v, f) >= 0 { + return Fixed, fmt.Sprintf("%s is at or past %s, the fixed release of its line", v, f) + } + return Vulnerable, fmt.Sprintf("%s is before %s, the fixed release of its line", v, f) + } + if Cmp(f, newest) > 0 { + newest = f + } + } + if Cmp(v.Line(), known.Line()) > 0 { + // A later line would carry the fix, but none was known on the + // check date: a version that claims one is not taken at its word + // (NGINX Plus's 37.x numbers, a forged or misread version line). + return Unknown, fmt.Sprintf("%s is on the %s line, newer than any known on %s (newest %s): not judged", v, v.Line(), Checked, known.Line()) + } + if Cmp(v.Line(), newest.Line()) > 0 { + return Fixed, fmt.Sprintf("%s is on the %s line, a known line that came after the fix (%s)", v, v.Line(), newest) + } + return Vulnerable, fmt.Sprintf("%s is on the %s line, which received no fix", v, v.Line()) +} + +// allFixed lists every CVE's fixed releases: the lines known to exist. +func allFixed(plus bool) []V { + var out []V + for _, c := range CVEs { + if plus { + out = append(out, c.PlusFixed...) + } else { + out = append(out, c.Fixed...) + } + } + return out +} + +// Nginx judges an upstream nginx version (three numbers). +func Nginx(c CVE, v V) (Status, string) { + if len(v) != 3 { + return Unknown, fmt.Sprintf("nginx version %s does not have three numbers", v) + } + if Cmp(v, c.Introduced) < 0 { + return NotAffected, fmt.Sprintf("nginx %s is older than %s, the first release with the flawed code", v, c.Introduced) + } + st, why := lines(v, c.Fixed, allFixed(false)) + return st, "nginx " + why +} + +// OpenResty releases: the newest known release on each nginx core +// (openresty/openresty tags, 2026-11-18). OpenResty backports nginx +// security fixes as patches without a new core, so a release newer than +// these on an unfixed core may carry the fix. +var OpenRestyNewest = map[string]int{ + "0.8.54": 9, "1.0.4": 2, "1.0.5": 1, "1.0.6": 22, "1.0.8": 26, "1.0.9": 10, "1.0.10": 48, "1.0.11": 28, "1.0.15": 11, + "1.1.12": 5, "1.1.13": 1, "1.2.1": 14, "1.2.3": 8, "1.2.4": 14, "1.2.6": 6, "1.2.7": 8, "1.2.8": 6, "1.4.1": 3, + "1.4.2": 9, "1.4.3": 9, "1.5.8": 1, "1.5.11": 1, "1.5.12": 1, "1.7.0": 1, "1.7.2": 1, "1.7.4": 1, "1.7.7": 2, + "1.7.10": 2, "1.9.3": 2, "1.9.7": 5, "1.9.15": 1, "1.11.2": 5, "1.13.6": 2, "1.15.8": 3, "1.17.8": 2, "1.19.3": 2, + "1.19.9": 2, "1.21.4": 4, "1.25.3": 2, "1.27.1": 2, "1.29.2": 5, "1.31.1": 1, "1.31.8": 1, +} + +// OpenResty judges an OpenResty release (four numbers: the nginx core and +// OpenResty's own). +func OpenResty(c CVE, v V) (Status, string) { + if len(v) != 4 { + return Unknown, fmt.Sprintf("OpenResty version %s does not have four numbers", v) + } + core := v[:3] + st, why := Nginx(c, core) + if st != Vulnerable { + return st, fmt.Sprintf("OpenResty %s bundles nginx %s: %s", v, core, strings.TrimPrefix(why, "nginx ")) + } + newest, ok := OpenRestyNewest[core.String()] + if !ok || v[3] > newest { + return Unknown, fmt.Sprintf("OpenResty %s is not a release known on %s; its nginx core %s has the flaw, and OpenResty backports fixes as patches, so a newer release may carry it", v, Checked, core) + } + return Vulnerable, fmt.Sprintf("OpenResty %s bundles nginx %s (%s), and no OpenResty release carries the fix (newest on %s: 1.31.8.1)", v, core, strings.TrimPrefix(why, "nginx "), Checked) +} + +// Newest known releases of the forks that carry the unfixed code +// (FACTS.md: inferred from their source). +var ( + TengineNewest = MustV("3.2.0") + AngieNewest = MustV("1.12.4") +) + +// Tengine judges a Tengine release by its own number, with its nginx core +// for the lower bound. +func Tengine(c CVE, v, core V, http2 bool) (Status, string) { + if core != nil && len(core) == 3 && Cmp(core, MustV("1.9.5")) < 0 && http2 { + // HTTP/2 on a core that predates it: Tengine 2.1.2 to 2.2.x carry + // nginx's HTTP/2 code with the unfixed WINDOW_UPDATE check and + // refund, and not the 2021 reuse change (alibaba/tengine + // src/http/v2 at tengine-2.1.2 and tengine-2.2.2; the change came + // with 2.4.0). + switch { + case Cmp(v, MustV("2.1.2")) >= 0 && Cmp(v, MustV("2.3.0")) < 0 && c.ID == Flow: + return Vulnerable, fmt.Sprintf("Tengine %s carries nginx's HTTP/2 code on core %s with the unfixed flow-control check (read from Tengine's source)", v, core) + case Cmp(v, MustV("2.1.2")) >= 0 && Cmp(v, MustV("2.3.0")) < 0: + return NotAffected, fmt.Sprintf("Tengine %s's HTTP/2 code predates the reuse change that brought the flaw (read from Tengine's source; it came with Tengine 2.4.0)", v) + } + return Unknown, fmt.Sprintf("Tengine %s has HTTP/2 on core %s, older than nginx's HTTP/2: which code it carries is not known", v, core) + } + if core != nil && len(core) == 3 && Cmp(core, c.Introduced) < 0 { + return NotAffected, fmt.Sprintf("Tengine %s is based on nginx %s, older than %s", v, core, c.Introduced) + } + if Cmp(v, TengineNewest) <= 0 { + if core == nil { + return Unknown, fmt.Sprintf("Tengine %s: its nginx core could not be read", v) + } + return Vulnerable, fmt.Sprintf("Tengine %s (nginx core %s) carries the unfixed HTTP/2 code; no Tengine release with the fix was known on %s (newest tag 3.2.0-rc5)", v, core, Checked) + } + return Unknown, fmt.Sprintf("Tengine %s is newer than the newest release known on %s (3.2.0-rc5); whether it carries the fix is not known", v, Checked) +} + +// Angie judges an Angie release. Angie forked from nginx 1.23 (2022), +// after both flaws were in the code. +func Angie(c CVE, v V) (Status, string) { + if Cmp(v, AngieNewest) <= 0 { + return Vulnerable, fmt.Sprintf("Angie %s carries the unfixed HTTP/2 code; no Angie release carries the fix (newest on %s: 1.12.4)", v, Checked) + } + return Unknown, fmt.Sprintf("Angie %s is newer than the newest release known on %s (1.12.4); whether it carries the fix is not known", v, Checked) +} + +// Plus judges NGINX Plus by its own release: "r33", "r33-p2" or a numbered +// release such as "37.0.7.1". core is the nginx version in the same +// binary, used for releases F5 does not list. +func Plus(c CVE, rel string, core V) (Status, string) { + if v, err := ParseV(rel); err == nil && len(v) == 4 { + if v[0] < 37 { + return Unknown, fmt.Sprintf("NGINX Plus %s: a numbered release before 37 is not known", v) + } + st, why := lines(v, c.PlusFixed, allFixed(true)) + return st, "NGINX Plus " + why + } + r, p, ok := plusR(rel) + if !ok { + return Unknown, fmt.Sprintf("NGINX Plus release %q could not be read", rel) + } + switch { + case r >= 37: + return Unknown, fmt.Sprintf("NGINX Plus R%d%s: how R%d patch releases map to the fixed releases (%s) is not known", r, p, r, plusFixedText(c)) + case r >= c.PlusFrom: + return Vulnerable, fmt.Sprintf("NGINX Plus R%d%s is affected (F5 lists R%d and later; fixed in %s)", r, p, c.PlusFrom, plusFixedText(c)) + case core != nil: + st, why := Nginx(c, core) + return st, fmt.Sprintf("NGINX Plus R%d%s is not listed by F5 (end of life); judged by its nginx core: %s", r, p, why) + } + return Unknown, fmt.Sprintf("NGINX Plus R%d%s is not listed by F5 and its nginx core could not be read", r, p) +} + +func plusFixedText(c CVE) string { + s := make([]string, len(c.PlusFixed)) + for i, v := range c.PlusFixed { + s[i] = v.String() + } + return strings.Join(s, " and ") +} + +// plusR reads "r33" or "r33-p2". +func plusR(s string) (int, string, bool) { + s = strings.ToLower(s) + if !strings.HasPrefix(s, "r") { + return 0, "", false + } + num, patch, _ := strings.Cut(s[1:], "-") + n, err := strconv.Atoi(num) + if err != nil || n <= 0 || n > 999 || len(num) > 3 { + return 0, "", false + } + if patch != "" { + if !strings.HasPrefix(patch, "p") { + return 0, "", false + } + if _, err := strconv.Atoi(patch[1:]); err != nil || len(patch) > 4 { + return 0, "", false + } + patch = "-" + patch + } + return n, patch, true +} + +// UpstreamOf reads the upstream nginx version from a package version: +// "1:1.22.1-9+deb12u10" (Debian), "1.30.6-r0" (Alpine), "1.31.8-1~trixie" +// (nginx.org), "1.24.0-4.module+el9.4.0+21950+8ebc21e1" (Red Hat). +func UpstreamOf(pkg string) (V, error) { + if _, after, ok := strings.Cut(pkg, ":"); ok { + pkg = after + } + up, _, _ := strings.Cut(pkg, "-") + return ParseV(up) +} diff --git a/detectors/nginxh2/internal/knowledge/knowledge_test.go b/detectors/nginxh2/internal/knowledge/knowledge_test.go new file mode 100644 index 0000000..28c238e --- /dev/null +++ b/detectors/nginxh2/internal/knowledge/knowledge_test.go @@ -0,0 +1,173 @@ +package knowledge + +import "testing" + +func TestParseV(t *testing.T) { + for _, bad := range []string{"", "1", "1.31.8-1", "1.31.8~", "1.31.8.1.2", "1..2", "a.b", "1.31.8 ", "+1.2", "1.2.3a", "1234567.1"} { + if _, err := ParseV(bad); err == nil { + t.Errorf("ParseV(%q) accepted", bad) + } + } + if v, err := ParseV("37.0.7.1"); err != nil || v.String() != "37.0.7.1" { + t.Errorf("ParseV 37.0.7.1 = %v %v", v, err) + } +} + +func TestNginxBoundaries(t *testing.T) { + flow, _ := ByID(Flow) + reuse, _ := ByID(Reuse) + cases := []struct { + v string + flow, reuse Status + }{ + {"1.9.4", NotAffected, NotAffected}, + {"1.9.5", Vulnerable, NotAffected}, + {"1.18.0", Vulnerable, NotAffected}, + {"1.19.6", Vulnerable, NotAffected}, + {"1.19.7", Vulnerable, Vulnerable}, + {"1.22.1", Vulnerable, Vulnerable}, + {"1.29.8", Vulnerable, Vulnerable}, + {"1.30.0", Vulnerable, Vulnerable}, + {"1.30.6", Vulnerable, Vulnerable}, + {"1.30.7", Fixed, Fixed}, + {"1.30.10", Fixed, Fixed}, + {"1.31.0", Vulnerable, Vulnerable}, + {"1.31.8", Vulnerable, Vulnerable}, + {"1.31.9", Fixed, Fixed}, + {"1.31.10", Fixed, Fixed}, + {"1.32.0", Unknown, Unknown}, // R5: above the newest known line + {"2.0.0", Unknown, Unknown}, + {"37.0.0", Unknown, Unknown}, + {"37.0.7", Unknown, Unknown}, + {"0.8.54", NotAffected, NotAffected}, + } + for _, c := range cases { + v := MustV(c.v) + if got, why := Nginx(flow, v); got != c.flow { + t.Errorf("%s flow = %s (%s), want %s", c.v, got, why, c.flow) + } + if got, why := Nginx(reuse, v); got != c.reuse { + t.Errorf("%s reuse = %s (%s), want %s", c.v, got, why, c.reuse) + } + } + if st, _ := Nginx(flow, MustV("1.31")); st != Unknown { + t.Errorf("two-part nginx version judged %s", st) + } +} + +func TestOpenResty(t *testing.T) { + flow, _ := ByID(Flow) + reuse, _ := ByID(Reuse) + for _, c := range []struct { + v string + want Status + cve CVE + }{ + {"1.31.8.1", Vulnerable, flow}, + {"1.31.8.2", Unknown, flow}, // newer than known: may carry a backport + {"1.27.1.2", Vulnerable, flow}, + {"1.27.1.3", Unknown, flow}, + {"1.31.9.1", Fixed, flow}, + {"1.19.3.2", NotAffected, reuse}, // core 1.19.3 < 1.19.7 + {"1.19.3.2", Vulnerable, flow}, + {"1.19.9.1", Vulnerable, reuse}, + {"1.23.0.1", Unknown, flow}, // core with no known release + {"1.31.8", Unknown, flow}, + } { + if got, why := OpenResty(c.cve, MustV(c.v)); got != c.want { + t.Errorf("OpenResty %s %s = %s (%s), want %s", c.v, c.cve.ID, got, why, c.want) + } + } +} + +func TestForks(t *testing.T) { + flow, _ := ByID(Flow) + reuse, _ := ByID(Reuse) + if st, _ := Tengine(reuse, MustV("3.2.0"), MustV("1.31.5"), true); st != Vulnerable { + t.Errorf("Tengine 3.2.0 = %s", st) + } + if st, _ := Tengine(reuse, MustV("2.3.3"), MustV("1.18.0"), true); st != NotAffected { + t.Errorf("Tengine 2.3.3 on 1.18.0 reuse = %s", st) + } + if st, _ := Tengine(flow, MustV("2.3.3"), MustV("1.18.0"), true); st != Vulnerable { + t.Errorf("Tengine 2.3.3 on 1.18.0 flow = %s", st) + } + if st, _ := Tengine(flow, MustV("3.3.0"), MustV("1.31.9"), true); st != Unknown { + t.Errorf("Tengine 3.3.0 = %s, want unknown (never cleared by its core)", st) + } + if st, _ := Tengine(flow, MustV("3.1.0"), nil, true); st != Unknown { + t.Errorf("Tengine without core = %s", st) + } + if st, _ := Angie(flow, MustV("1.12.4")); st != Vulnerable { + t.Errorf("Angie 1.12.4 = %s", st) + } + if st, _ := Angie(flow, MustV("1.13.0")); st != Unknown { + t.Errorf("Angie 1.13.0 = %s", st) + } +} + +func TestPlus(t *testing.T) { + flow, _ := ByID(Flow) + reuse, _ := ByID(Reuse) + cases := []struct { + rel string + flow, reuse Status + }{ + {"37.0.7.0", Vulnerable, Vulnerable}, + {"37.0.7.1", Vulnerable, Fixed}, + {"37.0.8.1", Fixed, Fixed}, + {"37.1.5.0", Vulnerable, Vulnerable}, + {"37.2.0.0", Vulnerable, Vulnerable}, + {"37.2.0.1", Vulnerable, Fixed}, + {"37.3.0.0", Vulnerable, Fixed}, + {"37.3.0.1", Fixed, Fixed}, + {"37.4.0.0", Unknown, Unknown}, + {"r33", Vulnerable, Vulnerable}, + {"r36-p1", Vulnerable, Vulnerable}, + {"r37", Unknown, Unknown}, + {"r37-p3", Unknown, Unknown}, + {"rx", Unknown, Unknown}, + {"36.0.1.0", Unknown, Unknown}, + } + for _, c := range cases { + if got, why := Plus(flow, c.rel, MustV("1.27.2")); got != c.flow { + t.Errorf("Plus %s flow = %s (%s), want %s", c.rel, got, why, c.flow) + } + if got, why := Plus(reuse, c.rel, MustV("1.27.2")); got != c.reuse { + t.Errorf("Plus %s reuse = %s (%s), want %s", c.rel, got, why, c.reuse) + } + } + // Before R33 F5 lists nothing: the core decides. + if st, _ := Plus(reuse, "r23", MustV("1.19.5")); st != NotAffected { + t.Errorf("Plus r23 on 1.19.5 = %s", st) + } + if st, _ := Plus(reuse, "r30", nil); st != Unknown { + t.Errorf("Plus r30 without core = %s", st) + } +} + +func TestUpstreamOf(t *testing.T) { + for in, want := range map[string]string{ + "1:1.22.1-9+deb12u10": "1.22.1", "1.30.6-r0": "1.30.6", "1.31.8-1~trixie": "1.31.8", + "1.24.0-4.module+el9.4.0+21950+8ebc21e1": "1.24.0", "1.24.0-2ubuntu7.19": "1.24.0", + } { + v, err := UpstreamOf(in) + if err != nil || v.String() != want { + t.Errorf("UpstreamOf(%q) = %v, %v", in, v, err) + } + } + if _, err := UpstreamOf("1.22.1+dfsg-1"); err == nil { + t.Error("UpstreamOf accepted a version with a suffix") + } +} + +func TestDistroOf(t *testing.T) { + for in, want := range map[[2]string]string{ + {"debian", ""}: "debian", {"ubuntu", "debian"}: "ubuntu", {"rocky", "rhel centos fedora"}: "rhel", + {"linuxmint", "ubuntu debian"}: "ubuntu", {"wolfi", ""}: "", {"alpine", ""}: "alpine", + } { + if got := DistroOf(in[0], in[1]); got != want { + t.Errorf("DistroOf%v = %q, want %q", in, got, want) + } + } +} diff --git a/detectors/nginxh2/internal/knowledge/vendors.go b/detectors/nginxh2/internal/knowledge/vendors.go new file mode 100644 index 0000000..1160106 --- /dev/null +++ b/detectors/nginxh2/internal/knowledge/vendors.go @@ -0,0 +1,71 @@ +package knowledge + +import "strings" + +// Backport is a distribution package that carries a CVE's fix without a +// new nginx version. +type Backport struct { + Distro string // os-release ID: debian, ubuntu, alpine, rhel + Release string // VERSION_ID for Debian and Ubuntu ("12"), the branch for Alpine ("3.24"); "" for any + Package string // source package + Fixed string // first fixed package version + CVEs []string + Advisory string +} + +// Backports is empty: no distribution had published a fixed nginx package +// on 2026-11-18 (FACTS.md). +var Backports []Backport + +// DistroStatus says, for a distribution's own nginx package, what was +// published by the check date. +var DistroStatus = map[string]string{ + "debian": "Debian had published no fixed nginx package on " + Checked + " (security tracker: unfixed in bookworm, trixie, forky and sid)", + "ubuntu": "Ubuntu had published no fixed nginx package on " + Checked + " (newest: jammy 1.18.0-6ubuntu14.22, noble 1.24.0-2ubuntu7.19, questing 1.28.0-6ubuntu1.8, resolute 1.28.3-2ubuntu1.12)", + "alpine": "Alpine published nginx 1.30.7-r0 for 3.24 and edge on " + Checked + " (17:06 UTC); 3.21 (1.26.3-r3), 3.22 and 3.23 (1.28.3-r7) had no fixed package at 17:47 UTC", + "rhel": "Red Hat's status could not be read on " + Checked + "; a Red Hat build is judged by its version until a fixed build is known", +} + +// AlpineFixed is the first fixed nginx package on each Alpine branch that +// has one: an upgrade to the fixed upstream release, so the binary's own +// version shows it (dl-cdn.alpinelinux.org APKINDEX, 2026-11-18 17:06 UTC +// for v3.24, 17:11 UTC for edge). +var AlpineFixed = map[string]string{"3.24": "1.30.7-r0", "edge": "1.30.7-r0"} + +// AlpineText says what an Alpine branch had published. +func AlpineText(branch string) string { + if v, ok := AlpineFixed[branch]; ok { + return "Alpine " + branch + " has the fixed nginx " + v + " (published " + Checked + ")" + } + if branch == "" { + return DistroStatus["alpine"] + } + return "Alpine " + branch + " had no fixed nginx package on " + Checked + " (17:47 UTC); Alpine 3.24 and edge have 1.30.7-r0" +} + +// DistroOf maps an os-release ID (and ID_LIKE) to the family whose status +// applies. +func DistroOf(id, like string) string { + for _, w := range append([]string{id}, strings.Fields(like)...) { + switch w { + case "debian", "ubuntu", "alpine": + return w + case "rhel", "centos", "rocky", "almalinux", "ol", "fedora", "amzn": + return "rhel" + } + } + return "" +} + +// NginxOrgMaintainer is in the Maintainer field of nginx.org's packages, +// which ship the upstream release and never backport. +func NginxOrgMaintainer(m string) bool { + m = strings.ToLower(m) + return strings.Contains(m, "nginx-packaging@f5.com") || strings.Contains(m, "nginx-packaging@nginx.com") || strings.Contains(m, "nginx packaging") +} + +// UpdateText is the fix text for an upstream build. +const UpdateText = "Update nginx to 1.31.9 (mainline) or 1.30.7 (stable): the Docker official image tags 1.31.9 and 1.30.7 (every variant), or nginx.org's packages of those releases." + +// Interim is the mitigation text, never a fix. +const Interim = "Until it is updated, turning HTTP/2 off (\"http2 off;\" from 1.25.1, and no \"http2\" parameter on any listen) removes the published path; it is not a fix." diff --git a/detectors/nginxh2/internal/ngx/binary.go b/detectors/nginxh2/internal/ngx/binary.go new file mode 100644 index 0000000..db3f835 --- /dev/null +++ b/detectors/nginxh2/internal/ngx/binary.go @@ -0,0 +1,421 @@ +// Package ngx reads what an nginx executable proves about itself: the +// product and version in its version line, whether HTTP/2 and TLS are +// compiled in, where its configuration lives, and its word size. It knows +// nothing about the engine. +package ngx + +import ( + "bytes" + "encoding/binary" + "strings" +) + +// Product is the server a binary is. +type Product string + +const ( + Nginx Product = "nginx" + OpenResty Product = "openresty" + Tengine Product = "tengine" + Angie Product = "angie" + Plus Product = "nginx-plus" + // Other is a version line naming something else ("nginx version: + // MyServer/2.0"): a renamed build. + Other Product = "other" + // Hidden is an nginx binary with no version line to read. + Hidden Product = "hidden" +) + +// Tri is a fact that may not be readable. +type Tri string + +const ( + Yes Tri = "yes" + No Tri = "no" + Unknown Tri = "unknown" +) + +// Binary is what one executable proves. +type Binary struct { + Path string `json:"path"` + Product Product `json:"product"` + // Name and Version are the version line's ("openresty", "1.31.8.1"). + Name string `json:"name,omitempty"` + Version string `json:"version,omitempty"` + // Core is the nginx version the build is based on (OpenResty, Tengine, + // Plus), "" when not read. + Core string `json:"core,omitempty"` + // Build is the version line's parenthesised text ("Ubuntu", + // "nginx-plus-r33-p2"). + Build string `json:"build,omitempty"` + // PlusRelease is NGINX Plus's own release ("r33-p2", "37.0.7.1"). + PlusRelease string `json:"plus_release,omitempty"` + HTTP2 Tri `json:"http2"` + TLS Tri `json:"tls"` + // Configure is the configure arguments, when the binary has them. + Configure string `json:"configure,omitempty"` + // ConfigureWhole is set when the configure arguments were read to + // their end, not cut at a limit. + ConfigureWhole bool `json:"configure_whole,omitempty"` + // ModuleList is set when the binary has nginx's module list (1.9.11 + // and later), the other witness of what is compiled in. + ModuleList bool `json:"module_list,omitempty"` + // ConfPath and Prefix are the defaults compiled in. + ConfPath string `json:"conf_path,omitempty"` + Prefix string `json:"prefix,omitempty"` + // ConfRaw is the configuration path as compiled in, before the + // prefix was applied: a relative one moves with -p. + ConfRaw string `json:"conf_raw,omitempty"` + Bits int `json:"bits,omitempty"` + Arch string `json:"arch,omitempty"` + // Conflict is set when the binary's version strings disagree. + Conflict string `json:"conflict,omitempty"` +} + +const maxField = 4096 + +var ( + configureMark = []byte("configure arguments:") + coreModule = []byte("\x00ngx_core_module\x00") + v2Module = []byte("\x00ngx_http_v2_module\x00") + sslModule = []byte("\x00ngx_http_ssl_module\x00") +) + +// Inspect reads data as an nginx executable. ok is false for anything +// else: an nginx binary has its "configure arguments:" line and either a +// version line or the core module's name. Dynamic modules have neither +// version nor configure line. +func Inspect(p string, data []byte) (*Binary, bool) { + if !bytes.Contains(data, configureMark) { + return nil, false + } + b := &Binary{Path: p, HTTP2: Unknown, TLS: Unknown} + found := b.versionLines(data) + if !found { + if !bytes.Contains(data, coreModule) { + return nil, false + } + b.Product = Hidden + } + b.Bits, b.Arch = header(data) + b.configure(data) + b.features(data) + b.paths(data) + b.consistent(data) + return b, true +} + +// line returns the text after mark up to a newline, NUL or limit. +func line(data []byte, at int) string { + end := at + for end < len(data) && end-at < maxField && data[end] != 0 && data[end] != '\n' && data[end] != '\r' { + end++ + } + return string(data[at:end]) +} + +// versionLines reads "nginx version: ", "Tengine version: " and "Angie +// version: " lines. The first nginx line decides; a second, different +// one is a conflict. +func (b *Binary) versionLines(data []byte) bool { + ng := lines(data, "nginx version: ") + te := lines(data, "Tengine version: ") + an := lines(data, "Angie version: ") + switch { + case len(an) > 0: + b.Product = Angie + b.Name, b.Version, b.Build = split(an[0]) + if len(uniq(an)) > 1 { + b.Conflict = "the binary has more than one Angie version line: " + strings.Join(uniq(an), "; ") + } + return true + case len(te) > 0: + b.Product = Tengine + b.Name, b.Version, b.Build = split(te[0]) + if len(uniq(te)) > 1 { + b.Conflict = "the binary has more than one Tengine version line: " + strings.Join(uniq(te), "; ") + } + if len(ng) > 0 { + if n, v, _ := split(ng[0]); n == "nginx" { + b.Core = v + } + } + // Before 2.3.3 one line: "Tengine/2.2.2 (nginx/1.8.1)". + if n, v, ok := strings.Cut(b.Build, "/"); ok && n == "nginx" && b.Core == "" { + b.Core = v + } + return true + case len(ng) == 0: + return false + } + if len(uniq(ng)) > 1 { + b.Conflict = "the binary has more than one nginx version line: " + strings.Join(uniq(ng), "; ") + } + b.Name, b.Version, b.Build = split(ng[0]) + switch { + case strings.EqualFold(b.Name, "openresty"): + b.Product = OpenResty + if parts := strings.Split(b.Version, "."); len(parts) == 4 { + b.Core = strings.Join(parts[:3], ".") + } + case b.Name == "nginx" && strings.Contains(asciiLower(b.Build), "nginx-plus"): + b.Product = Plus + b.Core = b.Version + low := asciiLower(b.Build) // same length as Build, so its indexes hold + i := strings.Index(low, "nginx-plus-") + if i >= 0 { + rel := b.Build[i+len("nginx-plus-"):] + if j := strings.IndexAny(rel, " ,;)"); j >= 0 { + rel = rel[:j] + } + b.PlusRelease = rel + } + case b.Name == "nginx": + b.Product = Nginx + b.Core = b.Version + default: + b.Product = Other + } + return true +} + +// asciiLower lowers ASCII letters only, keeping every byte where it is. +func asciiLower(s string) string { + b := []byte(s) + for i, c := range b { + if c >= 'A' && c <= 'Z' { + b[i] = c + 'a' - 'A' + } + } + return string(b) +} + +// lines returns each line that follows mark, in order. +func lines(data []byte, mark string) []string { + var out []string + m := []byte(mark) + for off := 0; off < len(data) && len(out) < 16; { + i := bytes.Index(data[off:], m) + if i < 0 { + break + } + at := off + i + len(m) + out = append(out, line(data, at)) + off = at + } + return out +} + +func uniq(xs []string) []string { + var out []string + seen := map[string]bool{} + for _, x := range xs { + if !seen[x] { + seen[x] = true + out = append(out, x) + } + } + return out +} + +// split reads "nginx/1.24.0 (Ubuntu)" into name, version and build. +func split(s string) (name, version, build string) { + s = strings.TrimSpace(s) + if i := strings.Index(s, " ("); i >= 0 && strings.HasSuffix(s, ")") { + build = s[i+2 : len(s)-1] + s = s[:i] + } + name, version, ok := strings.Cut(s, "/") + if !ok { + return s, "", build + } + return name, strings.TrimSpace(version), build +} + +func (b *Binary) configure(data []byte) { + i := bytes.Index(data, configureMark) + if i < 0 { + return + } + at := i + len(configureMark) + end := at + for end < len(data) && end-at < maxConfigure && data[end] != 0 && data[end] != '\n' && data[end] != '\r' { + end++ + } + b.Configure = strings.TrimSpace(string(data[at:end])) + b.ConfigureWhole = end < len(data) && end-at < maxConfigure + if len(b.Configure) > maxField { + b.Configure = b.Configure[:maxField] + b.ConfigureWhole = false // kept short: only its head is reported + } +} + +// maxConfigure is the most of the configure arguments read. +const maxConfigure = 64 << 10 + +// features decides HTTP/2 and TLS. The module's name in the module list +// proves it is compiled in. Its absence proves it is not only when the +// configure arguments were read and do not ask for it either (builds +// before 1.9.11 have no module list). +func (b *Binary) features(data []byte) { + cfg := " " + b.Configure + " " + b.ModuleList = bytes.Contains(data, coreModule) + decide := func(name []byte, flag string) Tri { + switch { + case bytes.Contains(data, name), strings.Contains(cfg, " "+flag+" "): + return Yes + case b.ConfigureWhole && b.ModuleList: + // Both witnesses read whole, and neither has it. + return No + } + return Unknown + } + b.HTTP2 = decide(v2Module, "--with-http_v2_module") + b.TLS = decide(sslModule, "--with-http_ssl_module") +} + +// paths reads the default configuration file and prefix: the help text +// first (it is what the binary uses), then the configure arguments. +func (b *Binary) paths(data []byte) { + if c := between(data, "set configuration file (default: ", ")"); c != "" { + b.ConfPath = c + } + if p := between(data, "set prefix path (default: ", ")"); p != "" { + b.Prefix = p + } + for _, w := range strings.Fields(b.Configure) { + if v, ok := strings.CutPrefix(w, "--conf-path="); ok && b.ConfPath == "" { + b.ConfPath = strings.Trim(v, "'\"") + } + if v, ok := strings.CutPrefix(w, "--prefix="); ok && b.Prefix == "" { + b.Prefix = strings.Trim(v, "'\"") + } + } + if b.ConfPath == "" { + b.ConfPath = "conf/nginx.conf" // nginx's own default, under the prefix + } + b.ConfRaw = b.ConfPath + if !strings.HasPrefix(b.ConfPath, "/") && b.Prefix == "" { + b.ConfPath = "" + } + if b.ConfPath != "" && !strings.HasPrefix(b.ConfPath, "/") && b.Prefix != "" { + b.ConfPath = strings.TrimSuffix(b.Prefix, "/") + "/" + b.ConfPath + } +} + +func between(data []byte, start, end string) string { + i := bytes.Index(data, []byte(start)) + if i < 0 { + return "" + } + rest := line(data, i+len(start)) + j := strings.Index(rest, end) + if j <= 0 || j > 1024 { + return "" + } + return rest[:j] +} + +// consistent checks the binary's other "/" strings (the +// Server header, the error page footer) against its version line: a +// binary whose strings disagree has been edited or merged, and is not +// judged by either. +func (b *Binary) consistent(data []byte) { + if b.Conflict != "" || b.Version == "" { + return + } + name := b.Name + if b.Product == Angie { + name = "Angie" + } + if b.Product == Tengine { + name = "Tengine" + } + mark := []byte(name + "/") + for off := 0; off < len(data); { + i := bytes.Index(data[off:], mark) + if i < 0 { + return + } + at := off + i + off = at + len(mark) + if at > 0 && isWord(data[at-1]) { + continue // part of a longer name or a path ("/etc/nginx/") + } + v := versionAt(data, off) + if v == "" { + continue + } + if v != b.Version { + b.Conflict = "the binary's version line says " + name + "/" + b.Version + " but it also carries " + name + "/" + v + return + } + } +} + +func isWord(c byte) bool { + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '-' || c == '/' || c == '.' +} + +// versionAt reads dotted digits at i, "" when there are none. +func versionAt(data []byte, i int) string { + j := i + for j < len(data) && j-i < 32 && (data[j] >= '0' && data[j] <= '9' || data[j] == '.') { + j++ + } + if j == i || data[i] == '.' { + return "" + } + return strings.TrimRight(string(data[i:j]), ".") +} + +// header reads the word size and CPU from an ELF, PE or Mach-O header. +func header(d []byte) (int, string) { + switch { + case len(d) >= 20 && bytes.HasPrefix(d, []byte("\x7fELF")): + bits := 0 + switch d[4] { + case 1: + bits = 32 + case 2: + bits = 64 + } + var order binary.ByteOrder = binary.LittleEndian + if d[5] == 2 { + order = binary.BigEndian + } + return bits, elfMachine[order.Uint16(d[18:20])] + case len(d) >= 64 && d[0] == 'M' && d[1] == 'Z': + off := int(binary.LittleEndian.Uint32(d[0x3c:])) + if off < 0 || off+6 > len(d) || string(d[off:off+4]) != "PE\x00\x00" { + return 0, "" + } + switch binary.LittleEndian.Uint16(d[off+4:]) { + case 0x8664: + return 64, "x86_64" + case 0xaa64: + return 64, "aarch64" + case 0x14c: + return 32, "i386" + } + return 0, "" + case len(d) >= 8: + magic := binary.LittleEndian.Uint32(d) + cpu := binary.LittleEndian.Uint32(d[4:]) + switch magic { + case 0xfeedfacf: + switch cpu { + case 0x01000007: + return 64, "x86_64" + case 0x0100000c: + return 64, "arm64" + } + return 64, "" + case 0xfeedface: + return 32, "" + } + } + return 0, "" +} + +var elfMachine = map[uint16]string{3: "i386", 8: "mips", 20: "ppc", 21: "ppc64", 22: "s390x", 40: "arm", 62: "x86_64", 183: "aarch64", 243: "riscv64"} diff --git a/detectors/nginxh2/internal/ngx/binary_test.go b/detectors/nginxh2/internal/ngx/binary_test.go new file mode 100644 index 0000000..53a8b25 --- /dev/null +++ b/detectors/nginxh2/internal/ngx/binary_test.go @@ -0,0 +1,164 @@ +package ngx_test + +import ( + "os" + "path/filepath" + "testing" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngx" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngxtest" +) + +func TestInspectOfficial(t *testing.T) { + b, ok := ngx.Inspect("/usr/sbin/nginx", ngxtest.Default("1.31.8").Bytes()) + if !ok { + t.Fatal("not recognised") + } + if b.Product != ngx.Nginx || b.Version != "1.31.8" || b.HTTP2 != ngx.Yes || b.TLS != ngx.Yes || b.ConfPath != "/etc/nginx/nginx.conf" || b.Bits != 64 || b.Arch != "x86_64" || b.Conflict != "" { + t.Errorf("got %+v", b) + } +} + +func TestInspectProducts(t *testing.T) { + ubuntu := ngxtest.Default("1.24.0") + ubuntu.Line = "nginx/1.24.0 (Ubuntu)" + or := ngxtest.Default("x") + or.Line, or.Extra = "openresty/1.31.8.1", []string{"openresty/1.31.8.1", "1.31.8"} + plus := ngxtest.Default("1.27.2") + plus.Line = "nginx/1.27.2 (nginx-plus-r33-p2)" + te := ngxtest.Default("1.31.5") + te.Tengine = "Tengine/3.2.0" + an := ngxtest.Default("1.31.3") + an.Angie, an.Extra = "Angie/1.12.4", []string{"Angie/1.12.4", "nginx/1.31.3"} + other := ngxtest.Default("1.0") + other.Line, other.Extra = "WAF/2.1", nil + cases := []struct { + name string + b ngxtest.Build + product ngx.Product + version string + core string + extra func(*ngx.Binary) bool + }{ + {"ubuntu", ubuntu, ngx.Nginx, "1.24.0", "1.24.0", func(b *ngx.Binary) bool { return b.Build == "Ubuntu" }}, + {"openresty", or, ngx.OpenResty, "1.31.8.1", "1.31.8", nil}, + {"plus", plus, ngx.Plus, "1.27.2", "1.27.2", func(b *ngx.Binary) bool { return b.PlusRelease == "r33-p2" }}, + {"tengine", te, ngx.Tengine, "3.2.0", "1.31.5", nil}, + {"angie", an, ngx.Angie, "1.12.4", "", nil}, + {"other", other, ngx.Other, "2.1", "", nil}, + } + for _, c := range cases { + b, ok := ngx.Inspect("/x", c.b.Bytes()) + if !ok { + t.Errorf("%s: not recognised", c.name) + continue + } + if b.Product != c.product || b.Version != c.version || b.Core != c.core || b.Conflict != "" || c.extra != nil && !c.extra(b) { + t.Errorf("%s: got %+v", c.name, b) + } + } +} + +func TestInspectHiddenAndConflicts(t *testing.T) { + hidden := ngxtest.Default("1.31.8") + hidden.Line, hidden.Extra = "", nil + b, ok := ngx.Inspect("/x", hidden.Bytes()) + if !ok || b.Product != ngx.Hidden { + t.Fatalf("hidden: %v %+v", ok, b) + } + // A version line that disagrees with the Server header string. + edited := ngxtest.Default("1.31.9") + edited.Extra = []string{"Server: nginx/1.31.8\r\n"} + if b, _ := ngx.Inspect("/x", edited.Bytes()); b.Conflict == "" { + t.Error("an edited version line was not noticed") + } + two := ngxtest.Default("1.31.9") + two.Extra = append(two.Extra, "nginx version: nginx/1.31.8\n") + if b, _ := ngx.Inspect("/x", two.Bytes()); b.Conflict == "" { + t.Error("two version lines were not noticed") + } + // Paths with nginx/ are not versions. + paths := ngxtest.Default("1.31.9") + paths.Extra = append(paths.Extra, "/etc/nginx/nginx.conf", "/usr/lib/nginx/1modules", "
nginx/1.31.9
") + if b, _ := ngx.Inspect("/x", paths.Bytes()); b.Conflict != "" { + t.Errorf("paths read as versions: %s", b.Conflict) + } +} + +func TestInspectRejects(t *testing.T) { + // A dynamic module imports ngx_core_module but has no configure line. + mod := []byte("\x7fELF\x02\x01\x00ngx_core_module\x00ngx_http_v2_module\x00") + if _, ok := ngx.Inspect("/m.so", mod); ok { + t.Error("a dynamic module was taken for nginx") + } + if _, ok := ngx.Inspect("/x", []byte("\x7fELF\x00configure arguments: --prefix=/x\n\x00")); ok { + t.Error("configure arguments alone made an nginx binary") + } +} + +func TestFeatures(t *testing.T) { + noV2 := ngxtest.Default("1.31.8") + noV2.Configure = "--prefix=/etc/nginx --with-http_ssl_module" + noV2.Modules = []string{"ngx_core_module", "ngx_http_ssl_module"} + b, _ := ngx.Inspect("/x", noV2.Bytes()) + if b.HTTP2 != ngx.No || b.TLS != ngx.Yes { + t.Errorf("no v2: %+v", b) + } + // Before 1.9.11 there is no module list: the configure flag shows + // what is in, and nothing shows what is out. + old := ngxtest.Build{Line: "nginx/1.9.6", Configure: "--with-http_v2_module"} + b, _ = ngx.Inspect("/x", old.Bytes()) + if b.HTTP2 != ngx.Yes || b.TLS != ngx.Unknown { + t.Errorf("old: %+v", b) + } + // Empty configure arguments and no module list: not known. + bare := ngxtest.Build{Line: "nginx/1.9.6"} + b, _ = ngx.Inspect("/x", bare.Bytes()) + if b.HTTP2 != ngx.Unknown { + t.Errorf("bare: %+v", b) + } + // --with-http_v2_module_x is not the flag. + near := ngxtest.Build{Line: "nginx/1.9.6", Configure: "--with-http_v2_modulex --prefix=/usr/local/nginx", Modules: []string{"ngx_core_module"}} + b, _ = ngx.Inspect("/x", near.Bytes()) + if b.HTTP2 != ngx.No || b.ConfPath != "/usr/local/nginx/conf/nginx.conf" { + t.Errorf("near: %+v", b) + } +} + +func TestBits(t *testing.T) { + b32 := ngxtest.Default("1.31.8") + b32.Bits, b32.Machine = 32, 3 + b, _ := ngx.Inspect("/x", b32.Bytes()) + if b.Bits != 32 || b.Arch != "i386" { + t.Errorf("32-bit: %+v", b) + } + arm := ngxtest.Default("1.31.8") + arm.Machine = 183 + b, _ = ngx.Inspect("/x", arm.Bytes()) + if b.Arch != "aarch64" { + t.Errorf("arm64: %+v", b) + } +} + +// TestRealBinaries reads the binaries in testdata/real when they are +// there (they are not committed: NGINXH2_REAL points at a directory of +// binaries copied out of images, named _). +func TestRealBinaries(t *testing.T) { + dir := os.Getenv("NGINXH2_REAL") + if dir == "" { + t.Skip("NGINXH2_REAL not set") + } + ms, _ := filepath.Glob(filepath.Join(dir, "*.bin")) + for _, m := range ms { + data, err := os.ReadFile(m) + if err != nil { + t.Fatal(err) + } + b, ok := ngx.Inspect(m, data) + if !ok || b.Conflict != "" || b.Version == "" || b.HTTP2 != ngx.Yes { + t.Errorf("%s: %v %+v", m, ok, b) + continue + } + t.Logf("%s: %s %s core %s build %q conf %s", filepath.Base(m), b.Product, b.Version, b.Core, b.Build, b.ConfPath) + } +} diff --git a/detectors/nginxh2/internal/ngx/fuzz_test.go b/detectors/nginxh2/internal/ngx/fuzz_test.go new file mode 100644 index 0000000..10263a9 --- /dev/null +++ b/detectors/nginxh2/internal/ngx/fuzz_test.go @@ -0,0 +1,73 @@ +package ngx_test + +import ( + "testing" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/knowledge" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngx" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngxtest" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/pkgdb" +) + +// FuzzInspect: no input panics, and a binary is never both conflicting +// and judged by a version it says it does not have. +func FuzzInspect(f *testing.F) { + or := ngxtest.Default("x") + or.Line = "openresty/1.31.8.1" + te := ngxtest.Default("1.31.5") + te.Tengine = "Tengine/3.2.0" + for _, b := range []ngxtest.Build{ngxtest.Default("1.31.8"), or, te, {Line: "nginx/1.24.0 (nginx-plus-r33-p2)"}} { + f.Add(b.Bytes()) + } + f.Add([]byte("configure arguments:\x00ngx_core_module\x00")) + f.Add([]byte("MZ\x00\x00configure arguments: nginx version: nginx/1.2.3 (x")) + f.Fuzz(func(t *testing.T, data []byte) { + b, ok := ngx.Inspect("/x", data) + if !ok { + return + } + if b.HTTP2 == "" || b.TLS == "" || b.Product == "" { + t.Fatalf("empty field: %+v", b) + } + if len(b.Configure) > 4096 || len(b.Version) > 4096 { + t.Fatalf("unbounded field") + } + }) +} + +// FuzzVersions: version parsing and comparison never panic, and +// comparison is antisymmetric. +func FuzzVersions(f *testing.F) { + f.Add("1.31.8", "1.22.1-9+deb12u10", "1.30.6-r0") + f.Add("37.0.7.1", "1:1.0~rc1-1", "1.0_p1-r2") + f.Fuzz(func(t *testing.T, v, deb, apk string) { + if x, err := knowledge.ParseV(v); err == nil { + for _, c := range knowledge.CVEs { + knowledge.Nginx(c, x) + knowledge.OpenResty(c, x) + knowledge.Plus(c, v, x) + knowledge.Angie(c, x) + knowledge.Tengine(c, x, x, true) + } + } + knowledge.UpstreamOf(deb) + if a, b := pkgdb.CompareDpkg(deb, apk), pkgdb.CompareDpkg(apk, deb); sign(a) != -sign(b) { + t.Fatalf("CompareDpkg not antisymmetric: %q %q", deb, apk) + } + a, ok1 := pkgdb.CompareAPK(apk, deb) + b, ok2 := pkgdb.CompareAPK(deb, apk) + if ok1 && ok2 && sign(a) != -sign(b) { + t.Fatalf("CompareAPK not antisymmetric: %q %q", apk, deb) + } + }) +} + +func sign(n int) int { + switch { + case n < 0: + return -1 + case n > 0: + return 1 + } + return 0 +} diff --git a/detectors/nginxh2/internal/ngx/testdata/fuzz/FuzzInspect/a7c21aa2e1261577 b/detectors/nginxh2/internal/ngx/testdata/fuzz/FuzzInspect/a7c21aa2e1261577 new file mode 100644 index 0000000..a8f1ab3 --- /dev/null +++ b/detectors/nginxh2/internal/ngx/testdata/fuzz/FuzzInspect/a7c21aa2e1261577 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("nginx version: nginx/ (\xd0nginX-plus-)\x00configure arguments:") diff --git a/detectors/nginxh2/internal/ngxtest/ngxtest.go b/detectors/nginxh2/internal/ngxtest/ngxtest.go new file mode 100644 index 0000000..8f92c4a --- /dev/null +++ b/detectors/nginxh2/internal/ngxtest/ngxtest.go @@ -0,0 +1,87 @@ +// Package ngxtest builds small files that read like nginx executables, +// for tests. They are not runnable. +package ngxtest + +import ( + "bytes" + "encoding/binary" +) + +// Build describes a fake nginx executable. +type Build struct { + // Line is the version line's text after "nginx version: " + // ("nginx/1.31.8", "openresty/1.31.8.1", "nginx/1.24.0 (Ubuntu)"). + Line string + // Tengine and Angie add their own version lines. + Tengine, Angie string + // Configure is the configure arguments ("" writes an empty line: every + // nginx binary has one). + Configure string + // Modules are module names in the module list. + Modules []string + // Extra strings (Server header, error pages). + Extra []string + // ConfPath is the help text's default configuration file. + ConfPath string + Bits int // 32 or 64 (default 64) + Machine uint16 +} + +// Default is an official-image-like nginx 1.31.8 with HTTP/2 and TLS. +func Default(version string) Build { + return Build{ + Line: "nginx/" + version, + Configure: "--prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --with-http_ssl_module --with-http_v2_module", + Modules: []string{"ngx_core_module", "ngx_http_module", "ngx_http_ssl_module", "ngx_http_v2_module"}, + Extra: []string{"nginx/" + version, "Server: nginx/" + version + "\r\n"}, + ConfPath: "/etc/nginx/nginx.conf", + } +} + +// Bytes renders the build. +func (b Build) Bytes() []byte { + var buf bytes.Buffer + hdr := make([]byte, 64) + copy(hdr, "\x7fELF") + hdr[4] = 2 + if b.Bits == 32 { + hdr[4] = 1 + } + hdr[5] = 1 + m := b.Machine + if m == 0 { + m = 62 + } + binary.LittleEndian.PutUint16(hdr[18:], m) + buf.Write(hdr) + s := func(x string) { + buf.WriteByte(0) + buf.WriteString(x) + buf.WriteByte(0) + } + for _, m := range b.Modules { + s(m) + } + if b.Angie != "" { + s("Angie version: " + b.Angie + "\n") + } + if b.Tengine != "" { + s("Tengine version: " + b.Tengine + "\n") + } + if b.Line != "" { + s("nginx version: " + b.Line + "\n") + } + s("configure arguments:" + func() string { + if b.Configure == "" { + return "" + } + return " " + b.Configure + }() + "\n") + if b.ConfPath != "" { + s(" -c filename : set configuration file (default: " + b.ConfPath + ")\n") + } + for _, x := range b.Extra { + s(x) + } + return buf.Bytes() +} diff --git a/detectors/nginxh2/internal/pkgdb/fuzz_test.go b/detectors/nginxh2/internal/pkgdb/fuzz_test.go new file mode 100644 index 0000000..05f2b3e --- /dev/null +++ b/detectors/nginxh2/internal/pkgdb/fuzz_test.go @@ -0,0 +1,16 @@ +package pkgdb + +import "testing" + +// FuzzDatabases: dpkg's status and .list files and apk's database parse +// without a panic. +func FuzzDatabases(f *testing.F) { + f.Add([]byte("Package: nginx\nStatus: install ok installed\nVersion: 1.22.1-9\nSource: nginx (1.22.1-9)\n\n"), []byte("P:nginx\nV:1.30.6-r0\nF:usr/sbin\nR:nginx\n\n")) + f.Add([]byte(":\n \n"), []byte("R:x\nF:\n")) + f.Fuzz(func(t *testing.T, dpkg, apk []byte) { + DpkgStatus(dpkg) + ListHas(dpkg, "/usr/sbin/nginx") + DpkgListName(string(dpkg)) + APKOwners(apk) + }) +} diff --git a/detectors/nginxh2/internal/pkgdb/pkgdb.go b/detectors/nginxh2/internal/pkgdb/pkgdb.go new file mode 100644 index 0000000..ea65447 --- /dev/null +++ b/detectors/nginxh2/internal/pkgdb/pkgdb.go @@ -0,0 +1,144 @@ +// Package pkgdb reads which package owns a file from dpkg's and apk's +// databases, and compares their versions. It knows nothing about the +// engine. +package pkgdb + +import ( + "bufio" + "bytes" + "path" + "strings" +) + +// Package is an installed package. +type Package struct { + Manager string `json:"manager"` // dpkg, apk + Name string `json:"name"` + Source string `json:"source,omitempty"` + Version string `json:"version"` + Maintainer string `json:"maintainer,omitempty"` +} + +const maxLine = 1 << 20 + +func scanner(b []byte) *bufio.Scanner { + s := bufio.NewScanner(bytes.NewReader(b)) + s.Buffer(make([]byte, 64<<10), maxLine) + return s +} + +// DpkgStatus reads /var/lib/dpkg/status: the installed packages by name. +func DpkgStatus(b []byte) map[string]Package { + out := map[string]Package{} + var cur Package + installed := false + flush := func() { + if cur.Name != "" && installed { + if cur.Source == "" { + cur.Source = cur.Name + } + out[cur.Name] = cur + } + cur, installed = Package{Manager: "dpkg"}, false + } + cur.Manager = "dpkg" + s := scanner(b) + for s.Scan() { + l := s.Text() + if strings.TrimSpace(l) == "" { + flush() + continue + } + k, v, ok := strings.Cut(l, ":") + if !ok || strings.HasPrefix(l, " ") { + continue + } + v = strings.TrimSpace(v) + switch k { + case "Package": + cur.Name = v + case "Version": + cur.Version = v + case "Maintainer": + cur.Maintainer = v + case "Source": + // "nginx (1.22.1-9)" names the source and its version. + src, _, _ := strings.Cut(v, " ") + cur.Source = src + case "Status": + installed = strings.HasSuffix(v, " installed") + } + } + flush() + return out +} + +// DpkgListName returns the package a /var/lib/dpkg/info/*.list file is +// for ("nginx-core:amd64.list" is nginx-core). +func DpkgListName(p string) string { + n := strings.TrimSuffix(path.Base(p), ".list") + n, _, _ = strings.Cut(n, ":") + return n +} + +// ListHas reports whether a dpkg .list file names p. +func ListHas(list []byte, p string) bool { + s := scanner(list) + for s.Scan() { + if strings.TrimSpace(s.Text()) == p { + return true + } + } + return false +} + +// APKOwners reads an apk installed database: the package owning each +// file, by absolute path. +func APKOwners(b []byte) map[string]Package { + out := map[string]Package{} + var cur Package + var files []string + dir := "" + flush := func() { + if cur.Name != "" { + if cur.Source == "" { + cur.Source = cur.Name + } + for _, f := range files { + out[f] = cur + } + } + cur, files, dir = Package{Manager: "apk"}, nil, "" + } + cur.Manager = "apk" + s := scanner(b) + for s.Scan() { + l := s.Text() + if l == "" { + flush() + continue + } + if len(l) < 2 || l[1] != ':' { + continue + } + v := l[2:] + switch l[0] { + case 'P': + cur.Name = v + case 'V': + cur.Version = v + case 'o': + cur.Source = v + case 'm': + cur.Maintainer = v + case 'F': + dir = v + case 'R': + if len(files) < 1<<16 { + files = append(files, "/"+path.Join(dir, v)) + } + } + } + flush() + return out +} diff --git a/detectors/nginxh2/internal/pkgdb/pkgdb_test.go b/detectors/nginxh2/internal/pkgdb/pkgdb_test.go new file mode 100644 index 0000000..745206f --- /dev/null +++ b/detectors/nginxh2/internal/pkgdb/pkgdb_test.go @@ -0,0 +1,124 @@ +package pkgdb + +import "testing" + +func TestCompareDpkg(t *testing.T) { + cases := []struct { + a, b string + want int + }{ + {"1.22.1-9+deb12u10", "1.22.1-9+deb12u9", 1}, + {"1.22.1-9+deb12u9", "1.22.1-9+deb12u10", -1}, + {"1.22.1-9", "1.22.1-9+deb12u1", -1}, + {"1.30.6-3", "1.30.6-3", 0}, + {"1:1.0", "2.0", 1}, + {"1.0~rc1", "1.0", -1}, + {"1.24.0-2ubuntu7.19", "1.24.0-2ubuntu7.9", 1}, + {"1.24.0-2ubuntu7", "1.24.0-2ubuntu7.1", -1}, + {"1.31.8-1~trixie", "1.31.9-1~trixie", -1}, + {"1.0a", "1.0", 1}, + {"1.0-0", "1.0", 0}, + {"1.00", "1.0", 0}, + } + for _, c := range cases { + if got := CompareDpkg(c.a, c.b); sign(got) != c.want { + t.Errorf("CompareDpkg(%q, %q) = %d, want %d", c.a, c.b, got, c.want) + } + } +} + +func TestCompareAPK(t *testing.T) { + cases := []struct { + a, b string + want int + }{ + {"1.30.6-r1", "1.30.6-r0", 1}, + {"1.30.6-r0", "1.30.7-r0", -1}, + {"1.28.3-r7", "1.28.3-r10", -1}, + {"1.0_rc1", "1.0", -1}, + {"1.0_p1", "1.0", 1}, + {"1.0a", "1.0", 1}, + {"1.0", "1.0.1", -1}, + {"1.30.6-r1", "1.30.6-r1", 0}, + } + for _, c := range cases { + got, ok := CompareAPK(c.a, c.b) + if !ok || sign(got) != c.want { + t.Errorf("CompareAPK(%q, %q) = %d %v, want %d", c.a, c.b, got, ok, c.want) + } + } + for _, bad := range []string{"", "1..2", "x", "1.0-rx", "1.0_zz", "1.0ab"} { + if _, ok := CompareAPK(bad, "1.0"); ok { + t.Errorf("CompareAPK(%q) accepted", bad) + } + } +} + +func sign(n int) int { + switch { + case n < 0: + return -1 + case n > 0: + return 1 + } + return 0 +} + +func TestDpkgStatus(t *testing.T) { + st := DpkgStatus([]byte(`Package: nginx +Status: install ok installed +Maintainer: Debian Nginx Maintainers +Version: 1.22.1-9+deb12u10 +Description: x + continued: line + +Package: nginx-common +Status: deinstall ok config-files +Version: 1.22.1-9+deb12u9 + +Package: libnginx-mod-http-geoip +Status: install ok installed +Source: nginx (1.22.1-9+deb12u10) +Version: 1.22.1-9+deb12u10 +`)) + if p := st["nginx"]; p.Version != "1.22.1-9+deb12u10" || p.Source != "nginx" || p.Manager != "dpkg" { + t.Errorf("nginx %+v", p) + } + if _, ok := st["nginx-common"]; ok { + t.Error("a removed package was read as installed") + } + if p := st["libnginx-mod-http-geoip"]; p.Source != "nginx" { + t.Errorf("source %+v", p) + } + if DpkgListName("/var/lib/dpkg/info/nginx-core:amd64.list") != "nginx-core" { + t.Error("list name") + } + if !ListHas([]byte("/.\n/usr\n/usr/sbin/nginx\n"), "/usr/sbin/nginx") || ListHas([]byte("/usr/sbin/nginx-debug\n"), "/usr/sbin/nginx") { + t.Error("ListHas") + } +} + +func TestAPKOwners(t *testing.T) { + own := APKOwners([]byte(`C:Q1abc +P:nginx +V:1.30.6-r0 +o:nginx +m:Jakub Jirutka +F:usr/sbin +R:nginx +F:etc/nginx +R:nginx.conf + +P:musl +V:1.2.5-r0 +F:lib +R:ld-musl-x86_64.so.1 +`)) + p, ok := own["/usr/sbin/nginx"] + if !ok || p.Name != "nginx" || p.Version != "1.30.6-r0" || p.Manager != "apk" { + t.Errorf("%+v", p) + } + if own["/lib/ld-musl-x86_64.so.1"].Name != "musl" || own["/etc/nginx/nginx.conf"].Name != "nginx" { + t.Error("owners") + } +} diff --git a/detectors/nginxh2/internal/pkgdb/version.go b/detectors/nginxh2/internal/pkgdb/version.go new file mode 100644 index 0000000..3545f21 --- /dev/null +++ b/detectors/nginxh2/internal/pkgdb/version.go @@ -0,0 +1,213 @@ +package pkgdb + +import ( + "strconv" + "strings" +) + +// CompareDpkg compares two Debian versions as dpkg does +// ([epoch:]upstream[-revision]). +func CompareDpkg(a, b string) int { + ea, ua, ra := splitDeb(a) + eb, ub, rb := splitDeb(b) + if c := cmpInt(ea, eb); c != 0 { + return c + } + if c := verrevcmp(ua, ub); c != 0 { + return c + } + return verrevcmp(ra, rb) +} + +func splitDeb(v string) (int, string, string) { + epoch := 0 + if e, rest, ok := strings.Cut(v, ":"); ok { + if n, err := strconv.Atoi(e); err == nil && len(e) < 10 { + epoch, v = n, rest + } + } + up, rev := v, "" + if i := strings.LastIndexByte(v, '-'); i >= 0 { + up, rev = v[:i], v[i+1:] + } + return epoch, up, rev +} + +func cmpInt(a, b int) int { + switch { + case a < b: + return -1 + case a > b: + return 1 + } + return 0 +} + +func order(c byte) int { + switch { + case c >= '0' && c <= '9': + return 0 + case c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z': + return int(c) + case c == '~': + return -1 + } + return int(c) + 256 +} + +func isDigit(c byte) bool { return c >= '0' && c <= '9' } + +// verrevcmp is dpkg's comparison of an upstream version or revision. +func verrevcmp(a, b string) int { + i, j := 0, 0 + for i < len(a) || j < len(b) { + for i < len(a) && !isDigit(a[i]) || j < len(b) && !isDigit(b[j]) { + ac, bc := 0, 0 + if i < len(a) && !isDigit(a[i]) { + ac = order(a[i]) + } + if j < len(b) && !isDigit(b[j]) { + bc = order(b[j]) + } + if ac != bc { + return cmpInt(ac, bc) + } + i++ + j++ + } + for i < len(a) && a[i] == '0' { + i++ + } + for j < len(b) && b[j] == '0' { + j++ + } + first := 0 + for i < len(a) && isDigit(a[i]) && j < len(b) && isDigit(b[j]) { + if first == 0 { + first = cmpInt(int(a[i]), int(b[j])) + } + i++ + j++ + } + if i < len(a) && isDigit(a[i]) { + return 1 + } + if j < len(b) && isDigit(b[j]) { + return -1 + } + if first != 0 { + return first + } + } + return 0 +} + +// apkSuffix orders apk's version suffixes: pre-releases before the +// release, post-releases after. +var apkSuffix = map[string]int{"alpha": -4, "beta": -3, "pre": -2, "rc": -1, "": 0, "cvs": 1, "svn": 2, "git": 3, "hg": 4, "p": 5} + +type apkVer struct { + nums []int + letter byte + suf []struct { + kind int + n int + } + rev int + ok bool +} + +func parseAPK(v string) apkVer { + var out apkVer + main, rev, hasRev := strings.Cut(v, "-r") + if hasRev { + n, err := strconv.Atoi(rev) + if err != nil || len(rev) > 9 { + return out + } + out.rev = n + } + body, sufs, _ := strings.Cut(main, "_") + for _, p := range strings.Split(body, ".") { + if p == "" { + return out + } + digits := strings.TrimRight(p, "abcdefghijklmnopqrstuvwxyz") + if len(p)-len(digits) > 1 || digits == "" || len(digits) > 9 { + return out + } + if len(digits) != len(p) { + out.letter = p[len(p)-1] + } + n, err := strconv.Atoi(digits) + if err != nil { + return out + } + out.nums = append(out.nums, n) + } + if sufs != "" { + for _, s := range strings.Split(sufs, "_") { + name := strings.TrimRight(s, "0123456789") + k, ok := apkSuffix[name] + if !ok || name == "" { + return out + } + n := 0 + if d := s[len(name):]; d != "" { + if len(d) > 9 { + return out + } + n, _ = strconv.Atoi(d) + } + out.suf = append(out.suf, struct { + kind int + n int + }{k, n}) + } + } + out.ok = true + return out +} + +// CompareAPK compares two apk versions; ok is false when either cannot be +// read. +func CompareAPK(a, b string) (int, bool) { + x, y := parseAPK(a), parseAPK(b) + if !x.ok || !y.ok { + return 0, false + } + for i := 0; i < len(x.nums) || i < len(y.nums); i++ { + p, q := -1, -1 + if i < len(x.nums) { + p = x.nums[i] + } + if i < len(y.nums) { + q = y.nums[i] + } + if c := cmpInt(p, q); c != 0 { + return c, true + } + } + if c := cmpInt(int(x.letter), int(y.letter)); c != 0 { + return c, true + } + for i := 0; i < len(x.suf) || i < len(y.suf); i++ { + var p, q struct { + kind int + n int + } + if i < len(x.suf) { + p = x.suf[i] + } + if i < len(y.suf) { + q = y.suf[i] + } + if c := cmpInt(p.kind, q.kind); c != 0 { + return c, true + } + if c := cmpInt(p.n, q.n); c != 0 { + return c, true + } + } + return cmpInt(x.rev, y.rev), true +} diff --git a/detectors/nginxh2/internal/repo/dockerfile.go b/detectors/nginxh2/internal/repo/dockerfile.go new file mode 100644 index 0000000..8ccc150 --- /dev/null +++ b/detectors/nginxh2/internal/repo/dockerfile.go @@ -0,0 +1,593 @@ +package repo + +import ( + "fmt" + "regexp" + "strings" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/knowledge" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/pkgdb" + "github.com/DefectDojo/earlylight/internal/refs" +) + +// stage is what a Dockerfile stage installs on. +type stage struct { + base string // the resolved FROM image, "" when not resolved + distro string // debian, ubuntu, alpine, rhel, "" when not known + branch string // the Alpine branch the base names ("3.24", "edge"), "" when it does not + nginxOrg bool // the stage adds nginx.org's package repository + vars map[string]string +} + +// dockerfile reads the packages each RUN installs, with the ARG and ENV +// values of its stage. +func (s *scanner) dockerfile(rel string, b []byte) { + ins, err := refs.Instructions(b) + if err != nil { + s.skips = append(s.skips, Skip{File: rel, Reason: "the Dockerfile could not be parsed (" + refs.CleanText(err.Error(), 120) + "): its RUN lines are not checked for nginx packages"}) + return + } + globals := map[string]string{} + stages := map[string]*stage{} + var cur *stage + index := -1 + fromLine := 0 + rootOf := map[string]int{} // stage name or index -> the FROM line of the image it builds on + for _, in := range ins { + if in.Onbuild && in.Cmd != "run" { + continue + } + s.copyFrom(rel, in, stages, globals, cur) + switch in.Cmd { + case "from", "label", "expose", "healthcheck", "stopsignal", "maintainer", "arg", "user", "workdir", "shell": + default: + // What the stage changes on top of the image it builds on + // (files, commands, environment): the built image's + // configuration is not the base image's. + if fromLine > 0 && s.stageMods != nil { + k := fmt.Sprintf("%s:%d", rel, fromLine) + if _, ok := s.stageMods[k]; !ok { + s.stageMods[k] = fmt.Sprintf("the Dockerfile builds on this image (%s at line %d), so the image it makes may load another configuration or command", strings.ToUpper(in.Cmd), in.Line) + } + } + } + if in.Cmd == "from" { + // A stage built on an earlier one changes the image that + // stage builds on: the change is recorded at its FROM. + fromLine = in.Line + w := words(in.Args) + if len(w) > 0 { + if r, ok := rootOf[strings.ToLower(w[0])]; ok { + fromLine = r + } + } + rootOf[fmt.Sprint(index+1)] = fromLine + if len(w) >= 3 && strings.EqualFold(w[len(w)-2], "as") { + rootOf[strings.ToLower(w[len(w)-1])] = fromLine + } + } + switch in.Cmd { + case "from": + index++ + cur = &stage{vars: map[string]string{}} + w := words(in.Args) + if len(w) > 0 { + if prev, ok := stages[strings.ToLower(w[0])]; ok { + // FROM an earlier stage: its base, repositories and ENV. + cur.base, cur.distro, cur.branch, cur.nginxOrg = prev.base, prev.distro, prev.branch, prev.nginxOrg + for k, v := range prev.vars { + cur.vars[k] = v + } + } else if r, ok := s.fromImage[fmt.Sprintf("%s:%d", rel, in.Line)]; ok { + cur.base = r.Image + cur.distro = distroOfImage(r.Image) + if cur.distro == "alpine" { + cur.branch = alpineBranchOf(r.Image) + } + } + } + stages[fmt.Sprint(index)] = cur + if len(w) >= 3 && strings.EqualFold(w[len(w)-2], "as") { + stages[strings.ToLower(w[len(w)-1])] = cur + } + case "arg": + for _, kv := range words(in.Args) { + k, v, ok := strings.Cut(kv, "=") + switch { + case cur == nil && ok: + globals[k] = v + case cur == nil: + case ok: + cur.vars[k] = v + default: + if g, set := globals[k]; set { + cur.vars[k] = g + } + } + } + case "env": + if cur == nil { + continue + } + ws := words(in.Args) + if len(ws) >= 2 && !strings.Contains(ws[0], "=") { + // ENV NAME value (the legacy form) + cur.vars[ws[0]] = strings.Join(ws[1:], " ") + continue + } + for _, kv := range ws { + if k, v, ok := strings.Cut(kv, "="); ok { + cur.vars[k] = v + } + } + case "run": + if cur == nil { + continue + } + run := in.Args + if in.JSON != nil { + run = strings.Join(in.JSON, " ") + } + texts := []string{run} + for _, h := range in.Heredocs { + texts = append(texts, heredocCommands(h)) + } + for _, t := range texts { + if nginxRepo.MatchString(t) { + cur.nginxOrg = true + } + s.packages(rel, in.Line, t, cur) + } + } + } +} + +// copyFrom judges the images COPY --from and RUN --mount=...,from= take +// files from: an nginx binary copied out of an image is that image's. +// fix does not edit them. +func (s *scanner) copyFrom(rel string, in refs.Instruction, stages map[string]*stage, globals map[string]string, cur *stage) { + 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)] != nil || strings.Trim(img, "0123456789") == "" { + continue + } + vars := globals + if cur != nil { + vars = cur.vars + } + img = expandVars(img, vars) + if strings.Contains(img, "$") { + s.skips = append(s.skips, Skip{File: rel, Line: in.Line, Reason: fmt.Sprintf("%s takes files from %s, which this file does not resolve: not checked for nginx", strings.ToUpper(in.Cmd), refs.CleanText(img, 80))}) + continue + } + before := len(s.findings) + s.image(&refs.Ref{File: rel, Line: in.Line, Kind: refs.KindDockerfile, Context: strings.ToUpper(in.Cmd) + " --from", Text: img, Image: img}) + for k := before; k < len(s.findings); k++ { + 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 + } + } + } +} + +// nginxRepo is nginx.org's package repository being added. +var nginxRepo = regexp.MustCompile(`nginx\.org/packages|packages\.nginx\.org|nginx_signing`) + +// heredocCommands turns a heredoc script into one command line. +func heredocCommands(body string) string { + var out []string + cur := "" + for _, l := range strings.Split(body, "\n") { + t := strings.TrimSpace(l) + if 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, " ; ") +} + +// distroOfImage tells a base image's distribution from its name; "" when +// the name does not say. +func distroOfImage(image string) string { + low := strings.ToLower(image) + repoName, tag, _ := splitImage(low) + name := repoName[strings.LastIndexByte(repoName, '/')+1:] + for _, w := range []struct{ word, distro string }{ + {"alpine", "alpine"}, {"ubuntu", "ubuntu"}, {"jammy", "ubuntu"}, {"noble", "ubuntu"}, {"focal", "ubuntu"}, {"resolute", "ubuntu"}, + {"debian", "debian"}, {"bookworm", "debian"}, {"trixie", "debian"}, {"bullseye", "debian"}, {"forky", "debian"}, + {"ubi", "rhel"}, {"rhel", "rhel"}, {"rockylinux", "rhel"}, {"almalinux", "rhel"}, {"centos", "rhel"}, {"fedora", "rhel"}, {"amazonlinux", "rhel"}, {"oraclelinux", "rhel"}, + } { + if name == w.word || strings.Contains(name, w.word) || strings.Contains(tag, w.word) { + return w.distro + } + } + switch { + case strings.HasSuffix(tag, "-slim") || tag == "slim": + return "debian" + case name == "nginx" || name == "nginx-unprivileged": + return "debian" // the official image's default variant is Debian + } + return "" +} + +var alpineBranchRE = regexp.MustCompile(`(?:^|[^0-9])(3\.\d{1,2})(?:\.\d+)?(?:$|[^0-9.])`) + +// alpineBranchOf reads the Alpine branch an image names: alpine:3.24, +// alpine:3.24.4, alpine:edge, python:3.12-alpine3.23, nginx:1.31.8-alpine3.24. +// A moving name (alpine:3, alpine:latest, -alpine) names none. +func alpineBranchOf(image string) string { + repoName, tag, _ := splitImage(strings.ToLower(image)) + name := repoName[strings.LastIndexByte(repoName, '/')+1:] + if name == "alpine" { + if tag == "edge" { + return "edge" + } + if m := alpineBranchRE.FindStringSubmatch(tag); m != nil && strings.HasPrefix(tag, m[1]) { + return m[1] + } + return "" + } + if i := strings.Index(tag, "alpine"); i >= 0 { + if m := alpineBranchRE.FindStringSubmatch(tag[i+len("alpine"):]); m != nil && strings.HasPrefix(tag[i+len("alpine"):], m[1]) { + return m[1] + } + } + return "" +} + +// nginxPackages are the packages that install an nginx server. +var nginxPackages = map[string]string{ + "nginx": "nginx", "nginx-core": "nginx", "nginx-full": "nginx", "nginx-light": "nginx", "nginx-extras": "nginx", + "nginx-mainline": "nginx", "openresty": "openresty", "angie": "angie", "nginx-plus": "nginx-plus", +} + +// pkg is one package argument. +type pkg struct { + name, product string + op, ver string + module string // a dnf module stream (nginx:1.24) +} + +// parsePkg reads a package argument of the tool: apt's name=version, +// apk's name=version (and ~ > >= < <=), dnf's and yum's name-version, a +// dnf module stream, with an apk @repo tag, a Debian :arch or +// /release removed. +func parsePkg(tool, w string) (pkg, bool) { + if m, ok := strings.CutPrefix(w, "@module:"); ok { + m = strings.TrimPrefix(m, "@") + name, stream, _ := strings.Cut(m, ":") + stream, _, _ = strings.Cut(stream, "/") + if p, ok := nginxPackages[name]; ok { + return pkg{name: name, product: p, module: stream}, true + } + return pkg{}, false + } + w = strings.TrimPrefix(w, "@") + for _, op := range []string{">=", "<=", "=", "~", ">", "<"} { + if i := strings.Index(w, op); i > 0 { + name := cleanName(w[:i]) + if p, ok := nginxPackages[name]; ok { + return pkg{name: name, product: p, op: op, ver: strings.Trim(w[i+len(op):], "'\"")}, true + } + if p := sidePackage(name); p != "" { + return pkg{name: name, product: p}, true + } + return pkg{}, false + } + } + name := cleanName(w) + if p, ok := nginxPackages[name]; ok { + return pkg{name: name, product: p}, true + } + if p := sidePackage(name); p != "" { + return pkg{name: name, product: p}, true + } + if tool == "dnf" || tool == "dnf5" || tool == "yum" || tool == "microdnf" || tool == "tdnf" || tool == "?" { + // name-version[-release][.arch] + for n, p := range nginxPackages { + if rest, ok := strings.CutPrefix(name, n+"-"); ok && rest != "" && (rest[0] >= '0' && rest[0] <= '9') { + return pkg{name: n, product: p, op: "=", ver: rest}, true + } + } + } + return pkg{}, false +} + +// sidePackage names packages that bring an nginx this scan does not +// judge: modules that depend on the nginx they extend, certbot's nginx +// plugin, Angie PRO (numbered on its own). +func sidePackage(name string) string { + switch { + case strings.HasPrefix(name, "libnginx-mod-"), strings.HasPrefix(name, "nginx-module-"), strings.HasPrefix(name, "nginx-mod-"), + name == "python3-certbot-nginx", name == "certbot-nginx": + return "module" + case name == "angie-pro" || strings.HasPrefix(name, "angie-pro-"): + return "angie-pro" + } + return "" +} + +func cleanName(n string) string { + if i := strings.IndexByte(n, '@'); i > 0 { + n = n[:i] + } + if i := strings.IndexByte(n, '/'); i > 0 { + n = n[:i] + } + if i := strings.IndexByte(n, ':'); i > 0 { + n = n[:i] + } + for _, a := range []string{".x86_64", ".aarch64", ".noarch"} { + n = strings.TrimSuffix(n, a) + } + return n +} + +// packages finds the nginx packages a RUN line installs. +func (s *scanner) packages(rel string, line int, run string, st *stage) { + run = expandVars(run, lineVars(run, st.vars)) + if !installRE.MatchString(run) && !strings.Contains(run, "$") { + return + } + for _, in := range installs(run, 0) { + for _, a := range in.args { + if o, ok := strings.CutPrefix(a, opaqueArg); ok { + s.skips = append(s.skips, Skip{File: rel, Line: line, Reason: fmt.Sprintf("installs packages named by %s, which this file does not set: not checked for nginx", refs.CleanText(o, 80))}) + continue + } + p, ok := parsePkg(in.tool, a) + if !ok { + continue + } + s.judgePackage(rel, line, in.tool, p, st) + } + } +} + +func (s *scanner) judgePackage(rel string, line int, tool string, p pkg, st *stage) { + props := map[string]string{"package": p.name, "tool": tool} + if st.base != "" { + props["base"] = st.base + } + if p.ver != "" { + props["pinned"] = p.op + p.ver + } + f := Finding{Rule: RulePackage, File: rel, Line: line, Level: "error", Props: props} + switch { + case p.product == "module": + f.Rule, f.Level, f.Status = RuleNotChecked, "note", knowledge.Unknown + f.Reason = "the nginx it goes with is installed as a dependency, at a release this file does not show" + f.Message = fmt.Sprintf("installs %s, which goes with an nginx installed as its dependency or elsewhere: that nginx is not checked here", p.name) + f.Fix = "Check the nginx this installs (nginx -v) or read the image that is built: 1.31.9 or 1.30.7 has the fix." + case p.product == "angie-pro": + f.Rule, f.Level, f.Status = RuleNotChecked, "note", knowledge.Unknown + f.Reason = "Angie PRO's releases are numbered on their own, and none was checked" + f.Message = "installs " + p.name + " (Angie PRO): its status for the HTTP/2 pair is not known" + f.Fix = "Check Angie PRO's advisories for CVE-2026-123007 and CVE-2026-123633." + case p.product == "nginx-plus": + f.Rule, f.Level, f.Status = RuleNotChecked, "note", knowledge.Unknown + f.Message = "installs NGINX Plus (" + p.name + "), whose release the Dockerfile does not show" + f.Fix = "Check the NGINX Plus release (nginx -v): 37.0.8.1 or 37.3.0.1 fixes both CVEs." + f.Reason = "the release is decided by F5's repository at build time" + case p.module != "": + f.Rule, f.Level, f.Status = RuleNotChecked, "note", knowledge.Unknown + props["module_stream"] = p.module + f.Message = fmt.Sprintf("enables the nginx:%s module stream: upstream %s received no fix, and Red Hat's status for these CVEs could not be read on %s", p.module, p.module, knowledge.Checked) + f.Reason = knowledge.DistroStatus["rhel"] + f.Fix = "Check Red Hat's advisories for CVE-2026-123007 and CVE-2026-123633 and update the stream's packages when a fixed build is published." + case p.op == "=" || p.op == "" && p.ver != "": + s.pinned(&f, p, st) + case (p.op == ">=" || p.op == ">") && p.ver != "": + if floorFixed(p) { + return + } + s.unpinned(&f, p, st) + default: + s.unpinned(&f, p, st) + } + if f.Status == "" || f.Status == knowledge.Fixed || f.Status == knowledge.NotAffected { + return + } + if f.Status == knowledge.Vulnerable { + f.Interim = "Until the package is updated, turn HTTP/2 off in the configuration (\"http2 off;\" and no \"http2\" on any listen): an interim step, not a fix." + } + s.add(f) +} + +// floorFixed reports a version floor at or past a fixed release. +func floorFixed(p pkg) bool { + v, err := knowledge.UpstreamOf(p.ver) + if err != nil { + return false + } + for _, c := range knowledge.CVEs { + st, _ := knowledge.Nginx(c, v) + if p.product == "openresty" { + st, _ = knowledge.OpenResty(c, v) + } + if st != knowledge.Fixed { + return false + } + } + return true +} + +// pinned judges a package pinned to a version. +func (s *scanner) pinned(f *Finding, p pkg, st *stage) { + v, err := knowledge.UpstreamOf(p.ver) + if err != nil { + f.Rule, f.Level, f.Status = RuleNotChecked, "note", knowledge.Unknown + f.Reason = "the pinned version could not be read" + f.Message = fmt.Sprintf("installs %s pinned to %q, which does not read as a release", p.name, p.ver) + f.Fix = "Pin a release with the fix: nginx 1.31.9 or 1.30.7." + return + } + verdicts := map[string]Verdict{} + for _, c := range knowledge.CVEs { + var x knowledge.Status + var why string + switch p.product { + case "openresty": + x, why = knowledge.OpenResty(c, v) + case "angie": + x, why = knowledge.Angie(c, v) + default: + x, why = knowledge.Nginx(c, v) + } + if x == knowledge.Vulnerable && p.product == "nginx" && !nginxOrgVersion(p.ver) && backported(st.distro, p, c.ID) { + x, why = knowledge.Fixed, "the distribution's backport" + } + verdicts[c.ID] = Verdict{x, why} + } + f.CVEs = cveList(verdicts) + f.Status = worst(f.CVEs) + f.Reason = reasons(f.CVEs) + f.Message = fmt.Sprintf("installs %s pinned to %s: %s", p.name, p.ver, f.Reason) + if f.Status == knowledge.Unknown { + f.Rule, f.Level = RuleNotChecked, "note" + } + switch { + case p.product == "nginx" && st.distro == "alpine" && f.Status == knowledge.Vulnerable: + v, ok := knowledge.AlpineFixed[st.branch] + newer, cmpOK := pkgdb.CompareAPK(v, p.ver) + switch { + case ok && p.op == "=" && cmpOK && newer > 0: + f.Fix = fmt.Sprintf("Pin %s=%s, the fixed package on Alpine %s (or the newer build its index lists), and rebuild.", p.name, v, st.branch) + f.Fixable = true + f.pin = &pinEdit{old: p.name + "=" + p.ver, repl: p.name + "=" + v, branch: st.branch} + case ok: + f.Fix = fmt.Sprintf("Alpine %s's fixed nginx (%s on %s) is not newer than this pin; pin a fixed release of the pinned line by hand (1.31.9 or later).", st.branch, v, knowledge.Checked) + default: + f.Fix = knowledge.AlpineText(st.branch) + ". Build on Alpine 3.24 with nginx>=1.30.7-r0." + } + case p.product == "nginx" && nginxOrgVersion(p.ver): + f.Fix = fmt.Sprintf("Pin nginx.org's package of 1.31.9 or 1.30.7 (for example nginx=1.31.9-1~%s) after checking that nginx.org's repository lists it, then rebuild.", codename(p.ver)) + case p.product == "nginx" && st.distro != "" && knowledge.DistroStatus[st.distro] != "": + f.Fix = knowledge.DistroStatus[st.distro] + ". Move the pin to the fixed package when it is published, or install nginx.org's 1.31.9 / 1.30.7." + case p.product == "openresty": + f.Fix = OpenResty.NoFix + "." + case p.product == "angie": + f.Fix = AngieImage.NoFix + "." + default: + f.Fix = "Pin a release with the fix: nginx 1.31.9 or 1.30.7." + } +} + +// unpinned judges a package installed without a version: the build gets +// whatever the repository has. +func (s *scanner) unpinned(f *Finding, p pkg, st *stage) { + f.CVEs = nil + switch { + case p.product == "openresty": + f.Status, f.Reason = knowledge.Vulnerable, OpenResty.NoFix + f.Message = "installs OpenResty without a version: " + OpenResty.NoFix + f.Fix = "Rebuild with an OpenResty release that has the fix once one is published." + case p.product == "angie": + f.Status, f.Reason = knowledge.Vulnerable, AngieImage.NoFix + f.Message = "installs Angie without a version: " + AngieImage.NoFix + f.Fix = "Rebuild with an Angie release that has the fix once one is published." + case st.nginxOrg: + f.Rule, f.Level, f.Status = RuleNotChecked, "note", knowledge.Unknown + f.Reason = "the release is decided when the image is built" + f.Message = "installs nginx from nginx.org without a version: the release it gets depends on when the image is built (the official images, built from nginx.org's packages, moved to 1.31.9 and 1.30.7 on 2026-11-18; nginx.org's own pages were not read here), and an image built before, or from a cached layer, keeps the older release" + f.Fix = "Pin nginx=1.31.9-1~ or 1.30.7-1~ (or a floor) so a cached layer cannot keep the vulnerable release, and rebuild." + case st.distro == "alpine" && knowledge.AlpineFixed[st.branch] != "": + v := knowledge.AlpineFixed[st.branch] + f.Rule, f.Level, f.Status = RuleNotChecked, "note", knowledge.Unknown + f.Reason = "the release is decided when the image is built" + f.Message = fmt.Sprintf("installs %s on Alpine %s (%s) without a version: Alpine's index listed the fixed %s on %s, so a build after that gets it or a later build; an image built before, or from a cached layer, keeps the older release", p.name, st.branch, st.base, v, knowledge.Checked) + f.Fix = fmt.Sprintf("Add a floor (apk add '%s>=%s') so a cached layer cannot keep the vulnerable release, and rebuild.", p.name, v) + case st.distro == "alpine" && st.branch == "": + f.Rule, f.Level, f.Status = RuleNotChecked, "note", knowledge.Unknown + f.Reason = "the base image does not name its Alpine branch" + f.Message = fmt.Sprintf("installs %s on %s, which does not name its Alpine branch: %s", p.name, st.base, knowledge.DistroStatus["alpine"]) + f.Fix = "Build on alpine:3.24 (or an image that names it) and add a floor: apk add 'nginx>=1.30.7-r0'." + case st.distro == "alpine": + f.Status, f.Reason = knowledge.Vulnerable, knowledge.AlpineText(st.branch) + f.Message = fmt.Sprintf("installs %s from Alpine %s's repository (%s): %s", p.name, st.branch, st.base, knowledge.AlpineText(st.branch)) + f.Fix = "Build on Alpine 3.24 (nginx 1.30.7-r0), or install nginx.org's 1.31.9 / 1.30.7." + case st.distro == "debian" || st.distro == "ubuntu": + f.Status, f.Reason = knowledge.Vulnerable, knowledge.DistroStatus[st.distro] + f.Message = fmt.Sprintf("installs %s from %s's repository (%s): %s", p.name, st.distro, st.base, knowledge.DistroStatus[st.distro]) + f.Fix = "Rebuild when " + st.distro + " publishes a fixed nginx package, or install nginx.org's 1.31.9 / 1.30.7, or build on nginx:1.31.9 / nginx:1.30.7." + case st.distro == "rhel": + f.Rule, f.Level, f.Status = RuleNotChecked, "note", knowledge.Unknown + f.Reason = knowledge.DistroStatus["rhel"] + f.Message = fmt.Sprintf("installs %s from a Red Hat family repository (%s): %s", p.name, st.base, knowledge.DistroStatus["rhel"]) + f.Fix = "Check the distribution's advisories for CVE-2026-123007 and CVE-2026-123633 and rebuild with the fixed package." + default: + f.Rule, f.Level, f.Status = RuleNotChecked, "note", knowledge.Unknown + f.Reason = "the base image's distribution could not be told from its name" + base := st.base + if base == "" { + base = "a base image this scan could not resolve" + } + f.Message = fmt.Sprintf("installs %s on %s, without a version: which release it gets is not known", p.name, base) + f.Fix = "Pin a release with the fix (nginx 1.31.9 or 1.30.7), or check the image this builds." + } +} + +// backported reports a backport table row that covers the pinned +// distribution package. +func backported(distro string, p pkg, cve string) bool { + for _, r := range knowledge.Backports { + if r.Distro != distro || r.Package != "nginx" || !hasCVE(r.CVEs, cve) { + continue + } + var cmp int + ok := true + if distro == "alpine" { + cmp, ok = pkgdb.CompareAPK(p.ver, r.Fixed) + } else { + cmp = pkgdb.CompareDpkg(p.ver, r.Fixed) + } + if ok && cmp >= 0 { + return true + } + } + return false +} + +func hasCVE(xs []string, s string) bool { + for _, x := range xs { + if x == s { + return true + } + } + return false +} + +// nginxOrgVersion reports nginx.org's package version form: +// 1.31.8-1~trixie (Debian, Ubuntu). +var nginxOrgRE = regexp.MustCompile(`^\d+\.\d+\.\d+-\d+~[a-z]+$`) + +func nginxOrgVersion(v string) bool { return nginxOrgRE.MatchString(v) } + +func codename(v string) string { + _, c, ok := strings.Cut(v, "~") + if !ok { + return "" + } + return c +} diff --git a/detectors/nginxh2/internal/repo/fuzz_test.go b/detectors/nginxh2/internal/repo/fuzz_test.go new file mode 100644 index 0000000..74b64b3 --- /dev/null +++ b/detectors/nginxh2/internal/repo/fuzz_test.go @@ -0,0 +1,27 @@ +package repo + +import ( + "context" + "testing" +) + +// FuzzScanText: any Dockerfile, configuration or YAML text scans without a +// panic, and every finding has a status and a message. +func FuzzScanText(f *testing.F) { + f.Add("FROM nginx:1.31.8\nRUN apt-get install -y nginx=1.22.1-9 && sh -c 'apk add nginx'\n", "server { listen 443 ssl http2; proxy_pass x; }", "kind: ConfigMap\ndata:\n a.conf: |\n server { listen 1 http2; }\n") + f.Add("ARG V=1\nFROM nginx:${V}-alpine AS a\nFROM a\nRUN <= 1 { + return Verdict{knowledge.Vulnerable, fmt.Sprintf("ingress-nginx controller %s runs nginx 1.20.1 or later (1.27.1 from v1.13), read from its build scripts; the project publishes no fix", v)} + } + if c.ID == knowledge.Flow { + return Verdict{knowledge.Vulnerable, fmt.Sprintf("ingress-nginx controller %s runs an nginx later than 1.9.5; the project publishes no fix", v)} + } + return Verdict{knowledge.Unknown, fmt.Sprintf("ingress-nginx controller %s: which nginx it runs was not read (before v1.0 some ran nginx older than 1.19.7)", v)} + case F5Ingress.ID: + if knowledge.Cmp(v.Line(), knowledge.MustV("5.8")) > 0 { + return Verdict{knowledge.Unknown, fmt.Sprintf("NGINX Ingress Controller %s is newer than any release known on %s (5.8.0): not judged", v, knowledge.Checked)} + } + if knowledge.Cmp(v, knowledge.MustV("5.8.0")) >= 0 { + return Verdict{knowledge.Fixed, fmt.Sprintf("NGINX Ingress Controller %s builds on nginx 1.31.9 (5.8.0's build file)", v)} + } + return Verdict{knowledge.Vulnerable, fmt.Sprintf("NGINX Ingress Controller %s builds on an nginx before 1.31.9 (5.7.1 used 1.31.8); 5.8.0 is the first on 1.31.9", v)} + } + return Verdict{knowledge.Unknown, "not a family the detector judges"} +} + +// FixedTag is the tag of the first fixed release on the same line and +// variant, "" when the family has none. +func (f Family) FixedTag(t Tag) string { + v, err := knowledge.ParseV(t.Version) + if err != nil || f.NoFix != "" { + return "" + } + switch f.ID { + case Official.ID, Unprivileged.ID: + c, _ := knowledge.ByID(knowledge.Flow) + for _, fx := range c.Fixed { + if knowledge.Cmp(fx.Line(), v.Line()) == 0 && knowledge.Cmp(v, fx) < 0 { + return fx.String() + t.Variant + } + } + case F5Ingress.ID: + if knowledge.Cmp(v, knowledge.MustV("5.8.0")) < 0 && v[0] == 5 { + return "5.8.0" + t.Variant + } + } + return "" +} + +// MoveText says what the move to FixedTag is: the next release of the same +// line, or for the F5 controller, a minor upgrade. +func (f Family) MoveText(t Tag) string { + if f.ID == F5Ingress.ID { + v, _ := knowledge.ParseV(t.Version) + return fmt.Sprintf("a minor upgrade (%s to 5.8) of the same variant, the first release on nginx 1.31.9; read its release notes before deploying", v.Line()) + } + return "the first release of the same line and variant" +} + +// LineText says why a vulnerable tag has no fixed tag of its own line. +func (f Family) LineText(t Tag) string { + if f.NoFix != "" { + return f.NoFix + } + for _, v := range f.Judge(t) { + if v.Status == knowledge.Unknown && strings.Contains(v.Reason, "newer than any") { + return fmt.Sprintf("%s %s is newer than any release known on %s: check its release notes for the fix for %s and %s, or read the image", f.Vendor, t.Version, knowledge.Checked, knowledge.Flow, knowledge.Reuse) + } + } + switch f.ID { + case Official.ID, Unprivileged.ID: + return fmt.Sprintf("nginx %s is on a line that received no fix (fixed lines: %s); move to 1.30.7 (stable) or 1.31.9 (mainline) by hand and test it", t.Version, knowledge.FixedText) + case F5Ingress.ID: + return fmt.Sprintf("NGINX Ingress Controller %s is not on the 5.x line; move to 5.8.0 by hand", t.Version) + } + return "no fixed tag is known" +} diff --git a/detectors/nginxh2/internal/repo/plan.go b/detectors/nginxh2/internal/repo/plan.go new file mode 100644 index 0000000..5c6adf4 --- /dev/null +++ b/detectors/nginxh2/internal/repo/plan.go @@ -0,0 +1,394 @@ +package repo + +import ( + "context" + "errors" + "fmt" + "os" + "path" + "path/filepath" + "regexp" + "strings" + "unicode" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/knowledge" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/pkgdb" + "github.com/DefectDojo/earlylight/internal/refs" +) + +// The planning here follows java4shell's (internal/repo/plan.go on that +// branch): one edit to one line, checked by rescanning the edited file in +// memory, applied only when the line still reads as planned. + +// 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 a tag move needs: the tags of a repository, +// and a check that the target holds only fixed nginx builds on every +// platform the current tag has, on the same base OS (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) + // APKIndex returns the nginx package version in an Alpine branch's + // main index ("3.24", "edge"); nil when the run is offline. + APKIndex func(ctx context.Context, branch 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.pin != nil { + return planPin(ctx, root, f, reg, opts) + } + if !f.Fixable || f.edit == nil { + return nil, declined("%s", f.Fix) + } + e, r := f.edit, f.ref + if r == nil { + return nil, declined("the image reference was not located; rescan to confirm") + } + 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 to %s", e.image, e.target) + } + if strings.Contains(e.image, "@") { + return nil, declined("%s is pinned by digest; change the tag and digest by hand (to %s and its digest)", e.image, e.target) + } + repoName, tag, _ := splitImage(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; change it to %s by hand", e.image, e.target) + } + tags, err := reg.Tags(ctx, repoName) + if err != nil { + return nil, declined("the tags of %s could not be listed (%v): not checked; try again later, or change it to %s by hand", repoName, err, e.target) + } + if !contains(tags, e.target) { + return nil, declined("%s has not published %s yet (the registry was checked); move to it when it does", repoName, e.target) + } + newImage := e.image[:start] + e.target + // 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 to %s by hand", e.image, e.target) + } + file := part.File + if file == "" { + file = r.File + } + col := part.Column - 1 + (start - off) + if part.Var != "" { + 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) + } + 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): not checked; try again later, or change it by hand", newImage, err) + } + where := "" + if part.Var != "" { + where = fmt.Sprintf(" (in the value of %s)", part.Var) + } + return planLine(ctx, root, f, file, part.Line, col, tag, e.target, opts, + fmt.Sprintf("Changes the image %s to %s on line %d of %s%s: %s with the fix for CVE-2026-123007 and CVE-2026-123633, read and judged on the platforms it is built for (the FROM line's --platform, else the --platform list, else linux/amd64 and linux/arm64) and published for each of them, on the same base OS (index digest %s). Rebuild and redeploy.", + e.image, newImage, part.Line, file, where, e.family.MoveText(e.tag), digest)) +} + +// planPin moves a package pin to the fixed package: the pin must be +// written once in the RUN instruction (its first line and the lines it +// continues onto). +func planPin(ctx context.Context, root string, f Finding, reg Registry, opts Options) (*Change, error) { + // The branch's index decides what the pin can be: Alpine keeps only + // the newest build of a package, and a dated table could move a pin + // to a build that is gone, or down a line. + if reg.APKIndex == nil { + return nil, declined("moving the pin %s needs Alpine %s's package index, which this run does not read; change it to %s by hand after checking the index", f.pin.old, f.pin.branch, f.pin.repl) + } + cur, err := reg.APKIndex(ctx, f.pin.branch) + if err != nil { + return nil, declined("Alpine %s's package index could not be read (%v): not checked; try again later, or change the pin by hand", f.pin.branch, err) + } + up, err := knowledge.UpstreamOf(cur) + if err != nil { + return nil, declined("Alpine %s's index lists nginx %q, which does not read as a release; change the pin by hand", f.pin.branch, cur) + } + for _, c := range knowledge.CVEs { + if st, _ := knowledge.Nginx(c, up); st != knowledge.Fixed { + return nil, declined("Alpine %s's index lists nginx %s, which does not have the fix for %s; change the pin by hand when it does", f.pin.branch, cur, c.ID) + } + } + name, oldVer, _ := strings.Cut(f.pin.old, "=") + if c, ok := pkgdb.CompareAPK(cur, oldVer); !ok || c <= 0 { + return nil, declined("Alpine %s's fixed nginx %s is not newer than the pinned %s; change the pin by hand", f.pin.branch, cur, oldVer) + } + if o, err := knowledge.UpstreamOf(oldVer); err != nil || knowledge.Cmp(o.Line(), up.Line()) != 0 { + return nil, declined("Alpine %s's fixed nginx %s is on another line than the pinned %s; change the pin by hand", f.pin.branch, cur, oldVer) + } + f.pin.repl = name + "=" + cur + b, ok := opts.Overlay[f.File] + if !ok { + var err error + if b, err = readFile(root, f.File); err != nil { + return nil, declined("%s could not be read: %v", f.File, err) + } + } + ls := strings.Split(string(b), "\n") + type hit struct{ line, col int } + var hits []hit + for i := f.Line - 1; i >= 0 && i < len(ls) && i < f.Line-1+200; i++ { + l := strings.TrimSuffix(ls[i], "\r") + for off := 0; ; { + j := strings.Index(l[off:], f.pin.old) + if j < 0 { + break + } + c := off + j + end := c + len(f.pin.old) + if (c == 0 || strings.ContainsRune(" \t'\"", rune(l[c-1]))) && (end == len(l) || strings.ContainsRune(" \t'\";&|\\", rune(l[end]))) { + hits = append(hits, hit{i + 1, c}) + } + off = end + } + if !strings.HasSuffix(strings.TrimRight(l, " \t"), "\\") { + break + } + } + if len(hits) != 1 { + return nil, declined("the pin %s is not written once in the instruction at line %d; change it to %s by hand", f.pin.old, f.Line, f.pin.repl) + } + return planLine(ctx, root, f, f.File, hits[0].line, hits[0].col, f.pin.old, f.pin.repl, opts, + fmt.Sprintf("Changes the package pin %s to %s on line %d of %s: the fixed nginx package Alpine %s's index lists now. Rebuild.", f.pin.old, f.pin.repl, hits[0].line, f.File, f.pin.branch)) +} + +// planLine replaces old with repl at col on a line and rescans 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 to confirm", 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 to confirm", 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}) + if err != nil { + return nil, err + } + after, err := Scan(ctx, root, Options{Overlay: over}) + if err != nil { + return nil, err + } + key := func(x Finding) string { return x.Rule + "|" + x.File + "|" + x.Props["image"] + "|" + string(x.Status) } + had := map[string]int{} + for _, x := range before.Findings { + had[key(x)]++ + } + for _, x := range after.Findings { + if x.File == f.File && x.Line == f.Line && x.Rule == f.Rule && x.Props["image"] == f.Props["image"] { + return nil, declined("after the edit, line %d of %s still names 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 + } + if !fi.Mode().IsRegular() { + return fmt.Errorf("%s is not a regular file", ch.File) + } + 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() +} + +// varUses counts the places a 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, a .env) that uses the variable too. +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 +} + +// 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 (Ubuntu on its full VERSION_ID): Debian 12 to 13 is not this +// fix's call, while Alpine 3.23 to 3.24 is what a rebuilt "-alpine" tag +// brings anyway. +func SameBase(current, target string) error { + major := func(s string) string { + id, ver, _ := strings.Cut(s, " ") + if id != "ubuntu" { + 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 +} + +// NamesBaseOS reports whether a tag's variant names its base OS. +func NamesBaseOS(variant string) bool { + v := strings.ToLower(variant) + for _, w := range []string{"alpine", "trixie", "bookworm", "bullseye", "debian", "jammy", "noble", "ubuntu", "ubi", "alma", "rocky"} { + if strings.Contains(v, w) { + return true + } + } + return false +} diff --git a/detectors/nginxh2/internal/repo/repo.go b/detectors/nginxh2/internal/repo/repo.go new file mode 100644 index 0000000..463f158 --- /dev/null +++ b/detectors/nginxh2/internal/repo/repo.go @@ -0,0 +1,852 @@ +// Package repo finds what in a source tree selects an nginx exposed to +// CVE-2026-123007 and CVE-2026-123633, and plans the edits that fix it: +// +// - image-pin: a Dockerfile, Compose, Kubernetes, Helm values or CI file +// names an nginx image (the official image, nginx-unprivileged, +// OpenResty, Bitnami, ingress-nginx, the F5 NGINX Ingress Controller, +// Angie) whose tag is a release without the fix, or a Helm chart that +// deploys ingress-nginx. +// - os-package: a Dockerfile installs nginx, OpenResty or Angie with apt, +// apk, dnf, yum, microdnf or zypper, pinned to a release without the +// fix or from a distribution that had no fixed package. +// - http2-config: an nginx configuration in the tree turns HTTP/2 on. A +// setting, not a vulnerable build: it is what makes a vulnerable nginx +// reachable. +// - not-checked: what could not be read or decided without reading an +// image (a moving tag, a digest, a variable). +// +// It knows nothing about the engine. +package repo + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "sort" + "strings" + + "gopkg.in/yaml.v3" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/conf" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/knowledge" + "github.com/DefectDojo/earlylight/internal/refs" +) + +// Rules. +const ( + RuleImage = "image-pin" + RulePackage = "os-package" + RuleHTTP2 = "http2-config" + RuleNotChecked = "not-checked" +) + +// CVEStatus is one CVE's status in a finding. +type CVEStatus struct { + ID string `json:"id"` + Status knowledge.Status `json:"status"` + Reason string `json:"reason"` +} + +// 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 knowledge.Status `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"` + CVEs []CVEStatus `json:"cves,omitempty"` + // Pull is set for an image reference only reading the image can + // decide (a moving tag, a digest). + Pull string `json:"pull,omitempty"` + // Platform is the FROM --platform the reference is built for. + Platform string `json:"platform,omitempty"` + // Interim is the optional HTTP/2-off edit fix prints and never applies. + Interim string `json:"interim,omitempty"` + ref *refs.Ref + edit *tagEdit + pin *pinEdit +} + +// pinEdit is a package pin to move to the fixed package. +type pinEdit struct { + old, repl string // "nginx=1.30.6-r0" -> "nginx=1.30.7-r0" + branch string +} + +// tagEdit is a tag to move. +type tagEdit struct { + image string + family Family + tag Tag + target string // the fixed tag +} + +// Skip is a file or reference 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 +} + +const ( + maxFileSize = 4 << 20 + maxFiles = 200000 + maxFindings = 10000 +) + +// maxDocs bounds the YAML documents read from one file. +const maxDocs = 1024 + +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 + if r, err := filepath.EvalSymlinks(root); err == nil { + root = r + } + var list []string + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + rel, _ := filepath.Rel(root, p) + res.Skips = append(res.Skips, Skip{File: filepath.ToSlash(rel), Reason: err.Error()}) + return nil + } + if ctx.Err() != nil { + return ctx.Err() + } + if d.IsDir() { + if p != root && skipDirs[d.Name()] { + return filepath.SkipDir + } + return nil + } + rel, err := filepath.Rel(root, p) + if err != nil { + return nil + } + rel = filepath.ToSlash(rel) + k := kindOf(rel) + if k == "" { + return nil + } + if !d.Type().IsRegular() { + if d.Type()&fs.ModeSymlink != 0 { + res.Skips = append(res.Skips, Skip{File: rel, Reason: "a symbolic link, which is not followed: not checked"}) + } + return nil + } + if len(list) >= maxFiles { + res.Truncated = true + return filepath.SkipAll + } + list = append(list, rel) + return nil + }) + if err != nil { + return res, err + } + for rel := range opts.Overlay { + if kindOf(rel) != "" && !contains(list, rel) { + list = append(list, rel) + } + } + sort.Strings(list) + s := &scanner{root: root, opts: opts, fromImage: map[string]refs.Ref{}, seen: map[string]bool{}, stageMods: map[string]string{}} + // Image references, with the place they are written. + rs, rskips, err := refs.ScanFiles(root, list, refs.Options{Overlay: opts.Overlay}) + if err != nil { + return res, err + } + for _, sk := range rskips { + if mayBeNginx(sk.Text) || sk.Text == "" && sk.Line == 0 { + res.Skips = append(res.Skips, Skip{File: sk.File, Line: sk.Line, Reason: refs.CleanText(sk.Reason, 300)}) + } + } + for i := range rs { + r := rs[i] + if r.Kind == refs.KindDockerfile && r.Context == "FROM" { + s.fromImage[fmt.Sprintf("%s:%d", r.File, r.Line)] = r + } + s.seen[r.File+"|"+r.Image] = true + s.image(&rs[i]) + } + for _, rel := range list { + if ctx.Err() != nil { + return res, ctx.Err() + } + b, ok := opts.Overlay[rel] + if !ok { + if b, err = readFile(root, rel); err != nil { + res.Skips = append(res.Skips, Skip{File: rel, Reason: err.Error()}) + continue + } + } + res.Files++ + switch kindOf(rel) { + case "dockerfile": + s.dockerfile(rel, b) + case "nginx-conf": + s.config(rel, b) + case "yaml": + s.yamlFile(rel, b) + } + } + s.deployments(root) + 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 +} + +// deploymentKeys are what a Compose service or Kubernetes container sets +// that changes what the image runs or the configuration it loads. +var deploymentKeys = []string{"command", "entrypoint", "args", "volumes", "volumeMounts", "configs", "environment", "env", "env_file", "envFrom", + "extends", "volumes_from", "variables"} + +// composeOverrides are the files Compose merges into a file of the same +// directory by default. +var composeOverrides = []string{"docker-compose.override.yml", "docker-compose.override.yaml", "compose.override.yml", "compose.override.yaml"} + +// deployments records, on each image reference that is read from its +// registry, what the deployment or build changes about it: the image's +// own command and configuration are then not what runs. +func (s *scanner) deployments(root string) { + docs := map[string][]*yaml.Node{} + for i := range s.findings { + f := &s.findings[i] + if f.Pull == "" || f.ref == nil { + continue + } + r := f.ref + if r.Kind == refs.KindDockerfile { + if why := s.stageMods[fmt.Sprintf("%s:%d", r.File, r.Line)]; why != "" { + f.Props["deployment"] = why + } + continue + } + if r.Kind == refs.KindHelmValues { + if why := s.helmTemplates(root, r.File); why != "" { + f.Props["deployment"] = why + } + continue + } + if r.Kind != refs.KindCompose && r.Kind != refs.KindKubernetes && r.Kind != refs.KindGitLabCI { + continue + } + load := func(file string) ([]*yaml.Node, bool) { + if ds, ok := docs[file]; ok { + return ds, true + } + b, found := s.opts.Overlay[file] + if !found { + var err error + if b, err = readFile(root, file); err != nil { + return nil, false + } + } + var ds []*yaml.Node + dec := yaml.NewDecoder(strings.NewReader(string(b))) + for len(ds) < maxDocs { + var d yaml.Node + if dec.Decode(&d) != nil { + break + } + ds = append(ds, &d) + } + docs[file] = ds + return ds, true + } + ds, ok := load(r.File) + if !ok { + f.Props["deployment"] = "the file could not be read again to see what it sets for the image" + continue + } + if r.Kind == refs.KindCompose { + if why := s.composeOverride(root, r, load); why != "" { + f.Props["deployment"] = why + continue + } + } + for _, d := range ds { + if m := mappingWithImageAt(d, r.Line, 0); m != nil { + var set []string + for _, k := range deploymentKeys { + if mapGet(m, k) != nil { + set = append(set, k) + } + } + if len(set) > 0 { + f.Props["deployment"] = fmt.Sprintf("the deployment sets %s for this image, so it may load another configuration or command", strings.Join(set, ", ")) + } + break + } + } + } +} + +// composeOverride reports a Compose override file of the same directory +// (docker-compose.override.yml and the like) that changes the service. +func (s *scanner) composeOverride(root string, r *refs.Ref, load func(string) ([]*yaml.Node, bool)) string { + parts := strings.Split(r.Context, ".") + if len(parts) < 3 || parts[0] != "services" { + return "" + } + svc := parts[1] + dir := path.Dir(r.File) + for _, o := range composeOverrides { + file := path.Join(dir, o) + if file == r.File { + continue + } + if _, err := os.Lstat(filepath.Join(root, filepath.FromSlash(file))); err != nil { + if _, inOverlay := s.opts.Overlay[file]; !inOverlay { + continue + } + } + ds, ok := load(file) + if !ok { + return fmt.Sprintf("%s could not be read, and Compose merges it into %s", file, r.File) + } + for _, d := range ds { + if len(d.Content) == 0 { + continue + } + m := mapGet(mapGet(d.Content[0], "services"), svc) + if m == nil { + continue + } + for _, k := range deploymentKeys { + if mapGet(m, k) != nil { + return fmt.Sprintf("%s sets %s for the service, so it may load another configuration or command", file, k) + } + } + } + } + return "" +} + +// helmTemplates reports a Helm chart whose templates may set the +// container's command or mount configuration: the templates next to the +// values file that set them, or no templates there to read (a chart from +// elsewhere). +func (s *scanner) helmTemplates(root, values string) string { + dir := path.Join(path.Dir(values), "templates") + full, err := refs.SafePath(root, dir) + if err != nil { + return "the chart's templates could not be read, so what they set for the image is not known" + } + if fi, err := os.Stat(full); err != nil || !fi.IsDir() { + return "the values are for a chart whose templates are not in this tree, so what they set for the image (command, mounted configuration) is not known" + } + // Every template, in every subdirectory, as Helm renders them, and + // every subchart's under charts/: a packaged subchart is not read. + why, seen := "", 0 + walk := func(full string, template func(rel string) bool) { + err := filepath.WalkDir(full, func(p string, d fs.DirEntry, err error) error { + rel, _ := filepath.Rel(root, p) + rel = filepath.ToSlash(rel) + if err != nil { + if errors.Is(err, fs.ErrNotExist) && p == full { + return nil + } + why = "a chart directory could not be read (" + rel + ")" + return filepath.SkipAll + } + if d.Type()&fs.ModeSymlink != 0 { + why = "the chart file " + rel + " is a symbolic link, which is not followed" + return filepath.SkipAll + } + if d.IsDir() { + return nil + } + if !d.Type().IsRegular() { + why = "the chart file " + rel + " is not a regular file" + return filepath.SkipAll + } + if !template(rel) { + if strings.HasSuffix(rel, ".tgz") || strings.HasSuffix(rel, ".tar.gz") { + why = "the packaged subchart " + rel + " is not read, so what it sets for the image is not known" + return filepath.SkipAll + } + return nil + } + if seen++; seen > 4096 { + why = "the chart has more templates than the detector reads" + return filepath.SkipAll + } + b, err := readFile(root, rel) + if err != nil { + why = "the chart template " + rel + " could not be read" + return filepath.SkipAll + } + for _, k := range []string{"volumeMounts", "command:", "args:", "envFrom", "env:"} { + if strings.Contains(string(b), k) { + why = fmt.Sprintf("the chart template %s sets %s, so the image may load another configuration or command", rel, strings.TrimSuffix(k, ":")) + return filepath.SkipAll + } + } + return nil + }) + if err != nil && why == "" { + why = "the chart's templates could not be read" + } + } + walk(full, func(string) bool { return true }) + if why == "" { + if charts, err := refs.SafePath(root, path.Join(path.Dir(values), "charts")); err == nil { + walk(charts, func(rel string) bool { return strings.Contains("/"+rel, "/templates/") }) + } + } + return why +} + +// mappingWithImageAt finds the mapping whose image key's value is on line. +func mappingWithImageAt(n *yaml.Node, line, depth int) *yaml.Node { + if n == nil || depth > 64 { + return nil + } + if n.Kind == yaml.MappingNode { + v := mapGet(n, "image") + if v == nil { + v = mapGet(n, "name") // a GitLab CI service + } + if v != nil && v.Kind == yaml.ScalarNode && v.Line == line { + return n + } + } + for _, c := range n.Content { + if m := mappingWithImageAt(c, line, depth+1); m != nil { + return m + } + } + return nil +} + +// mayBeNginx reports whether an unresolved reference could be an nginx +// image: it names one, or it is all variable. +func mayBeNginx(text string) bool { + low := strings.ToLower(text) + if strings.Contains(low, "nginx") || strings.Contains(low, "openresty") || strings.Contains(low, "angie") || strings.Contains(low, "tengine") { + return true + } + t := strings.TrimSpace(text) + return strings.HasPrefix(t, "$") || strings.HasPrefix(t, "{{") +} + +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 { + base := path.Base(rel) + low := strings.ToLower(base) + switch { + case low == "dockerfile" || low == "containerfile" || strings.HasPrefix(low, "dockerfile.") || strings.HasSuffix(low, ".dockerfile") || strings.HasPrefix(low, "containerfile."): + return "dockerfile" + case strings.HasSuffix(low, ".yaml") || strings.HasSuffix(low, ".yml"): + return "yaml" + case low == "nginx.conf" || strings.HasPrefix(low, "nginx.conf.") || strings.HasSuffix(low, ".conf") || strings.HasSuffix(low, ".conf.template") || strings.HasSuffix(low, ".nginx") || strings.HasSuffix(low, ".vhost"): + return "nginx-conf" + case strings.HasSuffix(low, ".template") || strings.HasSuffix(low, ".tmpl"): + if strings.Contains(strings.ToLower(rel), "nginx") || strings.Contains(low, ".conf") { + return "nginx-conf" + } + } + if strings.Contains(strings.ToLower(path.Dir(rel)), "sites-enabled") || strings.Contains(strings.ToLower(path.Dir(rel)), "sites-available") { + return "nginx-conf" + } + // refs reads Compose .env files and CI files of its own; those are + // handed to it through the list. + if low == ".env" || strings.HasSuffix(low, ".env") { + return "env" + } + return "" +} + +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: not checked", maxFileSize>>20) + } + return os.ReadFile(p) +} + +type scanner struct { + root string + opts Options + findings []Finding + skips []Skip + fromImage map[string]refs.Ref // "file:line" of a FROM -> its reference + seen map[string]bool // "file|image" judged + stageMods map[string]string // "file:line" of a FROM -> what its stage changes +} + +func (s *scanner) add(f Finding) { + if len(s.findings) < maxFindings { + s.findings = append(s.findings, f) + } +} + +// worst is the status a finding takes from its CVEs: vulnerable before +// unknown before the rest. +func worst(cs []CVEStatus) knowledge.Status { + st := knowledge.Fixed + for _, c := range cs { + switch c.Status { + case knowledge.Vulnerable: + return knowledge.Vulnerable + case knowledge.Unknown: + st = knowledge.Unknown + } + } + return st +} + +func cveList(v map[string]Verdict) []CVEStatus { + var out []CVEStatus + for _, c := range knowledge.CVEs { + x := v[c.ID] + out = append(out, CVEStatus{ID: c.ID, Status: x.Status, Reason: x.Reason}) + } + return out +} + +func reasons(cs []CVEStatus) string { + var parts []string + for _, c := range cs { + parts = append(parts, fmt.Sprintf("%s %s (%s)", c.ID, c.Status, c.Reason)) + } + return strings.Join(parts, "; ") +} + +// splitImage reads repository, tag and digest from a reference. +func splitImage(image string) (repo, tag, digest string) { + base, dg, _ := strings.Cut(image, "@") + digest = dg + slash := strings.LastIndexByte(base, '/') + if c := strings.LastIndexByte(base, ':'); c > slash { + return base[:c], base[c+1:], digest + } + return base, "", digest +} + +// image judges one image reference. +func (s *scanner) image(r *refs.Ref) { + fam, ok := Classify(r.Image) + if !ok { + if NginxShaped(r.Image) { + s.add(Finding{Rule: RuleNotChecked, File: r.File, Line: r.Line, Level: "note", Status: knowledge.Unknown, + Reason: "an image that may hold nginx, from a repository whose tags the detector does not read", + Message: fmt.Sprintf("%s may hold nginx (a mirror, or a product built on nginx or OpenResty): not judged from its name; it is read from its registry unless the run is offline", r.Image), + Fix: "Read the image (earlylight scan image " + r.Image + ").", + Props: map[string]string{"image": r.Image, "context": r.Context}, Pull: r.Image, Platform: r.Platform, ref: r}) + } + return + } + repoName, tag, digest := splitImage(r.Image) + props := map[string]string{"image": r.Image, "family": fam.ID, "context": r.Context} + t, exact := fam.ParseTag(tag) + if exact && digest != "" && worst(cveList(fam.Judge(t))) == knowledge.Vulnerable { + // The tag names a release without the fix; whatever the digest + // holds, the reference asks for that release. Moving it means + // moving the digest too. + v := fam.Judge(t) + cs := cveList(v) + props["tag"], props["version"], props["digest"] = tag, t.Version, digest + f := Finding{Rule: RuleImage, File: r.File, Line: r.Line, Level: "error", Status: knowledge.Vulnerable, Props: props, CVEs: cs, Platform: r.Platform, ref: r} + f.Reason = reasons(cs) + f.Message = fmt.Sprintf("%s names %s %s: %s", r.Image, fam.Vendor, t.Version, f.Reason) + if target := fam.FixedTag(t); target != "" { + f.Fix = fmt.Sprintf("Move to %s:%s and its digest (the reference is pinned by digest, so fix does not change it), then rebuild and redeploy.", repoName, target) + } else { + f.Fix = fam.LineText(t) + "." + } + s.add(f) + return + } + if !exact || digest != "" { + why := "its tag does not name one release (a moving tag)" + if digest != "" { + why = "it is pinned by digest, which decides what it holds" + } + if tag == "" && digest == "" { + why = "it has no tag (latest), which moves" + } + s.add(Finding{Rule: RuleNotChecked, File: r.File, Line: r.Line, Level: "note", Status: knowledge.Unknown, + Reason: "only reading the image says which nginx it holds", + Message: fmt.Sprintf("%s (%s) is not judged from its name: %s; it is read from its registry unless the run is offline", r.Image, fam.Vendor, why), + Fix: "Read the image (earlylight scan image " + r.Image + ") or pin a tag of a fixed release.", + Props: props, Pull: r.Image, Platform: r.Platform, ref: r}) + return + } + v := fam.Judge(t) + cs := cveList(v) + st := worst(cs) + if st == knowledge.Fixed || st == knowledge.NotAffected { + return + } + props["tag"] = tag + props["version"] = t.Version + f := Finding{Rule: RuleImage, File: r.File, Line: r.Line, Level: "error", Status: st, Props: props, CVEs: cs, Platform: r.Platform, ref: r} + f.Reason = reasons(cs) + f.Message = fmt.Sprintf("%s names %s %s: %s", r.Image, fam.Vendor, t.Version, f.Reason) + if st == knowledge.Unknown { + f.Level = "note" + f.Rule = RuleNotChecked + } + if target := fam.FixedTag(t); target != "" { + f.Fixable = true + f.edit = &tagEdit{image: r.Image, family: fam, tag: t, target: target} + f.Fix = fmt.Sprintf("Move to %s:%s, %s, then rebuild and redeploy.", repoName, target, fam.MoveText(t)) + } else { + f.Fix = fam.LineText(t) + "." + } + f.Interim = "Until then, turn HTTP/2 off in the configuration the image runs (\"http2 off;\" and no \"http2\" on any listen): an interim step, not a fix." + s.add(f) +} + +// config reports where an nginx configuration in the tree turns HTTP/2 +// on. +func (s *scanner) config(rel string, b []byte) { + s.configText(rel, 0, string(b)) +} + +// configText analyses one configuration text; base is added to its line +// numbers (a ConfigMap value starts below its key). +func (s *scanner) configText(rel string, base int, text string) { + ds, err := conf.Parse(rel, text) + if err != nil { + // Not every *.conf is nginx's. A file that names HTTP/2 and does + // not parse is not checked. + if strings.Contains(text, "http2") { + s.skips = append(s.skips, Skip{File: rel, Reason: "names http2 but could not be read as an nginx configuration (" + refs.CleanText(err.Error(), 120) + "): not checked"}) + } + return + } + // A conf.d or sites-enabled snippet holds server blocks (or server + // directives): read it inside http, where nginx includes it. + wrapped := ds + top := false + for _, d := range ds { + if d.Name == "http" || d.Name == "events" { + top = true + } + } + if !top { + wrapped = []conf.Directive{{Name: "http", HasBlock: true, Block: ds}} + if !hasServer(ds) { + wrapped[0].Block = []conf.Directive{{Name: "server", HasBlock: true, Block: ds, File: rel, Line: 1}} + } + } + e := conf.Analyze(&conf.Config{Main: rel, Root: wrapped, Files: []string{rel}}) + if e.HTTP2 != "on" { + return + } + for _, w := range e.Where { + file, line := splitWhere(w) + if file != rel { + continue + } + over := "over TLS" + if e.Flow != conf.Exposed { + over = "without TLS" + } + proxy := "in front of a proxy" + if e.Reuse != conf.Exposed { + proxy = "with no proxy directive in this file" + } + s.add(Finding{Rule: RuleHTTP2, File: rel, Line: base + line, Level: "note", Status: knowledge.NotAffected, + Reason: "a setting, not a vulnerable build: it makes a vulnerable nginx reachable", + Message: fmt.Sprintf("turns HTTP/2 on (%s, %s): an nginx before 1.31.9 or 1.30.7 that loads it is exposed to %s and %s", over, proxy, knowledge.Flow, knowledge.Reuse), + Fix: "Run nginx 1.31.9 or 1.30.7 or later. " + knowledge.Interim, + Interim: fmt.Sprintf("%s: on line %d, remove \"http2\" from the listen parameters and add \"http2 off;\" to the server (nginx 1.25.1 and later; older releases have only the listen parameter)", rel, base+line), + Props: map[string]string{"http2": "on", "flow": string(e.Flow), "reuse": string(e.Reuse)}}) + } +} + +func hasServer(ds []conf.Directive) bool { + for _, d := range ds { + if d.Name == "server" && d.HasBlock { + return true + } + } + return false +} + +func splitWhere(w string) (string, int) { + i := strings.LastIndexByte(w, ':') + if i < 0 { + return w, 0 + } + n := 0 + fmt.Sscanf(w[i+1:], "%d", &n) + return w[:i], n +} + +// yamlFile reads Helm charts that deploy ingress-nginx and ConfigMaps that +// carry an nginx configuration. +func (s *scanner) yamlFile(rel string, b []byte) { + dec := yaml.NewDecoder(strings.NewReader(string(b))) + for i := 0; ; i++ { + if i >= maxDocs { + s.skips = append(s.skips, Skip{File: rel, Reason: fmt.Sprintf("more than %d YAML documents: the rest are not checked for nginx configurations and charts", maxDocs)}) + return + } + var doc yaml.Node + if err := dec.Decode(&doc); err != nil { + if !errors.Is(err, io.EOF) { + s.skips = append(s.skips, Skip{File: rel, Reason: fmt.Sprintf("could not be read as YAML after %d documents (%s): the rest is not checked for nginx configurations and charts", i, refs.CleanText(err.Error(), 120))}) + } + return + } + if len(doc.Content) == 0 { + continue + } + m := doc.Content[0] + if m.Kind != yaml.MappingNode { + continue + } + if path.Base(rel) == "Chart.yaml" { + s.chart(rel, m) + } + s.helmImages(rel, m, 0) + if v := mapGet(m, "kind"); v != nil && v.Value == "ConfigMap" { + if data := mapGet(m, "data"); data != nil && data.Kind == yaml.MappingNode { + for j := 0; j+1 < len(data.Content); j += 2 { + k, val := data.Content[j], data.Content[j+1] + if strings.Contains(val.Value, "server") && strings.Contains(val.Value, "listen") { + // A block scalar's text starts on the line after + // its key; a plain or quoted one on the key's line. + base := val.Line - 1 + if val.Style&(yaml.LiteralStyle|yaml.FoldedStyle) != 0 { + base = val.Line + } + s.configText(rel+"#"+k.Value, base, val.Value) + } + } + } + } + } +} + +// helmImages finds images Helm values write as separate registry, image +// and tag keys (the ingress-nginx chart's controller.image), which the +// image reference scan does not assemble. +func (s *scanner) helmImages(rel string, m *yaml.Node, depth int) { + if m == nil || depth > 32 { + return + } + switch m.Kind { + case yaml.SequenceNode: + for _, c := range m.Content { + s.helmImages(rel, c, depth+1) + } + return + case yaml.MappingNode: + default: + return + } + img, tag := mapGet(m, "image"), mapGet(m, "tag") + if img != nil && tag != nil && img.Kind == yaml.ScalarNode && tag.Kind == yaml.ScalarNode && img.Value != "" && tag.Value != "" && !strings.ContainsAny(img.Value+tag.Value, ":@${}") { + ref := img.Value + if reg := mapGet(m, "registry"); reg != nil && reg.Kind == yaml.ScalarNode && reg.Value != "" && !strings.ContainsAny(reg.Value, "${}") { + ref = reg.Value + "/" + ref + } + ref += ":" + tag.Value + if d := mapGet(m, "digest"); d != nil && d.Kind == yaml.ScalarNode && strings.HasPrefix(d.Value, "sha256:") { + ref += "@" + d.Value + } + if _, ok := Classify(ref); ok && !s.seen[rel+"|"+ref] { + s.seen[rel+"|"+ref] = true + s.image(&refs.Ref{File: rel, Line: tag.Line, Kind: refs.KindHelmValues, Context: "image.tag", Text: ref, Image: ref}) + } + } + for i := 1; i < len(m.Content); i += 2 { + s.helmImages(rel, m.Content[i], depth+1) + } +} + +// chart reports a Helm chart dependency on ingress-nginx. +func (s *scanner) chart(rel string, m *yaml.Node) { + deps := mapGet(m, "dependencies") + if deps == nil || deps.Kind != yaml.SequenceNode { + return + } + for _, d := range deps.Content { + n := mapGet(d, "name") + if n == nil || n.Value != "ingress-nginx" { + continue + } + ver := "" + if v := mapGet(d, "version"); v != nil { + ver = v.Value + } + s.add(Finding{Rule: RuleImage, File: rel, Line: n.Line, Level: "error", Status: knowledge.Vulnerable, + Reason: Ingress.NoFix, + Message: fmt.Sprintf("the chart depends on the ingress-nginx chart %s, whose controller runs nginx without the fix for %s and %s and turns HTTP/2 on by default: %s", ver, knowledge.Flow, knowledge.Reuse, Ingress.NoFix), + Fix: "Replace ingress-nginx (for example with a maintained controller on nginx 1.31.9 or 1.30.7, or Gateway API); until then set use-http2: \"false\" in the controller's ConfigMap (an interim step, not a fix).", + Props: map[string]string{"chart": "ingress-nginx", "version": ver}, + CVEs: []CVEStatus{{ID: knowledge.Flow, Status: knowledge.Vulnerable, Reason: Ingress.NoFix}, + {ID: knowledge.Reuse, Status: knowledge.Vulnerable, Reason: Ingress.NoFix}}}) + } +} + +func mapGet(m *yaml.Node, key string) *yaml.Node { + if m == nil || m.Kind != yaml.MappingNode { + return nil + } + for i := 0; i+1 < len(m.Content); i += 2 { + if m.Content[i].Value == key { + return m.Content[i+1] + } + } + return nil +} diff --git a/detectors/nginxh2/internal/repo/repo_test.go b/detectors/nginxh2/internal/repo/repo_test.go new file mode 100644 index 0000000..2248044 --- /dev/null +++ b/detectors/nginxh2/internal/repo/repo_test.go @@ -0,0 +1,657 @@ +package repo + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/knowledge" +) + +func tree(t *testing.T, files map[string]string) string { + t.Helper() + root := t.TempDir() + for p, s := range files { + full := filepath.Join(root, filepath.FromSlash(p)) + if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(full, []byte(s), 0o644); err != nil { + t.Fatal(err) + } + } + return root +} + +func scan(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 +} + +func at(res Result, file string, line int) []Finding { + var out []Finding + for _, f := range res.Findings { + if f.File == file && f.Line == line { + out = append(out, f) + } + } + return out +} + +func one(t *testing.T, res Result, file string, line int, rule string, st knowledge.Status) Finding { + t.Helper() + fs := at(res, file, line) + for _, f := range fs { + if f.Rule == rule && f.Status == st { + return f + } + } + t.Fatalf("no %s %s at %s:%d; have %+v", rule, st, file, line, fs) + return Finding{} +} + +func TestClassifyAndTags(t *testing.T) { + for img, fam := range map[string]string{ + "nginx": "nginx", "docker.io/library/nginx:1.31.8": "nginx", "mirror.gcr.io/library/nginx:1": "nginx", "harbor.corp/dockerhub/library/nginx:1.30.6": "nginx", + "public.ecr.aws/nginx/nginx:1.31.8": "nginx", "nginxinc/nginx-unprivileged:1.31.7-alpine": "nginx-unprivileged", + "openresty/openresty:1.31.8.1-alpine": "openresty", "bitnamilegacy/nginx:1.29.1-debian-12-r0": "bitnami-nginx", + "registry.k8s.io/ingress-nginx/controller:v1.15.1": "ingress-nginx", "nginx/nginx-ingress:5.7.1-alpine": "nginx-ingress", + "docker.angie.software/angie:1.12.4": "angie", + } { + f, ok := Classify(img) + if !ok || f.ID != fam { + t.Errorf("Classify(%s) = %v %v, want %s", img, f.ID, ok, fam) + } + } + for _, img := range []string{"myorg/nginx:1.0", "nginxproxy/nginx-proxy:1.6", "python:3.12", "caddy:2", "traefik:3"} { + if f, ok := Classify(img); ok { + t.Errorf("Classify(%s) = %s", img, f.ID) + } + } + cases := []struct { + fam Family + tag string + version string + variant string + exact bool + fixed string + }{ + {Official, "1.31.8-alpine3.24-perl", "1.31.8", "-alpine3.24-perl", true, "1.31.9-alpine3.24-perl"}, + {Official, "1.30.6", "1.30.6", "", true, "1.30.7"}, + {Official, "1.29.8-bookworm", "1.29.8", "-bookworm", true, ""}, + {Official, "1.31", "", "", false, ""}, + {Official, "mainline-alpine", "", "", false, ""}, + {Unprivileged, "1.31.7-alpine-slim", "1.31.7", "-alpine-slim", true, "1.31.9-alpine-slim"}, + {OpenResty, "1.31.8.1-0-alpine-fat", "1.31.8.1", "-0-alpine-fat", true, ""}, + {OpenResty, "1.31-alpine", "", "", false, ""}, + {Ingress, "v1.15.1", "1.15.1", "", true, ""}, + {F5Ingress, "5.7.1-alpine", "5.7.1", "-alpine", true, "5.8.0-alpine"}, + {F5Ingress, "4.0.0", "4.0.0", "", true, ""}, + } + for _, c := range cases { + tg, ok := c.fam.ParseTag(c.tag) + if ok != c.exact || tg.Version != c.version || tg.Variant != c.variant { + t.Errorf("%s ParseTag(%s) = %+v %v", c.fam.ID, c.tag, tg, ok) + continue + } + if ok { + if got := c.fam.FixedTag(tg); got != c.fixed { + t.Errorf("%s FixedTag(%s) = %q, want %q", c.fam.ID, c.tag, got, c.fixed) + } + } + } + if v := Ingress.Judge(Tag{Version: "0.49.3"}); v[knowledge.Reuse].Status != knowledge.Unknown || v[knowledge.Flow].Status != knowledge.Vulnerable { + t.Errorf("ingress v0: %+v", v) + } + if v := F5Ingress.Judge(Tag{Version: "5.8.0"}); v[knowledge.Flow].Status != knowledge.Fixed { + t.Errorf("F5 5.8.0: %+v", v) + } + if v := F5Ingress.Judge(Tag{Version: "5.9.0"}); v[knowledge.Flow].Status != knowledge.Unknown { + t.Errorf("F5 5.9.0: %+v", v) + } + // R5: a tag on a line newer than any known is never cleared. + res := scan(t, map[string]string{"Dockerfile": "FROM nginx:37.0.0\nFROM nginx:1.32.0-alpine\n"}) + one(t, res, "Dockerfile", 1, RuleNotChecked, knowledge.Unknown) + one(t, res, "Dockerfile", 2, RuleNotChecked, knowledge.Unknown) +} + +func TestImages(t *testing.T) { + res := scan(t, map[string]string{ + "Dockerfile": "ARG T=1.30.6\nFROM nginx:${T}-perl AS a\nFROM nginx:1.31.9\nFROM nginx:mainline\nFROM nginx@sha256:" + strings.Repeat("a", 64) + "\nFROM nginx:1.18.0\nFROM nginx:1.8.1\n", + "compose.yaml": "services:\n a:\n image: registry.k8s.io/ingress-nginx/controller:v1.15.1@sha256:" + strings.Repeat("b", 64) + "\n b:\n image: nginx:1.31.9@sha256:" + strings.Repeat("c", 64) + "\n", + }) + f := one(t, res, "Dockerfile", 2, RuleImage, knowledge.Vulnerable) + if !f.Fixable || f.edit.target != "1.30.7-perl" { + t.Errorf("ARG-driven tag: %+v", f) + } + if fs := at(res, "Dockerfile", 3); len(fs) != 0 { + t.Errorf("a fixed tag gave findings: %+v", fs) + } + if f := one(t, res, "Dockerfile", 4, RuleNotChecked, knowledge.Unknown); f.Pull != "nginx:mainline" { + t.Errorf("moving tag: %+v", f) + } + one(t, res, "Dockerfile", 5, RuleNotChecked, knowledge.Unknown) + f = one(t, res, "Dockerfile", 6, RuleImage, knowledge.Vulnerable) + if f.CVEs[1].Status != knowledge.NotAffected || f.Fixable { + t.Errorf("1.18.0: %+v", f) + } + if fs := at(res, "Dockerfile", 7); len(fs) != 0 { + t.Errorf("1.8.1 predates HTTP/2: %+v", fs) + } + // A vulnerable tag pinned by digest is judged by its tag, not fixed. + if f := one(t, res, "compose.yaml", 3, RuleImage, knowledge.Vulnerable); f.Fixable { + t.Errorf("digest pinned: %+v", f) + } + // A fixed tag with a digest: the digest decides, so it is read. + if f := one(t, res, "compose.yaml", 5, RuleNotChecked, knowledge.Unknown); f.Pull == "" { + t.Errorf("fixed tag with digest: %+v", f) + } +} + +func TestPackages(t *testing.T) { + df := strings.Join([]string{ + "FROM debian:12", // 1 + "RUN apt-get update && apt-get install -y nginx=1.22.1-9+deb12u10", // 2 + "RUN apt-get install -y nginx-light", // 3 + "FROM alpine:3.24 AS a", // 4 + "RUN apk add --no-cache nginx~1.30 openresty=1.27.1.2-r0", // 5 + "RUN apk add 'nginx>=1.30.7-r0'", // 6 + "FROM a", // 7 + "ARG PKG=nginx", // 8 + "RUN set -eux; ( apk add --no-cache $PKG )", // 9 + "FROM rockylinux:9", // 10 + "RUN dnf install -y nginx-1.24.0-4.el9 && dnf module install -y nginx:1.26/common", // 11 + "FROM debian:trixie-slim", // 12 + "RUN echo nginx | xargs apt-get install -y", // 13 + "RUN bash -lc 'DEBIAN_FRONTEND=noninteractive apt-get -y install nginx=1.31.8-1~trixie'", // 14 + "RUN apt-get install -y $(cat pkgs.txt) $EXTRA", // 15 + "FROM ubuntu:24.04", // 16 + "RUN <"+target) + if r.fail != nil { + return "", r.fail + } + return "sha256:" + strings.Repeat("e", 64), nil + }, + } +} + +func plan(t *testing.T, root string, file string, line int, reg Registry) (*Change, error) { + t.Helper() + res, err := Scan(context.Background(), root, Options{}) + if err != nil { + t.Fatal(err) + } + for _, f := range res.Findings { + if f.File == file && f.Line == line && f.Rule == RuleImage { + return Plan(context.Background(), root, f, reg, Options{}) + } + } + t.Fatalf("no image finding at %s:%d: %+v", file, line, res.Findings) + return nil, nil +} + +func TestPlan(t *testing.T) { + root := tree(t, map[string]string{ + "Dockerfile": "ARG V=1.30.6\nFROM nginx:1.31.8-alpine AS a\nFROM nginx:${V}\nFROM nginx:1.29.8\n", + "compose.yaml": "services:\n web:\n image: \"nginxinc/nginx-unprivileged:${TAG:-1.31.7-alpine}\"\n", + }) + fr := &fakeRegistry{tags: []string{"1.31.8-alpine", "1.31.9-alpine", "1.30.7", "1.31.9-alpine-slim"}} + ch, err := plan(t, root, "Dockerfile", 2, fr.reg()) + if err != nil || ch.New != "FROM nginx:1.31.9-alpine AS a" { + t.Fatalf("plan: %+v %v", ch, err) + } + if err := Apply(root, ch); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(filepath.Join(root, "Dockerfile")) + if !strings.HasPrefix(string(b), "ARG V=1.30.6\nFROM nginx:1.31.9-alpine AS a\n") { + t.Errorf("applied: %s", b) + } + // Applying the same change twice fails: the line no longer reads as planned. + if err := Apply(root, ch); err == nil { + t.Error("a stale change was applied") + } + // The tag from an ARG default is edited where it is written. + ch, err = plan(t, root, "Dockerfile", 3, fr.reg()) + if err != nil || ch.Line != 1 || ch.New != "ARG V=1.30.7" { + t.Fatalf("ARG: %+v %v", ch, err) + } + // A line with no fix is declined, with the reason. + if _, err := plan(t, root, "Dockerfile", 4, fr.reg()); err == nil || !strings.Contains(err.Error(), "received no fix") { + t.Errorf("1.29: %v", err) + } + // The target is not published yet. + fr.tags = []string{"1.31.7-alpine", "1.31.8-alpine"} + if _, err := plan(t, root, "compose.yaml", 3, fr.reg()); err == nil || !strings.Contains(err.Error(), "has not published 1.31.9-alpine") { + t.Errorf("unpublished: %v", err) + } + // Verification fails: declined, nothing changes. + fr.tags = append(fr.tags, "1.31.9-alpine") + fr.fail = &Declined{Reason: "still holds /usr/sbin/nginx"} + if _, err := plan(t, root, "compose.yaml", 3, fr.reg()); err == nil || !strings.Contains(err.Error(), "still holds") { + t.Errorf("verify: %v", err) + } + fr.fail = errors.New("connection refused") + if _, err := plan(t, root, "compose.yaml", 3, fr.reg()); err == nil || !strings.Contains(err.Error(), "not checked") { + t.Errorf("verify error: %v", err) + } + // Without a registry (offline): declined. + if _, err := plan(t, root, "compose.yaml", 3, Registry{}); err == nil { + t.Error("offline plan was not declined") + } +} + +func TestPlanSharedVariable(t *testing.T) { + root := tree(t, map[string]string{ + "Dockerfile": "ARG V=1.30.6\nFROM nginx:${V}\nRUN echo ${V}\n", + }) + fr := &fakeRegistry{tags: []string{"1.30.7"}} + if _, err := plan(t, root, "Dockerfile", 2, fr.reg()); err == nil || !strings.Contains(err.Error(), "more than one place") { + t.Errorf("shared variable: %v", err) + } + if len(fr.verified) != 0 { + t.Error("verified before declining") + } +} + +func TestSameBase(t *testing.T) { + for _, c := range []struct { + a, b string + ok bool + }{ + {"debian 13", "debian 13", true}, {"alpine 3.23.4", "alpine 3.24.1", true}, {"debian 12", "debian 13", false}, + {"ubuntu 24.04", "ubuntu 24.10", false}, {"", "debian 13", false}, {"alpine 3.24", "debian 13", false}, + } { + if err := SameBase(c.a, c.b); (err == nil) != c.ok { + t.Errorf("SameBase(%q, %q) = %v", c.a, c.b, err) + } + } +} + +func TestShell(t *testing.T) { + got := installs(`set -e; if true; then apk add --virtual .x nginx; fi && sudo -E apt-get -o Dpkg::Options::=--force-confnew install -y nginx-full=1.2>/dev/null`, 0) + if len(got) != 2 || got[0].args[0] != "nginx" || got[1].args[0] != "nginx-full=1.2" { + t.Errorf("%+v", got) + } + if v := lineVars("P=nginx-light; apt-get install $P", nil); v["P"] != "nginx-light" { + t.Errorf("lineVars %v", v) + } + if v := lineVars("P=$(cat x); apt-get install $P", map[string]string{"P": "nginx"}); v["P"] != "" { + t.Errorf("lineVars from a command %v", v) + } +} + +func TestAlpineBranches(t *testing.T) { + for img, want := range map[string]string{ + "alpine:3.24": "3.24", "alpine:3.24.4": "3.24", "alpine:edge": "edge", "alpine:3": "", "alpine": "", "alpine:latest": "", + "python:3.12-alpine3.23": "3.23", "nginx:1.31.8-alpine3.24-perl": "3.24", "nginx:1.31.8-alpine": "", "node:22-alpine": "", + } { + if got := alpineBranchOf(img); got != want { + t.Errorf("alpineBranchOf(%s) = %q, want %q", img, got, want) + } + } + root := tree(t, map[string]string{"Dockerfile": strings.Join([]string{ + "FROM alpine:3.23", // 1 + "RUN apk add --no-cache nginx", // 2 + "FROM alpine:3.24", // 3 + "RUN apk add --no-cache \\", // 4 + " curl nginx=1.30.6-r0", // 5 + "FROM alpine:3", // 6 + "RUN apk add nginx", // 7 + "FROM alpine:3.22", // 8 + "RUN apk add nginx=1.28.3-r7", // 9 + "FROM alpine:3.24", // 10 + "RUN apk add nginx=1.30.7-r0", // 11 + }, "\n") + "\n"}) + res, err := Scan(context.Background(), root, Options{}) + if err != nil { + t.Fatal(err) + } + one(t, res, "Dockerfile", 2, RulePackage, knowledge.Vulnerable) + f := one(t, res, "Dockerfile", 4, RulePackage, knowledge.Vulnerable) + if !f.Fixable { + t.Fatalf("a 3.24 pin is fixable: %+v", f) + } + // R14: the branch's index decides; without it (offline) nothing moves. + if _, err := Plan(context.Background(), root, f, Registry{}, Options{}); err == nil { + t.Fatal("a pin moved without reading the branch's index") + } + index := func(v string) Registry { + return Registry{APKIndex: func(_ context.Context, branch string) (string, error) { return v, nil }} + } + ch, err := Plan(context.Background(), root, f, index("1.30.7-r0"), Options{}) + if err != nil || ch.Line != 5 || ch.New != " curl nginx=1.30.7-r0" { + t.Fatalf("pin plan: %+v %v", ch, err) + } + // The index has a later fixed build: that is the pin. + if ch, err := Plan(context.Background(), root, f, index("1.30.7-r1"), Options{}); err != nil || ch.New != " curl nginx=1.30.7-r1" { + t.Errorf("later build: %+v %v", ch, err) + } + // The index has no fixed build any more (or yet): declined. + if _, err := Plan(context.Background(), root, f, index("1.30.6-r0"), Options{}); err == nil { + t.Error("moved to an unfixed build") + } + one(t, res, "Dockerfile", 7, RuleNotChecked, knowledge.Unknown) + if f := one(t, res, "Dockerfile", 9, RulePackage, knowledge.Vulnerable); f.Fixable || !strings.Contains(f.Fix, "Alpine 3.22 had no fixed") { + t.Errorf("3.22 pin: %+v", f) + } + if fs := at(res, "Dockerfile", 11); len(fs) != 0 { + t.Errorf("the fixed pin: %+v", fs) + } +} + +// Review 2, finding 3: what a deployment changes about an image it reads +// (command, environment, mounted configuration, a Dockerfile building on +// it) is recorded, so the image's own configuration is not trusted. +func TestR3Deployment(t *testing.T) { + res := scan(t, map[string]string{ + "compose.yaml": "services:\n web:\n image: nginx:1.29\n command: [nginx, -c, /etc/nginx/site/nginx.conf]\n volumes:\n - ./conf.d:/etc/nginx/conf.d:ro\n plain:\n image: nginx:1.30\n", + "k8s.yaml": "apiVersion: apps/v1\nkind: Deployment\nmetadata: {name: x}\nspec:\n template:\n spec:\n containers:\n - name: a\n image: nginx:mainline\n volumeMounts:\n - {name: c, mountPath: /etc/nginx/conf.d}\n - name: b\n image: nginx:stable\n", + "Dockerfile": "FROM nginx:1.31 AS a\nCOPY site.conf /etc/nginx/conf.d/\nFROM nginx:alpine AS b\nLABEL x=y\n", + }) + for _, c := range []struct { + file string + line int + want bool + }{{"compose.yaml", 3, true}, {"compose.yaml", 8, false}, {"k8s.yaml", 9, true}, {"k8s.yaml", 13, false}, {"Dockerfile", 1, true}, {"Dockerfile", 3, false}} { + f := one(t, res, c.file, c.line, RuleNotChecked, knowledge.Unknown) + if got := f.Props["deployment"] != ""; got != c.want { + t.Errorf("%s:%d deployment %q, want %v", c.file, c.line, f.Props["deployment"], c.want) + } + } +} + +// Review 2, finding 9: nothing nginx-shaped is passed over in silence. +func TestR9NeverSilent(t *testing.T) { + root := tree(t, map[string]string{ + "Dockerfile": strings.Join([]string{ + "FROM registry.example.com/nginx:1.31.8", // 1 + "FROM cgr.dev/chainguard/nginx:1.31.8", // 2 + "FROM axizdkr/tengine:latest", // 3 + "FROM kong:3.9", // 4 + "FROM debian:12", // 5 + "COPY --from=nginx:1.31.8 /usr/sbin/nginx /usr/sbin/nginx", // 6 + "RUN apt-get install -y libnginx-mod-http-lua python3-certbot-nginx nginx-module-njs", // 7 + "RUN apt-get install -y angie-pro", // 8 + }, "\n") + "\n", + "real/compose.yaml": "services:\n web:\n image: nginx:1.31.8\n", + }) + if err := os.Symlink("real/compose.yaml", filepath.Join(root, "compose.yaml")); err != nil { + t.Fatal(err) + } + if err := os.Symlink("Dockerfile", filepath.Join(root, "Dockerfile.prod")); err != nil { + t.Fatal(err) + } + res, err := Scan(context.Background(), root, Options{}) + if err != nil { + t.Fatal(err) + } + for _, line := range []int{1, 2, 3, 4} { + if f := one(t, res, "Dockerfile", line, RuleNotChecked, knowledge.Unknown); f.Pull == "" { + t.Errorf("line %d is not read from its registry: %+v", line, f) + } + } + if f := one(t, res, "Dockerfile", 6, RuleImage, knowledge.Vulnerable); f.Fixable { + t.Errorf("COPY --from is not edited by fix: %+v", f) + } + if fs := at(res, "Dockerfile", 7); len(fs) != 3 { + t.Errorf("module packages: %+v", fs) + } + one(t, res, "Dockerfile", 8, RuleNotChecked, knowledge.Unknown) + skipped := map[string]bool{} + for _, s := range res.Skips { + skipped[s.File] = true + } + if !skipped["compose.yaml"] || !skipped["Dockerfile.prod"] { + t.Errorf("symbolic links not recorded: %+v", res.Skips) + } +} + +// R14: on edge, a pin above Alpine's fixed package is never moved down. +func TestR14EdgeNoDowngrade(t *testing.T) { + root := tree(t, map[string]string{"Dockerfile": "FROM alpine:edge\nRUN apk add nginx=1.31.8-r0\n"}) + res, err := Scan(context.Background(), root, Options{}) + if err != nil { + t.Fatal(err) + } + f := one(t, res, "Dockerfile", 2, RulePackage, knowledge.Vulnerable) + if strings.Contains(f.Fix, "1.30.7-r0, the fixed package") { + t.Errorf("fix text proposes a move down: %s", f.Fix) + } + reg := Registry{APKIndex: func(context.Context, string) (string, error) { return "1.30.7-r0", nil }} + if _, err := Plan(context.Background(), root, f, reg, Options{}); err == nil { + t.Error("planned a move down a line") + } +} + +// R15: the F5 controller's move to 5.8.0 is labelled a minor upgrade. +func TestR15MinorUpgrade(t *testing.T) { + res := scan(t, map[string]string{"compose.yaml": "services:\n ic:\n image: nginx/nginx-ingress:5.7.1\n"}) + f := one(t, res, "compose.yaml", 3, RuleImage, knowledge.Vulnerable) + if !strings.Contains(f.Fix, "minor upgrade") || strings.Contains(f.Fix, "same line") { + t.Errorf("%s", f.Fix) + } +} + +// R16: what is known only from a date or a version is worded so. +func TestR16Wording(t *testing.T) { + res := scan(t, map[string]string{"Dockerfile": "FROM debian:trixie-slim\nRUN echo 'deb http://nginx.org/packages/mainline/debian trixie nginx' > /etc/apt/sources.list.d/n.list && apt-get update && apt-get install -y nginx\n"}) + f := one(t, res, "Dockerfile", 2, RuleNotChecked, knowledge.Unknown) + if strings.Contains(f.Message, "a build from 2026-11-18 on gets") { + t.Errorf("certainty about nginx.org's packages: %s", f.Message) + } +} + +// R17: a YAML file that stops decoding, or has more documents than are +// read, is recorded as not checked. +func TestR17YAMLErrors(t *testing.T) { + many := strings.Repeat("---\nkind: Service\n", 1100) + res := scan(t, map[string]string{ + "bad.yaml": "kind: ConfigMap\ndata:\n a.conf: x\n---\nkey: [unclosed\n", + "many.yaml": many, + }) + got := map[string]bool{} + for _, s := range res.Skips { + got[s.File] = true + } + if !got["bad.yaml"] || !got["many.yaml"] { + t.Errorf("%+v", res.Skips) + } +} + +// Verification 3: changes a deployment makes reach the image they apply +// to, through FROM aliases, Helm charts, Compose overrides and extends. +func TestV3Deployments(t *testing.T) { + res := scan(t, map[string]string{ + "Dockerfile": "FROM nginx:1.29 AS base\nFROM base\nCOPY h2.conf /etc/nginx/conf.d/\n", + "chart/values.yaml": "image:\n repository: nginx\n tag: \"1.29\"\n", + "chart/templates/deploy.yaml": "spec:\n containers:\n - name: web\n volumeMounts:\n - {name: conf, mountPath: /etc/nginx/conf.d}\n", + "app/docker-compose.yml": "services:\n web:\n image: nginx:1.29\n other:\n image: nginx:1.30\n extends: {file: base.yml, service: web}\n third:\n image: nginx:1.31\n volumes_from: [web]\n", + "app/docker-compose.override.yml": "services:\n web:\n volumes:\n - ./conf.d:/etc/nginx/conf.d\n", + ".gitlab-ci.yml": "test:\n services:\n - name: nginx:1.29\n command: [nginx, -c, /builds/h2.conf]\n script: [true]\n", + }) + for _, c := range []struct { + file string + line int + }{{"Dockerfile", 1}, {"chart/values.yaml", 2}, {"app/docker-compose.yml", 3}, {"app/docker-compose.yml", 5}, {"app/docker-compose.yml", 8}, {".gitlab-ci.yml", 3}} { + f := one(t, res, c.file, c.line, RuleNotChecked, knowledge.Unknown) + if f.Props["deployment"] == "" { + t.Errorf("%s:%d has no deployment note: %+v", c.file, c.line, f.Props) + } + } +} + +// Verification nit: a tag on a line newer than any known says so, not +// that its line received no fix. +func TestVNitNewerLineText(t *testing.T) { + res := scan(t, map[string]string{"compose.yaml": "services:\n a:\n image: nginx:1.32.0\n b:\n image: nginx/nginx-ingress:5.9.0\n"}) + for _, line := range []int{3, 5} { + f := one(t, res, "compose.yaml", line, RuleNotChecked, knowledge.Unknown) + if strings.Contains(f.Fix, "received no fix") || strings.Contains(f.Fix, "not on the 5.x line") || !strings.Contains(f.Fix, "newer") { + t.Errorf("line %d: %s", line, f.Fix) + } + } +} + +// Round-3 verification 5: Helm templates in subdirectories are read. +func TestW5HelmSubdirectories(t *testing.T) { + res := scan(t, map[string]string{ + "chart/values.yaml": "image:\n repository: nginx\n tag: \"1.29\"\n", + "chart/templates/_helpers.tpl": "{{- define \"x\" -}}{{- end -}}\n", + "chart/templates/web/deploy.yaml": "spec:\n containers:\n - name: web\n volumeMounts:\n - {name: conf, mountPath: /etc/nginx/conf.d}\n", + "plain/values.yaml": "image:\n repository: nginx\n tag: \"1.30\"\n", + "plain/templates/web/deploy.yaml": "spec:\n containers:\n - name: web\n image: x\n", + }) + if f := one(t, res, "chart/values.yaml", 2, RuleNotChecked, knowledge.Unknown); f.Props["deployment"] == "" { + t.Errorf("a template in a subdirectory was not read: %+v", f.Props) + } + if f := one(t, res, "plain/values.yaml", 2, RuleNotChecked, knowledge.Unknown); f.Props["deployment"] != "" { + t.Errorf("templates that set nothing: %+v", f.Props) + } +} + +// Round-4 verification nits: a subchart's templates render too, and a +// linked template is named by its path in the tree. +func TestX11HelmSubcharts(t *testing.T) { + res := scan(t, map[string]string{ + "chart/values.yaml": "image:\n repository: nginx\n tag: \"1.29\"\n", + "chart/templates/svc.yaml": "kind: Service\n", + "chart/charts/web/templates/deploy.yml": "spec:\n containers:\n - name: web\n volumeMounts:\n - {name: conf, mountPath: /etc/nginx/conf.d}\n", + "packed/values.yaml": "image:\n repository: nginx\n tag: \"1.30\"\n", + "packed/templates/svc.yaml": "kind: Service\n", + "packed/charts/web-1.0.0.tgz": "\x1f\x8b", + }) + if f := one(t, res, "chart/values.yaml", 2, RuleNotChecked, knowledge.Unknown); !strings.Contains(f.Props["deployment"], "charts/web/templates/deploy.yml") { + t.Errorf("a subchart template was not read: %+v", f.Props) + } + if f := one(t, res, "packed/values.yaml", 2, RuleNotChecked, knowledge.Unknown); f.Props["deployment"] == "" { + t.Errorf("a packaged subchart was taken as setting nothing: %+v", f.Props) + } +} + +func TestX11HelmLinkMessage(t *testing.T) { + root := t.TempDir() + for p, b := range map[string]string{ + "chart/values.yaml": "image:\n repository: nginx\n tag: \"1.29\"\n", + "chart/templates/svc.yaml": "kind: Service\n", + } { + full := filepath.Join(root, p) + os.MkdirAll(filepath.Dir(full), 0o755) + os.WriteFile(full, []byte(b), 0o644) + } + os.Symlink("svc.yaml", filepath.Join(root, "chart/templates/link.yaml")) + s := &scanner{} + why := s.helmTemplates(root, "chart/values.yaml") + if !strings.Contains(why, "chart/templates/link.yaml") || strings.Contains(why, root) { + t.Errorf("%q", why) + } +} diff --git a/detectors/nginxh2/internal/repo/shell.go b/detectors/nginxh2/internal/repo/shell.go new file mode 100644 index 0000000..d4dc994 --- /dev/null +++ b/detectors/nginxh2/internal/repo/shell.go @@ -0,0 +1,391 @@ +package repo + +import ( + "path" + "regexp" + "strings" +) + +// The shell reading here follows java4shell's (internal/repo and +// internal/jvm on that branch): a RUN line is read the way the builder's +// shell would run it, so an install hidden in a subshell, behind sh -c, +// in a variable or after xargs is still found. + +// words splits a command on white space, with quotes grouping and a +// backslash escaping. +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 +} + +// splitCommands returns the simple commands of a shell line (split on ; +// && || | & outside quotes). +func splitCommands(line string) []string { + var out []string + var q byte + start := 0 + 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 == ';' || c == '&' || c == '|': + out = append(out, strings.TrimSpace(line[start:min(i, len(line))])) + if i+1 < len(line) && line[i+1] == c { + i++ + } + start = i + 1 + } + } + if start <= len(line) { + out = append(out, strings.TrimSpace(line[start:])) + } + return out +} + +var ( + installRE = regexp.MustCompile(`\b(?:apt-get|aptitude|apt|apt-fast|nala|install_packages|apk|dnf5?|yum|microdnf|tdnf|zypper)\b`) + 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} + // pkgVerbs install the packages named after them. An upgrade that + // names a package installs a release of it too. + pkgVerbs = map[string]bool{"install": true, "add": true, "in": true, "reinstall": 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, "--prefix": true} + assignment = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*=`) + bareVar = regexp.MustCompile(`^\$\{?[A-Za-z_][A-Za-z0-9_]*\}?$`) + // redirect is a redirection written onto a word (nginx>/dev/null); + // apk and zypper write version ranges with > and <, followed by a + // version, not by a path or a descriptor. + redirect = regexp.MustCompile(`(?:>>?|<)[/&].*$|(?:>>?|<)$`) + 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} + varRef = regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}|\$([A-Za-z_][A-Za-z0-9_]*)`) +) + +// opaqueArg marks an install argument whose package names the scan +// cannot read: a variable the file does not set, or a command's output. +const opaqueArg = "\x00opaque:" + +// leadWords returns the index of a command's own word: after assignments +// and the words that run another command (env, exec, sudo...). +func leadWords(ws []string) int { + i := 0 + for i < len(ws) && i < 12 { + w := ws[i] + switch b := path.Base(w); { + case b == "chroot" && i+1 < len(ws): + 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 +} + +// shellText returns the script of "sh -c TEXT" (also -ec, -lc, su -c, +// eval). +func shellText(ws []string) (string, bool) { + i := leadWords(ws) + if i >= len(ws) { + return "", false + } + script := func(text string) (string, bool) { return strings.ReplaceAll(text, "\n", " ; "), true } + switch path.Base(ws[i]) { + case "sh", "bash", "ash", "dash", "zsh", "ksh": + c := false + for j := i + 1; j < len(ws); j++ { + w := ws[j] + switch { + case w == "-o" || w == "+o" || w == "-O" || w == "+O" || w == "--rcfile" || w == "--init-file": + j++ + case strings.HasPrefix(w, "--"): + case strings.HasPrefix(w, "-") || strings.HasPrefix(w, "+"): + if strings.HasPrefix(w, "-") && strings.Contains(w, "c") { + c = true + } + if strings.HasSuffix(w, "o") { + j++ + } + case c: + return script(w) + default: + return "", false + } + } + case "su": + for j := i + 1; j+1 < len(ws); j++ { + if ws[j] == "-c" || ws[j] == "--command" { + return script(ws[j+1]) + } + } + case "eval": + if i+1 < len(ws) { + return script(strings.Join(ws[i+1:], " ")) + } + } + return "", false +} + +// install is the package arguments of one install command, with its tool. +type install struct { + tool string + args []string +} + +// installs returns the install commands of a RUN line: the words after +// " [flags] install|add", without flags and their values. +func installs(run string, depth int) []install { + var out []install + var prev []string + at := 0 + for _, cmd := range splitCommands(run) { + 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) + } + ws := words(cmd) + last := prev + prev = ws + for k, w := range ws { + if t := strings.TrimLeft(w, "({"); t != "" { + w = t + } + if !strings.Contains(w, "(") { + if t := strings.TrimRight(w, ")"); t != "" { + w = t + } + } + ws[k] = w + } + for len(ws) > 0 && shellLead[ws[0]] { + ws = ws[1:] + } + if text, ok := shellText(ws); ok && depth < 4 { + out = append(out, installs(text, depth+1)...) + continue + } + i := 0 + for i < len(ws) && (strings.HasPrefix(ws[i], "-") || !pkgTools[path.Base(ws[i])]) { + i++ + } + if i == len(ws) { + // A tool named by a variable this file does not set ($INSTALL + // nginx): the words after it are read as packages. + if k := leadWords(ws); k < len(ws) && bareVar.MatchString(ws[k]) { + var args []string + for _, w := range ws[k+1:] { + if strings.HasPrefix(w, "#") { + break + } + if !strings.HasPrefix(w, "-") && !strings.HasPrefix(w, "$") { + args = append(args, w) + } + } + if len(args) > 0 { + out = append(out, install{tool: "?", args: args}) + } + } + continue + } + var args []string + for _, w := range ws[: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, "`") { + args = append(args, opaqueArg+a) + } else { + args = append(args, a) + } + } + } else { + args = append(args, opaqueArg+"xargs") + } + break + } + tool := path.Base(ws[i]) + i++ + isWrapper := tool == "install_packages" // Bitnami's wrapper: the packages follow it + for i < len(ws) && strings.HasPrefix(ws[i], "-") { + if pkgValueFlags[ws[i]] { + i++ + } + i++ + } + // dnf module install nginx:1.24, dnf module enable nginx:1.24 + if (tool == "dnf" || tool == "yum" || tool == "microdnf") && i < len(ws) && ws[i] == "module" { + i++ + for i < len(ws) && strings.HasPrefix(ws[i], "-") { + i++ + } + if i < len(ws) && (ws[i] == "install" || ws[i] == "enable" || ws[i] == "switch-to" || ws[i] == "reset") { + for _, w := range ws[i+1:] { + if !strings.HasPrefix(w, "-") { + args = append(args, "@module:"+w) + } + } + } + if len(args) > 0 { + out = append(out, install{tool: tool, args: args}) + } + continue + } + if isWrapper { + i-- + } else if i >= len(ws) || !pkgVerbs[ws[i]] { + if len(args) > 0 { + out = append(out, install{tool: tool, args: args}) + } + continue + } + for j := i + 1; j < len(ws); j++ { + if strings.HasPrefix(ws[j], "#") { + break + } + w := redirect.ReplaceAllString(ws[j], "") + switch { + case w == "": + case strings.HasPrefix(w, "$") || strings.HasPrefix(w, "`"): + args = append(args, opaqueArg+w) + case pkgValueFlags[w]: + j++ + case strings.HasPrefix(w, "-"), strings.Contains(w, "://"), strings.HasPrefix(w, "/"): + default: + args = append(args, w) + } + } + if len(args) > 0 { + out = append(out, install{tool: tool, args: args}) + } + } + return out +} + +// expandVars puts in the values the Dockerfile's ARG and ENV lines give; +// 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) + n := g[1] + g[3] + if v, ok := vars[n]; ok && v != "" { + return v + } + if g[2] != "" { + return g[2] + } + return m + }) +} + +// lineVars returns the variables in force for a RUN line: the stage's, +// changed by what the line itself assigns (NAME=x && ..., export NAME=x). +// One set from a command, another variable or by read has no value here. +func lineVars(run string, vars map[string]string) map[string]string { + if !strings.Contains(run, "$") { + return vars + } + out := make(map[string]string, len(vars)+2) + for k, v := range vars { + out[k] = v + } + for _, cmd := range splitCommands(run) { + ws := words(cmd) + for len(ws) > 0 && shellLead[strings.TrimLeft(ws[0], "({")] { + ws = ws[1:] + } + if len(ws) == 0 { + continue + } + switch { + case ws[0] == "for" && len(ws) >= 3 && ws[2] == "in": + list := strings.Join(ws[3:], " ") + if strings.ContainsAny(list, "$`*") { + delete(out, ws[1]) + } else { + out[ws[1]] = list + } + case ws[0] == "read": + for _, w := range ws[1:] { + if !strings.HasPrefix(w, "-") { + delete(out, w) + } + } + case assignment.MatchString(ws[0]): + all := true + for _, w := range ws { + all = all && assignment.MatchString(w) + } + if !all { + k, v, _ := strings.Cut(ws[0], "=") + if strings.HasPrefix(v, "$(") || strings.HasPrefix(v, "`") { + delete(out, k) + } + continue + } + for _, w := range ws { + k, v, _ := strings.Cut(w, "=") + if strings.ContainsAny(v, "$`") { + delete(out, k) + } else { + out[k] = v + } + } + } + } + return out +} diff --git a/detectors/nginxh2/nginxh2.go b/detectors/nginxh2/nginxh2.go new file mode 100644 index 0000000..9817514 --- /dev/null +++ b/detectors/nginxh2/nginxh2.go @@ -0,0 +1,1999 @@ +// Package nginxh2 is the detector for the nginx HTTP/2 pair disclosed on +// 2026-11-18: CVE-2026-123007 (memory corruption in HTTP/2 flow control, +// nginx 1.9.5 to 1.31.8) and CVE-2026-123633 (use-after-free in HTTP/2 +// connection reuse, 1.19.7 to 1.31.8), both fixed in nginx 1.31.9 and +// 1.30.7. +// +// It finds nginx, OpenResty, Tengine, Angie and NGINX Plus binaries in +// filesystems and container images by what the binary carries (its +// version line, configure arguments and module list), judges each CVE on +// each binary on its own, applies the distribution backport table through +// the package database, and reads the configuration the binary loads +// (includes, globs, templates, the container's -c) to report whether +// HTTP/2 is on over TLS and in front of a proxy. Exposure is a fact on the +// finding; it never clears one. In a source tree it finds the nginx images, +// packages and configurations a project uses, and fix moves image tags to +// the fixed release of their line after reading the new image. +// +// internal/knowledge, internal/ngx, internal/conf, internal/pkgdb, +// internal/assess and internal/repo know nothing about the engine; this +// file adapts them. +package nginxh2 + +import ( + "bufio" + "bytes" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "regexp" + "sort" + "strings" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/assess" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/knowledge" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngx" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/pkgdb" + "github.com/DefectDojo/earlylight/internal/archive" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// ID is the detector's ID. +const ID = "nginxh2" + +// Kind IDs. +const ( + KindFlow = assess.KindFlow + KindReuse = assess.KindReuse +) + +// Detector implements engine.Detector, engine.Reader, engine.RepoScanner +// and engine.Fixer. +type Detector struct{} + +func init() { engine.Register(&Detector{}) } + +const about = " Fixed in nginx 1.31.9 (mainline) and 1.30.7 (stable) on 2026-11-18; lines 1.29 and older received no fix." + + " Debian, Ubuntu, Alpine, OpenResty, Tengine and Angie had published no fixed build that day; NGINX Plus is fixed in" + + " 37.0.7.1 and 37.2.0.1 (CVE-2026-123633) and 37.0.8.1 and 37.3.0.1 (CVE-2026-123007). Turning HTTP/2 off" + + " (\"http2 off;\" and no \"http2\" on any listen) removes the published path until the update; it is not a fix." + +// Manifest describes the detector. +func (d *Detector) Manifest() engine.Manifest { + return engine.Manifest{ + ID: ID, + Title: "nginx HTTP/2 remote code execution pair (" + knowledge.Flow + ", " + knowledge.Reuse + ")", + CVEs: []string{knowledge.Flow, knowledge.Reuse}, + Advisories: []string{ + "https://nginx.org/en/security_advisories.html", + "https://www.wiz.io/blog/nginx-http2-rce-vulnerabilities", + "https://my.f5.com/manage/s/article/K000163926", + "https://my.f5.com/manage/s/article/K000163928", + "https://github.com/nginx/nginx/commit/e27f5fa84fe6e98505e70bc543b748747dad0a3b", + "https://github.com/nginx/nginx/commit/2df48a501d0fb8212b7d39dffeeff5876332ba59", + }, + Disclosed: knowledge.Disclosed, + Targets: []engine.TargetKind{engine.Filesystem, engine.Image, engine.Repository}, + Kinds: append([]engine.Kind{ + {ID: KindFlow, Title: "nginx vulnerable to " + knowledge.Flow + " (HTTP/2 flow control memory corruption)", Level: "error", SecuritySeverity: knowledge.CVSS, CWEs: []string{"CWE-787", "CWE-190"}, + Description: "An nginx binary (or OpenResty, Tengine, Angie, NGINX Plus) from 1.9.5 to 1.31.8 built with HTTP/2. A client's WINDOW_UPDATE frames can push the connection's send window past its limit when a stream ends with queued data, and the next send copies out of bounds: Wiz showed pre-authentication code execution over HTTP/2 with TLS on the official 64-bit images. The finding reports whether the configuration turns HTTP/2 on over TLS." + about}, + {ID: KindReuse, Title: "nginx vulnerable to " + knowledge.Reuse + " (HTTP/2 connection reuse use-after-free)", Level: "error", SecuritySeverity: knowledge.CVSS, CWEs: []string{"CWE-416"}, + Description: "An nginx binary (or OpenResty, Tengine, Angie, NGINX Plus) from 1.19.7 to 1.31.8 built with HTTP/2. A connection marked reusable while a HEADERS frame is incomplete can be closed under connection pressure while one of its streams is being proxied, and the error path frees memory still in use. The finding reports whether the configuration turns HTTP/2 on in front of a proxy, and worker_connections." + about}, + }, repoKinds()...), + Tags: []string{"security", "nginx", "http2", "openresty", "ingress-nginx"}, + Data: "nginx fixed releases (1.31.9, 1.30.7), the releases that introduced each flaw (1.9.5, 1.19.7), NGINX Plus fixed releases, OpenResty, Tengine and Angie releases, distribution and image status, checked " + knowledge.Checked, + } +} + +// Load checks the release data. +func (d *Detector) Load() error { + for _, c := range knowledge.CVEs { + if len(c.Fixed) == 0 || len(c.PlusFixed) == 0 || len(c.Introduced) != 3 { + return errData(c.ID) + } + for _, f := range c.Fixed { + if knowledge.Cmp(f, c.Introduced) <= 0 || len(f) != 3 { + return errData(c.ID) + } + } + } + return nil +} + +type errData string + +func (e errData) Error() string { return "release data for " + string(e) + " contradicts itself" } + +// Wants reads executables (possible nginx binaries), configuration files, +// package databases and os-release. +func (d *Detector) Wants(p string, head []byte, _ bool) bool { + return archive.IsExecutable(head) || keepDB(p) || keepConf(p) || isScript(head) +} + +// isScript reports a "#!" script: an entrypoint, or a file one runs. +func isScript(head []byte) bool { return len(head) > 2 && head[0] == '#' && head[1] == '!' } + +// Limits on the scripts kept. +const ( + maxScript = 256 << 10 + maxScripts = 32 << 20 +) + +// Limits on what one target keeps. +const ( + maxConf = 4 << 20 + maxConfTotal = 64 << 20 + maxConfFiles = 8192 + maxDB = 32 << 20 + maxDBTotal = 128 << 20 + maxBinaries = 512 +) + +// confDirs are directories whose every file can be a configuration file +// (mime.types, fastcgi_params and sites-enabled/default have no .conf). +var confDirs = []string{"/etc/nginx/", "/usr/local/nginx/conf/", "/usr/local/openresty/nginx/conf/", "/etc/openresty/", + "/etc/angie/", "/usr/local/angie/conf/", "/etc/tengine/", "/usr/local/tengine/conf/", "/opt/bitnami/nginx/conf/", + "/etc/nginx-plus/", "/usr/local/etc/nginx/"} + +// confSuffixes are names any of whose files the scan keeps, wherever they +// are. +var confSuffixes = []string{".conf", ".conf.template", ".template", ".conf.tmpl", ".tmpl", ".vhost"} + +// confNames are file names a configuration commonly includes without a +// .conf suffix. +var confNames = map[string]bool{"mime.types": true, "fastcgi_params": true, "scgi_params": true, "uwsgi_params": true, + "proxy_params": true, "koi-utf": true, "koi-win": true, "win-utf": true, "default": true, "nginx.conf": true} + +// keepConf reports a file that can be part of an nginx configuration: +// every file under a directory nginx builds read their configuration +// from, files with a configuration suffix anywhere, and under a directory +// named for nginx, files without an extension or with a configuration +// one (not the libraries, scripts and pages OpenResty keeps there). +func keepConf(p string) bool { + for _, d := range confDirs { + if strings.HasPrefix(p, d) { + return true + } + } + base := path.Base(p) + if confSuffix(base) { + return true + } + if !nginxDir(path.Dir(p)) { + return false + } + ext := path.Ext(base) + return confNames[base] || ext == "" || ext == ".types" || ext == ".inc" || ext == ".cfg" || ext == ".site" || strings.HasSuffix(base, "_params") +} + +func confSuffix(base string) bool { + for _, s := range confSuffixes { + if strings.HasSuffix(base, s) { + return true + } + } + return false +} + +func nginxDir(dir string) bool { + for _, part := range strings.Split(dir, "/") { + low := strings.ToLower(part) + if strings.Contains(low, "nginx") || strings.Contains(low, "openresty") || low == "sites-enabled" || low == "sites-available" || low == "conf.d" || low == "http.d" { + return true + } + } + return false +} + +// keptByAll reports whether every file a glob pattern can match is one +// keepConf keeps, so that the matches seen are all there are: the pattern +// is under a directory read whole, or every name it matches ends in a +// configuration suffix. +func keptByAll(pattern string) bool { + dir := pattern + if i := strings.IndexAny(dir, "*?["); i >= 0 { + dir = dir[:i] + } + dir = dir[:strings.LastIndexByte(dir, '/')+1] + for _, d := range confDirs { + if strings.HasPrefix(dir, d) { + return true + } + } + return confSuffix(path.Base(pattern)) +} + +func keepDB(p string) bool { + switch p { + case "/var/lib/dpkg/status", "/lib/apk/db/installed", "/usr/lib/apk/db/installed", "/etc/os-release", "/usr/lib/os-release", "/etc/alpine-release": + return true + } + if strings.HasPrefix(p, "/var/lib/dpkg/info/") && strings.HasSuffix(p, ".list") { + n := pkgdb.DpkgListName(p) + return strings.Contains(n, "nginx") || strings.Contains(n, "openresty") || strings.Contains(n, "angie") || strings.Contains(n, "tengine") + } + return strings.HasPrefix(p, "/docker-entrypoint.d/") || unitPath(p) || strings.HasSuffix(p, ".service") || envFileDir(p) || managerPath(p) +} + +// managerConf are the service manager's settings and the drop-in +// directories next to them; managerGenerators hold programs that set the +// manager's environment. Either can give a unit variables it does not +// set itself. +var ( + managerConf = []string{"/etc/systemd/system.conf", "/run/systemd/system.conf", "/usr/local/lib/systemd/system.conf", "/usr/lib/systemd/system.conf", "/lib/systemd/system.conf"} + managerGenerators = []string{"/etc/systemd/system-environment-generators/", "/run/systemd/system-environment-generators/", "/usr/local/lib/systemd/system-environment-generators/", "/usr/lib/systemd/system-environment-generators/", "/lib/systemd/system-environment-generators/"} +) + +// managerConfPath reports the manager's settings file or a drop-in of it. +func managerConfPath(p string) bool { + for _, c := range managerConf { + if p == c || strings.HasPrefix(p, c+".d/") { + return true + } + } + return false +} + +// managerPath reports a file of the service manager's own settings. +func managerPath(p string) bool { + for _, c := range managerConf { + if p == c || strings.HasPrefix(p, c+".d/") { + return true + } + } + for _, g := range managerGenerators { + if strings.HasPrefix(p, g) { + return true + } + } + return false +} + +// envFileDir reports a file where units keep their EnvironmentFile +// (/etc/sysconfig/nginx, /etc/default/nginx): kept whole, so one that is +// not kept is not there. +func envFileDir(p string) bool { + return strings.HasPrefix(p, "/etc/sysconfig/") || strings.HasPrefix(p, "/etc/default/") +} + +// unitDirs hold systemd units; a unit's drop-ins are in /.d. +var unitDirs = []string{"/etc/systemd/system/", "/run/systemd/system/", "/lib/systemd/system/", "/usr/lib/systemd/system/"} + +// unitPath reports a systemd service unit or one of its drop-ins. +func unitPath(p string) bool { + for _, d := range unitDirs { + if rest, ok := strings.CutPrefix(p, d); ok { + return strings.HasSuffix(rest, ".service") && !strings.Contains(rest, "/") || + strings.Contains(rest, ".service.d/") && strings.HasSuffix(rest, ".conf") + } + } + return false +} + +// NewScan starts a filesystem or image scan. +func (d *Detector) NewScan(kind engine.TargetKind) engine.Scan { + return &scan{kind: kind, conf: map[string][]byte{}, db: map[string][]byte{}, tooLarge: map[string]bool{}} +} + +type scan struct { + kind engine.TargetKind + binaries []*ngx.Binary + conf map[string][]byte + confBytes int + confFull bool // the limit on configuration files was reached + tooLarge map[string]bool // configuration files over maxConf, not kept + db map[string][]byte + scripts map[string][]byte // "#!" scripts, by path + units map[string]map[string]bool + epSeen map[string]bool // every file seen under /docker-entrypoint.d + generator string // a manager environment generator seen + mgrDone bool + mgrWhy string + scriptBytes int + unread map[string]string + unreadAll bool + dbBytes int + ingress bool + f5ingress bool + dropped int +} + +func (s *scan) Visit(f engine.File) []engine.Skip { + if f.Member { + return nil // installed servers only + } + if strings.HasPrefix(f.Path, "/docker-entrypoint.d/") { + // Everything there is run or skipped by the official + // entrypoint: each file is recorded, and kept to be checked. + if s.epSeen == nil { + s.epSeen = map[string]bool{} + } + if len(s.epSeen) < maxUnread { + s.epSeen[f.Path] = true + } else { + s.unreadAll = true + } + if len(f.Data) <= maxDB && s.dbBytes+len(f.Data) <= maxDBTotal { + s.db[f.Path] = f.Data + s.dbBytes += len(f.Data) + } else { + s.VisitSkips([]engine.Skip{{Path: f.Path, Reason: "over the detector's size limits"}}) + } + } + if s.generator == "" && managerPath(f.Path) && !managerConfPath(f.Path) { + s.generator = f.Path + } + if archive.IsExecutable(f.Data) { + switch path.Base(f.Path) { + case "nginx-ingress-controller": + s.ingress = true + case "nginx-ingress": + s.f5ingress = true + } + if b, ok := ngx.Inspect(f.Path, f.Data); ok { + if len(s.binaries) >= maxBinaries { + s.dropped++ + return []engine.Skip{{Path: f.Path, Reason: "an nginx binary past the detector's limit of 512 per target; not checked"}} + } + s.binaries = append(s.binaries, b) + } + return nil + } + if isScript(f.Data) && len(f.Data) <= maxScript && s.scriptBytes+len(f.Data) <= maxScripts { + if s.scripts == nil { + s.scripts = map[string][]byte{} + } + s.scripts[f.Path] = f.Data + s.scriptBytes += len(f.Data) + } + if keepDB(f.Path) { + if len(f.Data) <= maxDB && s.dbBytes+len(f.Data) <= maxDBTotal { + s.db[f.Path] = f.Data + s.dbBytes += len(f.Data) + } else { + // Not kept is not absent: a unit or environment file + // dropped here leaves what it sets unknown. + s.VisitSkips([]engine.Skip{{Path: f.Path, Reason: "over the detector's size limits"}}) + } + return nil + } + if keepConf(f.Path) { + switch { + case len(f.Data) > maxConf: + if len(s.tooLarge) < maxConfFiles { + s.tooLarge[f.Path] = true + } else { + s.confFull = true + } + return nil + case s.confBytes+len(f.Data) > maxConfTotal || len(s.conf) >= maxConfFiles: + s.confFull = true + return nil + } + s.conf[f.Path] = f.Data + s.confBytes += len(f.Data) + } + return nil +} + +// maxUnread bounds the not-scanned records kept. +const maxUnread = 1 << 16 + +// VisitSkips records what the walk could not read: a configuration file +// among them leaves exposure unknown, never off. +func (s *scan) VisitSkips(skips []engine.Skip) { + if s.unread == nil { + s.unread = map[string]string{} + } + for _, sk := range skips { + if len(s.unread) >= maxUnread { + s.unreadAll = true + return + } + s.unread[path.Clean("/"+sk.Path)] = sk.Reason + } +} + +func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { + if len(s.binaries) == 0 { + return nil + } + if s.dropped > 0 { + ctx.Problem("nginxh2: more nginx binaries than the detector's limit; some were not checked") + } + links, hardlinks := ctx.Links() + src := &confSource{kept: s.conf, full: s.confFull, tooLarge: s.tooLarge, root: ctx.SystemRoot(), links: links, hardlinks: hardlinks, unread: s.unread, unreadAll: s.unreadAll} + cmds := s.commands(links, hardlinks, workdirOf(ctx), ctx.Env(), ctx.Exists) + tplWhy := "" + if s.kind == engine.Image && assess.OfficialEntrypointRuns(ctx.Command(), cmds.launcher) && s.db["/docker-entrypoint.d/20-envsubst-on-templates.sh"] != nil { + // Only then does the entrypoint write the templates. + tplWhy = src.templates(ctx.Env()) + } + id, like, ver := osRelease(s.read(src, "/etc/os-release", "/usr/lib/os-release")) + distro := knowledge.DistroOf(id, like) + release := ver + if distro == "alpine" { + release = alpineBranch(string(s.read(src, "/etc/alpine-release"))) + } + if distro != "" { + ctx.Annotate("nginxh2_os", id+" "+ver) + } + owners := s.owners(src) + found := assess.Run(assess.Input{ + Binaries: s.binaries, + Source: src, + Owner: func(p string) *pkgdb.Package { + for _, a := range ctx.Aliases(p) { + if pk, ok := owners(a); ok { + return pk + } + } + return nil + }, + Distro: distro, + Release: release, + Command: ctx.Command(), + CommandFrom: "the image's command", + CommandFor: s.commandFor(src), + Launcher: cmds.launcher, + Starts: cmds.starts, + Ingress: s.ingress, + Generated: firstOf2(s.generated(), tplWhy), + }) + out := make([]engine.Finding, 0, len(found)) + for _, x := range found { + out = append(out, finding(x)) + } + return out +} + +// commands resolves the words of a target's start command and judges +// the official entrypoint, once per scan. +type commands struct { + s *scan + src *confSource + links map[string]string + hardlinks map[string]string + workdir string + env []string + exists func(string) bool + epDone bool + epOK bool + epWhy string + words map[string]wordAnswer +} + +type wordAnswer struct { + ok bool + why string +} + +func (s *scan) commands(links, hardlinks map[string]string, workdir string, env []string, exists func(string) bool) *commands { + return &commands{s: s, src: &confSource{links: links, hardlinks: hardlinks}, links: links, hardlinks: hardlinks, + workdir: workdir, env: env, exists: exists, words: map[string]wordAnswer{}} +} + +// real follows a path's links inside the target ("" for a loop). +func (c *commands) real(p string) string { + r := c.src.resolve(p) + if to, ok := c.hardlinks[r]; ok && r != "" { + r = to + } + return r +} + +// content is a kept file's bytes, through links. +func (c *commands) content(p string) ([]byte, bool) { + r := c.real(p) + if r == "" { + return nil, false + } + if b, ok := c.s.scripts[r]; ok { + return b, true + } + b, ok := c.s.db[r] + return b, ok +} + +// present reports a path that is in the target: a file the walk read or +// kept, or a link, read or not (a PATH search stops at the first). +func (c *commands) present(q string) bool { + if _, ok := c.links[q]; ok { + return true + } + if _, ok := c.hardlinks[q]; ok { + return true + } + if c.exists != nil && c.exists(q) { + return true + } + if _, ok := c.s.unread[q]; ok { + return true + } + _, ok := c.content(q) + return ok +} + +// resolve resolves a command word as the runtime does. +func (c *commands) resolve(word string) (string, string) { + return resolveCommand(word, c.workdir, c.env, c.present) +} + +// launcher reports whether a word that starts the command is the official +// nginx image's entrypoint (by content), with everything it runs from +// /docker-entrypoint.d read and official. +func (c *commands) launcher(word string) (bool, string) { + if a, ok := c.words[word]; ok { + return a.ok, a.why + } + ok, why := c.launcherOnce(word) + c.words[word] = wordAnswer{ok, why} + return ok, why +} + +func (c *commands) launcherOnce(word string) (bool, string) { + p, why := c.resolve(word) + if p == "" { + return false, why + } + b, ok := c.content(p) + if !ok { + return false, fmt.Sprintf("nginx is started through %s, which was not read", word) + } + if !officialScripts["docker-entrypoint.sh"][sha(b)] { + return false, fmt.Sprintf("nginx is started through %s, which is not the official nginx image's entrypoint and can change the configuration", word) + } + if !c.epDone { + c.epOK, c.epWhy = c.entrypointDir() + c.epDone = true + } + return c.epOK, c.epWhy +} + +// starts reports whether a word that starts nginx resolves to the binary +// judged, through the working directory, PATH and links. +func (c *commands) starts(word, binary string) (bool, string) { + p, why := c.resolve(word) + if p == "" { + return false, why + } + if r := c.real(p); r == "" || r != c.real(binary) { + return false, fmt.Sprintf("the command starts %s (%s), not this binary (%s), so how this binary is started and what it loads is not known", p, word, binary) + } + return true, "" +} + +// entrypointDir checks /docker-entrypoint.d as the official entrypoint +// runs it (find -follow): every file reachable there, whatever its name, +// size or first line, must have been read and be one of the official +// scripts; a directory link that leads out of it, or anything not read, +// leaves exposure unknown. +func (c *commands) entrypointDir() (bool, string) { + const dir = "/docker-entrypoint.d" + s := c.s + if s.unreadAll { + return false, "more files were not scanned than the detector keeps a record of, so the entrypoint's scripts are not known" + } + if r := c.real(dir); r != dir { + return false, dir + " is a symbolic link, so what the entrypoint runs is not read" + } + if why, ok := s.unread[dir]; ok { + return false, fmt.Sprintf("the entrypoint runs what is in %s, which was not read (%s)", dir, why) + } + var paths []string + add := func(q string) { + if strings.HasPrefix(q, dir+"/") { + paths = append(paths, q) + } + } + for q := range s.epSeen { + add(q) + } + for _, m := range []map[string][]byte{s.scripts, s.db} { + for q := range m { + if !s.epSeen[q] { + add(q) + } + } + } + for _, m := range []map[string]string{c.links, c.hardlinks, s.unread} { + for q := range m { + add(q) + } + } + sort.Strings(paths) + for _, q := range paths { + if why, ok := s.unread[q]; ok { + return false, fmt.Sprintf("the entrypoint runs what is in %s, and %s was not read (%s)", dir, q, why) + } + if _, isLink := c.links[q]; isLink { + t := c.real(q) + if t == "" || !strings.HasPrefix(t, dir+"/") { + if _, read := c.content(q); !read { + return false, fmt.Sprintf("%s leads out of %s to %s, which the scan does not read whole", q, dir, t) + } + } + } + b, read := c.content(q) + if !read { + if _, isLink := c.links[q]; isLink && strings.HasPrefix(c.real(q), dir+"/") { + continue // a link to a directory inside: its files are listed themselves + } + return false, fmt.Sprintf("the entrypoint runs what is in %s, and %s was not read", dir, q) + } + if !officialScripts[path.Base(q)][sha(b)] { + return false, fmt.Sprintf("%s holds %s, which is not one of the official image's scripts and can change the configuration", dir, q) + } + } + return true, "" +} + +// defaultPath is the PATH a container runs with when its image sets none. +const defaultPath = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + +// resolveCommand resolves a command word as the runtime does: an absolute +// path as written, one with a slash against the working directory, a bare +// name through the image's PATH. "" when nothing is found. +func resolveCommand(word, workdir string, env []string, exists func(string) bool) (string, string) { + if strings.HasPrefix(word, "/") { + return path.Clean(word), "" + } + if workdir == "" { + workdir = "/" + } + if strings.Contains(word, "/") { + return path.Join("/", workdir, word), "" + } + pathVar, set := defaultPath, false + for _, kv := range env { + if v, ok := strings.CutPrefix(kv, "PATH="); ok { + pathVar, set = v, true + } + } + for _, d := range strings.Split(pathVar, ":") { + if d == "" { + d = workdir + } + if !strings.HasPrefix(d, "/") { + d = path.Join("/", workdir, d) + } + if p := path.Join(d, word); exists(p) { + return p, "" + } + } + from := "the default PATH" + if set { + from = "the image's PATH" + } + return "", fmt.Sprintf("nginx is started through %s, which is not found on %s, so what it runs is not known", word, from) +} + +func sha(b []byte) string { + h := sha256.Sum256(b) + return hex.EncodeToString(h[:]) +} + +// commandFor returns, for a filesystem, the start command of each binary +// from the systemd units that run it; an image has its own command. +func (s *scan) commandFor(src *confSource) func(string) ([]string, string, string) { + if s.kind == engine.Image { + return nil + } + units, unsure := s.systemdStarts(src) + return func(bin string) ([]string, string, string) { + if unsure != "" { + return nil, "", unsure + } + var found [][]string + var from []string + for _, u := range units { + if u.cmd[0] == bin || !strings.HasPrefix(u.cmd[0], "/") && path.Base(u.cmd[0]) == path.Base(bin) { + if u.unsure != "" { + return nil, "", u.unsure + } + found = append(found, u.cmd) + from = append(from, u.unit) + } + } + switch len(found) { + case 0: + return nil, "", "no service unit that starts " + bin + " was found (systemd), so the configuration it loads is not known" + case 1: + return found[0], "the service unit " + from[0], "" + } + for _, c := range found[1:] { + if strings.Join(c, "\x00") != strings.Join(found[0], "\x00") { + return nil, "", "more than one service unit starts " + bin + " (" + strings.Join(from, ", ") + ")" + } + } + return found[0], "the service units " + strings.Join(from, ", "), "" + } +} + +type unitStart struct { + unit string + cmd []string + unsure string // why this unit's start is not read in full +} + +// unitFiles lists the names in a unit directory: files the walk read, +// links, records of files not read, and below a system root the +// directory on disk. why is set when the directory could not be listed. +func (s *scan) unitFiles(src *confSource, dir string) (names map[string]bool, why string) { + names = map[string]bool{} + for n := range s.unitIndex(src)[dir] { + names[n] = true + } + if w, ok := src.unreadAt(dir); ok { + why = dir + " was not read (" + w + ")" + } + if src.root != "" { + if full, ok := src.diskPath(dir); ok { + ents, err := os.ReadDir(full) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + why = dir + " could not be listed (" + err.Error() + ")" + } + for _, e := range ents { + names[e.Name()] = true + } + } + } + return names, why +} + +// unitIndex lists, once per scan, the names in each directory under the +// unit directories (files read, links, records of files not read), so a +// unit's drop-in directories are looked up, not searched for. +func (s *scan) unitIndex(src *confSource) map[string]map[string]bool { + if s.units != nil { + return s.units + } + s.units = map[string]map[string]bool{} + add := func(p string) { + for _, d := range unitDirs { + if strings.HasPrefix(p, d) { + dir := path.Dir(p) + if s.units[dir] == nil { + s.units[dir] = map[string]bool{} + } + s.units[dir][path.Base(p)] = true + return + } + } + } + for p := range s.db { + add(p) + } + for _, m := range []map[string]string{src.links, src.hardlinks, s.unread} { + for p := range m { + add(p) + } + } + return s.units +} + +// unitRead reads a unit or drop-in, following links inside the target. +func (s *scan) unitRead(src *confSource, p string) ([]byte, string, bool) { + r := src.resolve(p) + if r == "" { + return nil, "", false + } + if to, ok := src.hardlinks[r]; ok { + r = to + } + if r == "/dev/null" { + return nil, "/dev/null", true // masked + } + if b, ok := s.db[r]; ok { + return b, r, true + } + if src.root != "" { + if b := src.disk(r, maxDB); b != nil { + return b, r, true + } + } + return nil, r, false +} + +// systemdStarts reads every service unit that runs an nginx build: the +// unit of the first directory that has it (/etc, /run, /lib, /usr/lib), +// its drop-ins from every directory applied in order ("ExecStart=" +// clears), links followed inside the target. A unit or drop-in that was +// not read, or a command run before or after nginx starts other than an +// nginx test, makes that start unsure; a unit directory that could not +// be read makes every start unsure. +func (s *scan) systemdStarts(src *confSource) ([]unitStart, string) { + byName := map[string]string{} // unit name -> path, the first directory wins + var names []string + for _, d := range unitDirs { + d = strings.TrimSuffix(d, "/") + ns, why := s.unitFiles(src, d) + if why != "" { + return nil, "a systemd unit directory " + why + ", so the unit that starts nginx is not known" + } + for n := range ns { + if strings.HasSuffix(n, ".service") { + if _, ok := byName[n]; !ok { + byName[n] = d + "/" + n + names = append(names, n) + } + } + } + } + sort.Strings(names) + var out []unitStart + for _, n := range names { + u := unitStart{unit: byName[n]} + b, real, ok := s.unitRead(src, byName[n]) + if real == "/dev/null" { + continue // masked: not started + } + files := [][]byte{b} + if !ok { + u.unsure = byName[n] + " was not read" + if why, un := src.unreadAt(real); un { + u.unsure += " (" + why + ")" + } + } + var drops []string + for _, d := range unitDirs { + dd := strings.TrimSuffix(d, "/") + "/" + n + ".d" + ns, why := s.unitFiles(src, dd) + if why != "" && u.unsure == "" { + u.unsure = "the drop-in directory " + why + } + for f := range ns { + if strings.HasSuffix(f, ".conf") { + drops = append(drops, dd+"/"+f) + } + } + } + sort.Slice(drops, func(i, j int) bool { return path.Base(drops[i]) < path.Base(drops[j]) }) + for _, dp := range drops { + db, _, ok := s.unitRead(src, dp) + if !ok && u.unsure == "" { + u.unsure = "the drop-in " + dp + " was not read" + } + files = append(files, db) + } + var execs []string + around := map[string][]string{} // one list per directive, as systemd keeps them + var envs []string // Environment= assignments, in order + var envFiles []string // EnvironmentFile= paths, "-" kept + pidFile := "" + odd := "" // the first setting the scan does not apply exactly + note := func(why string) { + if odd == "" { + odd = why + } + } + for _, f := range files { + for _, l := range strings.Split(string(f), "\n") { + l = strings.TrimSpace(l) + if strings.HasSuffix(l, "\\") { + note(fmt.Sprintf("the line %q is continued on the next", clip(l))) + } + if l == "" || l[0] == '#' || l[0] == ';' { + continue + } + k, v, ok := strings.Cut(l, "=") + if !ok { + continue + } + k, v = strings.TrimSpace(k), strings.TrimSpace(v) + switch k { + case "ExecStart", "ExecStartPre", "ExecStartPost", "ExecCondition", "Environment", "EnvironmentFile", "PIDFile": + if strings.Contains(v, "%") { + note(fmt.Sprintf("%s=%s uses a specifier (%%), which the scan does not expand", k, clip(v))) + } + } + switch k { + case "ExecStart": + if v == "" { + execs = nil + } else { + execs = append(execs, v) + } + case "ExecStartPre", "ExecStartPost", "ExecCondition": + if v == "" { + around[k] = nil + } else { + around[k] = append(around[k], v) + } + case "Environment": + if v == "" { + envs = nil + } else { + envs = append(envs, unitWords(v)...) + } + case "EnvironmentFile": + if strings.ContainsAny(v, "*?[") { + note(fmt.Sprintf("EnvironmentFile=%s is a glob, which the scan does not expand", clip(v))) + } + if v == "" { + envFiles = nil + } else { + envFiles = append(envFiles, v) + } + case "PIDFile": + pidFile = v + case "PassEnvironment", "UnsetEnvironment", "RootDirectory", "RootImage", "MountImages", "ExtensionImages", + "ExtensionDirectories", "BindPaths", "BindReadOnlyPaths", "TemporaryFileSystem": + if v != "" { + note(fmt.Sprintf("%s=%s is set, which changes what nginx reads in a way the scan does not apply", k, clip(v))) + } + } + } + } + if len(execs) == 0 { + continue + } + // EnvironmentFile= overrides Environment=, whatever their order. + env := map[string]string{} + for _, kv := range envs { + if k, v, ok := strings.Cut(kv, "="); ok { + env[k] = v + } + } + for _, ef := range envFiles { + optional := strings.HasPrefix(ef, "-") + ef = strings.TrimPrefix(ef, "-") + b, real, ok := s.unitRead(src, ef) + _, unread := src.unreadAt(real) + var diskErr error + if !ok && !unread && src.root != "" { + _, diskErr = src.diskRead(real, maxDB) + } + switch { + case unread: + note(fmt.Sprintf("%s reads its environment from %s, which was not read", u.unit, ef)) + case diskErr != nil && !errors.Is(diskErr, fs.ErrNotExist): + note(fmt.Sprintf("%s reads its environment from %s, which could not be read (%v)", u.unit, ef, diskErr)) + case !ok && !optional: + note(fmt.Sprintf("%s reads its environment from %s, which is not in the target", u.unit, ef)) + case !ok && src.root == "" && !envFileDir(real) && !unitPath(real): + // Optional, but outside what the scan reads whole: whether + // it is there is not known. + note(fmt.Sprintf("%s reads its environment from %s, which the scan does not read", u.unit, ef)) + case ok: + vars, why := envFile(b) + if why != "" { + note(fmt.Sprintf("%s reads its environment from %s, where %s", u.unit, ef, why)) + } + for k, v := range vars { + env[k] = v + } + } + } + exec := execs[len(execs)-1] + pfx, x := execPrefix(exec) + cmd := expandUnit(x, env) + if len(cmd) == 0 || !nginxStart(path.Base(cmd[0])) { + continue + } + u.cmd = cmd + if len(execs) > 1 { + note(fmt.Sprintf("%s has more than one ExecStart=", u.unit)) + } + if strings.ContainsAny(pfx, "@|") || strings.Contains(pfx, ":") && strings.Contains(x, "$") { + note(fmt.Sprintf("ExecStart=%s has a prefix that changes how it runs", clip(exec))) + } + lines := []string{x} + for _, k := range []string{"ExecCondition", "ExecStartPre", "ExecStartPost"} { + for _, a := range around[k] { + p, ax := execPrefix(a) + lines = append(lines, ax) + if strings.ContainsAny(p, "@|:") || !harmless(expandUnit(ax, env), pidFile, cmd[0]) { + note(fmt.Sprintf("%s runs %q before or after nginx starts, which can change the configuration", u.unit, clip(a))) + } + } + } + for _, l := range lines { + if n := unsetVar(l, env); n != "" { + if why := s.managerEnv(src); why != "" { + note(fmt.Sprintf("%s uses $%s, which the unit does not set, and %s", u.unit, n, why)) + } + } + } + if u.unsure == "" { + u.unsure = odd + } + out = append(out, u) + } + return out, "" +} + +// managerEnv reports, once per scan, why a variable a unit does not set +// may still be set for it: the manager's DefaultEnvironment= or +// ManagerEnvironment=, an environment generator, or a settings file or +// directory that was not read. Empty means the unit's own settings are +// all there is (the kernel command line aside). +func (s *scan) managerEnv(src *confSource) string { + if s.mgrDone { + return s.mgrWhy + } + s.mgrDone = true + s.mgrWhy = s.managerEnvWhy(src) + return s.mgrWhy +} + +func (s *scan) managerEnvWhy(src *confSource) string { + if s.generator != "" { + return "the environment generator " + s.generator + " can set it" + } + under := func(dir string) []string { + var out []string + for _, m := range []map[string]string{src.links, src.hardlinks, s.unread} { + for p := range m { + if strings.HasPrefix(p, dir) { + out = append(out, p) + } + } + } + for p := range s.db { + if strings.HasPrefix(p, dir) { + out = append(out, p) + } + } + sort.Strings(out) + return out + } + listDisk := func(dir string) ([]string, string) { + if src.root == "" { + return nil, "" + } + full, ok := src.diskPath(dir) + if !ok { + return nil, "" + } + ents, err := os.ReadDir(full) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return nil, dir + " could not be listed (" + err.Error() + ")" + } + var out []string + for _, e := range ents { + out = append(out, strings.TrimSuffix(dir, "/")+"/"+e.Name()) + } + return out, "" + } + for _, g := range managerGenerators { + if why, ok := src.unreadAt(strings.TrimSuffix(g, "/")); ok { + return g + " was not read (" + why + ")" + } + if ps := under(g); len(ps) > 0 { + return "the environment generator " + ps[0] + " can set it" + } + ps, why := listDisk(g) + if why != "" { + return why + } + if len(ps) > 0 { + return "the environment generator " + ps[0] + " can set it" + } + } + for _, c := range managerConf { + files := []string{c} + files = append(files, under(c+".d/")...) + ps, why := listDisk(c + ".d") + if why != "" { + return why + } + files = append(files, ps...) + for _, f := range files { + b, real, ok := s.unitRead(src, f) + if !ok { + if why, un := src.unreadAt(real); un { + return f + " was not read (" + why + ")" + } + if src.root != "" { + if _, err := src.diskRead(real, maxDB); err != nil && !errors.Is(err, fs.ErrNotExist) { + return f + " could not be read (" + err.Error() + ")" + } + } + continue + } + for _, l := range strings.Split(string(b), "\n") { + l = strings.TrimSpace(l) + if strings.HasSuffix(l, "\\") { + return f + " has a continued line" + } + k, v, ok := strings.Cut(l, "=") + k = strings.TrimSpace(k) + if ok && (k == "DefaultEnvironment" || k == "ManagerEnvironment") && strings.TrimSpace(v) != "" { + return f + " sets " + k + "=" + } + } + } + } + return "" +} + +// execPrefix splits an Exec line's special prefixes ("-", "@", ":", "+", +// "!", "|") from its command. +func execPrefix(v string) (string, string) { + x := strings.TrimLeft(v, "-@:+!|") + return v[:len(v)-len(x)], x +} + +// clip shortens a unit line quoted in a reason. +func clip(s string) string { + if len(s) > 120 { + return s[:120] + "..." + } + return s +} + +// unsetVar returns a variable an Exec line uses that env does not set. +func unsetVar(line string, env map[string]string) string { + for _, w := range unitWords(line) { + if m := bareUnitVar.FindStringSubmatch(w); m != nil { + if _, ok := env[m[1]]; !ok { + return m[1] + } + continue + } + for _, r := range bracedUnitVar.FindAllString(w, -1) { + if _, ok := env[r[2:len(r)-1]]; !ok { + return r[2 : len(r)-1] + } + } + } + return "" +} + +// envFile reads an EnvironmentFile: KEY=VALUE lines, # and ; comments, +// one pair of quotes around a value removed. why is set for a line systemd +// may read differently (a continued line, an escape, a variable, a quote +// inside a value, a key that is not a plain name such as "export NAME"). +func envFile(b []byte) (map[string]string, string) { + out := map[string]string{} + why := "" + for _, l := range strings.Split(string(b), "\n") { + l = strings.TrimSpace(l) + if l == "" || l[0] == '#' || l[0] == ';' { + continue + } + k, v, ok := strings.Cut(l, "=") + k, v = strings.TrimSpace(k), strings.TrimSpace(v) + if len(v) >= 2 && (v[0] == '"' && v[len(v)-1] == '"' || v[0] == '\'' && v[len(v)-1] == '\'') { + v = v[1 : len(v)-1] + } + if !ok || !envName.MatchString(k) || strings.ContainsAny(v, "\\$\"'`") { + if why == "" { + why = fmt.Sprintf("the line %q may be read differently by systemd", clip(l)) + } + continue + } + if len(out) < 1024 { + out[k] = v + } else if why == "" { + why = "more variables are set than the scan keeps" + } + } + return out, why +} + +var envName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) + +// expandUnit splits an Exec line into words and puts in the unit's +// environment as systemd does: a word that is one $NAME becomes the +// value's words (none when empty); ${NAME} inside a word is replaced in +// place; an unset variable is empty. +func expandUnit(line string, env map[string]string) []string { + var out []string + for _, w := range unitWords(line) { + if m := bareUnitVar.FindStringSubmatch(w); m != nil { + out = append(out, strings.Fields(env[m[1]])...) + continue + } + out = append(out, bracedUnitVar.ReplaceAllStringFunc(w, func(r string) string { + return env[r[2:len(r)-1]] + })) + } + return out +} + +var ( + bareUnitVar = regexp.MustCompile(`^\$([A-Za-z_][A-Za-z0-9_]*)$`) + bracedUnitVar = regexp.MustCompile(`\$\{[A-Za-z_][A-Za-z0-9_]*\}`) +) + +// harmless reports a command run around nginx's start that cannot change +// its configuration: a test by the very nginx the unit starts, or rm -f of +// the pid file by the system's rm. +func harmless(w []string, pidFile, nginx string) bool { + if len(w) == 0 { + return false + } + if w[0] == nginx { + return nginxTest(w[1:]) + } + if w[0] != "/bin/rm" && w[0] != "/usr/bin/rm" { + return false + } + files := 0 + for _, a := range w[1:] { + switch { + case a == "-f" || a == "--force": + case strings.HasPrefix(a, "-"): + return false + case strings.HasSuffix(a, ".pid") || a == pidFile && pidFile != "": + files++ + default: + return false + } + } + return files > 0 +} + +// nginxTest reports nginx arguments that only test or show the +// configuration (-t, -T, -q, -g, -c, -p): they serve nothing. +func nginxTest(args []string) bool { + test := false + for i := 0; i < len(args); i++ { + a := args[i] + if !strings.HasPrefix(a, "-") || len(a) < 2 { + return false + } + for j := 1; j < len(a); j++ { + switch a[j] { + case 't', 'T': + test = true + case 'q': + case 'g', 'c', 'p', 'e': + if j == len(a)-1 { + i++ + } + j = len(a) + default: + return false + } + } + } + return test +} + +func nginxStart(b string) bool { + switch b { + case "nginx", "nginx-debug", "openresty", "angie", "tengine": + return true + } + return false +} + +// unitWords splits an ExecStart value on white space, with quotes +// grouping and a backslash escaping. +func unitWords(v string) []string { + var out []string + var b strings.Builder + in, q := false, byte(0) + for i := 0; i < len(v); i++ { + c := v[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(v): + i++ + b.WriteByte(v[i]) + in = true + case c == ' ' || c == '\t': + 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 +} + +// workdirOf is an image's working directory, "" when the target has none. +func workdirOf(ctx engine.TargetContext) string { + if w, ok := ctx.(engine.WorkingDirer); ok { + return w.WorkingDir() + } + return "" +} + +func firstOf2(a, b string) string { + if a != "" { + return a + } + return b +} + +// generated says why the configuration on disk is not what runs. +func (s *scan) generated() string { + if s.f5ingress && !s.ingress { + return "the F5 NGINX Ingress Controller writes nginx.conf at start; HTTP/2 follows its ConfigMap key http2 (off by default) and the VirtualServer and Ingress resources, which the image does not hold" + } + return "" +} + +func (s *scan) read(src *confSource, ps ...string) []byte { + for _, p := range ps { + if b, ok := s.db[p]; ok { + return b + } + if src.root != "" { + if b := src.disk(p, maxDB); b != nil { + return b + } + } + } + return nil +} + +// owners returns a lookup of the package that owns a file, from dpkg's +// status and .list files and apk's database. +func (s *scan) owners(src *confSource) func(string) (*pkgdb.Package, bool) { + var dpkg map[string]pkgdb.Package + if st := s.read(src, "/var/lib/dpkg/status"); st != nil { + dpkg = pkgdb.DpkgStatus(st) + } + apk := map[string]pkgdb.Package{} + for _, p := range []string{"/lib/apk/db/installed", "/usr/lib/apk/db/installed"} { + if b := s.read(src, p); b != nil { + for k, v := range pkgdb.APKOwners(b) { + apk[k] = v + } + } + } + lists := map[string][]byte{} + for p, b := range s.db { + if strings.HasPrefix(p, "/var/lib/dpkg/info/") { + lists[p] = b + } + } + names := make([]string, 0, len(lists)) + for p := range lists { + names = append(names, p) + } + sort.Strings(names) + return func(p string) (*pkgdb.Package, bool) { + if pk, ok := apk[p]; ok { + return &pk, true + } + for _, l := range names { + if pkgdb.ListHas(lists[l], p) { + if pk, ok := dpkg[pkgdb.DpkgListName(l)]; ok { + return &pk, true + } + } + } + return nil, false + } +} + +var verdicts = map[knowledge.Status]engine.Verdict{ + knowledge.Vulnerable: engine.Vulnerable, + knowledge.Fixed: engine.Fixed, + knowledge.NotAffected: engine.Inactive, + knowledge.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)} + for k, val := range x.Facts { + facts[k] = val + } + return engine.Finding{ + Kind: x.Kind, + Path: x.Path, + Verdict: v, + Reason: x.Reason, + Message: x.Message, + Method: "binary", + Facts: facts, + CVEs: []engine.CVEResult{{ID: x.CVE, Verdict: v, Reason: x.Reason}}, + Fix: x.Fix, + Severity: x.Severity, + Details: x, + } +} + +// osRelease reads ID, ID_LIKE and VERSION_ID. +func osRelease(b []byte) (id, like, ver string) { + sc := bufio.NewScanner(bytes.NewReader(b)) + for sc.Scan() { + k, v, ok := strings.Cut(sc.Text(), "=") + if !ok { + continue + } + v = strings.Trim(strings.TrimSpace(v), `"'`) + switch k { + case "ID": + id = v + case "ID_LIKE": + like = v + case "VERSION_ID": + ver = v + } + } + return +} + +// alpineBranch turns "3.24.4" into "3.24"; edge stays "edge". +func alpineBranch(r string) string { + r = strings.TrimSpace(r) + parts := strings.Split(r, ".") + if len(parts) >= 2 { + return parts[0] + "." + parts[1] + } + return r +} + +// confSource serves configuration files: what the scan kept, and below a +// system root, the root's files from disk. +type confSource struct { + kept map[string][]byte + full bool + tooLarge map[string]bool + root string + links map[string]string + // hardlinks are an image's hard links (path -> the path it names), + // which the walk does not hand out as files of their own. + hardlinks map[string]string + // unread are the paths the walk recorded as not scanned, with why. + unread map[string]string + unreadAll bool // more not-scanned records than kept: any path may be one + index *globIndex + wildGlobs int + // virtual are files the image's entrypoint writes at start + // (templates), by the path they get. + virtual map[string][]byte +} + +// templates maps the official image's /etc/nginx/templates/*.template to +// the /etc/nginx/conf.d files its entrypoint writes from them. +func (s *confSource) templates(env []string) string { + dir, out, suffix := "/etc/nginx/templates", "/etc/nginx/conf.d", ".template" + for _, kv := range env { + k, v, _ := strings.Cut(kv, "=") + switch k { + case "NGINX_ENVSUBST_TEMPLATE_DIR": + dir = v + case "NGINX_ENVSUBST_OUTPUT_DIR": + out = v + case "NGINX_ENVSUBST_TEMPLATE_SUFFIX": + suffix = v + case "NGINX_ENVSUBST_FILTER": + return "the entrypoint puts in only the variables NGINX_ENVSUBST_FILTER selects, which the scan does not apply" + } + } + if !keptByAll(path.Clean("/"+dir) + "/*") { + return "the entrypoint writes templates from " + dir + ", which the scan does not read whole" + } + dir, out = path.Clean("/"+dir), path.Clean("/"+out) + for p, b := range s.kept { + if strings.HasPrefix(p, dir+"/") && strings.HasSuffix(p, suffix) && suffix != "" { + rel := strings.TrimSuffix(strings.TrimPrefix(p, dir+"/"), suffix) + if s.virtual == nil { + s.virtual = map[string][]byte{} + } + s.virtual[path.Join(out, rel)] = envsubst(b, env) + } + } + return "" +} + +// envsubst puts in the image's environment as the entrypoint's envsubst +// does: only variables that are set, $NAME and ${NAME}. A variable left +// as written makes what it decides unknown (internal/conf). +func envsubst(b []byte, env []string) []byte { + vals := map[string]string{} + for _, kv := range env { + if k, v, ok := strings.Cut(kv, "="); ok { + vals[k] = v + } + } + return envRef.ReplaceAllFunc(b, func(m []byte) []byte { + name := strings.Trim(string(m), "${}") + if v, ok := vals[name]; ok { + return []byte(v) + } + return m + }) +} + +var envRef = regexp.MustCompile(`\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*`) + +// resolve follows symbolic links within the target, as the kernel would. +func (s *confSource) 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 := s.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 "" +} + +func (s *confSource) Read(p string) ([]byte, bool, string) { + if b, ok := s.virtual[p]; ok { + return b, true, "" + } + r := s.resolve(p) + if r == "" { + return nil, false, "a symbolic link loop" + } + if to, ok := s.hardlinks[r]; ok { + r = to + } + if b, ok := s.virtual[r]; ok { + return b, true, "" + } + if b, ok := s.kept[r]; ok { + return b, true, "" + } + if s.root != "" { + if b := s.disk(r, maxConf); b != nil { + return b, true, "" + } + } + if why, ok := s.unreadAt(r); ok { + return nil, false, "not scanned: " + why + } + switch { + case s.tooLarge[r]: + return nil, false, fmt.Sprintf("larger than the %d bytes the detector reads of a configuration file", maxConf) + case s.full: + return nil, false, "not kept: the scan reached its limit on configuration files" + case !keepConf(r): + return nil, false, "not a file the scan reads as configuration, or not in the target" + } + return nil, false, "not in the target, or not readable" +} + +// unreadAt reports a path, or a directory above it, the walk could not +// read. +func (s *confSource) unreadAt(p string) (string, bool) { + for q := p; q != "/" && q != "."; q = path.Dir(q) { + if why, ok := s.unread[q]; ok { + return why, true + } + } + if s.unreadAll { + return "more files were not scanned than the detector keeps a record of", true + } + return "", false +} + +// globIndex is what Glob looks through, by directory: the files kept, the +// virtual ones, the links, the not-scanned records and the files too large +// to keep. It is built on the first glob. +type globIndex struct { + files, unread, large map[string][]string + disk map[string]diskList +} + +type diskList struct { + names []string // regular files and links + err bool // the directory could not be listed +} + +// maxWildGlobs bounds the globs with a wildcard in their directory part, +// which are matched against every path: past it a glob is not complete. +const maxWildGlobs = 64 + +func (s *confSource) idx() *globIndex { + if s.index != nil { + return s.index + } + x := &globIndex{files: map[string][]string{}, unread: map[string][]string{}, large: map[string][]string{}, disk: map[string]diskList{}} + for _, m := range []map[string][]byte{s.kept, s.virtual} { + for p := range m { + x.files[path.Dir(p)] = append(x.files[path.Dir(p)], p) + } + } + for _, m := range []map[string]string{s.links, s.hardlinks} { + for p := range m { + x.files[path.Dir(p)] = append(x.files[path.Dir(p)], p) + } + } + for p := range s.unread { + x.unread[path.Dir(p)] = append(x.unread[path.Dir(p)], p) + } + for p := range s.tooLarge { + x.large[path.Dir(p)] = append(x.large[path.Dir(p)], p) + } + s.index = x + return x +} + +// diskDir lists a directory below the system root, once. +func (s *confSource) diskDir(dir string) diskList { + x := s.idx() + if l, ok := x.disk[dir]; ok { + return l + } + var l diskList + if full, ok := s.diskPath(dir); ok { + ents, err := os.ReadDir(full) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + l.err = true + } + for _, e := range ents { + if e.Type().IsRegular() || e.Type()&fs.ModeSymlink != 0 { + l.names = append(l.names, e.Name()) + } + } + } else { + l.err = true + } + x.disk[dir] = l + return l +} + +func (s *confSource) Glob(pattern string) ([]string, bool) { + complete := !s.full + match := func(pat, p string) bool { + ok, err := globMatch(pat, p) + if err != nil { + complete = false // a pattern nginx's glob(3) reads and this one does not + } + return ok + } + seen := map[string]bool{} + var out []string + add := func(p string) { + if !seen[p] { + seen[p] = true + out = append(out, p) + } + } + x := s.idx() + dir, base := path.Dir(pattern), path.Base(pattern) + if strings.ContainsAny(dir, "*?[") { + // A wildcard in the directory part: every path is a candidate, so + // only a few such globs are matched. + s.wildGlobs++ + if s.wildGlobs > maxWildGlobs { + return nil, false + } + if s.root != "" { + return s.diskGlob(pattern) + } + for _, ps := range x.files { + for _, p := range ps { + if match(pattern, p) { + add(p) + } + } + } + prefix := dir[:strings.IndexAny(dir, "*?[")] + // A link on the pattern's path (the directory it starts in, or + // one below it) leads where this match does not look. + if r := s.resolve(strings.TrimSuffix(prefix, "/")); r == "" || r != path.Clean(strings.TrimSuffix(prefix, "/")) { + complete = false + } + for _, m := range []map[string]string{s.links, s.hardlinks} { + for q := range m { + if strings.HasPrefix(q, prefix) { + complete = false + } + } + } + for _, ps := range x.unread { + for _, u := range ps { + if strings.HasPrefix(u, prefix) { + complete = false + } + } + } + for _, ps := range x.large { + for _, p := range ps { + if match(pattern, p) { + complete = false + } + } + } + if _, ok := s.unreadAt(prefix); ok || s.unreadAll { + complete = false + } + sort.Strings(out) + return out, complete && keptByAll(pattern) + } + // Symbolic and hard links match too (sites-enabled/default -> + // ../sites-available/default); Read follows them, and one that leads + // nowhere the scan read is reported as not read. + for _, p := range x.files[dir] { + if match(pattern, p) { + add(p) + } + } + resolved := pattern + switch r := s.resolve(dir); { + case r == "": + complete = false + case r != dir: + // A directory reached through a symbolic link: its target's files + // and links, under the linked name. Whether the list is complete + // is decided on the directory the files are really in. + resolved = path.Join(r, base) + for _, p := range x.files[r] { + if match(base, path.Base(p)) { + add(path.Join(dir, path.Base(p))) + } + } + } + complete = complete && keptByAll(pattern) && keptByAll(resolved) + // A file or directory the walk could not read where the pattern looks + // may hold a match. + for _, pat := range []string{pattern, resolved} { + d := path.Dir(pat) + if _, ok := s.unreadAt(d); ok { + complete = false + } + for _, u := range x.unread[d] { + if match(pat, u) { + complete = false + } + } + for _, p := range x.large[d] { + if match(pat, p) { + complete = false + } + } + } + if s.root != "" { + // Below a system root the directory is read from disk: every + // entry, symbolic links included (Read follows them inside the + // root). A directory that cannot be listed leaves the list + // incomplete; one that does not exist matches nothing, as for + // nginx. What the walk recorded as not read still counts. + diskComplete := !s.full + l := s.diskDir(dir) + if l.err { + diskComplete = false + } + for _, n := range l.names { + if match(base, n) { + add(path.Join(dir, n)) + } + } + walkGap := false + for _, pat := range []string{pattern, resolved} { + if _, ok := s.unreadAt(path.Dir(pat)); ok { + walkGap = true + } + } + complete = diskComplete && !walkGap + } + sort.Strings(out) + return out, complete +} + +// maxDiskGlobEntries bounds the directory entries one wildcard glob +// reads from disk below a system root. +const maxDiskGlobEntries = 20000 + +// diskGlob matches a pattern with a wildcard in its directory part +// against the disk below the system root, one part at a time, as glob(3) +// does: directories (links to directories too) for the middle parts, +// regular files and links for the last. A directory that cannot be +// listed, one the walk did not read, or more entries than the bound +// leaves the list incomplete. +func (s *confSource) diskGlob(pattern string) ([]string, bool) { + parts := strings.Split(strings.TrimPrefix(path.Clean(pattern), "/"), "/") + complete, seen := !s.full, 0 + cur := []string{"/"} + for i, part := range parts { + last := i == len(parts)-1 + var next []string + for _, dir := range cur { + if _, ok := s.unreadAt(dir); ok && dir != "/" { + complete = false + } + if !strings.ContainsAny(part, "*?[") { + p := path.Join(dir, part) + full, ok := s.diskPath(p) + if !ok { + complete = false + continue + } + fi, err := os.Lstat(full) + switch { + case err != nil && !errors.Is(err, fs.ErrNotExist): + complete = false + case err != nil: + case fi.Mode()&fs.ModeSymlink != 0 && last: + next = append(next, p) // Read follows it inside the root + case fi.Mode()&fs.ModeSymlink != 0: + complete = false // a linked directory: not followed here + case last && fi.Mode().IsRegular() || !last && fi.IsDir(): + next = append(next, p) + } + continue + } + full, ok := s.diskPath(dir) + if !ok { + complete = false + continue + } + ents, err := os.ReadDir(full) + if err != nil { + if !errors.Is(err, fs.ErrNotExist) { + complete = false + } + continue + } + for _, e := range ents { + if seen++; seen > maxDiskGlobEntries { + return nil, false + } + ok, err := globMatch(part, e.Name()) + if err != nil { + complete = false + } + if !ok { + continue + } + p := path.Join(dir, e.Name()) + switch { + case e.Type()&fs.ModeSymlink != 0 && last: + next = append(next, p) // Read follows it inside the root, or reports it + case e.Type()&fs.ModeSymlink != 0: + // A linked directory: its target is decided inside the + // root, which this walk does not do. + complete = false + case last && e.Type().IsRegular() || !last && e.IsDir(): + next = append(next, p) + } + } + } + cur = next + } + if s.unreadAll { + complete = false + } + sort.Strings(cur) + return cur, complete +} + +// globMatch matches a path as nginx's glob(3) does: "[!...]" negates, a +// wildcard does not match a leading dot, and each "/"-separated part +// matches on its own. +func globMatch(pattern, p string) (bool, error) { + pp, np := strings.Split(pattern, "/"), strings.Split(p, "/") + if len(pp) != len(np) { + return false, nil + } + for i := range pp { + pc, err := posixClasses(strings.ReplaceAll(pp[i], "[!", "[^")) + if err != nil { + return false, err + } + if strings.HasPrefix(np[i], ".") && !strings.HasPrefix(pc, ".") { + return false, nil + } + ok, err := path.Match(pc, np[i]) + if err != nil { + return false, err + } + if !ok { + return false, nil + } + } + return true, nil +} + +// posixClasses turns glob(3)'s character classes ([[:digit:]]) into the +// ranges path.Match reads. An unknown class is an error, so the list it +// would give is not taken as complete. +func posixClasses(p string) (string, error) { + for { + i := strings.Index(p, "[:") + if i < 0 { + return p, nil + } + // The closing ":]" is looked for after the opening "[:", so "[:]" + // does not close on itself. + j := strings.Index(p[i+2:], ":]") + if j < 0 { + return "", path.ErrBadPattern + } + r, ok := classRanges[p[i+2:i+2+j]] + if !ok { + return "", path.ErrBadPattern + } + p = p[:i] + r + p[i+2+j+2:] + } +} + +var classRanges = map[string]string{"digit": "0-9", "alpha": "a-zA-Z", "alnum": "a-zA-Z0-9", "upper": "A-Z", "lower": "a-z", + "xdigit": "0-9a-fA-F", "space": " \t", "blank": " \t", "punct": "!-/:-@\\[-`{-~"} + +func (s *confSource) diskPath(p string) (string, bool) { + clean := path.Clean("/" + p) + full := filepath.Join(s.root, filepath.FromSlash(clean)) + rel, err := filepath.Rel(s.root, full) + if err != nil || strings.HasPrefix(rel, "..") { + return "", false + } + return full, true +} + +// disk reads a regular file below the system root, following symbolic +// links only while they stay inside it. +func (s *confSource) disk(p string, limit int64) []byte { + b, _ := s.diskRead(p, limit) + return b +} + +// diskRead is disk with the reason a file was not read: an error matching +// fs.ErrNotExist only when it is not there. +func (s *confSource) diskRead(p string, limit int64) ([]byte, error) { + full, ok := s.diskPath(p) + if !ok { + return nil, errors.New("outside the system root") + } + real, err := filepath.EvalSymlinks(full) + if err != nil { + return nil, err + } + root, err := filepath.EvalSymlinks(s.root) + if err != nil { + return nil, err + } + if rel, err := filepath.Rel(root, real); err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return nil, errors.New("a link leaves the system root") + } + f, err := os.OpenFile(real, os.O_RDONLY|syscallNoFollow, 0) + if err != nil { + return nil, err + } + defer f.Close() + fi, err := f.Stat() + if err != nil { + return nil, err + } + if !fi.Mode().IsRegular() || fi.Size() > limit { + return nil, errors.New("not a regular file within the size limit") + } + b, err := io.ReadAll(io.LimitReader(f, limit+1)) + if err == nil && int64(len(b)) > limit { + err = errors.New("over the size limit") + } + if err != nil { + return nil, err + } + return b, nil +} diff --git a/detectors/nginxh2/nginxh2_test.go b/detectors/nginxh2/nginxh2_test.go new file mode 100644 index 0000000..cd51ab2 --- /dev/null +++ b/detectors/nginxh2/nginxh2_test.go @@ -0,0 +1,217 @@ +package nginxh2 + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngxtest" + "github.com/DefectDojo/earlylight/internal/engine" +) + +func write(t *testing.T, root string, files map[string][]byte) { + t.Helper() + for p, b := range files { + full := filepath.Join(root, filepath.FromSlash(p)) + if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(full, b, 0o755); err != nil { + t.Fatal(err) + } + } +} + +func scanFS(t *testing.T, files map[string][]byte, opts engine.Options) *engine.Target { + t.Helper() + root := t.TempDir() + write(t, root, files) + opts.AsRoot = true + tg := engine.ScanFS([]engine.Detector{&Detector{}}, root, opts) + if tg.Error != "" { + t.Fatal(tg.Error) + } + return tg +} + +func find(tg *engine.Target, kind, p string) *engine.Finding { + for i := range tg.Findings { + if tg.Findings[i].Kind == kind && tg.Findings[i].Path == p { + return &tg.Findings[i] + } + } + return nil +} + +func TestScanDebianLayout(t *testing.T) { + tg := scanFS(t, map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.22.1").Bytes(), + "/etc/nginx/nginx.conf": []byte("events {} http { include /etc/nginx/sites-enabled/*; }"), + "/etc/nginx/sites-enabled/default": []byte("server { listen 443 ssl http2; location / { proxy_pass http://app; } }"), + "/etc/os-release": []byte("ID=debian\nVERSION_ID=\"12\"\n"), + "/var/lib/dpkg/status": []byte("Package: nginx\nStatus: install ok installed\nMaintainer: Debian Nginx Maintainers\nVersion: 1.22.1-9+deb12u10\n"), + "/var/lib/dpkg/info/nginx.list": []byte("/usr/sbin/nginx\n"), + "/usr/share/nginx/html/index.html": []byte(""), + "/usr/lib/nginx/modules/ngx_x.so": []byte("\x7fELF\x02\x01ngx_core_module\x00"), + "/srv/app/static/big.conf.bak": []byte("listen 443 ssl http2;"), + "/etc/nginx/sites-available/unused": []byte("server { listen 8443 ssl http2; }"), + }, engine.Options{}) + for _, k := range []string{KindFlow, KindReuse} { + f := find(tg, k, "/usr/sbin/nginx") + if f == nil { + t.Fatalf("%s missing: %+v", k, tg.Findings) + } + if f.Verdict != engine.Vulnerable || f.Facts["exposure"] != "exposed" || f.Facts["package"] != "nginx 1.22.1-9+deb12u10" || f.Facts["distro"] != "debian 12" || f.Severity != "critical" { + t.Errorf("%s: %+v", k, f) + } + if len(f.CVEs) != 1 || f.CVEs[0].Verdict != engine.Vulnerable { + t.Errorf("%s CVEs: %+v", k, f.CVEs) + } + } + if n := len(tg.Findings); n != 2 { + t.Errorf("%d findings, want 2 (the dynamic module is not a server): %+v", n, tg.Findings) + } +} + +func TestScanFixedAndOff(t *testing.T) { + tg := scanFS(t, map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.31.9").Bytes(), + "/opt/old/sbin/nginx": ngxtest.Default("1.30.6").Bytes(), + "/etc/nginx/nginx.conf": []byte("http { include conf.d/*.conf; }"), + "/etc/nginx/conf.d/a.conf": []byte("server { listen 80; }"), + "/etc/systemd/system/old-nginx.service": []byte("[Service]\nExecStart=/opt/old/sbin/nginx -g 'daemon on;'\n"), + }, engine.Options{}) + if f := find(tg, KindFlow, "/usr/sbin/nginx"); f == nil || f.Verdict != engine.Fixed || f.Reason == "" { + t.Errorf("fixed: %+v", f) + } + f := find(tg, KindFlow, "/opt/old/sbin/nginx") + if f == nil || f.Verdict != engine.Vulnerable || f.Facts["exposure"] != "not-exposed" || f.Facts["http2"] != "off" { + t.Errorf("off: %+v", f) + } +} + +func TestScanUnreadInclude(t *testing.T) { + tg := scanFS(t, map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/etc/nginx/nginx.conf": []byte("http { include /srv/vhosts/*; server { listen 80; } }"), + "/srv/vhosts/site": []byte("server { listen 443 ssl http2; }"), + }, engine.Options{}) + f := find(tg, KindFlow, "/usr/sbin/nginx") + if f == nil || f.Verdict != engine.Vulnerable || f.Facts["exposure"] != "unknown" { + t.Errorf("a glob the scan does not read whole must leave exposure unknown: %+v", f) + } +} + +func TestScanSymlinkedConfig(t *testing.T) { + root := t.TempDir() + write(t, root, map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/etc/nginx/nginx.conf": []byte("http { include /etc/nginx/sites-enabled/*; }"), + "/etc/nginx/sites-available/site.conf": []byte("server { listen 443 ssl http2; }"), + }) + if err := os.MkdirAll(filepath.Join(root, "etc/nginx/sites-enabled"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink("../sites-available/site.conf", filepath.Join(root, "etc/nginx/sites-enabled/site.conf")); err != nil { + t.Fatal(err) + } + // A link loop must not hang or crash the scan. + if err := os.Symlink("loop.conf", filepath.Join(root, "etc/nginx/loop.conf")); err != nil { + t.Fatal(err) + } + tg := engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true}) + f := find(tg, KindFlow, "/usr/sbin/nginx") + if f == nil || f.Facts["exposure"] != "exposed" { + t.Errorf("a site enabled through a symbolic link: %+v", f) + } +} + +func TestScanBelowRoot(t *testing.T) { + // Scanning /usr/sbin of a system root still reads its configuration + // and package database from disk. + root := t.TempDir() + write(t, root, map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.30.6").Bytes(), + "/etc/nginx/nginx.conf": []byte("http { include /etc/nginx/conf.d/*.conf; }"), + "/etc/nginx/conf.d/s.conf": []byte("server { listen 443 ssl; http2 on; }"), + "/etc/os-release": []byte("ID=alpine\nVERSION_ID=3.24.4\n"), + "/etc/alpine-release": []byte("3.24.4\n"), + "/lib/apk/db/installed": []byte("P:nginx\nV:1.30.6-r0\nm:Jakub Jirutka\nF:usr/sbin\nR:nginx\n\n"), + }) + tg := engine.ScanFS([]engine.Detector{&Detector{}}, filepath.Join(root, "usr/sbin"), engine.Options{SystemRoot: root}) + if tg.Error != "" { + t.Fatal(tg.Error) + } + f := find(tg, KindFlow, "/usr/sbin/nginx") + if f == nil || f.Facts["exposure"] != "exposed" || f.Facts["package"] != "nginx 1.30.6-r0" || f.Facts["distro"] != "alpine 3.24" { + t.Errorf("%+v", f) + } + if !strings.Contains(f.Fix, "apk upgrade nginx") { + t.Errorf("fix: %s", f.Fix) + } +} + +func TestTemplates(t *testing.T) { + s := &confSource{kept: map[string][]byte{ + "/etc/nginx/templates/default.conf.template": []byte("server { listen ${PORT} ssl http2; }"), + "/etc/nginx/tpl/x.conf.tpl": []byte("server { listen 1 ssl http2; }"), + }} + s.templates(nil) + if _, ok, _ := s.Read("/etc/nginx/conf.d/default.conf"); !ok { + t.Error("default template not mapped") + } + s2 := &confSource{kept: s.kept} + if why := s2.templates([]string{"NGINX_ENVSUBST_TEMPLATE_DIR=/etc/nginx/tpl", "NGINX_ENVSUBST_TEMPLATE_SUFFIX=.tpl", "NGINX_ENVSUBST_OUTPUT_DIR=/etc/nginx/http.d"}); why != "" { + t.Errorf("templates under /etc/nginx: %s", why) + } + // A template directory the scan does not read whole is not applied. + if why := (&confSource{kept: s.kept}).templates([]string{"NGINX_ENVSUBST_TEMPLATE_DIR=/srv/t"}); why == "" { + t.Error("templates from /srv/t were taken as read whole") + } + if _, ok, _ := s2.Read("/etc/nginx/http.d/x.conf"); !ok { + t.Error("template settings from the environment not used") + } + if ms, _ := s2.Glob("/etc/nginx/http.d/*.conf"); len(ms) != 1 { + t.Errorf("glob over templates: %v", ms) + } +} + +func TestKeepConf(t *testing.T) { + for p, want := range map[string]bool{ + "/etc/nginx/mime.types": true, "/etc/nginx/sites-enabled/default": true, "/app/site.conf": true, + "/usr/local/openresty/lualib/resty/core.lua": false, "/usr/local/openresty/luajit/lib/libluajit-5.1.a": false, + "/usr/local/openresty/nginx/conf/mime.types": true, "/opt/nginx/vhosts/example": true, "/usr/bin/python3": false, + "/srv/nginx/html/index.html": false, + } { + if got := keepConf(p); got != want { + t.Errorf("keepConf(%s) = %v", p, got) + } + } + for p, want := range map[string]bool{ + "/etc/nginx/conf.d/*.conf": true, "/etc/nginx/sites-enabled/*": true, "/srv/vhosts/*": false, "/srv/vhosts/*.conf": true, + "/opt/nginx/vhosts/*": false, + } { + if got := keptByAll(p); got != want { + t.Errorf("keptByAll(%s) = %v", p, got) + } + } +} + +func TestManifestLoads(t *testing.T) { + d := &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 + if strings.Contains(k.Description, "\u2014") || strings.Contains(k.Title, "\u2014") { + t.Errorf("kind %s has an em dash", k.ID) + } + } +} diff --git a/detectors/nginxh2/open_other.go b/detectors/nginxh2/open_other.go new file mode 100644 index 0000000..072d7ca --- /dev/null +++ b/detectors/nginxh2/open_other.go @@ -0,0 +1,7 @@ +//go:build !unix + +package nginxh2 + +// syscallNoFollow is not available here; disk still checks that the file +// it opened is regular. +const syscallNoFollow = 0 diff --git a/detectors/nginxh2/open_unix.go b/detectors/nginxh2/open_unix.go new file mode 100644 index 0000000..a99e4f7 --- /dev/null +++ b/detectors/nginxh2/open_unix.go @@ -0,0 +1,9 @@ +//go:build unix + +package nginxh2 + +import "syscall" + +// syscallNoFollow refuses a symbolic link (the path was resolved first) and +// does not block on a FIFO or device. +const syscallNoFollow = syscall.O_NOFOLLOW | syscall.O_NONBLOCK diff --git a/detectors/nginxh2/repo.go b/detectors/nginxh2/repo.go new file mode 100644 index 0000000..9256db0 --- /dev/null +++ b/detectors/nginxh2/repo.go @@ -0,0 +1,615 @@ +package nginxh2 + +import ( + "context" + "fmt" + "io" + "sort" + "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/nginxh2/internal/knowledge" + "github.com/DefectDojo/earlylight/detectors/nginxh2/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.RuleImage + KindPackage = repo.RulePackage + KindHTTP2 = repo.RuleHTTP2 + KindNotChecked = repo.RuleNotChecked + KindImage = "image" +) + +func repoKinds() []engine.Kind { + cwe := []string{"CWE-787", "CWE-416"} + return []engine.Kind{ + {ID: KindImagePin, Title: "Source tree uses an nginx image without the fix for the HTTP/2 pair", Level: "error", SecuritySeverity: knowledge.CVSS, CWEs: cwe, + Description: "A Dockerfile, Compose, Kubernetes, Helm values or CI file names an nginx image (the official nginx image, nginx-unprivileged, OpenResty, Bitnami, the ingress-nginx controller, the F5 NGINX Ingress Controller, Angie) whose tag is a release without the fix for CVE-2026-123007 and CVE-2026-123633, or a Helm chart deploys ingress-nginx, which will publish no fix."}, + {ID: KindImage, Title: "Image the source tree uses holds an nginx vulnerable to the HTTP/2 pair", Level: "error", SecuritySeverity: knowledge.CVSS, CWEs: cwe, + Description: "An image the tree builds on or deploys under a moving tag or a digest, read from its registry for linux/amd64 and linux/arm64 and judged as scan image does."}, + {ID: KindPackage, Title: "Dockerfile installs nginx without the fix for the HTTP/2 pair", Level: "error", SecuritySeverity: knowledge.CVSS, CWEs: cwe, + Description: "An apt, apk, dnf, yum, microdnf or zypper install of nginx, OpenResty or Angie pinned to a release without the fix, or without a version from a distribution that had published no fixed package."}, + {ID: KindHTTP2, Title: "nginx configuration turns HTTP/2 on", Level: "note", + Description: "An nginx configuration in the tree (a file, a template or a ConfigMap) turns HTTP/2 on, which makes an nginx without the fix reachable. A setting, not a vulnerable build; fix prints the interim HTTP/2-off edit and never applies it."}, + {ID: KindNotChecked, Title: "nginx not checked for the fix for the HTTP/2 pair", Level: "note", + Description: "An nginx image whose tag does not name one release (a moving tag, a digest) that was not read, a package whose release the file does not show, or a file or reference 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{}) + 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(ctx, 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 +} + +var repoVerdicts = map[knowledge.Status]engine.Verdict{ + knowledge.Vulnerable: engine.Vulnerable, + knowledge.Unknown: engine.Unknown, + knowledge.NotAffected: engine.Inactive, + knowledge.Fixed: engine.Fixed, +} + +func repoFinding(f repo.Finding) engine.Finding { + v, ok := repoVerdicts[f.Status] + if !ok { + v = engine.Unknown + } + reason := f.Reason + if reason == "" && v != engine.Vulnerable { + reason = "not decided" + } + facts := map[string]string{"status": string(f.Status)} + for k, val := range f.Props { + facts[k] = val + } + out := engine.Finding{Kind: f.Rule, Path: f.File, Line: f.Line, Verdict: v, Reason: reason, Message: f.Message, Method: "source", Facts: facts, Fix: f.Fix} + for _, c := range f.CVEs { + cv, ok := repoVerdicts[c.Status] + if !ok { + cv = engine.Unknown + } + out.CVEs = append(out.CVEs, engine.CVEResult{ID: c.ID, Verdict: cv, Reason: c.Reason}) + } + if out.CVEs == nil && f.Rule != repo.RuleHTTP2 { + for _, c := range knowledge.CVEs { + out.CVEs = append(out.CVEs, engine.CVEResult{ID: c.ID, Verdict: v, Reason: reason}) + } + } + if f.Level == "warning" { + out.Severity = "medium" + } + return out +} + +// Limits on what one source-tree scan reads from registries. +const ( + maxRepoImages = 20 +) + +// repoPlatforms are the platforms a pulled image is judged on: the ones +// the tree builds (--platform), else linux/amd64 and linux/arm64, where +// nginx is affected alike. +func repoPlatforms(o engine.Options, fromLine string) []string { + if fromLine != "" && !strings.Contains(fromLine, "$") { + return []string{fromLine} + } + if len(o.Platforms) > 0 { + return o.Platforms + } + return []string{"linux/amd64", "linux/arm64"} +} + +// pulled reads an image the tree references through the guarded +// transport on each platform, and reports what it holds at the +// reference. +func (d *Detector) pulled(ctx context.Context, f repo.Finding, o engine.Options, cache map[string][]*engine.Target, t *engine.Target) []engine.Finding { + img := f.Pull + key := img + "|" + f.Platform + its, ok := cache[key] + 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)} + } + have, err := platforms(ctx, img, o) + want := repoPlatforms(o, f.Platform) + switch { + case err != nil: + its = []*engine.Target{{Name: img, Error: err.Error()}} + case have == nil: + // One image, not an index: its own platform. + its = []*engine.Target{d.scanImage(img, "", o)} + default: + for _, p := range want { + if !containsPlatform(have, p) { + continue + } + its = append(its, d.scanImage(img, p, o)) + } + if len(its) == 0 { + its = []*engine.Target{{Name: img, Error: fmt.Sprintf("the image has none of the platforms %s", strings.Join(want, ", "))}} + } + } + cache[key] = its + } + var out []engine.Finding + for _, it := range its { + out = append(out, fromPulled(f, it)...) + } + return out +} + +func containsPlatform(have []string, p string) bool { + for _, h := range have { + if h == p || strings.HasPrefix(h, p+"/") { + return true + } + } + return false +} + +func (d *Detector) scanImage(ref, platform string, o engine.Options) *engine.Target { + return engine.ScanImage([]engine.Detector{d}, ref, engine.Options{Platform: platform, MaxFileSize: o.MaxFileSize, Guarded: true, PublicOnly: o.PublicOnly}) +} + +// fromPulled turns what an image scan found into findings at the +// reference. An image read only in part, where nothing was found, is not +// checked: no finding is not proof of no nginx. +func fromPulled(f repo.Finding, it *engine.Target) (out []engine.Finding) { + img := f.Pull + at := img + if it.Platform != "" { + at += " (" + it.Platform + ")" + } + if it.Error != "" { + g := repoFinding(f) + g.Message = fmt.Sprintf("image %s could not be read for the nginx HTTP/2 pair: %s", at, refs.CleanText(it.Error, 300)) + g.Reason = "the image could not be read" + for i := range g.CVEs { + g.CVEs[i].Reason = g.Reason + } + return []engine.Finding{g} + } + partial := it.Incomplete != "" || it.Gaps() > 0 || len(it.Problems) > 0 + found := false + for _, x := range it.Findings { + found = true + 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["server"] = img, x.Path + if it.Digest != "" { + g.Facts["digest"] = it.Digest + } + if it.Platform != "" { + g.Facts["platform"] = it.Platform + } + g.Message = fmt.Sprintf("image %s (%s): %s: %s", at, it.Digest, x.Path, x.Message) + g.Fix = x.Fix + " Use a release of " + img + " built with the fix (nginx 1.31.9 or 1.30.7), then redeploy." + if why := f.Props["deployment"]; why != "" && g.Facts["exposure"] != "exposed" { + // The image's own configuration is not what this deployment + // runs: a weaker answer from it does not hold. + g.Facts["exposure"], g.Facts["exposure_unknown"] = "unknown", why + if g.Facts["http2"] == "off" { + g.Facts["http2"] = "unknown" // off in the image, not known where it is deployed + } + g.Message += " Exposure in this deployment is not known: " + why + "." + if g.Verdict == engine.Vulnerable { + g.Severity = "high" + } + } + out = append(out, g) + } + switch { + case len(out) > 0: + case partial: + // Read in part: what was read clearing (or nothing found) does + // not clear the image. + g := repoFinding(f) + g.Verdict, g.Reason = engine.Unknown, "the image could not be read in full, so an nginx in it may have been missed" + g.Message = fmt.Sprintf("image %s (%s) was read only in part (%d files not scanned, %d problems): not checked", at, it.Digest, it.Gaps(), len(it.Problems)) + for i := range g.CVEs { + g.CVEs[i].Verdict, g.CVEs[i].Reason = g.Verdict, g.Reason + } + out = append(out, g) + case !found: + // An nginx image in which no nginx binary was recognised (a packed + // or renamed build): not checked, never clean. + g := repoFinding(f) + g.Verdict, g.Reason = engine.Unknown, "no nginx binary was recognised in an image of an nginx family" + g.Message = fmt.Sprintf("image %s (%s): no nginx binary was recognised in it: not checked", at, it.Digest) + for i := range g.CVEs { + g.CVEs[i].Verdict, g.CVEs[i].Reason = g.Verdict, g.Reason + } + out = append(out, g) + } + return out +} + +// platforms lists the platforms of an image through the guarded +// transport, within the timeout; nil for a single image. +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 (it may still be being published)", ref) + } + sort.Strings(out) + return out, 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 +} + +// 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 + } +} + +// verifier reads the replacement image and requires: every platform the +// tree builds (--platform), or else every platform the current tag has, is +// published for it; on each platform judged +// (linux/amd64 and linux/arm64, or --platform) it is read in full and +// every nginx in it has the fix for both CVEs (at least one nginx found); +// and it is on the same base OS as the current image. +func (d *Detector) verifier(o engine.Options, label string) 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, curErr := platforms(ctx, current, o) + tp, err := platforms(ctx, target, o) + if err != nil { + return "", err + } + // The platforms that must be there: those the tree builds + // (--platform), else every one the current tag has. + need, from := cur, current + switch { + case len(o.Platforms) > 0: + need, from = o.Platforms, label + case curErr != nil: + return "", &repo.Declined{Reason: fmt.Sprintf("the platforms of %s could not be listed (%v), so whether %s covers them is not checked; rescan to confirm, or name the platforms you build with --platform", current, curErr, target)} + } + if tp == nil && len(need) > 1 { + return "", &repo.Declined{Reason: fmt.Sprintf("%s is a single image, and %s needs %s; change it by hand", target, from, strings.Join(need, ", "))} + } + for _, p := range need { + if tp != nil && !containsPlatform(tp, p) { + return "", &repo.Declined{Reason: missingPlatform(target, p, from)} + } + } + judge := repoPlatforms(o, "") + if tp == nil { + judge = []string{""} + } + curOS := "" + if curErr == nil { + c := d.scanImage(current, firstOf(judge, tp), o) + if c.Error == "" { + curOS = annotation(c, "nginxh2_os") + } + } + judged := 0 + for _, p := range judge { + if p != "" && !containsPlatform(tp, p) { + continue + } + t := d.scanImage(target, p, o) + where := target + if p != "" { + where += " (" + p + ")" + } + if t.Error != "" { + return "", fmt.Errorf("reading %s: %s", where, t.Error) + } + if t.Incomplete != "" || t.Gaps() > 0 || len(t.Problems) > 0 { + return "", &repo.Declined{Reason: fmt.Sprintf("%s could not be read in full; change it by hand", where)} + } + fixed := 0 + for _, f := range t.Findings { + if f.Verdict != engine.Fixed { + return "", &repo.Declined{Reason: fmt.Sprintf("%s still holds %s (%s for %s); change it by hand", where, f.Path, f.Verdict, f.Kind)} + } + fixed++ + } + if fixed == 0 { + return "", &repo.Declined{Reason: fmt.Sprintf("no nginx was found in %s, so the fix could not be shown; change it by hand", where)} + } + _, tag, _ := strings.Cut(target[strings.LastIndex(target, "/")+1:], ":") + if curOS != "" || !repo.NamesBaseOS(tag) { + if err := repo.SameBase(curOS, annotation(t, "nginxh2_os")); err != nil { + return "", err + } + } + judged++ + } + if judged == 0 { + return "", &repo.Declined{Reason: fmt.Sprintf("%s has none of the platforms %s; change it by hand", target, strings.Join(judge, ", "))} + } + 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 firstOf(judge, have []string) string { + for _, p := range judge { + if p == "" || containsPlatform(have, p) { + return p + } + } + return "" +} + +func annotation(t *engine.Target, key string) string { + if t == nil || t.Error != "" { + return "" + } + v, _ := t.Annotations[key].(string) + return v +} + +// Fix moves image tags to the first fixed release of the same line and +// variant, after reading the new image. Everything else is explained: a +// package without a published fix, a moving tag, an image with no fixed +// tag, and the optional HTTP/2-off edit, which is never applied. +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 = memoVerify(d.verifier(o, "the tree's --platform")) + reg.APKIndex = apkIndex(o) + } + // One verifier per platform list, each reading a pair once. + byPlatforms := map[string]func(context.Context, string, string) (string, error){} + verifiers := func(oo engine.Options, label string) func(context.Context, string, string) (string, error) { + k := strings.Join(oo.Platforms, ",") + "|" + label + if v, ok := byPlatforms[k]; ok { + return v + } + v := memoVerify(d.verifier(oo, label)) + byPlatforms[k] = v + return v + } + code := 0 + for _, dir := range dirs { + res, err := repo.Scan(ctx, dir, repo.Options{}) + 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 { + where := sk.File + if sk.Line > 0 { + where = fmt.Sprintf("%s:%d", sk.File, sk.Line) + } + fmt.Fprintf(stdout, "not checked %s %s; rescan to confirm once it can be read\n", repo.Printable(where), 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) + switch { + case f.Rule == repo.RuleHTTP2: + fmt.Fprintf(stdout, "note %s %s\n optional interim edit (not applied, not a fix):\n %s\n", where, repo.Printable(f.Message), repo.Printable(f.Interim)) + continue + case f.Pull != "": + if o.Offline { + fmt.Fprintf(stdout, "not checked %s %s (offline: the image was not read); rescan online to confirm\n", where, repo.Printable(f.Message)) + code = max(code, 1) + continue + } + for _, g := range d.pulled(ctx, f, o, pulls, &engine.Target{}) { + verb := "not fixed " + if g.Verdict == engine.Unknown { + verb = "not checked" + } + fmt.Fprintf(stdout, "%s %s %s\n %s\n", verb, where, repo.Printable(g.Message), repo.Printable(g.Fix)) + code = max(code, 1) + } + continue + case f.Status == knowledge.Unknown || f.Rule == repo.RuleNotChecked: + fmt.Fprintf(stdout, "not checked %s %s\n %s\n", where, repo.Printable(f.Message), repo.Printable(f.Fix)) + code = max(code, 1) + continue + case !f.Fixable: + fmt.Fprintf(stdout, "not fixed %s %s\n %s\n", where, repo.Printable(f.Message), repo.Printable(f.Fix)) + if f.Interim != "" { + fmt.Fprintf(stdout, " optional interim step (not applied, not a fix): %s\n", repo.Printable(f.Interim)) + } + code = max(code, 1) + continue + } + freg := reg + if !o.Offline { + freg.Verify = verifiers(verifyOptions(o, f)) + } + ch, err := repo.Plan(ctx, dir, f, freg, repo.Options{}) + 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 +} + +// memoVerify reads each current and target pair once in a fix run. +func memoVerify(v func(context.Context, string, string) (string, error)) func(context.Context, string, string) (string, error) { + type res struct { + digest string + err error + } + memo := map[string]res{} + return func(ctx context.Context, cur, target string) (string, error) { + k := cur + "\x00" + target + if r, ok := memo[k]; ok { + return r.digest, r.err + } + d, err := v(ctx, cur, target) + memo[k] = res{d, err} + return d, err + } +} + +// verifyOptions are the options a tag move is verified with: a FROM +// line's own --platform is the platform it builds, whatever the run's +// --platform says. +func verifyOptions(o engine.Options, f repo.Finding) (engine.Options, string) { + if f.Platform != "" && !strings.Contains(f.Platform, "$") { + o.Platforms = []string{f.Platform} + return o, "the FROM line's --platform" + } + return o, "the tree's --platform" +} + +// missingPlatform says that a target lacks a platform: one the current +// tag has, or one the tree's or the FROM line's --platform names. +func missingPlatform(target, platform, from string) string { + verb := "needs" + if !strings.Contains(from, "--platform") { + verb = "has" // the current tag + } + return fmt.Sprintf("%s is not published for %s, which %s %s (it may still be being published); try again later or change it by hand", target, platform, from, verb) +} + +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() +} diff --git a/detectors/nginxh2/repo_internal_test.go b/detectors/nginxh2/repo_internal_test.go new file mode 100644 index 0000000..b05ff50 --- /dev/null +++ b/detectors/nginxh2/repo_internal_test.go @@ -0,0 +1,166 @@ +package nginxh2 + +import ( + "context" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/knowledge" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/repo" + "github.com/DefectDojo/earlylight/internal/engine" + "github.com/DefectDojo/earlylight/internal/source" +) + +func pullFinding() repo.Finding { + return repo.Finding{Rule: repo.RuleNotChecked, File: "Dockerfile", Line: 1, Level: "note", Status: knowledge.Unknown, + Reason: "only reading the image says which nginx it holds", Message: "nginx:mainline is not judged", Pull: "nginx:mainline"} +} + +func TestFromPulled(t *testing.T) { + f := pullFinding() + // An image that could not be read is not checked. + out := fromPulled(f, &engine.Target{Error: "no such host"}) + if len(out) != 1 || out[0].Verdict != engine.Unknown || len(out[0].CVEs) != 2 { + t.Errorf("error: %+v", out) + } + // Read in part, nothing found: not checked, never clear. + out = fromPulled(f, &engine.Target{Platform: "linux/arm64", Skipped: []source.Skip{{Path: "/usr/sbin/nginx", Reason: "larger than --max-file-size"}}}) + if len(out) != 1 || out[0].Verdict != engine.Unknown { + t.Errorf("partial: %+v", out) + } + // Read in full, no nginx recognised in an nginx image: not checked. + if out = fromPulled(f, &engine.Target{Files: 10}); len(out) != 1 || out[0].Verdict != engine.Unknown { + t.Errorf("no nginx: %+v", out) + } + // Read in full, only fixed servers: nothing to report. + fixed := &engine.Target{Files: 10, Findings: []engine.Finding{{Kind: KindFlow, Path: "/usr/sbin/nginx", Verdict: engine.Fixed, Reason: "r"}}} + if out = fromPulled(f, fixed); len(out) != 0 { + t.Errorf("fixed: %+v", out) + } + // Read in part, only fixed servers: not checked, never cleared. + fixed.Skipped = []source.Skip{{Path: "/usr/lib/x", Reason: "unreadable"}} + if out = fromPulled(f, fixed); len(out) != 1 || out[0].Verdict != engine.Unknown { + t.Errorf("partial fixed: %+v", out) + } + // A vulnerable server is reported at the reference with the platform + // and digest; a fixed one is not. + it := &engine.Target{Platform: "linux/amd64", Digest: "sha256:abc", Findings: []engine.Finding{ + {Kind: KindFlow, Path: "/usr/sbin/nginx", Verdict: engine.Vulnerable, Message: "m", Facts: map[string]string{"version": "1.31.8"}}, + {Kind: KindReuse, Path: "/usr/sbin/nginx", Verdict: engine.Fixed, Reason: "r"}, + }} + out = fromPulled(f, it) + if len(out) != 1 || out[0].Kind != KindImage || out[0].Facts["platform"] != "linux/amd64" || out[0].Facts["digest"] != "sha256:abc" || out[0].Path != "Dockerfile" { + t.Errorf("vulnerable: %+v", out) + } +} + +func TestRepoFinding(t *testing.T) { + g := repoFinding(repo.Finding{Rule: repo.RuleHTTP2, File: "a.conf", Line: 3, Level: "note", Status: knowledge.NotAffected, Reason: "a setting", Message: "m"}) + if g.Verdict != engine.Inactive || g.Reason == "" || len(g.CVEs) != 0 { + t.Errorf("http2 note: %+v", g) + } + g = repoFinding(pullFinding()) + if g.Verdict != engine.Unknown || len(g.CVEs) != 2 { + t.Errorf("not checked: %+v", g) + } +} + +func TestRepoPlatforms(t *testing.T) { + if p := repoPlatforms(engine.Options{}, ""); len(p) != 2 { + t.Errorf("default %v", p) + } + if p := repoPlatforms(engine.Options{Platforms: []string{"linux/arm64"}}, ""); len(p) != 1 || p[0] != "linux/arm64" { + t.Errorf("--platform %v", p) + } + if p := repoPlatforms(engine.Options{}, "linux/amd64"); len(p) != 1 { + t.Errorf("FROM --platform %v", p) + } + if !containsPlatform([]string{"linux/arm64/v8"}, "linux/arm64") || containsPlatform([]string{"linux/arm/v7"}, "linux/arm64") { + t.Error("containsPlatform") + } + if registryRef("docker-archive:/x.tar") == nil || registryRef("rootfs:/x") == nil || registryRef("nginx:1.31.9") != nil { + t.Error("registryRef") + } +} + +// R3: a deployment that changes the image's command or configuration +// leaves the pulled image's exposure unknown. +func TestR3PulledDeployment(t *testing.T) { + f := pullFinding() + f.Props = map[string]string{"deployment": "the Compose service sets command and volumes"} + it := &engine.Target{Platform: "linux/amd64", Findings: []engine.Finding{ + {Kind: KindFlow, Path: "/usr/sbin/nginx", Verdict: engine.Vulnerable, Severity: "medium", Message: "m", Facts: map[string]string{"exposure": "not-exposed"}}, + {Kind: KindReuse, Path: "/usr/sbin/nginx", Verdict: engine.Vulnerable, Severity: "critical", Message: "m", Facts: map[string]string{"exposure": "exposed"}}, + }} + out := fromPulled(f, it) + if len(out) != 2 || out[0].Facts["exposure"] != "unknown" || out[0].Severity != "high" || out[1].Facts["exposure"] != "exposed" { + t.Errorf("%+v", out) + } +} + +// R8: a FROM line's own --platform is what fix verifies, whatever the +// run's --platform says. +func TestR8FromPlatform(t *testing.T) { + o := engine.Options{Platforms: []string{"linux/amd64", "linux/arm64"}} + if got := first(verifyOptions(o, repo.Finding{Platform: "linux/riscv64"})).Platforms; len(got) != 1 || got[0] != "linux/riscv64" { + t.Errorf("FROM --platform: %v", got) + } + if got := first(verifyOptions(o, repo.Finding{})).Platforms; len(got) != 2 { + t.Errorf("no FROM --platform: %v", got) + } + if got := first(verifyOptions(o, repo.Finding{Platform: "$BUILDPLATFORM"})).Platforms; len(got) != 2 { + t.Errorf("a variable platform: %v", got) + } +} + +// R13: fix reads each image pair once, however many references name it. +func TestR13VerifyOnce(t *testing.T) { + calls := 0 + v := memoVerify(func(_ context.Context, cur, target string) (string, error) { + calls++ + return "sha256:x", nil + }) + for i := 0; i < 3; i++ { + if d, err := v(context.Background(), "nginx:1.31.8", "nginx:1.31.9"); err != nil || d != "sha256:x" { + t.Fatal(d, err) + } + } + v(context.Background(), "nginx:1.30.6", "nginx:1.30.7") + if calls != 2 { + t.Errorf("%d reads, want 2", calls) + } +} + +// Verification nits: an unknown exposure drops the image's "http2: off"; +// the platforms a move must have are labelled by where they came from. +func TestVNits(t *testing.T) { + f := pullFinding() + f.Props = map[string]string{"deployment": "the deployment sets volumes"} + it := &engine.Target{Findings: []engine.Finding{{Kind: KindFlow, Path: "/usr/sbin/nginx", Verdict: engine.Vulnerable, Facts: map[string]string{"exposure": "not-exposed", "http2": "off"}}}} + if out := fromPulled(f, it); out[0].Facts["http2"] == "off" { + t.Errorf("http2 off kept: %+v", out[0].Facts) + } + _, from := verifyOptions(engine.Options{Platforms: []string{"linux/amd64"}}, repo.Finding{Platform: "linux/riscv64"}) + if from != "the FROM line's --platform" { + t.Errorf("FROM label: %q", from) + } + _, from = verifyOptions(engine.Options{Platforms: []string{"linux/amd64"}}, repo.Finding{}) + if from != "the tree's --platform" { + t.Errorf("--platform label: %q", from) + } +} + +// first is the options verifyOptions returns. +func first(o engine.Options, _ string) engine.Options { return o } + +// Round-3 nit: the sentence for a missing platform reads whole. +func TestWNitPlatformSentence(t *testing.T) { + _, from := verifyOptions(engine.Options{}, repo.Finding{Platform: "linux/riscv64"}) + got := missingPlatform("nginx:1.31.9", "linux/riscv64", from) + if got != "nginx:1.31.9 is not published for linux/riscv64, which the FROM line's --platform needs (it may still be being published); try again later or change it by hand" { + t.Errorf("%q", got) + } + if got := missingPlatform("nginx:1.31.9", "linux/386", "nginx:1.31.8"); !strings.Contains(got, "which nginx:1.31.8 has (") { + t.Errorf("%q", got) + } +} diff --git a/detectors/nginxh2/review_test.go b/detectors/nginxh2/review_test.go new file mode 100644 index 0000000..9d1b4cb --- /dev/null +++ b/detectors/nginxh2/review_test.go @@ -0,0 +1,92 @@ +package nginxh2 + +import ( + "os" + "path/filepath" + "testing" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/conf" + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngxtest" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// Cases from the independent review: each read as "not exposed" before. + +func TestTemplateVariables(t *testing.T) { + kept := map[string][]byte{ + "/etc/nginx/nginx.conf": []byte("http { include /etc/nginx/conf.d/*.conf; }"), + "/etc/nginx/templates/default.conf.template": []byte("server { listen 443 ssl ${NGINX_H2}; location / { proxy_pass http://$host; } }"), + } + for _, c := range []struct { + env []string + want conf.State + }{ + {[]string{"NGINX_H2=http2"}, conf.Exposed}, + {nil, conf.Unknown}, + {[]string{"NGINX_H2="}, conf.NotExposed}, + } { + s := &confSource{kept: kept} + s.templates(c.env) + e := conf.Analyze(conf.Load(s, "/etc/nginx/nginx.conf", nil)) + if e.Flow != c.want { + t.Errorf("env %v: %s (%v)", c.env, e.Flow, e.Unread) + } + } +} + +func TestBelowRootSymlinkedSite(t *testing.T) { + root := t.TempDir() + write(t, root, map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/etc/nginx/nginx.conf": []byte("http { include /etc/nginx/sites-enabled/*; }"), + "/etc/nginx/sites-available/default": []byte("server { listen 443 ssl http2; }"), + }) + os.MkdirAll(filepath.Join(root, "etc/nginx/sites-enabled"), 0o755) + if err := os.Symlink("../sites-available/default", filepath.Join(root, "etc/nginx/sites-enabled/default")); err != nil { + t.Fatal(err) + } + tg := engine.ScanFS([]engine.Detector{&Detector{}}, filepath.Join(root, "usr/sbin"), engine.Options{SystemRoot: root}) + if f := find(tg, KindFlow, "/usr/sbin/nginx"); f == nil || f.Facts["exposure"] != "exposed" { + t.Errorf("%+v", f) + } +} + +func TestSymlinkedIncludeDir(t *testing.T) { + root := t.TempDir() + write(t, root, map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/etc/nginx/nginx.conf": []byte("http { include /etc/nginx/vhosts/*; server { listen 80; } }"), + "/data/vhosts/site": []byte("server { listen 443 ssl http2; }"), + }) + if err := os.Symlink("/data/vhosts", filepath.Join(root, "etc/nginx/vhosts")); err != nil { + t.Fatal(err) + } + tg := engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true}) + if f := find(tg, KindFlow, "/usr/sbin/nginx"); f == nil || f.Facts["exposure"] != "unknown" { + t.Errorf("a directory linked out of the kept ones: %+v", f) + } +} + +func TestGlobSemantics(t *testing.T) { + tg := scanFS(t, map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/etc/nginx/nginx.conf": []byte("http { include /etc/nginx/conf.d/[!_]*.conf; }"), + "/etc/nginx/conf.d/site.conf": []byte("server { listen 443 ssl http2; }"), + "/etc/nginx/conf.d/.hidden.conf": []byte("server { listen 8443 ssl http2; }"), + }, engine.Options{}) + f := find(tg, KindFlow, "/usr/sbin/nginx") + if f == nil || f.Facts["exposure"] != "exposed" || f.Facts["http2_where"] != "/etc/nginx/conf.d/site.conf:1" { + t.Errorf("%+v", f) + } + for p, want := range map[[2]string]bool{ + {"/a/[!_]*.conf", "/a/x.conf"}: true, {"/a/[!_]*.conf", "/a/_x.conf"}: false, {"/a/*.conf", "/a/.x.conf"}: false, + {"/a/.*.conf", "/a/.x.conf"}: true, {"/a/*", "/a/b/c"}: false, + } { + if got, _ := globMatch(p[0], p[1]); got != want { + t.Errorf("globMatch(%s, %s) = %v", p[0], p[1], got) + } + } + if _, err := globMatch("/a/[", "/a/x"); err == nil { + t.Error("a bad pattern was accepted") + } +} diff --git a/detectors/nginxh2/round2_test.go b/detectors/nginxh2/round2_test.go new file mode 100644 index 0000000..10a8cd0 --- /dev/null +++ b/detectors/nginxh2/round2_test.go @@ -0,0 +1,120 @@ +package nginxh2 + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "os" + "path/filepath" + "testing" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngxtest" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// Findings of the second independent review (job 1118-111751-8721), each +// a case that read as "not exposed" or cleared where it should not. + +// R1: an include the walk could not read (mode 000), scanned at a root, +// leaves exposure unknown: the engine's "not scanned" list says so. +func TestR1UnreadableIncludeAtRoot(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root reads mode 000 files") + } + for _, unreadable := range []string{"etc/nginx/conf.d/a.conf", "etc/nginx/conf.d"} { + root := t.TempDir() + write(t, root, map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/etc/nginx/nginx.conf": []byte("http { include /etc/nginx/conf.d/*.conf; server { listen 80; } }"), + "/etc/nginx/conf.d/a.conf": []byte("server { listen 443 ssl http2; }"), + }) + p := filepath.Join(root, unreadable) + if err := os.Chmod(p, 0); err != nil { + t.Fatal(err) + } + tg := engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true}) + os.Chmod(p, 0o755) + f := find(tg, KindFlow, "/usr/sbin/nginx") + if f == nil || f.Facts["exposure"] != "unknown" { + t.Errorf("%s unreadable: %+v", unreadable, f) + } + } +} + +// R2: a host's nginx is judged with the command its service unit runs, +// drop-ins applied. +func TestR2SystemdUnit(t *testing.T) { + base := map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/etc/nginx/nginx.conf": []byte("http { server { listen 80; } }"), + "/etc/nginx/h2.conf": []byte("http { server { listen 443 ssl http2; } }"), + "/lib/systemd/system/nginx.service": []byte("[Service]\nExecStartPre=/usr/sbin/nginx -t -q -g 'daemon on; master_process on;'\nExecStart=/usr/sbin/nginx -g 'daemon on; master_process on;'\n"), + } + tg := scanFS(t, base, engine.Options{}) + if f := find(tg, KindFlow, "/usr/sbin/nginx"); f == nil || f.Facts["exposure"] != "not-exposed" || f.Facts["config_from"] != "the binary's default" { + t.Errorf("unit: %+v", f) + } + base["/etc/systemd/system/nginx.service.d/override.conf"] = []byte("[Service]\nExecStart=\nExecStart=/usr/sbin/nginx -c /etc/nginx/h2.conf -g 'daemon on;'\n") + tg = scanFS(t, base, engine.Options{}) + if f := find(tg, KindFlow, "/usr/sbin/nginx"); f == nil || f.Facts["exposure"] != "exposed" { + t.Errorf("drop-in: %+v", f) + } + delete(base, "/etc/systemd/system/nginx.service.d/override.conf") + delete(base, "/lib/systemd/system/nginx.service") + tg = scanFS(t, base, engine.Options{}) + if f := find(tg, KindFlow, "/usr/sbin/nginx"); f == nil || f.Facts["exposure"] != "unknown" { + t.Errorf("no unit: %+v", f) + } +} + +// TestR2EntrypointScripts gave way to TestV1EntrypointContent: scripts +// are trusted by content, never by name. + +// R10: POSIX classes in an include glob match as glob(3) matches them. +func TestR10PosixClasses(t *testing.T) { + for p, want := range map[[2]string]bool{ + {"/a/[[:digit:]]*.conf", "/a/10-site.conf"}: true, {"/a/[[:digit:]]*.conf", "/a/site.conf"}: false, + {"/a/[[:alpha:]]*", "/a/x"}: true, {"/a/[![:digit:]]*", "/a/1x"}: false, {"/a/[[:alnum:]_]*", "/a/_x"}: true, + } { + got, err := globMatch(p[0], p[1]) + if err != nil || got != want { + t.Errorf("globMatch(%s, %s) = %v %v", p[0], p[1], got, err) + } + } + if _, err := globMatch("/a/[[:bogus:]]", "/a/x"); err == nil { + t.Error("an unknown class was accepted") + } +} + +// R11: a site enabled through a hard link (an image layer's tar link) +// is read. +func TestR11HardLinkedSite(t *testing.T) { + s := &confSource{kept: map[string][]byte{"/etc/nginx/sites-available/app": []byte("server { listen 443 ssl http2; }")}, + hardlinks: map[string]string{"/etc/nginx/sites-enabled/app": "/etc/nginx/sites-available/app"}} + if b, ok, _ := s.Read("/etc/nginx/sites-enabled/app"); !ok || len(b) == 0 { + t.Error("hard link not read") + } + if ms, _ := s.Glob("/etc/nginx/sites-enabled/*"); len(ms) != 1 { + t.Errorf("hard link not matched: %v", ms) + } +} + +// R14: the nginx version is read from an APKINDEX.tar.gz. +func TestR14IndexReader(t *testing.T) { + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + body := "P:musl\nV:1.2.5-r0\n\nP:nginx\nV:1.30.7-r0\no:nginx\n\n" + tw.WriteHeader(&tar.Header{Name: "APKINDEX", Mode: 0o644, Size: int64(len(body))}) + tw.Write([]byte(body)) + tw.Close() + gz.Close() + v, err := nginxInIndex(&buf) + if err != nil || v != "1.30.7-r0" { + t.Errorf("%q %v", v, err) + } + if _, err := apkIndex(engine.Options{})(context.Background(), "3.24; rm"); err == nil { + t.Error("a malformed branch was fetched") + } +} diff --git a/detectors/nginxh2/round3_test.go b/detectors/nginxh2/round3_test.go new file mode 100644 index 0000000..4d746c7 --- /dev/null +++ b/detectors/nginxh2/round3_test.go @@ -0,0 +1,162 @@ +package nginxh2 + +import ( + "os" + "path/filepath" + "strconv" + "testing" + "time" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngxtest" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// Findings of the round-2 verification (job 1118-150713-c2aa). + +func official(t testing.TB, name string) []byte { + t.Helper() + b, err := os.ReadFile(filepath.Join("testdata", "entrypoint", name)) + if err != nil { + t.Fatal(err) + } + return b +} + +// V1: an entrypoint is trusted by its content, never its name, and every +// /docker-entrypoint.d script it runs must be read and official. +func TestV1EntrypointContent(t *testing.T) { + ep := official(t, "docker-entrypoint.sh") + scripts := map[string][]byte{} + for _, n := range []string{"10-listen-on-ipv6-by-default.sh", "15-local-resolvers.envsh", "20-envsubst-on-templates.sh", "30-tune-worker-processes.sh"} { + scripts["/docker-entrypoint.d/"+n] = official(t, n) + } + mk := func() *scan { + s := &scan{kind: engine.Image, db: map[string][]byte{}, scripts: map[string][]byte{"/docker-entrypoint.sh": ep}} + for p, b := range scripts { + s.scripts[p] = b + } + return s + } + cases := []struct { + name string + edit func(s *scan, links map[string]string) + word string + trust bool + }{ + {"official", func(*scan, map[string]string) {}, "/docker-entrypoint.sh", true}, + {"same name, other content", func(s *scan, _ map[string]string) { + s.scripts["/docker-entrypoint.sh"] = []byte("#!/bin/sh\nsed -i 's/listen 80;/listen 443 ssl http2;/' /etc/nginx/conf.d/default.conf\nexec \"$@\"\n") + }, "/docker-entrypoint.sh", false}, + {"other path, not read", func(*scan, map[string]string) {}, "/usr/local/bin/docker-entrypoint.sh", false}, + {"a custom script", func(s *scan, _ map[string]string) { + s.scripts["/docker-entrypoint.d/40-h2.sh"] = []byte("#!/bin/sh\necho\n") + }, "/docker-entrypoint.sh", false}, + {"an official name, other content", func(s *scan, _ map[string]string) { + s.scripts["/docker-entrypoint.d/30-tune-worker-processes.sh"] = []byte("#!/bin/sh\nsed -i s/80/443/ /etc/nginx/conf.d/default.conf\n") + }, "/docker-entrypoint.sh", false}, + {"a symbolic link to a script", func(_ *scan, l map[string]string) { l["/docker-entrypoint.d/40-h2.sh"] = "/opt/h2.sh" }, "/docker-entrypoint.sh", false}, + {"a script not read", func(s *scan, _ map[string]string) { + s.unread = map[string]string{"/docker-entrypoint.d/50-x.sh": "permission denied"} + }, "/docker-entrypoint.sh", false}, + {"a symbolic link to the official entrypoint", func(_ *scan, l map[string]string) { l["/usr/local/bin/docker-entrypoint.sh"] = "/docker-entrypoint.sh" }, "/usr/local/bin/docker-entrypoint.sh", true}, + } + for _, c := range cases { + s := mk() + links := map[string]string{} + c.edit(s, links) + ok, why := s.commands(links, nil, "/", nil, nil).launcher(c.word) + if ok != c.trust { + t.Errorf("%s: trusted %v (%s), want %v", c.name, ok, why, c.trust) + } + } +} + +// V2: a host's systemd unit is read with its drop-ins and overrides, +// wherever they are, and anything not read or run first is unknown. +func TestV2Systemd(t *testing.T) { + base := func() map[string][]byte { + return map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/etc/nginx/nginx.conf": []byte("http { server { listen 80; } }"), + "/etc/nginx/h2.conf": []byte("http { server { listen 443 ssl http2; } }"), + "/usr/lib/systemd/system/nginx.service": []byte("[Service]\nExecStart=/usr/sbin/nginx -g 'daemon on;'\n"), + } + } + exposure := func(tg *engine.Target) string { + if f := find(tg, KindFlow, "/usr/sbin/nginx"); f != nil { + return f.Facts["exposure"] + } + return "no finding" + } + // A drop-in outside the walk (a scan of /usr below the root). + root := t.TempDir() + files := base() + files["/etc/systemd/system/nginx.service.d/override.conf"] = []byte("[Service]\nExecStart=\nExecStart=/usr/sbin/nginx -c /etc/nginx/h2.conf\n") + write(t, root, files) + if got := exposure(engine.ScanFS([]engine.Detector{&Detector{}}, filepath.Join(root, "usr"), engine.Options{SystemRoot: root})); got != "exposed" { + t.Errorf("drop-in outside the walk: %s", got) + } + // /etc/systemd/system/nginx.service links to a unit elsewhere. + root = t.TempDir() + files = base() + files["/opt/units/nginx.service"] = []byte("[Service]\nExecStart=/usr/sbin/nginx -c /etc/nginx/h2.conf\n") + write(t, root, files) + os.MkdirAll(filepath.Join(root, "etc/systemd/system"), 0o755) + if err := os.Symlink("/opt/units/nginx.service", filepath.Join(root, "etc/systemd/system/nginx.service")); err != nil { + t.Fatal(err) + } + if got := exposure(engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true})); got != "exposed" { + t.Errorf("linked override: %s", got) + } + // A script run first. + files = base() + files["/usr/lib/systemd/system/nginx.service"] = []byte("[Service]\nExecStartPre=/usr/local/bin/gen-conf.sh\nExecStartPre=/usr/sbin/nginx -t -q\nExecStart=/usr/sbin/nginx\n") + if got := exposure(scanFS(t, files, engine.Options{})); got != "unknown" { + t.Errorf("ExecStartPre script: %s", got) + } + // nginx -t first is fine. + files["/usr/lib/systemd/system/nginx.service"] = []byte("[Service]\nExecStartPre=/usr/sbin/nginx -t -q -g 'daemon on;'\nExecStart=/usr/sbin/nginx\n") + if got := exposure(scanFS(t, files, engine.Options{})); got != "not-exposed" { + t.Errorf("nginx -t first: %s", got) + } +} + +// V2: an override that cannot be read leaves exposure unknown. +func TestV2SystemdUnreadable(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root reads mode 000 files") + } + for _, p := range []string{"etc/systemd/system/nginx.service.d", "etc/systemd/system/nginx.service.d/override.conf", "etc/systemd/system/nginx.service"} { + root := t.TempDir() + write(t, root, map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/etc/nginx/nginx.conf": []byte("http { server { listen 80; } }"), + "/usr/lib/systemd/system/nginx.service": []byte("[Service]\nExecStart=/usr/sbin/nginx\n"), + "/etc/systemd/system/nginx.service": []byte("[Service]\nExecStart=/usr/sbin/nginx\n"), + "/etc/systemd/system/nginx.service.d/override.conf": []byte("[Service]\nExecStart=\nExecStart=/usr/sbin/nginx -c /x\n"), + }) + full := filepath.Join(root, p) + os.Chmod(full, 0) + tg := engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true}) + os.Chmod(full, 0o755) + if f := find(tg, KindFlow, "/usr/sbin/nginx"); f == nil || f.Facts["exposure"] != "unknown" { + t.Errorf("%s unreadable: %+v", p, f) + } + } +} + +// V7: glob includes do not each walk every link of the target. +func TestV7GlobWork(t *testing.T) { + links := map[string]string{} + for i := 0; i < 30000; i++ { + links["/usr/share/x/l"+strconv.Itoa(i)] = "/elsewhere" + } + s := &confSource{kept: map[string][]byte{"/etc/nginx/conf.d/a.conf": []byte("x")}, links: links} + start := time.Now() + for i := 0; i < 2000; i++ { + s.Glob("/etc/nginx/conf.d/*.conf") + } + if d := time.Since(start); d > 2*time.Second { + t.Errorf("2,000 globs over 30,000 links took %s", d) + } +} diff --git a/detectors/nginxh2/round4_test.go b/detectors/nginxh2/round4_test.go new file mode 100644 index 0000000..60ccf78 --- /dev/null +++ b/detectors/nginxh2/round4_test.go @@ -0,0 +1,169 @@ +package nginxh2 + +import ( + "strconv" + "strings" + "testing" + "time" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngxtest" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// Findings of the round-3 verification (job 1118-150713-c2aa). + +// W1: a relative command word is resolved as the runtime resolves it: +// "./x" against the image's working directory, "x" through its PATH. +func TestW1RelativeEntrypoint(t *testing.T) { + ep := official(t, "docker-entrypoint.sh") + custom := []byte("#!/bin/sh\nsed -i 's/listen 80;/listen 443 ssl http2;/' /etc/nginx/conf.d/default.conf\nexec \"$@\"\n") + s := &scan{kind: engine.Image, db: map[string][]byte{}, scripts: map[string][]byte{ + "/docker-entrypoint.sh": ep, "/app/docker-entrypoint.sh": custom, "/usr/local/bin/docker-entrypoint.sh": custom, "/opt/bin/ok.sh": ep, + }} + exists := func(p string) bool { _, ok := s.scripts[p]; return ok } + for _, c := range []struct { + word, dir string + env []string + trust bool + }{ + {"/docker-entrypoint.sh", "/app", nil, true}, + {"./docker-entrypoint.sh", "/app", nil, false}, + {"./docker-entrypoint.sh", "/", nil, true}, + {"docker-entrypoint.sh", "/", nil, false}, // the default PATH finds /usr/local/bin first + {"docker-entrypoint.sh", "/", []string{"PATH=/opt/none:/"}, true}, + {"ok.sh", "/", []string{"PATH=/opt/bin"}, true}, + {"missing.sh", "/", nil, false}, + {"bin/ok.sh", "/opt", nil, true}, + } { + ok, why := s.commands(nil, nil, c.dir, c.env, exists).launcher(c.word) + if ok != c.trust { + t.Errorf("%s in %s with %v: trusted %v (%s), want %v", c.word, c.dir, c.env, ok, why, c.trust) + } + } +} + +// W2: a symbolic link to a directory inside /docker-entrypoint.d is +// descended into, as find -follow does: what it holds is run. +func TestW2LinkedDirectory(t *testing.T) { + ep := official(t, "docker-entrypoint.sh") + for _, c := range []struct { + name string + scripts map[string][]byte + unread map[string]string + trust bool + }{ + {"a script in the linked directory", map[string][]byte{"/opt/scripts/40-h2.sh": []byte("#!/bin/sh\nsed -i x\n")}, nil, false}, + {"an envsh in it", map[string][]byte{"/opt/scripts/sub/a.envsh": []byte("#!/bin/sh\nexport X=1\n")}, nil, false}, + // A directory link out of /docker-entrypoint.d is unknown whatever + // it holds: the scan does not keep every file there (round 5). + {"an official script in it", map[string][]byte{"/opt/scripts/30-tune-worker-processes.sh": official(t, "30-tune-worker-processes.sh")}, nil, false}, + {"something there not read", nil, map[string]string{"/opt/scripts/50.sh": "permission denied"}, false}, + {"a link to nothing read", nil, nil, false}, + } { + s := &scan{kind: engine.Image, db: map[string][]byte{}, scripts: map[string][]byte{"/docker-entrypoint.sh": ep}, unread: c.unread} + for p, b := range c.scripts { + s.scripts[p] = b + } + links := map[string]string{"/docker-entrypoint.d/extra": "/opt/scripts"} + ok, why := s.commands(links, nil, "/", nil, nil).launcher("/docker-entrypoint.sh") + if ok != c.trust { + t.Errorf("%s: trusted %v (%s), want %v", c.name, ok, why, c.trust) + } + } +} + +// W3 and W4: a unit's Environment= and EnvironmentFile= are applied to +// ExecStart (nginx.org's pkg-oss unit), and commands run around the start +// that cannot change the configuration (rm -f of a pid file, nginx -t) do +// not void "not exposed". +func TestW3W4UnitEnvironment(t *testing.T) { + pkgOSS := "[Service]\nType=forking\nPIDFile=/run/nginx.pid\nEnvironment=\"cmdopts=\"\nEnvironment=\"conffile=/etc/nginx/nginx.conf\"\nEnvironmentFile=-/etc/sysconfig/nginx\nExecStart=/usr/sbin/nginx -c ${conffile} $cmdopts\n" + files := func(unit string) map[string][]byte { + return map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/etc/nginx/nginx.conf": []byte("http { include /etc/nginx/conf.d/*.conf; }"), + "/etc/nginx/conf.d/a.conf": []byte("server { listen 443 ssl http2; location / { proxy_pass http://u; } }"), + "/etc/nginx/off.conf": []byte("http { server { listen 80; } }"), + "/usr/lib/systemd/system/nginx.service": []byte(unit), + } + } + exposure := func(fs map[string][]byte) string { + if f := find(scanFS(t, fs, engine.Options{}), KindFlow, "/usr/sbin/nginx"); f != nil { + return f.Facts["exposure"] + " " + f.Facts["config"] + } + return "no finding" + } + if got := exposure(files(pkgOSS)); got != "exposed /etc/nginx/nginx.conf" { + t.Errorf("pkg-oss unit: %s", got) + } + // The EnvironmentFile overrides the unit's value. + fs := files(pkgOSS) + fs["/etc/sysconfig/nginx"] = []byte("# nginx options\nconffile=/etc/nginx/off.conf\n") + if got := exposure(fs); got != "not-exposed /etc/nginx/off.conf" { + t.Errorf("EnvironmentFile: %s", got) + } + // A required EnvironmentFile that is not there: unknown (with the + // default configuration off, so nothing shows HTTP/2 on). + fs = files(strings.Replace(pkgOSS, "EnvironmentFile=-", "EnvironmentFile=", 1)) + fs["/etc/nginx/conf.d/a.conf"] = []byte("server { listen 80; }") + if got := exposure(fs); !strings.HasPrefix(got, "unknown") { + t.Errorf("missing EnvironmentFile: %s", got) + } + // A harmless ExecStartPre on a not-exposed host. + fs = files("[Service]\nPIDFile=/run/nginx.pid\nExecStartPre=/usr/bin/rm -f /run/nginx.pid\nExecStartPre=/usr/sbin/nginx -t\nExecStart=/usr/sbin/nginx -c /etc/nginx/off.conf\n") + if got := exposure(fs); got != "not-exposed /etc/nginx/off.conf" { + t.Errorf("rm -f pid then nginx -t: %s", got) + } + // rm of anything else still voids it. + fs = files("[Service]\nExecStartPre=/usr/bin/rm -f /etc/nginx/conf.d/a.conf\nExecStart=/usr/sbin/nginx -c /etc/nginx/off.conf\n") + fs["/etc/nginx/conf.d/a.conf"] = []byte("server { listen 80; }") + if got := exposure(fs); !strings.HasPrefix(got, "unknown") { + t.Errorf("rm of a configuration file: %s", got) + } + // An optional EnvironmentFile outside what the scan reads whole. + fs = files(strings.Replace(pkgOSS, "/etc/sysconfig/nginx", "/opt/env/nginx-env", 1)) + fs["/etc/nginx/conf.d/a.conf"] = []byte("server { listen 80; }") + if got := exposure(fs); !strings.HasPrefix(got, "unknown") { + t.Errorf("an optional file the scan does not read: %s", got) + } +} + +// W6: reading many units does not walk every link of the target per +// unit directory. +func TestW6UnitIndex(t *testing.T) { + db := map[string][]byte{} + for i := 0; i < 3000; i++ { + db["/usr/lib/systemd/system/u"+strconv.Itoa(i)+".service"] = []byte("[Service]\nExecStart=/bin/true\n") + } + links := map[string]string{} + for i := 0; i < 150000; i++ { + links["/usr/share/x/l"+strconv.Itoa(i)] = "/y" + } + s := &scan{kind: engine.Filesystem, db: db} + start := time.Now() + s.systemdStarts(&confSource{links: links}) + if d := time.Since(start); d > 3*time.Second { + t.Errorf("3,000 units with 150,000 links took %s", d) + } +} + +// W7: below a system root, a glob with a wildcard in its directory part +// reads the directories from disk, as --as-root does. +func TestW7WildcardBelowRoot(t *testing.T) { + root := t.TempDir() + write(t, root, map[string][]byte{ + "/opt/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/opt/app/conf/nginx.conf": []byte("http { include /opt/app/conf/vhosts/*/site.conf; }"), + "/opt/app/conf/vhosts/a/site.conf": []byte("server { listen 80; }"), + "/opt/app/conf/vhosts/b/site.conf": []byte("server { listen 443 ssl http2; }"), + "/etc/systemd/system/nginx.service": []byte("[Service]\nExecStart=/opt/sbin/nginx -c /opt/app/conf/nginx.conf\n"), + }) + for name, tg := range map[string]*engine.Target{ + "--as-root": engine.ScanFS([]engine.Detector{&Detector{}}, root, engine.Options{AsRoot: true}), + "--root": engine.ScanFS([]engine.Detector{&Detector{}}, root+"/opt", engine.Options{SystemRoot: root}), + } { + if f := find(tg, KindFlow, "/opt/sbin/nginx"); f == nil || f.Facts["exposure"] != "exposed" { + t.Errorf("%s: %+v", name, f) + } + } +} diff --git a/detectors/nginxh2/round5_test.go b/detectors/nginxh2/round5_test.go new file mode 100644 index 0000000..922ec5a --- /dev/null +++ b/detectors/nginxh2/round5_test.go @@ -0,0 +1,390 @@ +package nginxh2 + +import ( + "os" + "path" + "path/filepath" + "sort" + "strconv" + "testing" + "time" + + "github.com/DefectDojo/earlylight/detectors/nginxh2/internal/ngxtest" + "github.com/DefectDojo/earlylight/internal/archive" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// Findings of the round-4 verification (job 1118-184956-3834), and the +// rule that closes them: "not exposed" only when the start command +// resolves to the binary judged, the entrypoint and everything it runs +// were read and are official, and every configuration file was read. + +// fakeImage is an image target for Visit and Finish. +type fakeImage struct { + files map[string][]byte + links map[string]string + unread map[string]string + cmd, env []string + workdir string + seen map[string]bool +} + +func (f *fakeImage) Kind() engine.TargetKind { return engine.Image } +func (f *fakeImage) Exists(p string) bool { return f.seen[p] } +func (f *fakeImage) Env() []string { return f.env } +func (f *fakeImage) Command() []string { return f.cmd } +func (f *fakeImage) Aliases(p string) []string { + return []string{p} +} +func (f *fakeImage) Links() (map[string]string, map[string]string) { return f.links, nil } +func (f *fakeImage) SystemRoot() string { return "" } +func (f *fakeImage) Problem(string) {} +func (f *fakeImage) Annotate(string, any) {} +func (f *fakeImage) WorkingDir() string { return f.workdir } + +// run scans the image as the engine would: files the detector wants are +// read, the not-scanned records are handed over, then Finish. +func (f *fakeImage) run(t *testing.T) []engine.Finding { + t.Helper() + d := &Detector{} + s := d.NewScan(engine.Image) + f.seen = map[string]bool{} + var ps []string + for p := range f.files { + ps = append(ps, p) + } + sort.Strings(ps) + for _, p := range ps { + b := f.files[p] + head := b + if len(head) > 4096 { + head = head[:4096] + } + exe := archive.IsExecutable(head) + if !d.Wants(p, head, exe) { + continue + } + f.seen[p] = true + s.Visit(engine.File{Path: p, Data: b, Executable: exe}) + } + var sk []engine.Skip + for p, why := range f.unread { + sk = append(sk, engine.Skip{Path: p, Reason: why}) + } + s.(engine.SkipVisitor).VisitSkips(sk) + return s.Finish(f) +} + +func (f *fakeImage) exposure(t *testing.T) string { + for _, x := range f.run(t) { + if x.Kind == KindFlow && x.Path == "/usr/sbin/nginx" { + return x.Facts["exposure"] + } + } + return "no finding" +} + +// officialImage is nginx:1.31.8's layout: the official entrypoint and its +// four scripts, a default site on port 80. +func officialImage(t *testing.T) *fakeImage { + files := map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/etc/nginx/nginx.conf": []byte("events {} http { include /etc/nginx/conf.d/*.conf; }"), + "/etc/nginx/conf.d/default.conf": []byte("server { listen 80; location / { root /usr/share/nginx/html; } }"), + "/docker-entrypoint.sh": official(t, "docker-entrypoint.sh"), + } + for _, n := range []string{"10-listen-on-ipv6-by-default.sh", "15-local-resolvers.envsh", "20-envsubst-on-templates.sh", "30-tune-worker-processes.sh"} { + files["/docker-entrypoint.d/"+n] = official(t, n) + } + return &fakeImage{files: files, links: map[string]string{}, unread: map[string]string{}, + cmd: []string{"/docker-entrypoint.sh", "nginx", "-g", "daemon off;"}, env: []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}} +} + +var elf = []byte("\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00binary") + +func TestX0OfficialLayout(t *testing.T) { + if got := officialImage(t).exposure(t); got != "not-exposed" { + t.Fatalf("the official layout: %s", got) + } +} + +// X1: everything reachable from /docker-entrypoint.d must be read and +// official; a directory link out of it is unknown. +func TestX1EntrypointCompleteness(t *testing.T) { + for name, edit := range map[string]func(*fakeImage){ + "a directory link out, a script without #!": func(f *fakeImage) { + f.links["/docker-entrypoint.d/extra"] = "/opt/scripts" + f.files["/opt/scripts/30-tune-worker-processes.sh"] = official(t, "30-tune-worker-processes.sh") + f.files["/opt/scripts/40-h2.envsh"] = []byte("sed -i 's/listen 80;/listen 80 http2;/' /etc/nginx/conf.d/default.conf\n") + }, + "an envsh without #!": func(f *fakeImage) { f.files["/docker-entrypoint.d/40-h2.envsh"] = []byte("sed -i x\n") }, + "an ELF file": func(f *fakeImage) { f.files["/docker-entrypoint.d/40-h2.sh"] = elf }, + "any other file": func(f *fakeImage) { f.files["/docker-entrypoint.d/README"] = []byte("notes\n") }, + "a large script": func(f *fakeImage) { + f.files["/docker-entrypoint.d/40.sh"] = append([]byte("#!/bin/sh\n"), make([]byte, 300<<10)...) + }, + } { + f := officialImage(t) + edit(f) + if got := f.exposure(t); got != "unknown" { + t.Errorf("%s: %s", name, got) + } + } +} + +// X2, X3: the word that starts nginx must resolve to the binary judged, +// with no env indirection. +func TestX2X3StartWord(t *testing.T) { + for name, edit := range map[string]func(*fakeImage){ + "a wrapper named nginx on PATH": func(f *fakeImage) { + f.files["/usr/local/bin/nginx"] = []byte("#!/bin/sh\nsed -i x /etc/nginx/nginx.conf\nexec /usr/sbin/nginx \"$@\"\n") + }, + "./nginx in the working directory": func(f *fakeImage) { + f.workdir = "/app" + f.files["/app/nginx"] = []byte("#!/bin/sh\nexec /usr/sbin/nginx \"$@\"\n") + f.cmd = []string{"/docker-entrypoint.sh", "./nginx", "-g", "daemon off;"} + }, + "env PATH=": func(f *fakeImage) { + f.cmd = []string{"env", "PATH=/app:/usr/sbin:/usr/bin:/bin", "/docker-entrypoint.sh", "nginx"} + }, + "env --chdir": func(f *fakeImage) { + f.cmd = []string{"env", "--chdir=/", "./docker-entrypoint.sh", "nginx"} + }, + "a linked PATH entry first": func(f *fakeImage) { + f.env = []string{"PATH=/custom:/usr/sbin:/"} + f.links["/custom/docker-entrypoint.sh"] = "/opt/bin/wrapper" + f.files["/opt/bin/wrapper"] = elf + f.cmd = []string{"docker-entrypoint.sh", "nginx"} + }, + "a nginx word that resolves to nothing read": func(f *fakeImage) { + f.env = []string{"PATH=/nowhere"} + }, + } { + f := officialImage(t) + edit(f) + if got := f.exposure(t); got != "unknown" { + t.Errorf("%s: %s", name, got) + } + } + // The binary itself, by absolute path or through PATH, is fine. + f := officialImage(t) + f.cmd = []string{"/usr/sbin/nginx", "-g", "daemon off;"} + if got := f.exposure(t); got != "not-exposed" { + t.Errorf("the binary by path: %s", got) + } +} + +// X4: templates are written only when the official entrypoint runs and +// is given nginx or nginx-debug. +func TestX4Templates(t *testing.T) { + setup := func() *fakeImage { + f := officialImage(t) + f.files["/etc/nginx/conf.d/default.conf"] = []byte("server { listen 443 ssl http2; location / { proxy_pass http://u; } }") + f.files["/etc/nginx/templates/default.conf.template"] = []byte("server { listen 80; }") + return f + } + if got := setup().exposure(t); got != "not-exposed" { + t.Errorf("the entrypoint writes the template over default.conf: %s", got) + } + for name, cmd := range map[string][]string{ + "nginx directly": {"/usr/sbin/nginx", "-g", "daemon off;"}, + "through tini": {"tini", "--", "nginx", "-g", "daemon off;"}, + "sh -c exec nginx": {"sh", "-c", "exec nginx -g 'daemon off;'"}, + "entrypoint, not $1": {"/docker-entrypoint.sh", "/usr/sbin/nginx", "-g", "daemon off;"}, + } { + f := setup() + f.cmd = cmd + if got := f.exposure(t); got != "exposed" { + t.Errorf("%s: %s (the template is not written)", name, got) + } + } + _ = path.Base +} + +// X4: templates the scan cannot apply exactly leave exposure unknown: a +// template directory outside what the scan reads whole, or a filter on +// the variables put in. +func TestX4TemplateLimits(t *testing.T) { + for name, env := range map[string][]string{ + "a template directory elsewhere": {"NGINX_ENVSUBST_TEMPLATE_DIR=/srv/tpl"}, + "a variable filter": {"NGINX_ENVSUBST_FILTER=^NGINX_"}, + } { + f := officialImage(t) + f.env = append(f.env, env...) + f.files["/etc/nginx/templates/default.conf.template"] = []byte("server { listen 80; }") + if got := f.exposure(t); got != "unknown" { + t.Errorf("%s: %s", name, got) + } + } +} + +// X5: below --root, a wildcard-directory glob keeps links (Read decides +// them inside the root) and reads a permission error as incomplete. +func TestX5DiskGlobLinks(t *testing.T) { + root := t.TempDir() + write(t, root, map[string][]byte{ + "/opt/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/opt/app/conf/nginx.conf": []byte("http { include /opt/app/conf/vhosts/*/site.conf; server { listen 80; } }"), + "/opt/app/conf/vhosts/a/site.conf": []byte("server { listen 80; }"), + "/srv/sites/b.conf": []byte("server { listen 443 ssl http2; }"), + "/etc/systemd/system/nginx.service": []byte("[Service]\nExecStart=/opt/sbin/nginx -c /opt/app/conf/nginx.conf\n"), + }) + os.MkdirAll(filepath.Join(root, "opt/app/conf/vhosts/b"), 0o755) + if err := os.Symlink("/srv/sites/b.conf", filepath.Join(root, "opt/app/conf/vhosts/b/site.conf")); err != nil { + t.Fatal(err) + } + tg := engine.ScanFS([]engine.Detector{&Detector{}}, filepath.Join(root, "opt"), engine.Options{SystemRoot: root}) + if f := find(tg, KindFlow, "/opt/sbin/nginx"); f == nil || f.Facts["exposure"] == "not-exposed" { + t.Errorf("an absolute link under the glob: %+v", f) + } +} + +func TestX5DiskGlobPermission(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root lists mode 000 directories") + } + root := t.TempDir() + write(t, root, map[string][]byte{ + "/opt/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/opt/app/conf/nginx.conf": []byte("http { include /opt/app/conf/vhosts/*/site.conf; server { listen 80; } }"), + "/opt/app/conf/vhosts/a/site.conf": []byte("server { listen 80; }"), + "/opt/app/conf/vhosts/b/site.conf": []byte("server { listen 443 ssl http2; }"), + "/etc/systemd/system/nginx.service": []byte("[Service]\nExecStart=/opt/sbin/nginx -c /opt/app/conf/nginx.conf\n"), + }) + b := filepath.Join(root, "opt/app/conf/vhosts/b") + os.Chmod(b, 0) + tg := engine.ScanFS([]engine.Detector{&Detector{}}, filepath.Join(root, "opt/sbin"), engine.Options{SystemRoot: root}) + os.Chmod(b, 0o755) + if f := find(tg, KindFlow, "/opt/sbin/nginx"); f == nil || f.Facts["exposure"] != "unknown" { + t.Errorf("an unreadable directory under the glob: %+v", f) + } +} + +// X6: in an image (or --as-root), a wildcard-directory glob through a +// linked directory is not taken as complete. +func TestX6WildcardThroughLink(t *testing.T) { + for name, links := range map[string]map[string]string{ + "the directory": {"/etc/nginx/sites": "/data/sites"}, + "a subdirectory": {"/etc/nginx/sites/b": "/data/sites/b"}, + } { + f := officialImage(t) + f.files["/etc/nginx/nginx.conf"] = []byte("events {} http { include /etc/nginx/sites/*/site.conf; include /etc/nginx/conf.d/*.conf; }") + f.files["/data/sites/b/site.conf"] = []byte("server { listen 443 ssl http2; }") + for k, v := range links { + f.links[k] = v + } + if got := f.exposure(t); got == "not-exposed" { + t.Errorf("%s: %s", name, got) + } + } +} + +// X7: the entrypoint walk is linear and answered once per scan, however +// many links /docker-entrypoint.d holds and however many binaries there +// are. +func TestX7WalkTime(t *testing.T) { + f := officialImage(t) + for i := 0; i < 100000; i++ { + f.links["/docker-entrypoint.d/l"+strconv.Itoa(i)] = "/opt/dir" + } + for i := 0; i < 8; i++ { + f.files["/opt/nginx"+strconv.Itoa(i)+"/sbin/nginx"] = ngxtest.Default("1.31.8").Bytes() + } + start := time.Now() + f.run(t) + if d := time.Since(start); d > 5*time.Second { + t.Errorf("100,000 links and 9 binaries took %s", d) + } +} + +// X8, X9, X10: systemd settings the scan cannot apply exactly, and +// commands around the start judged by their path, not their name. +func TestX8X10Units(t *testing.T) { + base := func(unit string) map[string][]byte { + return map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/etc/nginx/nginx.conf": []byte("http { server { listen 80; } }"), + "/usr/lib/systemd/system/nginx.service": []byte("[Service]\nPIDFile=/run/nginx.pid\n" + unit), + } + } + exposure := func(fs map[string][]byte) string { + if f := find(scanFS(t, fs, engine.Options{}), KindFlow, "/usr/sbin/nginx"); f != nil { + return f.Facts["exposure"] + } + return "no finding" + } + ok := "ExecStartPre=/usr/bin/rm -f /run/nginx.pid\nExecStartPre=/usr/sbin/nginx -t\nExecStart=/usr/sbin/nginx\n" + if got := exposure(base(ok)); got != "not-exposed" { + t.Fatalf("the stock unit: %s", got) + } + for name, unit := range map[string]string{ + "rm elsewhere": "ExecStartPre=/opt/tools/rm -f /run/nginx.pid\nExecStart=/usr/sbin/nginx\n", + "another nginx -t": "ExecStartPre=/opt/tools/nginx -t\nExecStart=/usr/sbin/nginx\n", + "a reset of another directive": "ExecStartPre=/usr/bin/sed -i x /etc/nginx/nginx.conf\nExecStartPost=\nExecStart=/usr/sbin/nginx\n", + "%N in an EnvironmentFile path": "EnvironmentFile=-/etc/sysconfig/%N\nExecStart=/usr/sbin/nginx $OPTS\n", + "a glob in an EnvironmentFile": "EnvironmentFile=-/etc/sysconfig/ngin*\nExecStart=/usr/sbin/nginx $OPTS\n", + "a continued Environment": "Environment=\"OPTS=-c \\\n /etc/nginx/h2.conf\"\nExecStart=/usr/sbin/nginx $OPTS\n", + "PassEnvironment": "PassEnvironment=OPTS\nExecStart=/usr/sbin/nginx $OPTS\n", + "BindReadOnlyPaths": "BindReadOnlyPaths=/etc/nginx/h2.conf:/etc/nginx/nginx.conf\nExecStart=/usr/sbin/nginx\n", + "RootDirectory": "RootDirectory=/srv/chroot\nExecStart=/usr/sbin/nginx\n", + "TemporaryFileSystem": "TemporaryFileSystem=/etc/nginx\nExecStart=/usr/sbin/nginx\n", + } { + if got := exposure(base(unit)); got != "unknown" { + t.Errorf("%s: %s", name, got) + } + } + for name, unit := range map[string]string{ + "argv0 prefix": "ExecStart=@/usr/sbin/nginx nginx -c /etc/nginx/h2.conf\n", + "two ExecStart": "ExecStart=/usr/bin/sed -i x /etc/nginx/nginx.conf\nExecStart=/usr/sbin/nginx\n", + "a shell prefix on Pre": "ExecStartPre=|/usr/sbin/nginx -t\nExecStart=/usr/sbin/nginx\n", + } { + if got := exposure(base(unit)); got != "unknown" { + t.Errorf("%s: %s", name, got) + } + } + // "export NAME=" is not stripped: systemd may read the line otherwise. + fs := base("EnvironmentFile=/etc/sysconfig/nginx\nExecStart=/usr/sbin/nginx $OPTS\n") + fs["/etc/sysconfig/nginx"] = []byte("export OPTS=-c /etc/nginx/h2.conf\n") + fs["/etc/nginx/h2.conf"] = []byte("http { server { listen 443 ssl http2; } }") + if got := exposure(fs); got != "unknown" { + t.Errorf("an export line: %s", got) + } + // A variable the unit does not set is empty, unless the manager can + // set it. + unset := "ExecStart=/usr/sbin/nginx $OPTS\n" + if got := exposure(base(unset)); got != "not-exposed" { + t.Errorf("an unset variable: %s", got) + } + fs = base(unset) + fs["/etc/systemd/system.conf.d/env.conf"] = []byte("[Manager]\nDefaultEnvironment=OPTS=\"-c /etc/nginx/h2.conf\"\n") + if got := exposure(fs); got != "unknown" { + t.Errorf("DefaultEnvironment: %s", got) + } + fs = base(unset) + fs["/usr/lib/systemd/system-environment-generators/90-x"] = []byte("#!/bin/sh\necho OPTS=-c\n") + if got := exposure(fs); got != "unknown" { + t.Errorf("an environment generator: %s", got) + } +} + +// X9: an optional EnvironmentFile that exists but cannot be read, below +// --root, is not taken as absent. +func TestX9UnreadableEnvironmentFile(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root reads mode 000 files") + } + root := t.TempDir() + write(t, root, map[string][]byte{ + "/usr/sbin/nginx": ngxtest.Default("1.31.8").Bytes(), + "/etc/nginx/nginx.conf": []byte("http { server { listen 80; } }"), + "/usr/lib/systemd/system/nginx.service": []byte("[Service]\nEnvironmentFile=-/etc/sysconfig/nginx\nExecStart=/usr/sbin/nginx $OPTS\n"), + "/etc/sysconfig/nginx": []byte("OPTS=-c /x\n"), + }) + p := filepath.Join(root, "etc/sysconfig/nginx") + os.Chmod(p, 0) + tg := engine.ScanFS([]engine.Detector{&Detector{}}, filepath.Join(root, "usr"), engine.Options{SystemRoot: root}) + os.Chmod(p, 0o644) + if f := find(tg, KindFlow, "/usr/sbin/nginx"); f == nil || f.Facts["exposure"] != "unknown" { + t.Errorf("%+v", f) + } +} diff --git a/detectors/nginxh2/testdata/entrypoint/10-listen-on-ipv6-by-default.sh b/detectors/nginxh2/testdata/entrypoint/10-listen-on-ipv6-by-default.sh new file mode 100644 index 0000000..339200e --- /dev/null +++ b/detectors/nginxh2/testdata/entrypoint/10-listen-on-ipv6-by-default.sh @@ -0,0 +1,67 @@ +#!/bin/sh +# vim:sw=4:ts=4:et + +set -e + +entrypoint_log() { + if [ -z "${NGINX_ENTRYPOINT_QUIET_LOGS:-}" ]; then + echo "$@" + fi +} + +ME=$(basename "$0") +DEFAULT_CONF_FILE="etc/nginx/conf.d/default.conf" + +# check if we have ipv6 available +if [ ! -f "/proc/net/if_inet6" ]; then + entrypoint_log "$ME: info: ipv6 not available" + exit 0 +fi + +if [ ! -f "/$DEFAULT_CONF_FILE" ]; then + entrypoint_log "$ME: info: /$DEFAULT_CONF_FILE is not a file or does not exist" + exit 0 +fi + +# check if the file can be modified, e.g. not on a r/o filesystem +touch /$DEFAULT_CONF_FILE 2>/dev/null || { entrypoint_log "$ME: info: can not modify /$DEFAULT_CONF_FILE (read-only file system?)"; exit 0; } + +# check if the file is already modified, e.g. on a container restart +grep -q "listen \[::\]:80;" /$DEFAULT_CONF_FILE && { entrypoint_log "$ME: info: IPv6 listen already enabled"; exit 0; } + +if [ -f "/etc/os-release" ]; then + . /etc/os-release +else + entrypoint_log "$ME: info: can not guess the operating system" + exit 0 +fi + +entrypoint_log "$ME: info: Getting the checksum of /$DEFAULT_CONF_FILE" + +case "$ID" in + "debian") + CHECKSUM=$(dpkg-query --show --showformat='${Conffiles}\n' nginx | grep $DEFAULT_CONF_FILE | cut -d' ' -f 3) + echo "$CHECKSUM /$DEFAULT_CONF_FILE" | md5sum -c - >/dev/null 2>&1 || { + entrypoint_log "$ME: info: /$DEFAULT_CONF_FILE differs from the packaged version" + exit 0 + } + ;; + "alpine") + CHECKSUM=$(apk manifest --no-network nginx 2>/dev/null| grep $DEFAULT_CONF_FILE | cut -d' ' -f 1 | cut -d ':' -f 2) + echo "$CHECKSUM /$DEFAULT_CONF_FILE" | sha1sum -c - >/dev/null 2>&1 || { + entrypoint_log "$ME: info: /$DEFAULT_CONF_FILE differs from the packaged version" + exit 0 + } + ;; + *) + entrypoint_log "$ME: info: Unsupported distribution" + exit 0 + ;; +esac + +# enable ipv6 on default.conf listen sockets +sed -i -E 's,listen 80;,listen 80;\n listen [::]:80;,' /$DEFAULT_CONF_FILE + +entrypoint_log "$ME: info: Enabled listen on IPv6 in /$DEFAULT_CONF_FILE" + +exit 0 diff --git a/detectors/nginxh2/testdata/entrypoint/15-local-resolvers.envsh b/detectors/nginxh2/testdata/entrypoint/15-local-resolvers.envsh new file mode 100644 index 0000000..e830dda --- /dev/null +++ b/detectors/nginxh2/testdata/entrypoint/15-local-resolvers.envsh @@ -0,0 +1,15 @@ +#!/bin/sh +# vim:sw=2:ts=2:sts=2:et + +set -eu + +LC_ALL=C +PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin + +[ "${NGINX_ENTRYPOINT_LOCAL_RESOLVERS:-}" ] || return 0 + +NGINX_LOCAL_RESOLVERS=$(awk 'BEGIN{ORS=" "} $1=="nameserver" {if ($2 ~ ":") {print "["$2"]"} else {print $2}}' /etc/resolv.conf) + +NGINX_LOCAL_RESOLVERS="${NGINX_LOCAL_RESOLVERS% }" + +export NGINX_LOCAL_RESOLVERS diff --git a/detectors/nginxh2/testdata/entrypoint/20-envsubst-on-templates.sh b/detectors/nginxh2/testdata/entrypoint/20-envsubst-on-templates.sh new file mode 100644 index 0000000..b82915d --- /dev/null +++ b/detectors/nginxh2/testdata/entrypoint/20-envsubst-on-templates.sh @@ -0,0 +1,78 @@ +#!/bin/sh + +set -e + +ME=$(basename "$0") + +entrypoint_log() { + if [ -z "${NGINX_ENTRYPOINT_QUIET_LOGS:-}" ]; then + echo "$@" + fi +} + +add_stream_block() { + local conffile="/etc/nginx/nginx.conf" + + if grep -q -E "\s*stream\s*\{" "$conffile"; then + entrypoint_log "$ME: $conffile contains a stream block; include $stream_output_dir/*.conf to enable stream templates" + else + # check if the file can be modified, e.g. not on a r/o filesystem + touch "$conffile" 2>/dev/null || { entrypoint_log "$ME: info: can not modify $conffile (read-only file system?)"; exit 0; } + entrypoint_log "$ME: Appending stream block to $conffile to include $stream_output_dir/*.conf" + cat << END >> "$conffile" +# added by "$ME" on "$(date)" +stream { + include $stream_output_dir/*.conf; +} +END + fi +} + +auto_envsubst() { + local template_dir="${NGINX_ENVSUBST_TEMPLATE_DIR:-/etc/nginx/templates}" + local suffix="${NGINX_ENVSUBST_TEMPLATE_SUFFIX:-.template}" + local output_dir="${NGINX_ENVSUBST_OUTPUT_DIR:-/etc/nginx/conf.d}" + local stream_suffix="${NGINX_ENVSUBST_STREAM_TEMPLATE_SUFFIX:-.stream-template}" + local stream_output_dir="${NGINX_ENVSUBST_STREAM_OUTPUT_DIR:-/etc/nginx/stream-conf.d}" + local filter="${NGINX_ENVSUBST_FILTER:-}" + + local template defined_envs relative_path output_path subdir + defined_envs=$(printf '${%s} ' $(awk -v filter="$filter" 'END { for (name in ENVIRON) { print ( name ~ filter ) ? name : "" } }' < /dev/null)) + [ -d "$template_dir" ] || return 0 + if [ ! -w "$output_dir" ]; then + entrypoint_log "$ME: ERROR: $template_dir exists, but $output_dir is not writable" + return 0 + fi + find "$template_dir" -follow -type f -name "*$suffix" -print | while read -r template; do + relative_path="${template#"$template_dir/"}" + output_path="$output_dir/${relative_path%"$suffix"}" + subdir=$(dirname "$relative_path") + # create a subdirectory where the template file exists + mkdir -p "$output_dir/$subdir" + entrypoint_log "$ME: Running envsubst on $template to $output_path" + envsubst "$defined_envs" < "$template" > "$output_path" + done + + # Print the first file with the stream suffix, this will be false if there are none + if test -n "$(find "$template_dir" -name "*$stream_suffix" -print -quit)"; then + mkdir -p "$stream_output_dir" + if [ ! -w "$stream_output_dir" ]; then + entrypoint_log "$ME: ERROR: $template_dir exists, but $stream_output_dir is not writable" + return 0 + fi + add_stream_block + find "$template_dir" -follow -type f -name "*$stream_suffix" -print | while read -r template; do + relative_path="${template#"$template_dir/"}" + output_path="$stream_output_dir/${relative_path%"$stream_suffix"}" + subdir=$(dirname "$relative_path") + # create a subdirectory where the template file exists + mkdir -p "$stream_output_dir/$subdir" + entrypoint_log "$ME: Running envsubst on $template to $output_path" + envsubst "$defined_envs" < "$template" > "$output_path" + done + fi +} + +auto_envsubst + +exit 0 diff --git a/detectors/nginxh2/testdata/entrypoint/30-tune-worker-processes.sh b/detectors/nginxh2/testdata/entrypoint/30-tune-worker-processes.sh new file mode 100644 index 0000000..defb994 --- /dev/null +++ b/detectors/nginxh2/testdata/entrypoint/30-tune-worker-processes.sh @@ -0,0 +1,188 @@ +#!/bin/sh +# vim:sw=2:ts=2:sts=2:et + +set -eu + +LC_ALL=C +ME=$(basename "$0") +PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin + +[ "${NGINX_ENTRYPOINT_WORKER_PROCESSES_AUTOTUNE:-}" ] || exit 0 + +touch /etc/nginx/nginx.conf 2>/dev/null || { echo >&2 "$ME: error: can not modify /etc/nginx/nginx.conf (read-only file system?)"; exit 0; } + +ceildiv() { + num=$1 + div=$2 + echo $(( (num + div - 1) / div )) +} + +get_cpuset() { + cpusetroot=$1 + cpusetfile=$2 + ncpu=0 + [ -f "$cpusetroot/$cpusetfile" ] || return 1 + for token in $( tr ',' ' ' < "$cpusetroot/$cpusetfile" ); do + case "$token" in + *-*) + count=$( seq $(echo "$token" | tr '-' ' ') | wc -l ) + ncpu=$(( ncpu+count )) + ;; + *) + ncpu=$(( ncpu+1 )) + ;; + esac + done + echo "$ncpu" +} + +get_quota() { + cpuroot=$1 + ncpu=0 + [ -f "$cpuroot/cpu.cfs_quota_us" ] || return 1 + [ -f "$cpuroot/cpu.cfs_period_us" ] || return 1 + cfs_quota=$( cat "$cpuroot/cpu.cfs_quota_us" ) + cfs_period=$( cat "$cpuroot/cpu.cfs_period_us" ) + [ "$cfs_quota" = "-1" ] && return 1 + [ "$cfs_period" = "0" ] && return 1 + ncpu=$( ceildiv "$cfs_quota" "$cfs_period" ) + [ "$ncpu" -gt 0 ] || return 1 + echo "$ncpu" +} + +get_quota_v2() { + cpuroot=$1 + ncpu=0 + [ -f "$cpuroot/cpu.max" ] || return 1 + cfs_quota=$( cut -d' ' -f 1 < "$cpuroot/cpu.max" ) + cfs_period=$( cut -d' ' -f 2 < "$cpuroot/cpu.max" ) + [ "$cfs_quota" = "max" ] && return 1 + [ "$cfs_period" = "0" ] && return 1 + ncpu=$( ceildiv "$cfs_quota" "$cfs_period" ) + [ "$ncpu" -gt 0 ] || return 1 + echo "$ncpu" +} + +get_cgroup_v1_path() { + needle=$1 + found= + foundroot= + mountpoint= + + [ -r "/proc/self/mountinfo" ] || return 1 + [ -r "/proc/self/cgroup" ] || return 1 + + while IFS= read -r line; do + case "$needle" in + "cpuset") + case "$line" in + *cpuset*) + found=$( echo "$line" | cut -d ' ' -f 4,5 ) + break + ;; + esac + ;; + "cpu") + case "$line" in + *cpuset*) + ;; + *cpu,cpuacct*|*cpuacct,cpu|*cpuacct*|*cpu*) + found=$( echo "$line" | cut -d ' ' -f 4,5 ) + break + ;; + esac + esac + done << __EOF__ +$( grep -F -- '- cgroup ' /proc/self/mountinfo ) +__EOF__ + + while IFS= read -r line; do + controller=$( echo "$line" | cut -d: -f 2 ) + case "$needle" in + "cpuset") + case "$controller" in + cpuset) + mountpoint=$( echo "$line" | cut -d: -f 3 ) + break + ;; + esac + ;; + "cpu") + case "$controller" in + cpu,cpuacct|cpuacct,cpu|cpuacct|cpu) + mountpoint=$( echo "$line" | cut -d: -f 3 ) + break + ;; + esac + ;; + esac +done << __EOF__ +$( grep -F -- 'cpu' /proc/self/cgroup ) +__EOF__ + + case "${found%% *}" in + "/") + foundroot="${found##* }$mountpoint" + ;; + "$mountpoint") + foundroot="${found##* }" + ;; + esac + echo "$foundroot" +} + +get_cgroup_v2_path() { + found= + foundroot= + mountpoint= + + [ -r "/proc/self/mountinfo" ] || return 1 + [ -r "/proc/self/cgroup" ] || return 1 + + while IFS= read -r line; do + found=$( echo "$line" | cut -d ' ' -f 4,5 ) + done << __EOF__ +$( grep -F -- '- cgroup2 ' /proc/self/mountinfo ) +__EOF__ + + while IFS= read -r line; do + mountpoint=$( echo "$line" | cut -d: -f 3 ) +done << __EOF__ +$( grep -F -- '0::' /proc/self/cgroup ) +__EOF__ + + case "${found%% *}" in + "") + return 1 + ;; + "/") + foundroot="${found##* }$mountpoint" + ;; + "$mountpoint" | /../*) + foundroot="${found##* }" + ;; + esac + echo "$foundroot" +} + +ncpu_online=$( getconf _NPROCESSORS_ONLN ) +ncpu_cpuset= +ncpu_quota= +ncpu_cpuset_v2= +ncpu_quota_v2= + +cpuset=$( get_cgroup_v1_path "cpuset" ) && ncpu_cpuset=$( get_cpuset "$cpuset" "cpuset.effective_cpus" ) || ncpu_cpuset=$ncpu_online +cpu=$( get_cgroup_v1_path "cpu" ) && ncpu_quota=$( get_quota "$cpu" ) || ncpu_quota=$ncpu_online +cgroup_v2=$( get_cgroup_v2_path ) && ncpu_cpuset_v2=$( get_cpuset "$cgroup_v2" "cpuset.cpus.effective" ) || ncpu_cpuset_v2=$ncpu_online +cgroup_v2=$( get_cgroup_v2_path ) && ncpu_quota_v2=$( get_quota_v2 "$cgroup_v2" ) || ncpu_quota_v2=$ncpu_online + +ncpu=$( printf "%s\n%s\n%s\n%s\n%s\n" \ + "$ncpu_online" \ + "$ncpu_cpuset" \ + "$ncpu_quota" \ + "$ncpu_cpuset_v2" \ + "$ncpu_quota_v2" \ + | sort -n \ + | head -n 1 ) + +sed -i.bak -r 's/^(worker_processes)(.*)$/# Commented out by '"$ME"' on '"$(date)"'\n#\1\2\n\1 '"$ncpu"';/' /etc/nginx/nginx.conf diff --git a/detectors/nginxh2/testdata/entrypoint/README b/detectors/nginxh2/testdata/entrypoint/README new file mode 100644 index 0000000..f82790c --- /dev/null +++ b/detectors/nginxh2/testdata/entrypoint/README @@ -0,0 +1,3 @@ +These are the official nginx image's entrypoint and /docker-entrypoint.d scripts, copied +unchanged from github.com/nginx/docker-nginx (entrypoint/, commit a2a986d19a, BSD 2-Clause License, +Copyright (C) 2011-2023 F5, Inc.), for the tests that recognise them by content. diff --git a/detectors/nginxh2/testdata/entrypoint/docker-entrypoint.sh b/detectors/nginxh2/testdata/entrypoint/docker-entrypoint.sh new file mode 100644 index 0000000..8ea04f2 --- /dev/null +++ b/detectors/nginxh2/testdata/entrypoint/docker-entrypoint.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# vim:sw=4:ts=4:et + +set -e + +entrypoint_log() { + if [ -z "${NGINX_ENTRYPOINT_QUIET_LOGS:-}" ]; then + echo "$@" + fi +} + +if [ "$1" = "nginx" ] || [ "$1" = "nginx-debug" ]; then + if /usr/bin/find "/docker-entrypoint.d/" -mindepth 1 -maxdepth 1 -type f -print -quit 2>/dev/null | read v; then + entrypoint_log "$0: /docker-entrypoint.d/ is not empty, will attempt to perform configuration" + + entrypoint_log "$0: Looking for shell scripts in /docker-entrypoint.d/" + find "/docker-entrypoint.d/" -follow -type f -print | sort -V | while read -r f; do + case "$f" in + *.envsh) + if [ -x "$f" ]; then + entrypoint_log "$0: Sourcing $f"; + . "$f" + else + # warn on shell scripts without exec bit + entrypoint_log "$0: Ignoring $f, not executable"; + fi + ;; + *.sh) + if [ -x "$f" ]; then + entrypoint_log "$0: Launching $f"; + "$f" + else + # warn on shell scripts without exec bit + entrypoint_log "$0: Ignoring $f, not executable"; + fi + ;; + *) entrypoint_log "$0: Ignoring $f";; + esac + done + + entrypoint_log "$0: Configuration complete; ready for start up" + else + entrypoint_log "$0: No files found in /docker-entrypoint.d/, skipping configuration" + fi +fi + +exec "$@" diff --git a/detectors/nginxh2/testdata/fuzz/FuzzSource/79c15ee6e9e42c95 b/detectors/nginxh2/testdata/fuzz/FuzzSource/79c15ee6e9e42c95 new file mode 100644 index 0000000..6453e6b --- /dev/null +++ b/detectors/nginxh2/testdata/fuzz/FuzzSource/79c15ee6e9e42c95 @@ -0,0 +1,7 @@ +go test fuzz v1 +string("[:]") +string("0") +string("0") +string("0") +string("0") +string("0") diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 2d24d21..0ed654e 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -192,6 +192,25 @@ type Reader interface { Wants(path string, head []byte, executable bool) bool } +// WorkingDirer is implemented by the TargetContext of an image: the +// working directory its configuration sets ("" is /), against which the +// runtime resolves a relative command. +type WorkingDirer interface { + WorkingDir() string +} + +// SkipVisitor is implemented by a Scan whose verdicts must not rest on a +// file's absence. Before Finish it is given every file and directory the +// walk recorded as not scanned (unreadable, a directory that could not be +// listed, over --max-file-size, a file a detector failed on), one record +// per path with every reason, as the target reports them, and with paths +// inside the system root. Deliberate exclusions (pseudo-filesystems, +// container storage, a file over a detector's own limit) are left out, and +// so are the gaps a detector reports only at the end (FinishSkipper). +type SkipVisitor interface { + VisitSkips(skips []Skip) +} + // 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 diff --git a/internal/engine/run.go b/internal/engine/run.go index 6a244c6..6096ec7 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -138,6 +138,7 @@ type targetCtx struct { seen map[string]bool env []string cmd []string + workdir string symlinks map[string]string // absolute path -> target as written hardlinks map[string]string // absolute path -> absolute path it names } @@ -162,6 +163,9 @@ func (c *targetCtx) Kind() TargetKind { return c.kind } func (c *targetCtx) Exists(p string) bool { return c.seen[p] } func (c *targetCtx) Env() []string { return c.env } func (c *targetCtx) Command() []string { return c.cmd } + +// WorkingDir is the image configuration's working directory. +func (c *targetCtx) WorkingDir() string { return c.workdir } func (c *targetCtx) Aliases(p string) []string { out := []string{p} seen := map[string]bool{p: true} @@ -217,6 +221,10 @@ type walker struct { // exclusions are the exclusion records made for each scan, by path, so // a gap the scan reports at the end replaces its exclusion. exclusions []map[string]string + // walked is how many of t.Skipped the walker recorded during a + // filesystem walk, with paths inside the system root; the source + // walk's records follow, below the directory it started at. + walked int // 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 @@ -593,7 +601,15 @@ func (w *walker) visitHeadSafely(id string, h HeadVisitor, p string, head []byte func (w *walker) finish() { defer func() { w.t.Skipped = oneRecordPerPath(w.t.Skipped) }() + var gaps []Skip // the walk's, for every SkipVisitor alike + for _, s := range w.scans { + if _, ok := s.(SkipVisitor); ok { + gaps = w.walkGaps() + break + } + } for i, s := range w.scans { + w.visitSkips(i, s, gaps) fs, err := finishSafely(s, w.ctx) if err != nil { w.t.Error = fmt.Sprintf("detector %s failed: %v", w.dets[i].Manifest().ID, err) @@ -614,6 +630,45 @@ func (w *walker) finish() { } } +// walkGaps are the coverage gaps the walk recorded, one per path as the +// target reports them (oneRecordPerPath), with paths inside the system +// root. They are taken before any Finish, so what one detector reports at +// the end (FinishSkipper: a file over its own limit, which the others were +// shown) is not a gap for another, whatever the order. +func (w *walker) walkGaps() []Skip { + recs := make([]source.Skip, len(w.t.Skipped)) + for k, sk := range w.t.Skipped { + // The walker's records are inside the system root already, and + // so are archive members, which carry their outer file's path. + if k >= w.walked && !strings.Contains(sk.Path, "!/") { + sk.Path = w.abs(sk.Path) + } + recs[k] = sk + } + var gaps []Skip + for _, sk := range oneRecordPerPath(recs) { + if !sk.Excluded && !strings.HasPrefix(sk.Reason, "excluded:") { + gaps = append(gaps, Skip{Path: sk.Path, Reason: sk.Reason}) + } + } + return gaps +} + +// visitSkips gives a SkipVisitor the walk's coverage gaps. +func (w *walker) visitSkips(i int, s Scan, gaps []Skip) { + sv, ok := s.(SkipVisitor) + if !ok { + return + } + skips := append([]Skip(nil), gaps...) // each scan its own copy + defer func() { + if r := recover(); r != nil { + w.t.Problems = append(w.t.Problems, fmt.Sprintf("detector %s failed reading the files not scanned (%v)", w.dets[i].Manifest().ID, r)) + } + }() + sv.VisitSkips(skips) +} + // 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 @@ -720,6 +775,7 @@ func ScanFS(dets []Detector, root string, opts Options) *Target { w.ctx.sysRoot = sysRoot } skips, n, err := source.Dir(real, so, w.visit) + w.walked = len(t.Skipped) t.Skipped, t.Files = append(t.Skipped, skips...), n if err != nil { t.Error = err.Error() @@ -776,6 +832,7 @@ func ScanImage(dets []Detector, ref string, opts Options) *Target { return t } rc, t.Digest, t.Platform, w.ctx.env = o.FS, o.Digest, o.Platform, o.Env + w.ctx.workdir = o.WorkingDir unresolved = o.Unresolved w.ctx.cmd = opts.Override.Apply(o.Entrypoint, o.Cmd) } diff --git a/internal/engine/skipvisitor_test.go b/internal/engine/skipvisitor_test.go new file mode 100644 index 0000000..2d0ed37 --- /dev/null +++ b/internal/engine/skipvisitor_test.go @@ -0,0 +1,110 @@ +package engine + +import ( + "path/filepath" + "strings" + "testing" +) + +// skipFake records the skips it is given before Finish. +type skipFake struct { + *fake + got []Skip + finished bool +} + +func (s *skipFake) NewScan(TargetKind) Scan { return s } +func (s *skipFake) VisitSkips(sk []Skip) { + if s.finished { + panic("VisitSkips after Finish") + } + s.got = append(s.got, sk...) +} +func (s *skipFake) Finish(ctx TargetContext) []Finding { + s.finished = true + return nil +} + +// A SkipVisitor gets the walk's coverage gaps before Finish, with paths +// inside the system root, and not the deliberate exclusions. +func TestSkipVisitor(t *testing.T) { + root := tree(t, map[string][]byte{"/etc/nginx/big.conf": make([]byte, 2048), "/etc/nginx/small.conf": []byte("x")}) + for _, c := range []struct { + name string + scan string + opts Options + }{ + {"at the root", root, Options{AsRoot: true, MaxFileSize: 1024}}, + {"below the root", filepath.Join(root, "etc"), Options{SystemRoot: root, MaxFileSize: 1024}}, + } { + d := &skipFake{fake: &fake{id: "s", seen: &[]string{}}} + tg := ScanFS([]Detector{d}, c.scan, c.opts) + if tg.Error != "" { + t.Fatal(tg.Error) + } + if len(d.got) != 1 || d.got[0].Path != "/etc/nginx/big.conf" || !d.finished { + t.Errorf("%s: %+v", c.name, d.got) + } + } +} + +// failing panics on every file named bad.conf. +type failing struct{ *fake } + +func (f failing) NewScan(TargetKind) Scan { return f } +func (f failing) Visit(file File) []Skip { + if filepath.Base(file.Path) == "bad.conf" { + panic("hostile file") + } + return nil +} + +// A SkipVisitor gets one record per path, as the target reports them, with +// every reason, and with the path inside the system root whether the walk +// or a detector made the record. +func TestSkipVisitorOneRecordPerPath(t *testing.T) { + root := tree(t, map[string][]byte{"/etc/nginx/big.conf": make([]byte, 2048), "/etc/nginx/bad.conf": []byte("x")}) + for _, c := range []struct { + name string + scan string + opts Options + }{ + {"at the root", root, Options{AsRoot: true, MaxFileSize: 1024}}, + {"below the root", filepath.Join(root, "etc"), Options{SystemRoot: root, MaxFileSize: 1024}}, + } { + d := &skipFake{fake: &fake{id: "s", seen: &[]string{}}} + a := failing{&fake{id: "a", seen: &[]string{}}} + b := failing{&fake{id: "b", seen: &[]string{}}} + tg := ScanFS([]Detector{a, b, d}, c.scan, c.opts) + if tg.Error != "" { + t.Fatal(tg.Error) + } + got := map[string]string{} + for _, sk := range d.got { + if _, dup := got[sk.Path]; dup { + t.Errorf("%s: %s given twice", c.name, sk.Path) + } + got[sk.Path] = sk.Reason + } + bad := got["/etc/nginx/bad.conf"] + if len(got) != 2 || got["/etc/nginx/big.conf"] == "" || !strings.Contains(bad, "detector a failed") || !strings.Contains(bad, "detector b failed") { + t.Errorf("%s: %+v", c.name, d.got) + } + } +} + +// What another detector reports as a gap at the end (FinishSkipper) is a +// file over its own limit: the SkipVisitor was shown that file, so it is +// not a gap for it, whichever order the detectors run in. +func TestSkipVisitorNotOthersFinishSkips(t *testing.T) { + root := tree(t, map[string][]byte{"etc/os-release": make([]byte, 100<<10)}) + _, g := gapDetector("t-finskip", false) + d := &skipFake{fake: &fake{id: "s", seen: &[]string{}}} + tg := ScanFS([]Detector{finishSkipper{g, true}, d}, root, Options{AsRoot: true}) + if tg.Error != "" || tg.Gaps() != 1 { + t.Fatalf("error %q skipped %+v", tg.Error, tg.Skipped) + } + if len(d.got) != 0 || strings.Join(*d.seen, ",") != "/etc/os-release" { + t.Errorf("given %+v, seen %v", d.got, *d.seen) + } +} diff --git a/internal/image/image.go b/internal/image/image.go index 40986db..ec340da 100644 --- a/internal/image/image.go +++ b/internal/image/image.go @@ -33,6 +33,8 @@ type Opened struct { Command []string // Entrypoint and Cmd are the configuration's own. Entrypoint, Cmd []string + // WorkingDir is the configuration's working directory ("" is /). + WorkingDir string } // Open resolves ref and returns the image's flattened filesystem. @@ -57,6 +59,7 @@ func opened(img v1.Image) (*Opened, error) { o.Env = cf.Config.Env o.Command = append(append([]string(nil), cf.Config.Entrypoint...), cf.Config.Cmd...) o.Entrypoint, o.Cmd = cf.Config.Entrypoint, cf.Config.Cmd + o.WorkingDir = cf.Config.WorkingDir if cf.OS != "" { o.Platform = cf.OS + "/" + cf.Architecture if cf.Variant != "" { diff --git a/parity/NGINXH2-RESULTS.md b/parity/NGINXH2-RESULTS.md new file mode 100644 index 0000000..8e5f3fa --- /dev/null +++ b/parity/NGINXH2-RESULTS.md @@ -0,0 +1,47 @@ +# nginx HTTP/2 pair (nginxh2) fixture results + +Generated by `parity/nginxh2.py`. Each row's expected findings come from [FACTS.md](../detectors/nginxh2/FACTS.md). Registry images are scanned by digest; the image digest scanned is listed. Image rows are platform, path, kind, verdict, status, exposure; source-tree rows are file:line, kind, verdict; fix rows are what fix printed for each place, and its exit status. + +| Case | What | Result | Findings | +| --- | --- | --- | --- | +| official-1.31.8 | Docker official 1.31.8 (Debian): the last mainline before the fix; default site, port 80; nginx-debug is installed but the command does not start it, so its exposure is unknown (round-4 verification 2)
`nginx:1.31.8@sha256:165ddde8751e75a1c907d24ef10d9f6deb08b57e0fe56caf67512486aff76d82`
linux/amd64 sha256:5cb45c65713151f856f6b64f6a9b6a96b74d6a10709a7aa18919a444fd00bffa | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| official-1.31.9 | Docker official 1.31.9: fixed
`nginx:1.31.9@sha256:08f354a3b44c422021a5c0f5efb3e27f8f90236b5447d3bac4053f5f50ab6760`
linux/amd64 sha256:5b9ebb95001cc4f5242fbc3e1a9ac76d313c8ba197c7e5803a77d3f7879f0cda | pass | linux/amd64 /usr/sbin/nginx connection-reuse fixed fixed not-exposed
linux/amd64 /usr/sbin/nginx flow-control fixed fixed not-exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse fixed fixed unknown
linux/amd64 /usr/sbin/nginx-debug flow-control fixed fixed unknown | +| official-1.30.6-alpine | Docker official 1.30.6-alpine: the last stable before the fix
`nginx:1.30.6-alpine@sha256:901e593c95dc85f5a729f5765516321366ef4ac401821431d408897e95287d0a`
linux/amd64 sha256:bb8f722b4be005fcd7827816a136ab779fd40185d85b5171be915cc7fc0575c7 | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| official-1.30.7-alpine | Docker official 1.30.7-alpine: fixed
`nginx:1.30.7-alpine@sha256:b24de00298eb7fb23839442d46c780991be7bc7ddb081b6c0876ac777012e352`
linux/amd64 sha256:4d1d4ce08432dc7dfe4af762cb224ce6b5273ae878f41e020ea2425d02ea91a4 | pass | linux/amd64 /usr/sbin/nginx connection-reuse fixed fixed not-exposed
linux/amd64 /usr/sbin/nginx flow-control fixed fixed not-exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse fixed fixed unknown
linux/amd64 /usr/sbin/nginx-debug flow-control fixed fixed unknown | +| official-1.31.8-perl | Docker official 1.31.8-perl
`nginx:1.31.8-perl@sha256:82a12bb0001413a9c1e243f67dbc6e742b59b537f88841a0c8b865a7a271aea5`
linux/amd64 sha256:8451f239ab5a5d54f84eab22627abc0c4dd37125228ad0127f639f1535bc831d | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| official-1.30.7-otel | Docker official 1.30.7-otel: fixed
`nginx:1.30.7-otel@sha256:6143bea44138201e86a48592d26dafcc230bcb56e71b5f72505f5cc1a27aeb16`
linux/amd64 sha256:7d5348f2b8fa436130c5d081786d841a7409e988c9c36559db7f1552fdc2421f | pass | linux/amd64 /usr/sbin/nginx connection-reuse fixed fixed not-exposed
linux/amd64 /usr/sbin/nginx flow-control fixed fixed not-exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse fixed fixed unknown
linux/amd64 /usr/sbin/nginx-debug flow-control fixed fixed unknown | +| official-1.31.8-arm64 | Docker official 1.31.8 on linux/arm64: affected alike
`nginx:1.31.8@sha256:165ddde8751e75a1c907d24ef10d9f6deb08b57e0fe56caf67512486aff76d82`
linux/arm64/v8 sha256:089c73daf1604108ee59172ab9e71bf3d3bcc8aa69ae61593eb0f4fe67108d80 | pass | linux/arm64/v8 /usr/sbin/nginx connection-reuse vulnerable vulnerable not-exposed
linux/arm64/v8 /usr/sbin/nginx flow-control vulnerable vulnerable not-exposed
linux/arm64/v8 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable unknown
linux/arm64/v8 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| official-1.31.8-386 | Docker official 1.31.8 on linux/386: a 32-bit build, still vulnerable (the published exploit needs 64-bit)
`nginx:1.31.8@sha256:165ddde8751e75a1c907d24ef10d9f6deb08b57e0fe56caf67512486aff76d82`
linux/386 sha256:be17d9f8c2d0c2e4508fe75792d8d7cf52964904615b3557beceb2bfd8596b20
32-bit | pass | linux/386 /usr/sbin/nginx connection-reuse vulnerable vulnerable not-exposed
linux/386 /usr/sbin/nginx flow-control vulnerable vulnerable not-exposed
linux/386 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable unknown
linux/386 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| official-1.20.2 | Docker official 1.20.2: an old line, no fix, in both ranges
`nginx:1.20.2@sha256:38f8c1d9613f3f42e7969c3b1dd5c3277e635d4576713e6453c6193e66270a6d`
linux/amd64 sha256:a76df3b4f1478766631c794de7ff466aca466f995fd5bb216bb9643a3dd2a6bb | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| official-1.18.0 | Docker official 1.18.0: before 1.19.7, so not affected by CVE-2026-123633; vulnerable to CVE-2026-123007
`nginx:1.18.0@sha256:e90ac5331fe095cea01b121a3627174b2e33e06e83720e9a934c7b8ccc9c55a0`
linux/amd64 sha256:9b0fc8e09ae1abb0144ce57018fc1e13d23abd108540f135dc83c0ed661081cf | pass | linux/amd64 /usr/sbin/nginx connection-reuse inactive not-affected not-exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse inactive not-affected unknown
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| official-1.19.6 | Docker official 1.19.6: the last release before 76672e650, so not affected by CVE-2026-123633; vulnerable to CVE-2026-123007
`nginx:1.19.6@sha256:8e10956422503824ebb599f37c26a90fe70541942687f70bbdb744530fc9eba4`
linux/amd64 sha256:1a53eb723d17523512bd25c27299046cfa034cce309f4ed330c943a304513f59 | pass | linux/amd64 /usr/sbin/nginx connection-reuse inactive not-affected not-exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse inactive not-affected unknown
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| official-1.19.7 | Docker official 1.19.7: the first release with both flaws
`nginx:1.19.7@sha256:f3693fe50d5b1df1ecd315d54813a77afd56b0245a404055a946574deb6b34fc`
linux/amd64 sha256:b08ecc9f7997452ef24358f3e43b9c66888fadb31f3e5de22fec922975caa75a | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| official-1.10.3 | Docker official 1.10.3 (a single-platform image): CVE-2026-123007 only. Tags before 1.10 (1.9.x, 1.8.x, the pre-HTTP/2 releases) are schema 1 manifests no current client reads; the version boundary at 1.9.5 is covered by the unit tests and the noh2 case
`nginx:1.10.3@sha256:6202beb06ea61f44179e02ca965e8e13b961d12640101fca213efbfd145d7575`
linux/amd64 sha256:6202beb06ea61f44179e02ca965e8e13b961d12640101fca213efbfd145d7575 | pass | linux/amd64 /usr/sbin/nginx connection-reuse inactive not-affected not-exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse inactive not-affected unknown
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| unprivileged-1.31.7-alpine | nginxinc/nginx-unprivileged 1.31.7-alpine (no fixed tag on Docker Hub at 16:50 UTC)
`nginxinc/nginx-unprivileged:1.31.7-alpine@sha256:b5047b9b76845eac124358373c6852377c52e4b05834a47647e955dd91cb8f1e`
linux/amd64 sha256:c3bcf3d1a53a027bfa515b9fe4fbbe7bf6b791476a5af853de439ad494b145bd | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| openresty-1.31.8.1 | OpenResty 1.31.8.1 (nginx 1.31.8): no OpenResty release with the fix
`openresty/openresty:1.31.8.1-alpine@sha256:fec9da11e7a975d67caf66aaf70e9af2a101fdb167e0b60502c94a4e4959b943`
linux/amd64 sha256:720b9e5d188afc7736a64d16f676ff357665a5f4b8f01ab28c6b72df5f9b78b2 | pass | linux/amd64 /usr/local/openresty/nginx/sbin/nginx connection-reuse vulnerable vulnerable not-exposed
linux/amd64 /usr/local/openresty/nginx/sbin/nginx flow-control vulnerable vulnerable not-exposed | +| bitnamilegacy-1.29.1 | Bitnami nginx 1.29.1 (bitnamilegacy, frozen): no fix; Bitnami starts nginx through its own entrypoint script, so exposure is unknown (review 2, finding 2)
`bitnamilegacy/nginx:1.29.1@sha256:b2e803958eda5723aae1e36ed0e418f6e0c79e7ce890820eba9cad85a6381286`
linux/amd64 sha256:5c10f50fade071e6132090c5d63ad591c23b73f6282f58f4f6efadd257e1a7e3 | pass | linux/amd64 /opt/bitnami/nginx/sbin/nginx connection-reuse vulnerable vulnerable unknown
linux/amd64 /opt/bitnami/nginx/sbin/nginx flow-control vulnerable vulnerable unknown | +| ingress-nginx-bitnami-1.13.1 | ingress-nginx controller 1.13.1 (Bitnami's build): archived project, HTTP/2 on by default
`bitnamilegacy/nginx-ingress-controller:1.13.1@sha256:95e574be03a97a1b829bc7e94a749d07cf31e587d55b2f18e756fa7eb21ebe3a`
linux/amd64 sha256:6117db41bd775f922ee090d3c60f500759c717da1b52fe87b0f1fa7d533ddd58 | pass | linux/amd64 /usr/local/nginx/sbin/nginx connection-reuse vulnerable vulnerable exposed
linux/amd64 /usr/local/nginx/sbin/nginx flow-control vulnerable vulnerable exposed | +| f5-ingress-5.7.1 | F5 NGINX Ingress Controller 5.7.1 (nginx 1.31.8); its configuration is written at start
`nginx/nginx-ingress:5.7.1@sha256:b6a970b8fccb0409030d8689087adc071e3344b6a88046fb31ede5a80bb6b480`
linux/amd64 sha256:461aec67116f0e363e5a4719bc31cd1173a56584f8079f54499392a884276a95 | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| f5-ingress-5.8.0 | F5 NGINX Ingress Controller 5.8.0 (nginx 1.31.9)
`nginx/nginx-ingress:5.8.0@sha256:57705208dfa8ffb13be2bd8fca234b8a5dd49502eb37d44be57de54c6fec37aa`
linux/amd64 sha256:e6157b4c27747c1006cab6c033dca2ad104eb613fbd196cfad550861dc27e5f9 | pass | linux/amd64 /usr/sbin/nginx connection-reuse fixed fixed unknown
linux/amd64 /usr/sbin/nginx flow-control fixed fixed unknown
linux/amd64 /usr/sbin/nginx-debug connection-reuse fixed fixed unknown
linux/amd64 /usr/sbin/nginx-debug flow-control fixed fixed unknown | +| h2-tls-proxy | 1.31.8, HTTP/2 over TLS in front of a proxy | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable exposed
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable exposed | +| h2-cleartext | 1.31.8, HTTP/2 without TLS in front of a proxy | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable http2-cleartext-only
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable exposed
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| h2-off | 1.31.8, TLS and a proxy with http2 off: not exposed, still vulnerable | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable not-exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| h2-static | 1.31.8, HTTP/2 over TLS serving files only | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable http2-without-proxy
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable exposed | +| templates | 1.31.8, HTTP/2 in a template the entrypoint writes to conf.d | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable exposed
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable exposed | +| cmdline | 1.31.8, the command loads another configuration (-c) with HTTP/2 | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable exposed
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable exposed
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable exposed | +| unread-include | 1.31.8, an include of files the scan does not read: exposure unknown | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| hostile | 1.31.8, include loops, a symbolic link loop, an include fan-out, deep nesting and a 5 MB configuration file | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx-debug connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx-debug flow-control vulnerable vulnerable unknown | +| hidden | synthetic: 1.31.8 without its version line | pass | linux/amd64 /usr/sbin/nginx connection-reuse unknown unknown not-exposed
linux/amd64 /usr/sbin/nginx flow-control unknown unknown not-exposed | +| renamed | synthetic: 1.31.8 renamed WAFsrv/9.9.9 throughout | pass | linux/amd64 /usr/sbin/nginx connection-reuse unknown unknown not-exposed
linux/amd64 /usr/sbin/nginx flow-control unknown unknown not-exposed | +| conflict | synthetic: 1.31.8 whose version line alone claims 1.31.9 | pass | linux/amd64 /usr/sbin/nginx connection-reuse unknown unknown not-exposed
linux/amd64 /usr/sbin/nginx flow-control unknown unknown not-exposed | +| noh2 | synthetic: 1.31.8 reading as built without HTTP/2 | pass | linux/amd64 /usr/sbin/nginx connection-reuse inactive not-affected not-exposed
linux/amd64 /usr/sbin/nginx flow-control inactive not-affected not-exposed | +| debian-pkg | Debian 12's nginx 1.22.1-9+deb12u10 (no fixed package), a site enabled through a symbolic link | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable exposed
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable exposed | +| debian-pkg-fs | the same image exported and scanned as a filesystem | pass | fs /usr/sbin/nginx connection-reuse vulnerable vulnerable exposed
fs /usr/sbin/nginx flow-control vulnerable vulnerable exposed | +| ubuntu-pkg | Ubuntu 24.04's nginx 1.24.0-2ubuntu7.19, the default site; the image's command is a shell, not nginx, so exposure is unknown unless the configuration shows HTTP/2 on (review 2, finding 2) | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable unknown | +| alpine-pkg | Alpine 3.24's nginx as published at build time (1.30.7-r0 since 2026-11-18 17:06 UTC), HTTP/2 on in http.d; the image's command is a shell, not nginx, so exposure is unknown unless the configuration shows HTTP/2 on (review 2, finding 2) | pass | linux/amd64 /usr/sbin/nginx connection-reuse fixed fixed unknown
linux/amd64 /usr/sbin/nginx flow-control fixed fixed exposed | +| alpine-3.23-pkg | Alpine 3.23's nginx 1.28.3-r7: no fixed package on that branch; the image's command is a shell, not nginx, so exposure is unknown unless the configuration shows HTTP/2 on (review 2, finding 2) | pass | linux/amd64 /usr/sbin/nginx connection-reuse vulnerable vulnerable unknown
linux/amd64 /usr/sbin/nginx flow-control vulnerable vulnerable unknown | +| repo | a source tree scanned offline: Dockerfile FROM (an ARG tag, a moving tag, OpenResty, a fixed tag), apt, apk, dnf module, sh -c and nginx.org installs, Compose, Kubernetes (a digest-pinned ingress-nginx, a ConfigMap with HTTP/2), Helm values (the ingress-nginx chart's registry/image/tag) and a chart depending on ingress-nginx | pass | Dockerfile:10 os-package vulnerable
Dockerfile:12 os-package vulnerable
Dockerfile:16 not-checked unknown
Dockerfile:16 not-checked unknown
Dockerfile:17 not-checked unknown
Dockerfile:18 image-pin vulnerable
Dockerfile:2 image-pin vulnerable
Dockerfile:20 not-checked unknown
Dockerfile:3 image-pin vulnerable
Dockerfile:6 os-package vulnerable
Dockerfile:8 not-checked unknown
chart/Chart.yaml:5 image-pin vulnerable
compose.yaml:3 image-pin vulnerable
compose.yaml:5 image-pin vulnerable
compose.yaml:7 image-pin vulnerable
conf.d/site.conf:3 http2-config inactive
helm/values.yaml:5 image-pin vulnerable
helm/values.yaml:8 image-pin vulnerable
k8s/deploy.yaml#default.conf:19 http2-config inactive
k8s/deploy.yaml:11 image-pin vulnerable
k8s/deploy.yaml:9 image-pin vulnerable | +| fix-offline | fix --dry-run --offline: every tag move needs the registry, so nothing is changed | pass | exit 1
not fixed Dockerfile:1
not fixed Dockerfile:2
not fixed Dockerfile:3 | +| fix-registry | fix --dry-run --platform linux/amd64,linux/arm64: 1.31.8 to 1.31.9 and 1.30.6-alpine to 1.30.7-alpine after reading both on both platforms; 1.29.8 has no fixed release on its line | pass | exit 1
not fixed Dockerfile:3
would fix Dockerfile:1
would fix Dockerfile:2 | + +39/39 cases match. diff --git a/parity/nginxh2.py b/parity/nginxh2.py new file mode 100644 index 0000000..c28bde7 --- /dev/null +++ b/parity/nginxh2.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""Check the nginxh2 detector against nginx builds whose status is known. + +usage: python3 parity/nginxh2.py path/to/earlylight [case ...] + +With case names, only those run and only their rows of the results file +change (a registry's pull limit can stop a full run part way). + +Needs Docker and registry access. Cases are in parity/nginxh2/cases.json: +published images scanned from Docker Hub by digest (one pull each), images +built from parity/nginxh2/*.Dockerfile with the classic builder on images +already pulled (no pulls) and scanned from `docker save` archives, one built +image exported and scanned as a filesystem, a source tree scanned offline, +and fix --dry-run on a small tree, offline and against the registry. Each +case's findings are compared with the expected rows, which come from +FACTS.md (fixed releases, the releases that introduced each flaw, what a +configuration turns on), not from earlier runs. Writes +parity/NGINXH2-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, "nginxh2") + + +def run(tool, args): + out = subprocess.run([tool] + args, capture_output=True, text=True) + return out + + +def scan(tool, args): + # Flags go before the target: the command line stops reading flags there. + out = run(tool, args[:2] + ["--detector", "nginxh2", "--format", "json", "--show-cleared"] + args[2:]) + try: + return json.loads(out.stdout) + except json.JSONDecodeError: + return {"targets": [{"error": (out.stderr or out.stdout).strip()[:300]}]} + + +def rows(report, repo=False, platform=None): + got, notes = [], [] + for t in report.get("targets", []): + if t.get("error"): + got.append(["error", t["error"][:120], "", "", "", ""]) + if t.get("digest"): + notes.append(t.get("platform", "") + " " + t["digest"]) + for f in t.get("findings", []): + facts = f.get("facts", {}) + if repo: + got.append([f["path"] + ":" + str(f.get("line", 0)), f["kind"], f["verdict"]]) + else: + got.append([platform or t.get("platform", ""), f["path"], f["kind"], f["verdict"], facts.get("status", ""), facts.get("exposure", "")]) + if facts.get("bits") == "32" and "32-bit" not in notes: + notes.append("32-bit") + return got, notes + + +def safe_extract(tar, dest): + 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 build(c): + tag = "earlylight-parity-nginxh2:" + c["name"].replace("-fs", "") + env = dict(os.environ, DOCKER_BUILDKIT="0") # the classic builder uses the local base images: no pulls + subprocess.run(["docker", "build", "-q", "--platform", "linux/amd64", "-t", tag, "-f", os.path.join(CASES, c["dockerfile"]), CASES], + check=True, stdout=subprocess.DEVNULL, env=env) + return tag + + +def fix_lines(out): + got = [] + for l in out.stdout.splitlines(): + if l.startswith(" "): + continue + parts = l.split() + if len(parts) >= 2 and parts[0] in ("fixed", "would", "not", "note", "incomplete"): + verb = parts[0] + rest = parts[1:] + if verb in ("would", "not"): + verb += " " + parts[1] + rest = parts[2:] + got.append([verb, rest[0] if rest else ""]) + got.append(["exit", str(out.returncode)]) + return got + + +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) + if kind == "fix": + args = ["fix", "--detector", "nginxh2", "--dry-run"] + c.get("args", []) + [os.path.join(CASES, c["dir"])] + return fix_lines(run(tool, args)), [] + tag = build(c) + 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", "--platform", "linux/amd64", 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) + return rows(scan(tool, ["scan", "fs", "--as-root", root]), platform="fs") + + +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, notes = run_case(tool, c, tmp) + want = c["expected"] + ok = sorted(got) == sorted(want) + failed += not ok + results.append((c, ok, got, want, notes)) + print(("pass " if ok else "FAIL ") + c["name"], flush=True) + path = os.path.join(HERE, "NGINXH2-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, notes 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 notes) + 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("# nginx HTTP/2 pair (nginxh2) fixture results\n\nGenerated by `parity/nginxh2.py`. Each row's expected findings come from " + "[FACTS.md](../detectors/nginxh2/FACTS.md). Registry images are scanned by digest; the image digest scanned is listed. " + "Image rows are platform, path, kind, verdict, status, exposure; source-tree rows are file:line, kind, verdict; " + "fix rows are what fix printed for each place, and its exit status.\n\n" + "| Case | What | Result | Findings |\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/nginxh2/alpine-3.23-pkg.Dockerfile b/parity/nginxh2/alpine-3.23-pkg.Dockerfile new file mode 100644 index 0000000..462a72c --- /dev/null +++ b/parity/nginxh2/alpine-3.23-pkg.Dockerfile @@ -0,0 +1,3 @@ +# Alpine 3.23's nginx (1.28.3-r7): that branch had no fixed package on 2026-11-18. +FROM alpine:3.23 +RUN apk add --no-cache nginx diff --git a/parity/nginxh2/alpine-pkg.Dockerfile b/parity/nginxh2/alpine-pkg.Dockerfile new file mode 100644 index 0000000..8130a96 --- /dev/null +++ b/parity/nginxh2/alpine-pkg.Dockerfile @@ -0,0 +1,4 @@ +# Alpine 3.24's nginx as published when built (1.30.7-r0 from 2026-11-18 17:06 UTC), HTTP/2 on in http.d. +FROM alpine:3 +RUN apk add --no-cache nginx +COPY conf/static-h2.conf /etc/nginx/http.d/default.conf diff --git a/parity/nginxh2/cases.json b/parity/nginxh2/cases.json new file mode 100644 index 0000000..8c53cfb --- /dev/null +++ b/parity/nginxh2/cases.json @@ -0,0 +1,1420 @@ +[ + { + "name": "official-1.31.8", + "what": "Docker official 1.31.8 (Debian): the last mainline before the fix; default site, port 80; nginx-debug is installed but the command does not start it, so its exposure is unknown (round-4 verification 2)", + "mode": "registry", + "ref": "nginx:1.31.8@sha256:165ddde8751e75a1c907d24ef10d9f6deb08b57e0fe56caf67512486aff76d82", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ] + }, + { + "name": "official-1.31.9", + "what": "Docker official 1.31.9: fixed", + "mode": "registry", + "ref": "nginx:1.31.9@sha256:08f354a3b44c422021a5c0f5efb3e27f8f90236b5447d3bac4053f5f50ab6760", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "fixed", + "fixed", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "fixed", + "fixed", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "fixed", + "fixed", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "fixed", + "fixed", + "unknown" + ] + ] + }, + { + "name": "official-1.30.6-alpine", + "what": "Docker official 1.30.6-alpine: the last stable before the fix", + "mode": "registry", + "ref": "nginx:1.30.6-alpine@sha256:901e593c95dc85f5a729f5765516321366ef4ac401821431d408897e95287d0a", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ] + }, + { + "name": "official-1.30.7-alpine", + "what": "Docker official 1.30.7-alpine: fixed", + "mode": "registry", + "ref": "nginx:1.30.7-alpine@sha256:b24de00298eb7fb23839442d46c780991be7bc7ddb081b6c0876ac777012e352", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "fixed", + "fixed", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "fixed", + "fixed", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "fixed", + "fixed", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "fixed", + "fixed", + "unknown" + ] + ] + }, + { + "name": "official-1.31.8-perl", + "what": "Docker official 1.31.8-perl", + "mode": "registry", + "ref": "nginx:1.31.8-perl@sha256:82a12bb0001413a9c1e243f67dbc6e742b59b537f88841a0c8b865a7a271aea5", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ] + }, + { + "name": "official-1.30.7-otel", + "what": "Docker official 1.30.7-otel: fixed", + "mode": "registry", + "ref": "nginx:1.30.7-otel@sha256:6143bea44138201e86a48592d26dafcc230bcb56e71b5f72505f5cc1a27aeb16", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "fixed", + "fixed", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "fixed", + "fixed", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "fixed", + "fixed", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "fixed", + "fixed", + "unknown" + ] + ] + }, + { + "name": "official-1.31.8-arm64", + "what": "Docker official 1.31.8 on linux/arm64: affected alike", + "mode": "registry", + "ref": "nginx:1.31.8@sha256:165ddde8751e75a1c907d24ef10d9f6deb08b57e0fe56caf67512486aff76d82", + "expected": [ + [ + "linux/arm64/v8", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/arm64/v8", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/arm64/v8", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/arm64/v8", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ], + "platform": "linux/arm64" + }, + { + "name": "official-1.31.8-386", + "what": "Docker official 1.31.8 on linux/386: a 32-bit build, still vulnerable (the published exploit needs 64-bit)", + "mode": "registry", + "ref": "nginx:1.31.8@sha256:165ddde8751e75a1c907d24ef10d9f6deb08b57e0fe56caf67512486aff76d82", + "expected": [ + [ + "linux/386", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/386", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/386", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/386", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ], + "platform": "linux/386" + }, + { + "name": "official-1.20.2", + "what": "Docker official 1.20.2: an old line, no fix, in both ranges", + "mode": "registry", + "ref": "nginx:1.20.2@sha256:38f8c1d9613f3f42e7969c3b1dd5c3277e635d4576713e6453c6193e66270a6d", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ] + }, + { + "name": "official-1.18.0", + "what": "Docker official 1.18.0: before 1.19.7, so not affected by CVE-2026-123633; vulnerable to CVE-2026-123007", + "mode": "registry", + "ref": "nginx:1.18.0@sha256:e90ac5331fe095cea01b121a3627174b2e33e06e83720e9a934c7b8ccc9c55a0", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "inactive", + "not-affected", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "inactive", + "not-affected", + "unknown" + ] + ] + }, + { + "name": "official-1.19.6", + "what": "Docker official 1.19.6: the last release before 76672e650, so not affected by CVE-2026-123633; vulnerable to CVE-2026-123007", + "mode": "registry", + "ref": "nginx:1.19.6@sha256:8e10956422503824ebb599f37c26a90fe70541942687f70bbdb744530fc9eba4", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "inactive", + "not-affected", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "inactive", + "not-affected", + "unknown" + ] + ] + }, + { + "name": "official-1.19.7", + "what": "Docker official 1.19.7: the first release with both flaws", + "mode": "registry", + "ref": "nginx:1.19.7@sha256:f3693fe50d5b1df1ecd315d54813a77afd56b0245a404055a946574deb6b34fc", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ] + }, + { + "name": "official-1.10.3", + "what": "Docker official 1.10.3 (a single-platform image): CVE-2026-123007 only. Tags before 1.10 (1.9.x, 1.8.x, the pre-HTTP/2 releases) are schema 1 manifests no current client reads; the version boundary at 1.9.5 is covered by the unit tests and the noh2 case", + "mode": "registry", + "ref": "nginx:1.10.3@sha256:6202beb06ea61f44179e02ca965e8e13b961d12640101fca213efbfd145d7575", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "inactive", + "not-affected", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "inactive", + "not-affected", + "unknown" + ] + ] + }, + { + "name": "unprivileged-1.31.7-alpine", + "what": "nginxinc/nginx-unprivileged 1.31.7-alpine (no fixed tag on Docker Hub at 16:50 UTC)", + "mode": "registry", + "ref": "nginxinc/nginx-unprivileged:1.31.7-alpine@sha256:b5047b9b76845eac124358373c6852377c52e4b05834a47647e955dd91cb8f1e", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ] + }, + { + "name": "openresty-1.31.8.1", + "what": "OpenResty 1.31.8.1 (nginx 1.31.8): no OpenResty release with the fix", + "mode": "registry", + "ref": "openresty/openresty:1.31.8.1-alpine@sha256:fec9da11e7a975d67caf66aaf70e9af2a101fdb167e0b60502c94a4e4959b943", + "expected": [ + [ + "linux/amd64", + "/usr/local/openresty/nginx/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/local/openresty/nginx/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "not-exposed" + ] + ] + }, + { + "name": "bitnamilegacy-1.29.1", + "what": "Bitnami nginx 1.29.1 (bitnamilegacy, frozen): no fix; Bitnami starts nginx through its own entrypoint script, so exposure is unknown (review 2, finding 2)", + "mode": "registry", + "ref": "bitnamilegacy/nginx:1.29.1@sha256:b2e803958eda5723aae1e36ed0e418f6e0c79e7ce890820eba9cad85a6381286", + "expected": [ + [ + "linux/amd64", + "/opt/bitnami/nginx/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/opt/bitnami/nginx/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ] + }, + { + "name": "ingress-nginx-bitnami-1.13.1", + "what": "ingress-nginx controller 1.13.1 (Bitnami's build): archived project, HTTP/2 on by default", + "mode": "registry", + "ref": "bitnamilegacy/nginx-ingress-controller:1.13.1@sha256:95e574be03a97a1b829bc7e94a749d07cf31e587d55b2f18e756fa7eb21ebe3a", + "expected": [ + [ + "linux/amd64", + "/usr/local/nginx/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "linux/amd64", + "/usr/local/nginx/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "exposed" + ] + ] + }, + { + "name": "f5-ingress-5.7.1", + "what": "F5 NGINX Ingress Controller 5.7.1 (nginx 1.31.8); its configuration is written at start", + "mode": "registry", + "ref": "nginx/nginx-ingress:5.7.1@sha256:b6a970b8fccb0409030d8689087adc071e3344b6a88046fb31ede5a80bb6b480", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ] + }, + { + "name": "f5-ingress-5.8.0", + "what": "F5 NGINX Ingress Controller 5.8.0 (nginx 1.31.9)", + "mode": "registry", + "ref": "nginx/nginx-ingress:5.8.0@sha256:57705208dfa8ffb13be2bd8fca234b8a5dd49502eb37d44be57de54c6fec37aa", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "fixed", + "fixed", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "fixed", + "fixed", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "fixed", + "fixed", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "fixed", + "fixed", + "unknown" + ] + ] + }, + { + "name": "h2-tls-proxy", + "what": "1.31.8, HTTP/2 over TLS in front of a proxy", + "mode": "build", + "dockerfile": "h2-tls-proxy.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "exposed" + ] + ] + }, + { + "name": "h2-cleartext", + "what": "1.31.8, HTTP/2 without TLS in front of a proxy", + "mode": "build", + "dockerfile": "h2-cleartext.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "http2-cleartext-only" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "exposed" + ] + ] + }, + { + "name": "h2-off", + "what": "1.31.8, TLS and a proxy with http2 off: not exposed, still vulnerable", + "mode": "build", + "dockerfile": "h2-off.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ] + }, + { + "name": "h2-static", + "what": "1.31.8, HTTP/2 over TLS serving files only", + "mode": "build", + "dockerfile": "h2-static.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "http2-without-proxy" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ] + }, + { + "name": "templates", + "what": "1.31.8, HTTP/2 in a template the entrypoint writes to conf.d", + "mode": "build", + "dockerfile": "templates.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "exposed" + ] + ] + }, + { + "name": "cmdline", + "what": "1.31.8, the command loads another configuration (-c) with HTTP/2", + "mode": "build", + "dockerfile": "cmdline.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "exposed" + ] + ] + }, + { + "name": "unread-include", + "what": "1.31.8, an include of files the scan does not read: exposure unknown", + "mode": "build", + "dockerfile": "unread-include.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ] + }, + { + "name": "hostile", + "what": "1.31.8, include loops, a symbolic link loop, an include fan-out, deep nesting and a 5 MB configuration file", + "mode": "build", + "dockerfile": "hostile.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx-debug", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ] + }, + { + "name": "hidden", + "what": "synthetic: 1.31.8 without its version line", + "mode": "build", + "dockerfile": "hidden.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "unknown", + "unknown", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "unknown", + "unknown", + "not-exposed" + ] + ] + }, + { + "name": "renamed", + "what": "synthetic: 1.31.8 renamed WAFsrv/9.9.9 throughout", + "mode": "build", + "dockerfile": "renamed.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "unknown", + "unknown", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "unknown", + "unknown", + "not-exposed" + ] + ] + }, + { + "name": "conflict", + "what": "synthetic: 1.31.8 whose version line alone claims 1.31.9", + "mode": "build", + "dockerfile": "conflict.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "unknown", + "unknown", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "unknown", + "unknown", + "not-exposed" + ] + ] + }, + { + "name": "noh2", + "what": "synthetic: 1.31.8 reading as built without HTTP/2", + "mode": "build", + "dockerfile": "noh2.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "inactive", + "not-affected", + "not-exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "inactive", + "not-affected", + "not-exposed" + ] + ] + }, + { + "name": "debian-pkg", + "what": "Debian 12's nginx 1.22.1-9+deb12u10 (no fixed package), a site enabled through a symbolic link", + "mode": "build", + "dockerfile": "debian-pkg.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "exposed" + ] + ] + }, + { + "name": "debian-pkg-fs", + "what": "the same image exported and scanned as a filesystem", + "mode": "fs", + "dockerfile": "debian-pkg.Dockerfile", + "expected": [ + [ + "fs", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "exposed" + ], + [ + "fs", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "exposed" + ] + ] + }, + { + "name": "ubuntu-pkg", + "what": "Ubuntu 24.04's nginx 1.24.0-2ubuntu7.19, the default site; the image's command is a shell, not nginx, so exposure is unknown unless the configuration shows HTTP/2 on (review 2, finding 2)", + "mode": "build", + "dockerfile": "ubuntu-pkg.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ] + }, + { + "name": "alpine-pkg", + "what": "Alpine 3.24's nginx as published at build time (1.30.7-r0 since 2026-11-18 17:06 UTC), HTTP/2 on in http.d; the image's command is a shell, not nginx, so exposure is unknown unless the configuration shows HTTP/2 on (review 2, finding 2)", + "mode": "build", + "dockerfile": "alpine-pkg.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "fixed", + "fixed", + "exposed" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "fixed", + "fixed", + "unknown" + ] + ] + }, + { + "name": "alpine-3.23-pkg", + "what": "Alpine 3.23's nginx 1.28.3-r7: no fixed package on that branch; the image's command is a shell, not nginx, so exposure is unknown unless the configuration shows HTTP/2 on (review 2, finding 2)", + "mode": "build", + "dockerfile": "alpine-3.23-pkg.Dockerfile", + "expected": [ + [ + "linux/amd64", + "/usr/sbin/nginx", + "flow-control", + "vulnerable", + "vulnerable", + "unknown" + ], + [ + "linux/amd64", + "/usr/sbin/nginx", + "connection-reuse", + "vulnerable", + "vulnerable", + "unknown" + ] + ] + }, + { + "name": "repo", + "what": "a source tree scanned offline: Dockerfile FROM (an ARG tag, a moving tag, OpenResty, a fixed tag), apt, apk, dnf module, sh -c and nginx.org installs, Compose, Kubernetes (a digest-pinned ingress-nginx, a ConfigMap with HTTP/2), Helm values (the ingress-nginx chart's registry/image/tag) and a chart depending on ingress-nginx", + "mode": "repo", + "dir": "repo", + "expected": [ + [ + "Dockerfile:2", + "image-pin", + "vulnerable" + ], + [ + "Dockerfile:3", + "image-pin", + "vulnerable" + ], + [ + "Dockerfile:6", + "os-package", + "vulnerable" + ], + [ + "Dockerfile:8", + "not-checked", + "unknown" + ], + [ + "Dockerfile:10", + "os-package", + "vulnerable" + ], + [ + "Dockerfile:12", + "os-package", + "vulnerable" + ], + [ + "Dockerfile:16", + "not-checked", + "unknown" + ], + [ + "Dockerfile:16", + "not-checked", + "unknown" + ], + [ + "Dockerfile:17", + "not-checked", + "unknown" + ], + [ + "Dockerfile:18", + "image-pin", + "vulnerable" + ], + [ + "Dockerfile:20", + "not-checked", + "unknown" + ], + [ + "chart/Chart.yaml:5", + "image-pin", + "vulnerable" + ], + [ + "compose.yaml:3", + "image-pin", + "vulnerable" + ], + [ + "compose.yaml:5", + "image-pin", + "vulnerable" + ], + [ + "compose.yaml:7", + "image-pin", + "vulnerable" + ], + [ + "conf.d/site.conf:3", + "http2-config", + "inactive" + ], + [ + "helm/values.yaml:5", + "image-pin", + "vulnerable" + ], + [ + "helm/values.yaml:8", + "image-pin", + "vulnerable" + ], + [ + "k8s/deploy.yaml:9", + "image-pin", + "vulnerable" + ], + [ + "k8s/deploy.yaml:11", + "image-pin", + "vulnerable" + ], + [ + "k8s/deploy.yaml#default.conf:19", + "http2-config", + "inactive" + ] + ] + }, + { + "name": "fix-offline", + "what": "fix --dry-run --offline: every tag move needs the registry, so nothing is changed", + "mode": "fix", + "dir": "fix", + "args": [ + "--offline" + ], + "expected": [ + [ + "not fixed", + "Dockerfile:1" + ], + [ + "not fixed", + "Dockerfile:2" + ], + [ + "not fixed", + "Dockerfile:3" + ], + [ + "exit", + "1" + ] + ] + }, + { + "name": "fix-registry", + "what": "fix --dry-run --platform linux/amd64,linux/arm64: 1.31.8 to 1.31.9 and 1.30.6-alpine to 1.30.7-alpine after reading both on both platforms; 1.29.8 has no fixed release on its line", + "mode": "fix", + "dir": "fix", + "args": [ + "--platform", + "linux/amd64,linux/arm64" + ], + "expected": [ + [ + "would fix", + "Dockerfile:1" + ], + [ + "would fix", + "Dockerfile:2" + ], + [ + "not fixed", + "Dockerfile:3" + ], + [ + "exit", + "1" + ] + ] + } +] diff --git a/parity/nginxh2/cmdline.Dockerfile b/parity/nginxh2/cmdline.Dockerfile new file mode 100644 index 0000000..4a39997 --- /dev/null +++ b/parity/nginxh2/cmdline.Dockerfile @@ -0,0 +1,4 @@ +# The image's command loads another configuration (-c) that turns HTTP/2 on. +FROM nginx:1.31.8 +COPY conf/app.conf /srv/app.conf +CMD ["nginx", "-c", "/srv/app.conf", "-g", "daemon off;"] diff --git a/parity/nginxh2/conf/app.conf b/parity/nginxh2/conf/app.conf new file mode 100644 index 0000000..b882e92 --- /dev/null +++ b/parity/nginxh2/conf/app.conf @@ -0,0 +1,11 @@ +events { worker_connections 256; } +http { + include /etc/nginx/mime.types; + server { + listen 443 ssl; + http2 on; + ssl_certificate /etc/nginx/cert.pem; + ssl_certificate_key /etc/nginx/key.pem; + location / { grpc_pass grpc://app:50051; } + } +} diff --git a/parity/nginxh2/conf/cleartext.conf b/parity/nginxh2/conf/cleartext.conf new file mode 100644 index 0000000..18fd632 --- /dev/null +++ b/parity/nginxh2/conf/cleartext.conf @@ -0,0 +1,4 @@ +server { + listen 8080 http2; + location / { proxy_pass http://app:8080; } +} diff --git a/parity/nginxh2/conf/off.conf b/parity/nginxh2/conf/off.conf new file mode 100644 index 0000000..15892ac --- /dev/null +++ b/parity/nginxh2/conf/off.conf @@ -0,0 +1,7 @@ +server { + listen 443 ssl; + http2 off; + ssl_certificate /etc/nginx/cert.pem; + ssl_certificate_key /etc/nginx/key.pem; + location / { proxy_pass http://app:8080; } +} diff --git a/parity/nginxh2/conf/static-h2.conf b/parity/nginxh2/conf/static-h2.conf new file mode 100644 index 0000000..9d6db9a --- /dev/null +++ b/parity/nginxh2/conf/static-h2.conf @@ -0,0 +1,7 @@ +server { + listen 443 ssl; + http2 on; + ssl_certificate /etc/nginx/cert.pem; + ssl_certificate_key /etc/nginx/key.pem; + root /usr/share/nginx/html; +} diff --git a/parity/nginxh2/conf/tls-proxy.conf b/parity/nginxh2/conf/tls-proxy.conf new file mode 100644 index 0000000..03ff12f --- /dev/null +++ b/parity/nginxh2/conf/tls-proxy.conf @@ -0,0 +1,6 @@ +server { + listen 443 ssl http2; + ssl_certificate /etc/nginx/cert.pem; + ssl_certificate_key /etc/nginx/key.pem; + location / { proxy_pass http://app:8080; } +} diff --git a/parity/nginxh2/conf/unread-main.conf b/parity/nginxh2/conf/unread-main.conf new file mode 100644 index 0000000..553b45a --- /dev/null +++ b/parity/nginxh2/conf/unread-main.conf @@ -0,0 +1,5 @@ +events {} +http { + include /srv/vhosts/*; + server { listen 80; } +} diff --git a/parity/nginxh2/conflict.Dockerfile b/parity/nginxh2/conflict.Dockerfile new file mode 100644 index 0000000..1fbf1d7 --- /dev/null +++ b/parity/nginxh2/conflict.Dockerfile @@ -0,0 +1,3 @@ +# Synthetic: 1.31.8 with only its version line edited to claim 1.31.9 (the Server header still says 1.31.8). Unknown, never fixed. +FROM nginx:1.31.8 +RUN rm /usr/sbin/nginx-debug && sed -i 's#nginx version: nginx/1\.31\.8#nginx version: nginx/1.31.9#' /usr/sbin/nginx diff --git a/parity/nginxh2/debian-pkg.Dockerfile b/parity/nginxh2/debian-pkg.Dockerfile new file mode 100644 index 0000000..a04e1a4 --- /dev/null +++ b/parity/nginxh2/debian-pkg.Dockerfile @@ -0,0 +1,5 @@ +# Debian 12's own nginx (1.22.1-9+deb12u10, no fixed package on 2026-11-18), a site enabled through a symbolic link. +FROM debian:12 +RUN apt-get update && apt-get install -y --no-install-recommends nginx && rm -rf /var/lib/apt/lists/* +COPY conf/tls-proxy.conf /etc/nginx/sites-available/app +RUN rm /etc/nginx/sites-enabled/default && ln -s ../sites-available/app /etc/nginx/sites-enabled/app diff --git a/parity/nginxh2/fix/Dockerfile b/parity/nginxh2/fix/Dockerfile new file mode 100644 index 0000000..89807f0 --- /dev/null +++ b/parity/nginxh2/fix/Dockerfile @@ -0,0 +1,3 @@ +FROM nginx:1.31.8 AS mainline +FROM nginx:1.30.6-alpine AS stable +FROM nginx:1.29.8 AS old diff --git a/parity/nginxh2/h2-cleartext.Dockerfile b/parity/nginxh2/h2-cleartext.Dockerfile new file mode 100644 index 0000000..8b27de8 --- /dev/null +++ b/parity/nginxh2/h2-cleartext.Dockerfile @@ -0,0 +1,3 @@ +# HTTP/2 without TLS (prior knowledge) in front of a proxy. +FROM nginx:1.31.8 +COPY conf/cleartext.conf /etc/nginx/conf.d/default.conf diff --git a/parity/nginxh2/h2-off.Dockerfile b/parity/nginxh2/h2-off.Dockerfile new file mode 100644 index 0000000..6c0d880 --- /dev/null +++ b/parity/nginxh2/h2-off.Dockerfile @@ -0,0 +1,3 @@ +# TLS, a proxy, and "http2 off;": not exposed, still vulnerable. +FROM nginx:1.31.8 +COPY conf/off.conf /etc/nginx/conf.d/default.conf diff --git a/parity/nginxh2/h2-static.Dockerfile b/parity/nginxh2/h2-static.Dockerfile new file mode 100644 index 0000000..fcfaf15 --- /dev/null +++ b/parity/nginxh2/h2-static.Dockerfile @@ -0,0 +1,3 @@ +# HTTP/2 over TLS serving static files only (no proxy): exposed to CVE-2026-123007, not the 123633 path. +FROM nginx:1.31.8 +COPY conf/static-h2.conf /etc/nginx/conf.d/default.conf diff --git a/parity/nginxh2/h2-tls-proxy.Dockerfile b/parity/nginxh2/h2-tls-proxy.Dockerfile new file mode 100644 index 0000000..70f6ec2 --- /dev/null +++ b/parity/nginxh2/h2-tls-proxy.Dockerfile @@ -0,0 +1,3 @@ +# nginx 1.31.8 (official, sha256:165ddde8751e...) serving HTTP/2 over TLS in front of a proxy: exposed to both. +FROM nginx:1.31.8 +COPY conf/tls-proxy.conf /etc/nginx/conf.d/default.conf diff --git a/parity/nginxh2/hidden.Dockerfile b/parity/nginxh2/hidden.Dockerfile new file mode 100644 index 0000000..3d7bef2 --- /dev/null +++ b/parity/nginxh2/hidden.Dockerfile @@ -0,0 +1,3 @@ +# Synthetic: the version line is renamed away (same length), as a patched or stripped build might be. Never cleared. +FROM nginx:1.31.8 +RUN rm /usr/sbin/nginx-debug && sed -i 's/nginx version: /nginx-build: v /' /usr/sbin/nginx diff --git a/parity/nginxh2/hostile.Dockerfile b/parity/nginxh2/hostile.Dockerfile new file mode 100644 index 0000000..eca19e0 --- /dev/null +++ b/parity/nginxh2/hostile.Dockerfile @@ -0,0 +1,13 @@ +# Include loops, a symbolic link loop, a fan-out of includes, deep nesting and an oversized +# configuration file: the scan finishes, the server stays vulnerable, exposure is unknown. +FROM nginx:1.31.8 +RUN cd /etc/nginx/conf.d \ + && printf 'include /etc/nginx/conf.d/b.inc;\n' > a.inc \ + && printf 'include /etc/nginx/conf.d/a.inc;\n' > b.inc \ + && printf 'include /etc/nginx/conf.d/a.inc;\n' > loop.conf \ + && ln -s self.conf self.conf \ + && for i in $(seq 0 15); do n=$((i+1)); printf 'include /etc/nginx/fan/l%d.inc; include /etc/nginx/fan/l%d.inc;\n' $n $n > /tmp/l$i.inc; done \ + && mkdir -p /etc/nginx/fan && mv /tmp/l*.inc /etc/nginx/fan/ && printf 'include /etc/nginx/fan/l0.inc;\n' > fan.conf \ + && awk 'BEGIN{for(i=0;i<80;i++) printf "location /%d {", i; for(i=0;i<80;i++) printf "}"; print ""}' > /etc/nginx/deep.inc \ + && printf 'server { listen 81; include /etc/nginx/deep.inc; }\n' > deep.conf \ + && head -c 5000000 /dev/zero | tr '\0' '#' > big.conf diff --git a/parity/nginxh2/noh2.Dockerfile b/parity/nginxh2/noh2.Dockerfile new file mode 100644 index 0000000..035ea3b --- /dev/null +++ b/parity/nginxh2/noh2.Dockerfile @@ -0,0 +1,3 @@ +# Synthetic: the module list and configure arguments edited to read as a build without HTTP/2. Not affected. +FROM nginx:1.31.8 +RUN rm /usr/sbin/nginx-debug && sed -i 's/ngx_http_v2_module/ngx_http_vX_module/g; s/--with-http_v2_module/--with-http_vX_module/g' /usr/sbin/nginx diff --git a/parity/nginxh2/renamed.Dockerfile b/parity/nginxh2/renamed.Dockerfile new file mode 100644 index 0000000..3aca284 --- /dev/null +++ b/parity/nginxh2/renamed.Dockerfile @@ -0,0 +1,3 @@ +# Synthetic: a build that names itself something else everywhere. Unknown. +FROM nginx:1.31.8 +RUN rm /usr/sbin/nginx-debug && sed -i 's#nginx/1\.31\.8#WAFsrv/9.9.9#g' /usr/sbin/nginx diff --git a/parity/nginxh2/repo/Dockerfile b/parity/nginxh2/repo/Dockerfile new file mode 100644 index 0000000..93887a4 --- /dev/null +++ b/parity/nginxh2/repo/Dockerfile @@ -0,0 +1,21 @@ +ARG NGINX_TAG=1.30.6 +FROM nginx:1.31.8-alpine AS edge +FROM nginx:${NGINX_TAG}-perl AS web +COPY conf.d/ /etc/nginx/conf.d/ +FROM debian:12 AS deb +RUN apt-get update && apt-get install -y --no-install-recommends nginx=1.22.1-9+deb12u10 && rm -rf /var/lib/apt/lists/* +FROM alpine:3.24 AS apk +RUN apk add --no-cache nginx +FROM ubuntu:24.04 AS ub +RUN sh -c "apt-get update && apt-get install -y nginx-full" +FROM debian:trixie-slim AS org +RUN curl -fsSL https://nginx.org/keys/nginx_signing.key | gpg --dearmor > /usr/share/keyrings/nginx.gpg \ + && echo "deb [signed-by=/usr/share/keyrings/nginx.gpg] http://nginx.org/packages/mainline/debian trixie nginx" > /etc/apt/sources.list.d/nginx.list \ + && apt-get update && apt-get install -y nginx=1.31.8-1~trixie +FROM rockylinux:9 AS rh +RUN dnf module enable -y nginx:1.24 && dnf install -y nginx +FROM nginx:mainline AS moving +FROM openresty/openresty:1.31.8.1-alpine AS or +ENV PKGS="nginx" +RUN apk add $PKGS $EXTRA +FROM nginx:1.31.9 AS ok diff --git a/parity/nginxh2/repo/chart/Chart.yaml b/parity/nginxh2/repo/chart/Chart.yaml new file mode 100644 index 0000000..911f49f --- /dev/null +++ b/parity/nginxh2/repo/chart/Chart.yaml @@ -0,0 +1,7 @@ +apiVersion: v2 +name: app +version: 1.0.0 +dependencies: + - name: ingress-nginx + version: 4.15.1 + repository: https://kubernetes.github.io/ingress-nginx diff --git a/parity/nginxh2/repo/compose.yaml b/parity/nginxh2/repo/compose.yaml new file mode 100644 index 0000000..4d5f6ec --- /dev/null +++ b/parity/nginxh2/repo/compose.yaml @@ -0,0 +1,9 @@ +services: + old: + image: nginx:1.29.8 + unpriv: + image: nginxinc/nginx-unprivileged:1.31.7-alpine + ic: + image: nginx/nginx-ingress:5.7.1 + fixed: + image: nginx:1.30.7-alpine diff --git a/parity/nginxh2/repo/conf.d/site.conf b/parity/nginxh2/repo/conf.d/site.conf new file mode 100644 index 0000000..e57a9f6 --- /dev/null +++ b/parity/nginxh2/repo/conf.d/site.conf @@ -0,0 +1,6 @@ +server { + listen 443 ssl; + http2 on; + location /api { grpc_pass grpc://backend:50051; } +} +server { listen 80; return 301 https://$host$request_uri; } diff --git a/parity/nginxh2/repo/helm/values.yaml b/parity/nginxh2/repo/helm/values.yaml new file mode 100644 index 0000000..9ab0df9 --- /dev/null +++ b/parity/nginxh2/repo/helm/values.yaml @@ -0,0 +1,9 @@ +controller: + image: + registry: registry.k8s.io + image: ingress-nginx/controller + tag: "v1.14.5" +web: + image: + repository: nginx + tag: 1.31.8-alpine-slim diff --git a/parity/nginxh2/repo/k8s/deploy.yaml b/parity/nginxh2/repo/k8s/deploy.yaml new file mode 100644 index 0000000..ba8a559 --- /dev/null +++ b/parity/nginxh2/repo/k8s/deploy.yaml @@ -0,0 +1,21 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: {name: ing} +spec: + template: + spec: + containers: + - name: controller + image: registry.k8s.io/ingress-nginx/controller:v1.15.1@sha256:594ceea76b01c592858f803f9ff4d2cb40542cae2060410b2c95f75907d659e1 + - name: web + image: nginx:1.27.5 +--- +apiVersion: v1 +kind: ConfigMap +metadata: {name: web-conf} +data: + default.conf: | + server { + listen 443 ssl http2; + location / { proxy_pass http://app:8080; } + } diff --git a/parity/nginxh2/templates.Dockerfile b/parity/nginxh2/templates.Dockerfile new file mode 100644 index 0000000..3078123 --- /dev/null +++ b/parity/nginxh2/templates.Dockerfile @@ -0,0 +1,4 @@ +# The official entrypoint writes /etc/nginx/templates/*.template to conf.d at start. +FROM nginx:1.31.8 +RUN rm /etc/nginx/conf.d/default.conf +COPY conf/tls-proxy.conf /etc/nginx/templates/default.conf.template diff --git a/parity/nginxh2/ubuntu-pkg.Dockerfile b/parity/nginxh2/ubuntu-pkg.Dockerfile new file mode 100644 index 0000000..ba2246c --- /dev/null +++ b/parity/nginxh2/ubuntu-pkg.Dockerfile @@ -0,0 +1,3 @@ +# Ubuntu 24.04's nginx (1.24.0-2ubuntu7.19), the default site. +FROM ubuntu:24.04 +RUN apt-get update && apt-get install -y --no-install-recommends nginx && rm -rf /var/lib/apt/lists/* diff --git a/parity/nginxh2/unread-include.Dockerfile b/parity/nginxh2/unread-include.Dockerfile new file mode 100644 index 0000000..8b0cd95 --- /dev/null +++ b/parity/nginxh2/unread-include.Dockerfile @@ -0,0 +1,4 @@ +# An include of files the scan does not read as configuration: exposure unknown, never off. +FROM nginx:1.31.8 +COPY conf/unread-main.conf /etc/nginx/nginx.conf +RUN mkdir -p /srv/vhosts && printf 'server { listen 443 ssl http2; }\n' > /srv/vhosts/site