From 11060f04d0f876251556809b279abe8ff0cc6235 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Thu, 5 Nov 2026 16:08:47 -0700 Subject: [PATCH 1/8] Add the sshole detector for the OpenSSH password bypass on musl Finds OpenSSH servers exposed to *sshole (fixed in OpenSSH 10.6p2 and in Alpine's openssh packages of 2026-11-05) and plans verified fixes in source trees. - fs and image: judges each sshd by its C library, its release and the apk database (Alpine 3.16 to 3.24 and edge backports), then follows musl's shadow lookup, sshd's salt choice and musl's crypt failures, and sshd_config with Include and Match, to report which accounts a crafted password reaches. PAM-checked builds are inactive. - host: reads the banner and the offered login methods; never sends a password. engine.ErrNotApplicable lets a host scan skip a detector whose service is not on that address. - repo and fix: apk installs of an OpenSSH server on Alpine (base release read from the image when the tag does not name it) get the fixed floor, and password fields set to "*" become "*NP*". Each edit is rescanned in memory before it is written. - parity/sshole.py: eight fixture images, all matching. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 3 + README.md | 16 +- detectors/all/all.go | 1 + detectors/sshole/internal/assess/accounts.go | 271 ++++++ detectors/sshole/internal/assess/apk.go | 136 +++ detectors/sshole/internal/assess/assess.go | 548 +++++++++++ .../sshole/internal/assess/assess_test.go | 339 +++++++ detectors/sshole/internal/assess/binary.go | 267 +++++ detectors/sshole/internal/assess/config.go | 356 +++++++ detectors/sshole/internal/assess/fuzz_test.go | 35 + .../testdata/fuzz/FuzzConfig/b0af9b0046ed84e0 | 2 + detectors/sshole/internal/repo/plan.go | 211 ++++ detectors/sshole/internal/repo/repo.go | 908 ++++++++++++++++++ detectors/sshole/internal/repo/repo_test.go | 237 +++++ detectors/sshole/internal/repo/shell.go | 199 ++++ detectors/sshole/internal/testelf/testelf.go | 134 +++ detectors/sshole/probe.go | 162 ++++ detectors/sshole/repo.go | 190 ++++ detectors/sshole/sshole.go | 346 +++++++ detectors/sshole/sshole_test.go | 211 ++++ go.mod | 2 +- go.sum | 2 + internal/engine/engine.go | 6 + internal/engine/run.go | 13 +- parity/SSHOLE-RESULTS.md | 16 + parity/sshole.py | 58 ++ parity/sshole/debian.Dockerfile | 3 + parity/sshole/expected.json | 10 + parity/sshole/fixed.Dockerfile | 4 + parity/sshole/latest.Dockerfile | 2 + parity/sshole/matchonly.Dockerfile | 2 + parity/sshole/pwoff.Dockerfile | 2 + parity/sshole/root.Dockerfile | 8 + parity/sshole/usepam.Dockerfile | 2 + parity/sshole/vuln.Dockerfile | 9 + 35 files changed, 4705 insertions(+), 6 deletions(-) create mode 100644 detectors/sshole/internal/assess/accounts.go create mode 100644 detectors/sshole/internal/assess/apk.go create mode 100644 detectors/sshole/internal/assess/assess.go create mode 100644 detectors/sshole/internal/assess/assess_test.go create mode 100644 detectors/sshole/internal/assess/binary.go create mode 100644 detectors/sshole/internal/assess/config.go create mode 100644 detectors/sshole/internal/assess/fuzz_test.go create mode 100644 detectors/sshole/internal/assess/testdata/fuzz/FuzzConfig/b0af9b0046ed84e0 create mode 100644 detectors/sshole/internal/repo/plan.go create mode 100644 detectors/sshole/internal/repo/repo.go create mode 100644 detectors/sshole/internal/repo/repo_test.go create mode 100644 detectors/sshole/internal/repo/shell.go create mode 100644 detectors/sshole/internal/testelf/testelf.go create mode 100644 detectors/sshole/probe.go create mode 100644 detectors/sshole/repo.go create mode 100644 detectors/sshole/sshole.go create mode 100644 detectors/sshole/sshole_test.go create mode 100644 parity/SSHOLE-RESULTS.md create mode 100644 parity/sshole.py create mode 100644 parity/sshole/debian.Dockerfile create mode 100644 parity/sshole/expected.json create mode 100644 parity/sshole/fixed.Dockerfile create mode 100644 parity/sshole/latest.Dockerfile create mode 100644 parity/sshole/matchonly.Dockerfile create mode 100644 parity/sshole/pwoff.Dockerfile create mode 100644 parity/sshole/root.Dockerfile create mode 100644 parity/sshole/usepam.Dockerfile create mode 100644 parity/sshole/vuln.Dockerfile diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 45be07f..a318bea 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,6 +29,9 @@ jobs: go test ./detectors/php2shell/internal/detect -run '^$' -fuzz '^FuzzInspect$' -fuzztime 20s go test ./detectors/brotli/internal/fingerprint -run '^$' -fuzz '^FuzzFingerprint$' -fuzztime 30s go test ./detectors/brotli/internal/pins -run '^$' -fuzz '^FuzzPins$' -fuzztime 30s + go test ./detectors/sshole/internal/assess -run '^$' -fuzz '^FuzzConfig$' -fuzztime 30s + go test ./detectors/sshole/internal/assess -run '^$' -fuzz '^FuzzAccounts$' -fuzztime 30s + go test ./detectors/sshole/internal/repo -run '^$' -fuzz '^FuzzScanText$' -fuzztime 30s for f in FuzzParseDpkgStatus FuzzParseAPKInstalled FuzzParseHeaderBlob FuzzReadBDB FuzzReadNDB FuzzResolver; do go test ./detectors/php2shell/internal/pkgdb -run '^$' -fuzz "^$f\$" -fuzztime 15s done diff --git a/README.md b/README.md index a2fd231..c1a0809 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,9 @@ One engine for DefectDojo's emerging-vulnerability scanners. Each new vulnerabil | `emudhra` | Trust in the eight eMudhra intermediate CA keys compromised in October 2026 ([Mozilla bug 2083449](https://bugzilla.mozilla.org/show_bug.cgi?id=2083449)): trust stores, bundles, keystores and binaries that still trust them, Go binaries without Go's blocklist (CVE-2026-111943), and servers presenting certificates the compromised keys signed | `fs`, `image`, `host` | | `php2shell` | PHP runtimes vulnerable to CVE-2026-109618 and CVE-2026-109619 ("PHP2Shell"), fixed in PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12 ([GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w), [GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp)). A packaged PHP is judged by its vendor's backport data, never by the version it reports. Also checks the images a source tree builds on and deploys, and can rewrite them to fixed images | `fs`, `image`, `repo`, `fix` | | `brotli` | Brotli decoders vulnerable to CVE-2026-111497 ("Node2Shell", "Broccoli2Shell"), Brotli 1.0.3 through 1.2.0, fixed in 1.0.10, 1.1.1 and 1.2.1 ([GHSA-9v8h-qqgm-4m35](https://github.com/advisories/GHSA-9v8h-qqgm-4m35)): system `libbrotlidec` and every copy bundled into other software (Node.js, .NET, Bun, Electron, Envoy and Istio, Python wheels such as Pillow, pyarrow, duckdb, pycurl and PyMuPDF, brotli4j, and more), on Linux, Windows and macOS. A decoder is judged first by the error code the fix added, so vendor backports are recognised without distribution data; a build that strips it by its own version stamp or by its code, which returns that error code only once fixed. In a source tree it finds the Node.js, .NET and Bun releases and the bundling packages a project pins, and `fix` moves each to the fixed release | `fs`, `image`, `repo`, `fix` | +| `sshole` | \*sshole, the OpenSSH password authentication bypass on musl libc fixed in OpenSSH 10.6p2 and in Alpine's openssh packages of November 5, 2026 ([release notes](https://www.openssh.org/releasenotes.html#10.6p2), [writeup](https://sshhole.com)). On musl, sshd from 7.3p1 to 10.6p1 compares an account's password field of `*` with the `*` that crypt returns when it fails, so a crafted password logs in to that account. It judges each installed sshd by its C library, its release and the apk database (Alpine backports keep the release number), then checks what the target's `sshd_config` (Include, Match, PasswordAuthentication, AuthenticationMethods, PermitRootLogin, AllowUsers and the rest) and account files make reachable, and reports the accounts. 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 and anything that sets a password field to `*`, and `fix` adds the fixed release floor and changes `*` to `*NP*` | `fs`, `image`, `host`, `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` was written here and runs through `earlylight` (`--detector brotli`). +The detectors ported from standalone scanners also build as standalone binaries under the names people search for: `emudhra-scan` and `php2shell-scan`. They keep their original commands, flags and exit status rules. `brotli` and `sshole` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`). ## Install @@ -44,6 +45,11 @@ earlylight scan image --detector php2shell php:8.3-fpm earlylight scan image --detector brotli node:24.22.0-slim earlylight scan repo --detector brotli . # Node.js, .NET, Bun and bundling packages a source tree pins earlylight fix --detector brotli --dry-run . # the one-line moves to fixed releases +earlylight scan image --detector sshole myorg/sshd:prod # OpenSSH servers on musl, their config and accounts +sudo earlylight scan fs --detector sshole / # this machine's sshd +earlylight scan host --detector sshole bastion.example:22 # banner and offered methods; sends no password +earlylight scan repo --detector sshole . # Dockerfiles, scripts and Ansible tasks +earlylight fix --detector sshole --dry-run . # fixed apk floors, "*" to "*NP*" earlylight scan image --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 @@ -106,6 +112,7 @@ The engine enforces one rule for every detector: a finding can only be `fixed`, | `detectors/emudhra` | Adapter, plus `internal/` copied verbatim from emudhra-scan | | `detectors/php2shell` | Adapter, `verbatim.go` from php2shell-scan's command line, and `internal/` copied verbatim from php2shell-scan | | `detectors/brotli` | Adapter, plus `internal/fingerprint` (what a binary proves: the decoder's error table, its tables and code, exports and version stamps), `internal/assess` (the verdict and fix for one file) and `internal/pins` (pins and bundling packages in a source tree, and their verified edits), which know nothing about the engine | +| `detectors/sshole` | Adapter and live-host probe, plus `internal/assess` (what an sshd binary proves, musl's shadow lookup and crypt failures, sshd's salt choice, sshd_config with Include and Match, and the verdict) and `internal/repo` (Dockerfiles, scripts and YAML in a source tree, and their verified edits), which know nothing about the engine | | `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 | @@ -119,6 +126,7 @@ Every port must give exactly the verdicts of the scanner it came from before it - `parity/parity.py` runs emudhra-scan and Early Light over emudhra-scan's public validation images, directories and live TLS servers ([RESULTS.md](parity/RESULTS.md)). - `parity/brotli.py` has no standalone scanner to compare with, so it checks every decoder in 38 images against the vendor's own fix status: Node.js, .NET, Bun, Envoy and curl images before and after their October 2026 releases, distribution packages pinned to their exact unfixed and backported builds, and the Python wheels ([BROTLI-RESULTS.md](parity/BROTLI-RESULTS.md)). - `parity/brotli_files.py` checks 73 release binaries and packages, unpacked and never run: Node.js, .NET and Bun for Windows and macOS, seven Electron releases, Envoy and Istio, and the packages that bundle the decoder ([BROTLI-FILES-RESULTS.md](parity/BROTLI-FILES-RESULTS.md)). A WebAssembly build of the decoder is the one case it cannot settle: it is reported as unknown. +- `parity/sshole.py` builds eight 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, and Debian) 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/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 @@ -136,6 +144,8 @@ go vet ./... && go test -race ./... go test ./internal/source -run '^$' -fuzz '^FuzzTar$' -fuzztime 60s go test ./internal/archive -run '^$' -fuzz '^FuzzWalk$' -fuzztime 60s go test ./detectors/emudhra/internal/detect -run '^$' -fuzz '^FuzzScan$' -fuzztime 60s +go test ./detectors/sshole/internal/assess -run '^$' -fuzz '^FuzzConfig$' -fuzztime 60s +go test ./detectors/sshole/internal/repo -run '^$' -fuzz '^FuzzScanText$' -fuzztime 60s 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 @@ -151,8 +161,8 @@ It only makes network connections when a scan needs them: | --- | --- | | Installing (`install.sh` and the GitHub Action) | GitHub, to download the release and its `checksums.txt`. When `cosign` is installed, it also fetches Sigstore's public trust root to check the signature | | `scan image` | The registry that hosts the image you name | -| `scan repo` and `fix` | The registries that host the images your source tree references. `--offline` turns this off, and `--public-registries-only` refuses private and internal addresses | -| `scan host` | The hosts you name, for a TLS handshake | +| `scan repo` and `fix` | The registries that host the images your source tree references (for `sshole`, the base images whose Alpine release a Dockerfile does not name). `--offline` turns this off, and `--public-registries-only` refuses private and internal addresses | +| `scan host` | The hosts you name: a TLS handshake, and for `sshole` an SSH handshake that asks which login methods the server offers (as user `earlylight-probe`) and stops before sending any password. The server logs it as a connection that did not authenticate | | `scan fs` | Nothing | Results stay where you put them: the SARIF file, the job summary and, when you set `upload-sarif: true`, GitHub code scanning in your own repository. diff --git a/detectors/all/all.go b/detectors/all/all.go index b6816a1..c1c78a4 100644 --- a/detectors/all/all.go +++ b/detectors/all/all.go @@ -5,4 +5,5 @@ import ( _ "github.com/DefectDojo/earlylight/detectors/brotli" _ "github.com/DefectDojo/earlylight/detectors/emudhra" _ "github.com/DefectDojo/earlylight/detectors/php2shell" + _ "github.com/DefectDojo/earlylight/detectors/sshole" ) diff --git a/detectors/sshole/internal/assess/accounts.go b/detectors/sshole/internal/assess/accounts.go new file mode 100644 index 0000000..e9d172a --- /dev/null +++ b/detectors/sshole/internal/assess/accounts.go @@ -0,0 +1,271 @@ +package assess + +import ( + "strconv" + "strings" +) + +// Account is one /etc/passwd entry and the password field sshd compares +// against, found the way musl and sshd find it. +type Account struct { + Name string `json:"name"` + UID int `json:"uid"` + GID int `json:"gid"` + Shell string `json:"shell"` + // Field is the effective password field: the shadow entry's when musl's + // getspnam returns one, else /etc/passwd's. + Field string `json:"-"` + // From is where Field came from: "shadow", "tcb" or "passwd". + From string `json:"from"` + // Expire is the shadow expiry in days since 1970, or -1. + Expire int64 `json:"expire,omitempty"` +} + +// Accounts is the account database of a target. +type Accounts struct { + List []Account // /etc/passwd order: the order getpwent walks + Groups map[string][]string // group name -> member names + GIDs map[int]string // gid -> group name + // Read is false when /etc/passwd was not in the target. + Read bool +} + +// musl reads shadow lines with a 256-byte buffer: a longer line makes +// getspnam fail (ERANGE), and sshd then uses the /etc/passwd field. +const muslShadowLine = 256 + +// ParseAccounts builds the account database from /etc/passwd, /etc/shadow, +// tcb shadow files (/etc/tcb/NAME/shadow, which musl reads first) and +// /etc/group. Missing files are nil. +func ParseAccounts(passwd, shadow, group []byte, tcb map[string][]byte) Accounts { + a := Accounts{Groups: map[string][]string{}, GIDs: map[int]string{}, Read: passwd != nil} + for _, line := range lines(passwd) { + f := strings.Split(line, ":") + if len(f) != 7 || f[0] == "" { + continue // musl's getpwent skips malformed lines + } + uid, err1 := strconv.Atoi(f[2]) + gid, err2 := strconv.Atoi(f[3]) + if err1 != nil || err2 != nil { + continue + } + acc := Account{Name: f[0], UID: uid, GID: gid, Shell: f[6], Field: f[1], From: "passwd", Expire: -1} + var sh []byte + from := "shadow" + if t, ok := tcb[acc.Name]; ok { + sh, from = t, "tcb" + } else { + sh = shadow + } + if field, expire, ok := spnam(sh, acc.Name); ok { + acc.Field, acc.From, acc.Expire = field, from, expire + } + a.List = append(a.List, acc) + } + for _, line := range lines(group) { + f := strings.Split(line, ":") + if len(f) != 4 { + continue + } + gid, err := strconv.Atoi(f[2]) + if err != nil { + continue + } + if _, ok := a.GIDs[gid]; !ok { + a.GIDs[gid] = f[0] + } + for _, m := range strings.Split(f[3], ",") { + if m != "" { + a.Groups[f[0]] = append(a.Groups[f[0]], m) + } + } + } + return a +} + +// GroupsOf returns the groups an account belongs to. +func (a Accounts) GroupsOf(acc Account) []string { + var out []string + if g, ok := a.GIDs[acc.GID]; ok { + out = append(out, g) + } + for g, ms := range a.Groups { + for _, m := range ms { + if m == acc.Name { + out = append(out, g) + } + } + } + return out +} + +// spnam is musl's getspnam_r over one shadow file: the first line for name, +// read through a 256-byte buffer, parsed as musl parses it. +func spnam(b []byte, name string) (field string, expire int64, ok bool) { + if b == nil || name == "" || name[0] == '.' || strings.Contains(name, "/") { + return "", -1, false + } + rest := string(b) + for len(rest) > 0 { + i := strings.IndexByte(rest, '\n') + var line string + terminated := i >= 0 + if terminated { + line, rest = rest[:i], rest[i+1:] + } else { + line, rest = rest, "" + } + if !strings.HasPrefix(line, name+":") { + continue + } + // fgets with a 256-byte buffer holds 255 bytes: the line plus its + // newline must fit, or getspnam fails with ERANGE. + if !terminated || len(line)+1 > muslShadowLine-1 { + return "", -1, false + } + f, ok := parseSpent(line) + if !ok { + continue // musl skips a line it cannot parse and keeps looking + } + return f[1], numField(f[7]), true + } + return "", -1, false +} + +// parseSpent follows musl's __parsespent: nine fields, numeric ones empty or +// decimal. +func parseSpent(line string) ([]string, bool) { + f := strings.SplitN(line, ":", 9) + if len(f) != 9 { + return nil, false + } + for _, n := range f[2:8] { + if n == "" { + continue + } + if _, err := strconv.ParseInt(n, 10, 64); err != nil { + return nil, false + } + } + return f, true +} + +func numField(s string) int64 { + if s == "" { + return -1 + } + n, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return -1 + } + return n +} + +func lines(b []byte) []string { + if b == nil { + return nil + } + return strings.Split(strings.ReplaceAll(string(b), "\r\n", "\n"), "\n") +} + +// Donor says which account's hash an unfixed sshd borrows a salt from, and +// what that salt makes musl's crypt do. +type Donor struct { + Account string `json:"account,omitempty"` + // Setting is the salt sshd passes to crypt ("$6$abc$"). + Setting string `json:"setting,omitempty"` + // Fails says which passwords make crypt fail with that setting: "none", + // "long" (more than 256 bytes, up to sshd's 1024-byte limit) or "any". + Fails string `json:"fails"` +} + +// PickSalt reproduces sshd's pick_salt (openbsd-compat/xcrypt.c before +// 10.6p2): the first account, in /etc/passwd order, whose password field +// starts with '$' and has another '$', cut to its last '$' and to 31 bytes. +// Without one the salt is "xx". +func PickSalt(a Accounts) Donor { + for _, acc := range a.List { + p := acc.Field + if len(p) == 0 || p[0] != '$' { + continue + } + last := strings.LastIndexByte(p[1:], '$') + if last < 0 { + continue + } + typelen := last + 2 // through the last '$' + setting := p[:min(typelen, len(p))] + if len(setting) > 31 { + setting = setting[:31] // strlcpy into char salt[32] + } + return Donor{Account: acc.Name, Setting: setting, Fails: CryptFails(setting)} + } + return Donor{Setting: "xx", Fails: "none"} +} + +// CryptFails says which keys make musl's crypt fail for a setting (see +// musl src/crypt): md5 never within sshd's 1024-byte limit, sha256 and +// sha512 above 256 bytes or always on a bad rounds= value, bcrypt always +// unless the setting carries its 22-character salt, DES never for a +// setting sshd builds. +func CryptFails(setting string) string { + if len(setting) >= 3 && setting[0] == '$' { + switch { + case setting[1] == '1' && setting[2] == '$': + return "none" + case setting[1] == '2' && len(setting) > 3 && setting[3] == '$': + if bcryptOK(setting) { + return "none" + } + return "any" + case (setting[1] == '5' || setting[1] == '6') && setting[2] == '$': + if !shaRoundsOK(setting[3:]) { + return "any" + } + return "long" + } + } + return "none" +} + +func bcryptOK(s string) bool { + if len(s) < 7+22 || s[1] != '2' || s[3] != '$' || s[6] != '$' { + return false + } + if !strings.ContainsRune("abxy", rune(s[2])) { + return false + } + if s[4] < '0' || s[4] > '1' || s[5] < '0' || s[5] > '9' { + return false + } + if (s[4]-'0')*10+(s[5]-'0') < 4 { + return false + } + for _, c := range s[7 : 7+22] { + if !strings.ContainsRune("./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", c) { + return false + } + } + return true +} + +// shaRoundsOK follows musl's rounds= parsing: present means a decimal value +// up to 9999999 closed by '$'. +func shaRoundsOK(salt string) bool { + r, ok := strings.CutPrefix(salt, "rounds=") + if !ok { + return true + } + if r == "" || r[0] < '0' || r[0] > '9' { + return false + } + end := 0 + for end < len(r) && r[end] >= '0' && r[end] <= '9' { + end++ + } + if end >= len(r) || r[end] != '$' { + return false + } + u, err := strconv.ParseUint(r[:end], 10, 64) + return err == nil && u <= 9999999 +} diff --git a/detectors/sshole/internal/assess/apk.go b/detectors/sshole/internal/assess/apk.go new file mode 100644 index 0000000..dd3a2ab --- /dev/null +++ b/detectors/sshole/internal/assess/apk.go @@ -0,0 +1,136 @@ +package assess + +import ( + "path" + "strconv" + "strings" +) + +// Package is an installed package that owns a file. +type Package struct { + Name string `json:"name"` + Version string `json:"version"` + Format string `json:"format"` // "apk" +} + +// APKOwners parses an apk installed database (/lib/apk/db/installed) into a +// map from absolute file path to the package that installed it. +func APKOwners(db []byte) map[string]Package { + out := map[string]Package{} + for _, rec := range strings.Split(strings.ReplaceAll(string(db), "\r\n", "\n"), "\n\n") { + var p Package + dir := "" + var files []string + for _, l := range strings.Split(rec, "\n") { + if len(l) < 2 || l[1] != ':' { + continue + } + v := l[2:] + switch l[0] { + case 'P': + p.Name = v + case 'V': + p.Version = v + case 'F': + dir = "/" + v + case 'R': + files = append(files, path.Join(dir, v)) + } + } + if p.Name == "" || p.Version == "" { + continue + } + p.Format = "apk" + for _, f := range files { + out[f] = p + } + } + return out +} + +// apkVersion is an Alpine openssh version: 10.0_p1-r11. +type apkVersion struct { + upstream Version + pkgver string // "10.0_p1" + rel int +} + +func parseAPK(v string) (apkVersion, bool) { + pkgver, rel, ok := strings.Cut(v, "-r") + if !ok { + return apkVersion{}, false + } + r, err := strconv.Atoi(rel) + if err != nil { + return apkVersion{}, false + } + up, ok := ParseRelease(strings.Replace(pkgver, "_p", "p", 1)) + if !ok { + return apkVersion{}, false + } + return apkVersion{upstream: up, pkgver: pkgver, rel: r}, true +} + +// alpineFixed is the first fixed release of each openssh version Alpine +// ships: aports pw.patch (upstream 4353fdc43), released 2026-11-05 on every +// branch from 3.16 to 3.24 and edge. Checked against each branch's APKINDEX +// and APKBUILD on 2026-11-05; 3.15 and older have no fixed package. +var alpineFixed = map[string]struct { + rel int + branch string +}{ + "9.0_p1": {6, "3.16"}, + "9.1_p1": {7, "3.17"}, + "9.3_p2": {4, "3.18"}, + "9.6_p1": {3, "3.19"}, + "9.7_p1": {6, "3.20"}, + "9.9_p2": {1, "3.21"}, + "10.0_p1": {11, "3.22"}, + "10.2_p1": {1, "3.23"}, + "10.3_p1": {2, "3.24"}, +} + +// AlpineFixedFor returns the fixed package version for an Alpine branch +// ("3.22"), and edge's for "edge". +func AlpineFixedFor(branch string) (string, bool) { + if branch == "edge" { + return "10.6_p2-r0", true + } + for pv, f := range alpineFixed { + if f.branch == branch { + return pv + "-r" + strconv.Itoa(f.rel), true + } + } + return "", false +} + +// AlpineBranches lists the branches with a fixed package, oldest first. +func AlpineBranches() []string { + return []string{"3.16", "3.17", "3.18", "3.19", "3.20", "3.21", "3.22", "3.23", "3.24", "edge"} +} + +// apkStatus judges an Alpine openssh package version. +func apkStatus(version string) (fixed bool, why string, ok bool) { + v, ok := parseAPK(version) + if !ok { + return false, "", false + } + if !v.upstream.Less(FixedRelease) { + return true, "Alpine package " + version + " is OpenSSH " + v.upstream.String() + " or later, which has the fix", true + } + if v.upstream.Less(FirstAffected) { + return true, "OpenSSH " + v.upstream.String() + " predates 7.3p1 and never borrows another account's salt", true + } + f, known := alpineFixed[v.pkgver] + switch { + case !known: + return false, "Alpine never shipped a fix for openssh " + v.pkgver + "; only each branch's current version was patched", true + case v.rel >= f.rel: + return true, "Alpine package " + version + " carries the backported fix (" + v.pkgver + "-r" + strconv.Itoa(f.rel) + " and later)", true + } + return false, "Alpine package " + version + " is older than the fixed " + v.pkgver + "-r" + strconv.Itoa(f.rel), true +} + +// APKFixed judges an Alpine openssh package version: fixed, why, and false +// when the version cannot be read. +func APKFixed(version string) (bool, string, bool) { return apkStatus(version) } diff --git a/detectors/sshole/internal/assess/assess.go b/detectors/sshole/internal/assess/assess.go new file mode 100644 index 0000000..cab4fdb --- /dev/null +++ b/detectors/sshole/internal/assess/assess.go @@ -0,0 +1,548 @@ +// Package assess decides whether an OpenSSH server is exposed to *sshole: +// on musl libc, sshd before 10.6p2 compares a password field of "*" with +// crypt's failure result "*", so a password that makes crypt fail logs in. +// crypt fails when sshd borrows the salt of another account (the "donor") +// whose hash is sha256 or sha512 crypt and the password is longer than 256 +// bytes, or always when that salt is a bcrypt or malformed one. PAM, when +// sshd uses it, checks passwords itself and is not affected. +// +// Everything here works from what the target holds: the binaries, the apk +// database, sshd_config and the account files. It knows nothing about the +// engine. +package assess + +import ( + "fmt" + "sort" + "strings" + "time" +) + +// CVE is empty until one is assigned. +const CVE = "" + +// Status is a verdict. +type Status string + +const ( + Vulnerable Status = "vulnerable" + Fixed Status = "fixed" + Inactive Status = "inactive" + Undecided Status = "unknown" +) + +// Kinds. +const ( + KindExposed = "exposed" // every condition holds + KindServer = "sshd" // an affected build; conditions incomplete, fixed or not in use +) + +// Target is an account sshd would accept a crafted password for. +type Target struct { + Account string `json:"account"` + // Reach is "yes" when every check passes for any connection, "maybe" + // when it depends on the connection (a Match on address or host). + Reach string `json:"reach"` + Why string `json:"why,omitempty"` +} + +// Finding is the verdict on one installed OpenSSH server. +type Finding struct { + Path string `json:"path"` + Kind string `json:"kind"` + Status Status `json:"status"` + Reason string `json:"reason,omitempty"` + Message string `json:"message"` + Fix string `json:"fix,omitempty"` + Severity string `json:"severity,omitempty"` + Release string `json:"release,omitempty"` + Libc Libc `json:"libc"` + PAM bool `json:"pam_built"` + UsePAM string `json:"use_pam,omitempty"` + Helpers []string `json:"helpers,omitempty"` + Package *Package `json:"package,omitempty"` + Config string `json:"config,omitempty"` + // Password says whether sshd accepts password logins ("yes", "no", + // "maybe" when it depends on the connection). + Password string `json:"password_auth,omitempty"` + Donor *Donor `json:"donor,omitempty"` + Targets []Target `json:"targets,omitempty"` + // Missing lists the conditions that do not hold today. + Missing []string `json:"missing,omitempty"` +} + +// Input is a target's evidence. +type Input struct { + Binaries []*Binary + Owners map[string]Package // apk database: file -> package + Files Files + Accounts Accounts + // Resolve returns the path a file path names after symlinks, and + // whether a regular file is there. + Resolve func(p string) (string, bool) + // Branch is the Alpine branch ("3.22", "edge"), when the target is Alpine. + Branch string + // Image is true for container images, whose accounts and configuration + // an entrypoint can still change. + Image bool + Now time.Time +} + +// Run assesses every OpenSSH server in the input. +func Run(in Input) []Finding { + if in.Now.IsZero() { + in.Now = time.Now() + } + byPath := map[string]*Binary{} + for _, b := range in.Binaries { + byPath[b.Path] = b + } + resolve := func(p string) *Binary { + if b, ok := byPath[p]; ok { + return b + } + if in.Resolve != nil { + if r, ok := in.Resolve(p); ok { + return byPath[r] + } + } + return nil + } + used := map[string]bool{} + var units [][]*Binary + for _, b := range in.Binaries { + if b.Role != "sshd" { + continue + } + u := []*Binary{b} + for _, h := range b.Helpers { + if hb := resolve(h); hb != nil && hb != b { + u = append(u, hb) + used[hb.Path] = true + } + } + units = append(units, u) + } + for _, b := range in.Binaries { + if b.Role != "sshd" && !used[b.Path] { + units = append(units, []*Binary{b}) // a helper no listener names + } + } + var out []Finding + for _, u := range units { + if f, ok := assessUnit(in, u); ok { + out = append(out, f) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path }) + return out +} + +func assessUnit(in Input, u []*Binary) (Finding, bool) { + main := u[0] + f := Finding{Path: main.Path, Kind: KindServer, Release: main.Release, Libc: main.Libc} + for _, b := range u { + f.PAM = f.PAM || b.PAM + if b != main { + f.Helpers = append(f.Helpers, b.Path) + } + if b.Libc != main.Libc && main.Libc == Unknown { + f.Libc = b.Libc + } + } + switch f.Libc { + case Glibc, Bionic: + return f, false // glibc's crypt returns NULL on failure: not affected + } + + // Fixed? The package database speaks for vendor backports; otherwise + // the release the binary reports. + fixed, why := false, "" + for _, b := range u { + if p, ok := in.Owners[b.Path]; ok && strings.HasPrefix(p.Name, "openssh") { + pp := p + f.Package = &pp + if fx, w, ok := apkStatus(p.Version); ok { + fixed, why = fx, w + } + break + } + } + if why == "" { + switch { + case !main.Version.Less(FixedRelease): + fixed, why = true, "OpenSSH "+main.Release+" has the fix (10.6p2 and later)" + case main.Version.Less(FirstAffected): + fixed, why = true, "OpenSSH "+main.Release+" predates 7.3p1 and never borrows another account's salt" + default: + why = "OpenSSH " + main.Release + " is older than 10.6p2 and no package database records a backported fix" + } + } + f.Fix = fixText(in, f) + if fixed { + f.Status, f.Reason = Fixed, why + f.Message = fmt.Sprintf("OpenSSH %s server has the *sshole fix", main.Release) + f.Fix = "" + return f, true + } + if f.Libc != Musl { + f.Status = Undecided + f.Reason = fmt.Sprintf("the C library (%s) could not be identified as musl or glibc; *sshole affects musl builds only", f.Libc) + f.Message = fmt.Sprintf("OpenSSH %s server without the *sshole fix on an unidentified C library", main.Release) + return f, true + } + + cfgPath := main.Config + if cfgPath == "" { + cfgPath = "/etc/ssh/sshd_config" + } + f.Config = cfgPath + cfg := ParseConfig(in.Files, cfgPath) + if !cfg.Read { + f.Status, f.Severity = Vulnerable, "medium" + f.Missing = append(f.Missing, cfgPath+" is not in the target, so the password settings are unknown") + f.Message = fmt.Sprintf("OpenSSH %s server on musl without the *sshole fix (%s not found)", main.Release, cfgPath) + f.Reason = why + return f, true + } + f.UsePAM = strings.ToLower(cfg.Global("usepam", "no")) + if f.PAM && f.UsePAM == "yes" { + f.Status = Inactive + f.Reason = "this build uses PAM (UsePAM yes), and PAM checks passwords without crypt's failure result" + f.Message = fmt.Sprintf("OpenSSH %s server on musl without the *sshole fix, with PAM checking passwords", main.Release) + return f, true + } + + donor := PickSalt(in.Accounts) + f.Donor = &donor + var missing []string + if !in.Accounts.Read { + missing = append(missing, "/etc/passwd is not in the target") + } else if donor.Fails == "none" { + if donor.Account == "" { + missing = append(missing, "no account has a $-style password hash, so sshd falls back to the DES salt \"xx\", which never fails") + } else { + missing = append(missing, fmt.Sprintf("the first account with a $-style hash (%s, %.3s...) is not a sha256, sha512 or bcrypt hash, so crypt does not fail", donor.Account, donor.Setting)) + } + } + + passwordSeen := map[string]bool{} + stars := 0 + for _, acc := range in.Accounts.List { + if acc.Field != "*" { + continue + } + stars++ + t, pw := reach(in, cfg, acc) + passwordSeen[pw] = true + if t.Reach != "no" { + f.Targets = append(f.Targets, t) + } else { + missing = append(missing, fmt.Sprintf("%s has password field \"*\" but %s", acc.Name, t.Why)) + } + } + switch { + case len(passwordSeen) == 0: + f.Password = passwordValues(cfg, Account{Name: "\x00"}, nil) + case len(passwordSeen) == 1: + for k := range passwordSeen { + f.Password = k + } + default: + f.Password = "maybe" + } + if in.Accounts.Read && stars == 0 { + missing = append(missing, "no account has the password field \"*\"") + } + f.Missing = missing + f.Reason = why + + exposed := len(f.Targets) > 0 && donor.Fails != "none" + if exposed { + f.Kind, f.Status = KindExposed, Vulnerable + names := make([]string, 0, len(f.Targets)) + sure := false + for _, t := range f.Targets { + names = append(names, t.Account) + sure = sure || t.Reach == "yes" + } + f.Severity = "critical" + if !sure { + f.Severity = "high" + } + length := "longer than 256 bytes" + if donor.Fails == "any" { + length = "of any length" + } + f.Message = fmt.Sprintf("OpenSSH %s server on musl without the *sshole fix accepts a password %s for %s (password field \"*\"); %s's %s hash supplies the salt", + main.Release, length, strings.Join(names, ", "), donor.Account, hashType(donor.Setting)) + if !sure { + f.Message += "; whether a connection reaches it depends on Match conditions" + } + if in.Image { + f.Message += " (as the image ships; an entrypoint can still change accounts or sshd_config)" + } + return f, true + } + f.Status, f.Severity = Vulnerable, "medium" + f.Message = fmt.Sprintf("OpenSSH %s server on musl without the *sshole fix; not exploitable as configured: %s", main.Release, strings.Join(missing, "; ")) + return f, true +} + +func hashType(setting string) string { + switch { + case strings.HasPrefix(setting, "$6$"): + return "sha512-crypt" + case strings.HasPrefix(setting, "$5$"): + return "sha256-crypt" + case strings.HasPrefix(setting, "$2"): + return "bcrypt" + } + return "password" +} + +// passwordValues says whether password authentication alone can succeed +// for acc: PasswordAuthentication on, and an AuthenticationMethods list +// that needs nothing but a password. +func passwordValues(cfg Config, acc Account, groups []string) string { + pa := cfg.Values("passwordauthentication", acc, groups, "yes") + am := cfg.Values("authenticationmethods", acc, groups, "any") + yes, no := false, false + for _, v := range pa { + if strings.EqualFold(v, "yes") { + yes = true + } else { + no = true + } + } + amOK, amNo := false, false + for _, v := range am { + if passwordAlone(v) { + amOK = true + } else { + amNo = true + } + } + switch { + case !yes || !amOK: + return "no" + case no || amNo: + return "maybe" + } + return "yes" +} + +func passwordAlone(v string) bool { + if strings.EqualFold(v, "any") { + return true + } + for _, list := range strings.Fields(v) { + only := true + for _, m := range strings.Split(list, ",") { + if !strings.EqualFold(m, "password") { + only = false + } + } + if only { + return true + } + } + return false +} + +// reach applies sshd's checks for one "*" account: password logins +// allowed, PermitRootLogin for uid 0, AllowUsers/DenyUsers/AllowGroups/ +// DenyGroups, an existing shell (unless chrooted) and account expiry. +func reach(in Input, cfg Config, acc Account) (Target, string) { + groups := in.Accounts.GroupsOf(acc) + t := Target{Account: acc.Name} + res := Yes + var why []string + add := func(tri Tri, reason string) { + if tri == No { + res = No + why = append(why, reason) + } else if tri == Maybe && res != No { + res = Maybe + why = append(why, reason) + } + } + pw := passwordValues(cfg, acc, groups) + switch pw { + case "no": + add(No, "password logins are off (PasswordAuthentication or AuthenticationMethods)") + case "maybe": + add(Maybe, "password logins depend on Match conditions") + } + if acc.UID == 0 { + v := cfg.Values("permitrootlogin", acc, groups, "prohibit-password") + tri := No + for _, x := range v { + if strings.EqualFold(x, "yes") { + tri = Maybe + if len(v) == 1 { + tri = Yes + } + } + } + add(tri, "PermitRootLogin does not allow passwords for uid 0") + } + add(listsAllow(cfg, acc, groups), "AllowUsers, DenyUsers, AllowGroups or DenyGroups excludes it") + + chroot := cfg.Values("chrootdirectory", acc, groups, "none") + needShell := false + for _, c := range chroot { + if strings.EqualFold(c, "none") { + needShell = true + } + } + if needShell { + sh := acc.Shell + if sh == "" { + sh = "/bin/sh" + } + if in.Resolve != nil { + if _, ok := in.Resolve(sh); !ok { + tri := No + if len(chroot) > 1 { + tri = Maybe + } + add(tri, "its shell "+sh+" does not exist") + } + } + } + if acc.Expire >= 0 && in.Now.Unix()/86400 > acc.Expire { + add(No, "the account has expired") + } + switch res { + case Yes: + t.Reach = "yes" + case Maybe: + t.Reach = "maybe" + default: + t.Reach = "no" + } + t.Why = strings.Join(why, "; ") + return t, pw +} + +func listsAllow(cfg Config, acc Account, groups []string) Tri { + type list struct { + key string + allow bool + group bool + } + res := Yes + for _, l := range []list{{"denyusers", false, false}, {"allowusers", true, false}, {"denygroups", false, true}, {"allowgroups", true, true}} { + alts := cfg.Lists(l.key, acc, groups) + pass, fail := false, false + for _, pats := range alts { + if pats == nil { + pass = true + continue + } + var m Tri + if l.group { + m = No + for _, g := range groups { + for _, p := range pats { + if matchPatternList(g, p) { + m = Yes + } + } + } + } else { + m = No + for _, p := range pats { + m = maxTri(m, userPattern(p, acc.Name)) + } + } + ok := m + if !l.allow { + ok = notTri(m) + } + switch ok { + case Yes: + pass = true + case No: + fail = true + default: + pass, fail = true, true + } + } + switch { + case !pass: + return No + case fail: + res = Maybe + } + } + return res +} + +// userPattern matches an AllowUsers/DenyUsers entry: USER or USER@HOST, +// where the host part depends on the connection. +func userPattern(p, name string) Tri { + u, host, hasHost := strings.Cut(p, "@") + if !matchPatternList(name, u) { + return No + } + if hasHost && host != "*" { + return Maybe + } + return Yes +} + +func maxTri(a, b Tri) Tri { + if b > a { + return b + } + return a +} + +func notTri(t Tri) Tri { + switch t { + case Yes: + return No + case No: + return Yes + } + return Maybe +} + +// fixText says how to fix this server. +func fixText(in Input, f Finding) string { + mitigate := "Until then, set PasswordAuthentication no (for example in /etc/ssh/sshd_config.d/00-sshole.conf, before any file that turns it on), or change each password field of \"*\" to \"*NP*\", which still allows key logins." + if f.Package != nil && f.Package.Format == "apk" { + name := f.Package.Name + if v, ok := AlpineFixedFor(in.Branch); ok { + return fmt.Sprintf("Upgrade %s to %s or later (apk upgrade --no-cache %s) and restart sshd. %s", name, v, name, mitigate) + } + return fmt.Sprintf("Upgrade %s (apk upgrade --no-cache %s); if this Alpine release has no fixed package, move to a supported Alpine branch. Fixed: %s. %s", + name, name, alpineFixedSummary(), mitigate) + } + return "Update OpenSSH to 10.6p2 or later, or rebuild with upstream commit 4353fdc43 (\"avoid password authn bypass\"), and restart sshd. " + mitigate +} + +func alpineFixedSummary() string { + var parts []string + for _, b := range AlpineBranches() { + v, _ := AlpineFixedFor(b) + parts = append(parts, b+" "+v) + } + return strings.Join(parts, ", ") +} + +// BranchFromRelease turns /etc/alpine-release ("3.22.2", "3.23_alpha2026") into +// a branch ("3.22", "edge"). +func BranchFromRelease(s string) string { + s = strings.TrimSpace(s) + if strings.Contains(s, "_alpha") || strings.Contains(s, "_git") { + return "edge" + } + parts := strings.Split(s, ".") + if len(parts) < 2 { + return "" + } + return parts[0] + "." + parts[1] +} diff --git a/detectors/sshole/internal/assess/assess_test.go b/detectors/sshole/internal/assess/assess_test.go new file mode 100644 index 0000000..113a9dd --- /dev/null +++ b/detectors/sshole/internal/assess/assess_test.go @@ -0,0 +1,339 @@ +package assess + +import ( + "github.com/DefectDojo/earlylight/detectors/sshole/internal/testelf" + "path" + "sort" + "strings" + "testing" + "time" +) + +const ( + muslInterp = "/lib/ld-musl-x86_64.so.1" + glibcInterp = "/lib64/ld-linux-x86-64.so.2" + sha512Alice = "$6$pRu5B1iB4..BuPoN$MkyXJ0p3G5hVfF0uZ0xn6" +) + +func TestInspect(t *testing.T) { + cases := []struct { + name string + path string + data []byte + ok bool + libc Libc + pam bool + release string + role string + helpers int + }{ + {"alpine listener", "/usr/sbin/sshd", testelf.ELF(muslInterp, []string{"libcrypto.so.3", "libc.musl-x86_64.so.1"}, testelf.SSHDStrings("10.0p2", "/usr/lib/ssh/sshd-session", "/usr/lib/ssh/sshd-auth")...), true, Musl, false, "10.0p2", "sshd", 2}, + {"alpine pam auth", "/usr/lib/ssh/sshd-auth.pam", testelf.ELF(muslInterp, []string{"libpam.so.0", "libc.musl-x86_64.so.1"}, testelf.SSHDStrings("10.0p2")...), true, Musl, true, "10.0p2", "sshd-auth", 0}, + {"glibc", "/usr/sbin/sshd", testelf.ELF(glibcInterp, []string{"libc.so.6"}, testelf.SSHDStrings("9.2p1")...), true, Glibc, false, "9.2p1", "sshd", 0}, + {"static musl", "/opt/sshd", testelf.ELF("", nil, append(testelf.SSHDStrings("9.9p2"), "/etc/tcb/%s/shadow")...), true, Musl, false, "9.9p2", "sshd", 0}, + {"static unknown", "/opt/sshd", testelf.ELF("", nil, testelf.SSHDStrings("9.9p2")...), true, Unknown, false, "9.9p2", "sshd", 0}, + {"musl via needed only", "/usr/sbin/sshd", testelf.ELF("", []string{"libc.musl-aarch64.so.1"}, testelf.SSHDStrings("9.6p1")...), true, Musl, false, "9.6p1", "sshd", 0}, + {"ssh client", "/usr/bin/ssh", testelf.ELF(muslInterp, nil, "OpenSSH_10.0p2", "/etc/ssh/ssh_config"), false, "", false, "", "", 0}, + {"no release", "/usr/sbin/sshd", testelf.ELF(muslInterp, nil, "OpenSSH_7.4*", "/etc/ssh/sshd_config"), false, "", false, "", "", 0}, + {"not elf", "/usr/sbin/sshd", []byte("#!/bin/sh\nexec sshd_config OpenSSH_10.0p2"), false, "", false, "", "", 0}, + } + for _, c := range cases { + b, ok := Inspect(c.path, c.data) + if ok != c.ok { + t.Errorf("%s: ok = %v", c.name, ok) + continue + } + if !ok { + continue + } + if b.Libc != c.libc || b.PAM != c.pam || b.Release != c.release || b.Role != c.role || len(b.Helpers) != c.helpers { + t.Errorf("%s: got libc %s pam %v release %s role %s helpers %v", c.name, b.Libc, b.PAM, b.Release, b.Role, b.Helpers) + } + } +} + +func TestParseRelease(t *testing.T) { + for in, want := range map[string]string{"10.6p2": "10.6p2", "OpenSSH_9.9p1": "9.9p1", "10.0": "10.0", "OpenSSH_7.4*": ""} { + v, ok := ParseRelease(in) + if (want == "") == ok || ok && v.String() != want { + t.Errorf("%s: %v %v", in, v, ok) + } + } + if !(Version{10, 6, 1}).Less(FixedRelease) || (Version{10, 6, 2}).Less(FixedRelease) || (Version{10, 7, 0}).Less(FixedRelease) { + t.Error("ordering around the fixed release") + } +} + +func TestCryptFails(t *testing.T) { + // Measured with musl 1.2.5 on Alpine 3.22: crypt() returning "*" + // (failure) for short and for 257-byte keys. + cases := map[string]string{ + "$6$abc$": "long", + "$5$abc$": "long", + "$6$rounds=5000$abc$": "long", + "$6$rounds=1$ab$": "long", + "$6$rounds=99999999$ab$": "any", + "$6$rounds=abc$ab$": "any", + "$6$rounds=5000": "any", + "$1$abc$": "none", + "$1$": "none", + "$2b$10$": "any", + "$2a$12$": "any", + "$2y$05$": "any", + "$2b$10$abcdefghijklmnopqrstuu": "none", + "$y$j9T$abc$": "none", + "xx": "none", + } + for s, want := range cases { + if got := CryptFails(s); got != want { + t.Errorf("%s: %s, want %s", s, got, want) + } + } +} + +func TestPickSalt(t *testing.T) { + passwd := "root:x:0:0:root:/root:/bin/sh\nbin:x:1:1:bin:/bin:/sbin/nologin\nalice:x:1000:1000::/home/alice:/bin/sh\nbob:x:1001:1001::/home/bob:/bin/sh\n" + cases := []struct { + shadow, account, fails string + }{ + {"root:*::0:::::\nbin:!::0:::::\nalice:" + sha512Alice + ":20762:0:99999:7:::\nbob:*:20762:0:99999:7:::\n", "alice", "long"}, + {"root:*::0:::::\nalice:$1$abc$xyz:1::::::\nbob:$6$ab$cd:1::::::\n", "alice", "none"}, // the first $-hash decides + {"root:$2b$10$abcdefghijklmnopqrstuu" + strings.Repeat("A", 31) + ":1::::::\n", "root", "any"}, + {"root:*::0:::::\n", "", "none"}, + } + for i, c := range cases { + d := PickSalt(ParseAccounts([]byte(passwd), []byte(c.shadow), nil, nil)) + if d.Account != c.account || d.Fails != c.fails { + t.Errorf("%d: %+v", i, d) + } + } + // pick_salt copies at most 31 bytes: a long rounds= value cut before + // its '$' makes crypt fail for every password. + long := "root:$6$rounds=00000000000000000000005000$abc$hash:1::::::\n" + if d := PickSalt(ParseAccounts([]byte(passwd), []byte(long), nil, nil)); d.Fails != "any" || len(d.Setting) != 31 { + t.Errorf("truncated setting: %+v", d) + } +} + +func TestShadowLookup(t *testing.T) { + passwd := []byte("bob:*:1001:1001::/home/bob:/bin/sh\ncarol:x:1002:1002::/home/carol:/bin/sh\ndan:x:1003:1003::/:/bin/sh\nerin:x:1004:1004::/:/bin/sh\n") + shadow := []byte("bob:" + strings.Repeat("y", 300) + ":1::::::\n" + // too long for musl's buffer + "carol:bad:notanumber::::::\ncarol:*:1::::::\n" + // first line unparsable: musl keeps looking + "dan:$6$x$y:1:::::5:\n") + tcb := map[string][]byte{"erin": []byte("erin:*:1::::::\n")} + a := ParseAccounts(passwd, shadow, nil, tcb) + got := map[string]string{} + for _, acc := range a.List { + got[acc.Name] = acc.From + " " + acc.Field + } + want := map[string]string{"bob": "passwd *", "carol": "shadow *", "dan": "shadow $6$x$y", "erin": "tcb *"} + for k, v := range want { + if got[k] != v { + t.Errorf("%s: %q, want %q", k, got[k], v) + } + } + if a.List[2].Expire != 5 { + t.Errorf("expire %d", a.List[2].Expire) + } +} + +// memFiles is a target filesystem for tests. +type memFiles map[string]string + +func (m memFiles) Read(p string) []byte { + if s, ok := m[p]; ok { + return []byte(s) + } + return nil +} + +func (m memFiles) Glob(pattern string) []string { + var out []string + for p := range m { + if ok, _ := path.Match(pattern, p); ok { + out = append(out, p) + } + } + sort.Strings(out) + return out +} + +const ( + stdPasswd = "root:x:0:0:root:/root:/bin/sh\nalice:x:1000:1000::/home/alice:/bin/sh\nbob:x:1001:1001::/home/bob:/bin/sh\nsvc:x:1002:1002::/:/sbin/nologin\n" + stdShadow = "root:*::0:::::\nalice:" + sha512Alice + ":20762:0:99999:7:::\nbob:*:20762:0:99999:7:::\nsvc:!::0:::::\n" + stdConfig = "Include /etc/ssh/sshd_config.d/*.conf\nAuthorizedKeysFile .ssh/authorized_keys\nSubsystem sftp internal-sftp\n" +) + +type world struct { + files memFiles + binaries []*Binary + owners map[string]Package + branch string +} + +func newWorld(release string, pam bool, extra map[string]string) *world { + v, _ := ParseRelease(release) + w := &world{files: memFiles{ + "/etc/passwd": stdPasswd, + "/etc/shadow": stdShadow, + "/etc/group": "root:x:0:root\nalice:x:1000:\nbob:x:1001:\nwheel:x:10:bob\n", + "/etc/ssh/sshd_config": stdConfig, + "/bin/sh": "", + "/sbin/nologin": "", + }} + for k, val := range extra { + if val == "\x00delete" { + delete(w.files, k) + continue + } + w.files[k] = val + } + w.binaries = []*Binary{ + {Path: "/usr/sbin/sshd", Role: "sshd", Release: release, Version: v, Libc: Musl, Helpers: []string{"/usr/lib/ssh/sshd-session"}, Config: "/etc/ssh/sshd_config"}, + {Path: "/usr/lib/ssh/sshd-session", Role: "sshd-session", Release: release, Version: v, Libc: Musl, PAM: pam}, + } + return w +} + +func (w *world) run() []Finding { + return Run(Input{ + Binaries: w.binaries, + Owners: w.owners, + Files: w.files, + Accounts: ParseAccounts(w.files.Read("/etc/passwd"), w.files.Read("/etc/shadow"), w.files.Read("/etc/group"), nil), + Resolve: func(p string) (string, bool) { + _, ok := w.files[p] + return p, ok + }, + Branch: w.branch, + Now: time.Unix(20800*86400, 0), + }) +} + +func one(t *testing.T, fs []Finding) Finding { + t.Helper() + if len(fs) != 1 { + t.Fatalf("%d findings: %+v", len(fs), fs) + } + return fs[0] +} + +func TestRun(t *testing.T) { + cases := []struct { + name string + release string + pam bool + extra map[string]string + libc Libc + owner *Package + kind string + status Status + severity string + targets string + none bool + }{ + {name: "exposed", release: "10.0p2", kind: KindExposed, status: Vulnerable, severity: "critical", targets: "bob"}, + {name: "fixed upstream", release: "10.6p2", kind: KindServer, status: Fixed}, + {name: "later release", release: "10.7p1", kind: KindServer, status: Fixed}, + {name: "before 7.3", release: "7.2p2", kind: KindServer, status: Fixed}, + {name: "glibc", release: "9.2p1", libc: Glibc, none: true}, + {name: "unknown libc", release: "9.2p1", libc: Unknown, kind: KindServer, status: Undecided}, + {name: "alpine backport", release: "10.0p2", owner: &Package{"openssh-server", "10.0_p1-r11", "apk"}, kind: KindServer, status: Fixed}, + {name: "alpine old release", release: "10.0p2", owner: &Package{"openssh-server", "10.0_p1-r10", "apk"}, kind: KindExposed, status: Vulnerable}, + {name: "alpine 3.24", release: "10.3p1", owner: &Package{"openssh-server", "10.3_p1-r2", "apk"}, kind: KindServer, status: Fixed}, + {name: "alpine unpatched version", release: "10.1p1", owner: &Package{"openssh-server", "10.1_p1-r5", "apk"}, kind: KindExposed, status: Vulnerable}, + {name: "pam in use", release: "10.0p2", pam: true, extra: map[string]string{"/etc/ssh/sshd_config.d/pam.conf": "UsePAM yes\n"}, kind: KindServer, status: Inactive}, + {name: "pam built but off", release: "10.0p2", pam: true, kind: KindExposed, status: Vulnerable}, + {name: "UsePAM without PAM build", release: "10.0p2", extra: map[string]string{"/etc/ssh/sshd_config.d/pam.conf": "UsePAM yes\n"}, kind: KindExposed, status: Vulnerable}, + {name: "passwords off", release: "10.0p2", extra: map[string]string{"/etc/ssh/sshd_config.d/00.conf": "PasswordAuthentication no\n"}, kind: KindServer, status: Vulnerable, severity: "medium"}, + {name: "first value wins", release: "10.0p2", extra: map[string]string{"/etc/ssh/sshd_config.d/00.conf": "PasswordAuthentication no\n", "/etc/ssh/sshd_config.d/10.conf": "PasswordAuthentication yes\n"}, kind: KindServer, status: Vulnerable, severity: "medium"}, + {name: "match address", release: "10.0p2", extra: map[string]string{"/etc/ssh/sshd_config.d/00.conf": "PasswordAuthentication no\nMatch Address 10.0.0.0/8\n PasswordAuthentication yes\n"}, kind: KindExposed, status: Vulnerable, severity: "high"}, + {name: "match user other", release: "10.0p2", extra: map[string]string{"/etc/ssh/sshd_config.d/00.conf": "PasswordAuthentication no\nMatch User alice\n PasswordAuthentication yes\n"}, kind: KindServer, status: Vulnerable}, + {name: "match group", release: "10.0p2", extra: map[string]string{"/etc/ssh/sshd_config.d/00.conf": "PasswordAuthentication no\nMatch Group wheel\n PasswordAuthentication yes\n"}, kind: KindExposed, status: Vulnerable, severity: "critical"}, + {name: "key required", release: "10.0p2", extra: map[string]string{"/etc/ssh/sshd_config.d/00.conf": "AuthenticationMethods publickey,password\n"}, kind: KindServer, status: Vulnerable}, + {name: "password alone allowed", release: "10.0p2", extra: map[string]string{"/etc/ssh/sshd_config.d/00.conf": "AuthenticationMethods publickey password\n"}, kind: KindExposed, status: Vulnerable}, + {name: "deny users", release: "10.0p2", extra: map[string]string{"/etc/ssh/sshd_config.d/00.conf": "DenyUsers bob\n"}, kind: KindServer, status: Vulnerable}, + {name: "allow users host part", release: "10.0p2", extra: map[string]string{"/etc/ssh/sshd_config.d/00.conf": "AllowUsers bob@10.*\n"}, kind: KindExposed, status: Vulnerable, severity: "high"}, + {name: "root needs PermitRootLogin yes", release: "10.0p2", extra: map[string]string{"/etc/shadow": strings.Replace(stdShadow, "bob:*", "bob:!", 1)}, kind: KindServer, status: Vulnerable}, + {name: "root with PermitRootLogin yes", release: "10.0p2", extra: map[string]string{"/etc/shadow": strings.Replace(stdShadow, "bob:*", "bob:!", 1), "/etc/ssh/sshd_config.d/00.conf": "PermitRootLogin yes\n"}, kind: KindExposed, status: Vulnerable, targets: "root"}, + {name: "no donor", release: "10.0p2", extra: map[string]string{"/etc/shadow": strings.Replace(stdShadow, sha512Alice, "!", 1)}, kind: KindServer, status: Vulnerable}, + {name: "md5 donor", release: "10.0p2", extra: map[string]string{"/etc/shadow": strings.Replace(stdShadow, sha512Alice, "$1$abc$def", 1)}, kind: KindServer, status: Vulnerable}, + {name: "shell missing", release: "10.0p2", extra: map[string]string{"/bin/sh": "\x00delete"}, kind: KindServer, status: Vulnerable}, + {name: "chroot skips the shell check", release: "10.0p2", extra: map[string]string{"/bin/sh": "\x00delete", "/etc/ssh/sshd_config.d/00.conf": "ChrootDirectory /srv\n"}, kind: KindExposed, status: Vulnerable}, + {name: "expired", release: "10.0p2", extra: map[string]string{"/etc/shadow": strings.Replace(stdShadow, "bob:*:20762:0:99999:7:::", "bob:*:20762:0:99999:7::20000:", 1)}, kind: KindServer, status: Vulnerable}, + {name: "no config", release: "10.0p2", extra: map[string]string{"/etc/ssh/sshd_config": "\x00delete"}, kind: KindServer, status: Vulnerable, severity: "medium"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + w := newWorld(c.release, c.pam, c.extra) + if c.libc != "" { + for _, b := range w.binaries { + b.Libc = c.libc + } + } + if c.owner != nil { + w.owners = map[string]Package{"/usr/sbin/sshd": *c.owner} + w.branch = "3.22" + } + fs := w.run() + if c.none { + if len(fs) != 0 { + t.Fatalf("want no finding, got %+v", fs) + } + return + } + f := one(t, fs) + if f.Kind != c.kind || f.Status != c.status { + t.Fatalf("got %s %s (%s; %s)", f.Kind, f.Status, f.Message, f.Reason) + } + if c.severity != "" && f.Severity != c.severity { + t.Errorf("severity %s, want %s", f.Severity, c.severity) + } + if c.targets != "" { + var names []string + for _, x := range f.Targets { + names = append(names, x.Account) + } + if strings.Join(names, ",") != c.targets { + t.Errorf("targets %v, want %s", names, c.targets) + } + } + if f.Status == Vulnerable && f.Fix == "" { + t.Error("no fix text") + } + if f.Status == Fixed && f.Reason == "" { + t.Error("cleared without a reason") + } + }) + } +} + +func TestHelperLinking(t *testing.T) { + // The Alpine PAM flavour: the listener links no libpam, its helpers do. + w := newWorld("10.0p2", false, map[string]string{"/etc/ssh/sshd_config.d/pam.conf": "UsePAM yes\n"}) + v, _ := ParseRelease("10.0p2") + w.binaries = []*Binary{ + {Path: "/usr/sbin/sshd.pam", Role: "sshd", Release: "10.0p2", Version: v, Libc: Musl, Helpers: []string{"/usr/lib/ssh/sshd-session.pam", "/usr/lib/ssh/sshd-auth.pam"}, Config: "/etc/ssh/sshd_config"}, + {Path: "/usr/lib/ssh/sshd-session.pam", Role: "sshd-session", Release: "10.0p2", Version: v, Libc: Musl, PAM: true}, + {Path: "/usr/lib/ssh/sshd-auth.pam", Role: "sshd-auth", Release: "10.0p2", Version: v, Libc: Musl, PAM: true}, + } + f := one(t, w.run()) + if f.Status != Inactive || len(f.Helpers) != 2 { + t.Fatalf("%+v", f) + } +} + +func TestBranchFromRelease(t *testing.T) { + for in, want := range map[string]string{"3.22.2\n": "3.22", "3.24.0": "3.24", "3.23_alpha20260101": "edge", "": ""} { + if got := BranchFromRelease(in); got != want { + t.Errorf("%q: %q", in, got) + } + } + for _, b := range AlpineBranches() { + if v, ok := AlpineFixedFor(b); !ok { + t.Errorf("%s: no fixed version", b) + } else if fixed, _, ok := APKFixed(v); !ok || !fixed { + t.Errorf("%s: %s is not judged fixed", b, v) + } + } +} diff --git a/detectors/sshole/internal/assess/binary.go b/detectors/sshole/internal/assess/binary.go new file mode 100644 index 0000000..22bd620 --- /dev/null +++ b/detectors/sshole/internal/assess/binary.go @@ -0,0 +1,267 @@ +package assess + +import ( + "bytes" + "debug/elf" + "path" + "regexp" + "strconv" + "strings" +) + +// Libc is the C library an sshd binary runs on. +type Libc string + +const ( + Musl Libc = "musl" + Glibc Libc = "glibc" + UClibc Libc = "uclibc" + Bionic Libc = "bionic" + Unknown Libc = "unknown" +) + +// Binary is what an OpenSSH server executable proves about itself. +type Binary struct { + Path string `json:"path"` + // Role is "sshd" (the listener, or a pre-9.8 monolithic server), + // "sshd-session" or "sshd-auth". + Role string `json:"role"` + // Release is the OpenSSH release the binary reports ("10.0p2"). + Release string `json:"release,omitempty"` + Version Version `json:"-"` + Interp string `json:"interpreter,omitempty"` + Libc Libc `json:"libc"` + Static bool `json:"static,omitempty"` + // PAM is true when the binary links libpam (or carries PAM statically). + PAM bool `json:"pam"` + // Helpers are the sshd-session and sshd-auth paths the binary runs. + Helpers []string `json:"helpers,omitempty"` + // Config is the default sshd_config path compiled in. + Config string `json:"config,omitempty"` +} + +// Version is an OpenSSH release: major.minor plus the portable patch level. +type Version struct { + Major, Minor, Portable int +} + +func (v Version) Less(o Version) bool { + if v.Major != o.Major { + return v.Major < o.Major + } + if v.Minor != o.Minor { + return v.Minor < o.Minor + } + return v.Portable < o.Portable +} + +func (v Version) String() string { + s := strconv.Itoa(v.Major) + "." + strconv.Itoa(v.Minor) + if v.Portable > 0 { + s += "p" + strconv.Itoa(v.Portable) + } + return s +} + +// Upstream releases that matter. +var ( + // FixedRelease is the first upstream release with the fix (commit + // 4353fdc43, "avoid password authn bypass", 2026-11-05). + FixedRelease = Version{10, 6, 2} + // FirstAffected is the first release that picks a salt from another + // account for a one-character password field (commit 9286875a7, + // "Determine appropriate salt for invalid users", OpenSSH 7.3p1). + // Before it, sshd hashed with the DES salt "xx", which musl never fails. + FirstAffected = Version{7, 3, 1} +) + +var releaseRE = regexp.MustCompile(`^OpenSSH_([0-9]{1,3})\.([0-9]{1,3})(?:p([0-9]{1,3}))?$`) + +// ParseRelease parses "10.0p2" or "OpenSSH_10.0p2". +func ParseRelease(s string) (Version, bool) { + if !strings.HasPrefix(s, "OpenSSH_") { + s = "OpenSSH_" + s + } + m := releaseRE.FindStringSubmatch(s) + if m == nil { + return Version{}, false + } + var v Version + v.Major, _ = strconv.Atoi(m[1]) + v.Minor, _ = strconv.Atoi(m[2]) + if m[3] != "" { + v.Portable, _ = strconv.Atoi(m[3]) + } + return v, true +} + +// cstrings returns the NUL-terminated printable strings of at least min bytes. +func cstrings(b []byte, min int, keep func(string) bool) []string { + var out []string + start := -1 + for i, c := range b { + printable := c >= 0x20 && c < 0x7f + switch { + case printable && start < 0: + start = i + case !printable: + if start >= 0 && c == 0 && i-start >= min { + if s := string(b[start:i]); keep(s) { + out = append(out, s) + } + } + start = -1 + } + } + return out +} + +// IsSSHD reports whether data looks like an OpenSSH server executable worth +// inspecting: an ELF file naming sshd_config and an OpenSSH release. +func IsSSHD(data []byte) bool { + return len(data) > 4 && bytes.HasPrefix(data, []byte("\x7fELF")) && + bytes.Contains(data, []byte("sshd_config")) && bytes.Contains(data, []byte("OpenSSH_")) +} + +// Inspect reads an OpenSSH server executable. ok is false for anything else. +func Inspect(p string, data []byte) (*Binary, bool) { + if !IsSSHD(data) { + return nil, false + } + f, err := elf.NewFile(bytes.NewReader(data)) + if err != nil { + return nil, false + } + defer f.Close() + if f.Type != elf.ET_EXEC && f.Type != elf.ET_DYN { + return nil, false + } + b := &Binary{Path: p, Libc: Unknown} + + // The release is the exact SSH_RELEASE string ("OpenSSH_10.0p2"); the + // compat table's patterns ("OpenSSH_7.4*") never match exactly. Some + // builds also carry SSH_VERSION alone ("OpenSSH_10.0"): keep the most + // specific one. + var best Version + found := false + for _, s := range cstrings(data, 9, func(s string) bool { return strings.HasPrefix(s, "OpenSSH_") }) { + v, ok := ParseRelease(s) + if !ok { + continue + } + // A release with its portable level beats one without; otherwise + // the higher wins. + if !found || (v.Portable > 0) != (best.Portable > 0) && v.Portable > 0 || (v.Portable > 0) == (best.Portable > 0) && best.Less(v) { + best, found = v, true + } + } + if !found { + return nil, false + } + b.Version, b.Release = best, best.String() + + for _, s := range cstrings(data, 8, func(s string) bool { return strings.HasPrefix(s, "/") }) { + switch { + case strings.HasSuffix(s, "/sshd_config") && b.Config == "": + b.Config = path.Clean(s) + case isHelper(s): + b.Helpers = appendOnce(b.Helpers, path.Clean(s)) + } + } + + for _, prog := range f.Progs { + if prog.Type != elf.PT_INTERP { + continue + } + buf := make([]byte, prog.Filesz) + if _, err := prog.ReadAt(buf, 0); err == nil { + b.Interp = string(bytes.TrimRight(buf, "\x00")) + } + } + needed, _ := f.ImportedLibraries() + for _, n := range needed { + if strings.HasPrefix(n, "libpam.so") { + b.PAM = true + } + } + b.Libc = libcOf(b.Interp, needed, data) + b.Static = b.Interp == "" && len(needed) == 0 + if b.Static && bytes.Contains(data, []byte("pam_authenticate")) { + b.PAM = true + } + b.Role = role(p, data) + return b, true +} + +func isHelper(s string) bool { + base := path.Base(s) + for _, h := range []string{"sshd-session", "sshd-auth"} { + if base == h || strings.HasPrefix(base, h+".") { + return true + } + } + return false +} + +func appendOnce(xs []string, s string) []string { + for _, x := range xs { + if x == s { + return xs + } + } + return append(xs, s) +} + +// role names the part of the server a binary is. File names decide first, +// since vendors rename (sshd.pam, sshd-session.krb5); strings decide for +// anything renamed beyond recognition. +func role(p string, data []byte) string { + base := path.Base(p) + switch { + case strings.HasPrefix(base, "sshd-session"): + return "sshd-session" + case strings.HasPrefix(base, "sshd-auth"): + return "sshd-auth" + case strings.HasPrefix(base, "sshd"): + return "sshd" + case bytes.Contains(data, []byte("Server listening on")): + return "sshd" + } + return "sshd-session" +} + +func libcOf(interp string, needed []string, data []byte) Libc { + base := path.Base(interp) + switch { + case strings.HasPrefix(base, "ld-musl-"): + return Musl + case strings.HasPrefix(base, "ld-uClibc"): + return UClibc + case base == "linker" || base == "linker64": + return Bionic + case strings.HasPrefix(base, "ld-linux") || strings.HasPrefix(base, "ld64.so") || strings.HasPrefix(base, "ld.so"): + return Glibc + } + for _, n := range needed { + switch { + case strings.HasPrefix(n, "libc.musl-") || n == "libc.musl.so": + return Musl + case n == "libc.so.6": + return Glibc + case strings.HasPrefix(n, "libc.so.0"): + return UClibc + } + } + if interp == "" && len(needed) == 0 { + // Statically linked. musl's getspnam reads tcb shadow files first, + // so a static musl sshd carries that path; glibc's carries its own + // markers. + switch { + case bytes.Contains(data, []byte("/etc/tcb/%s/shadow")): + return Musl + case bytes.Contains(data, []byte("GLIBC_PRIVATE")) || bytes.Contains(data, []byte("FATAL: kernel too old")): + return Glibc + } + } + return Unknown +} diff --git a/detectors/sshole/internal/assess/config.go b/detectors/sshole/internal/assess/config.go new file mode 100644 index 0000000..610b0e6 --- /dev/null +++ b/detectors/sshole/internal/assess/config.go @@ -0,0 +1,356 @@ +package assess + +import ( + "path" + "strings" +) + +// Config is an sshd_config, flattened through Include, as a list of +// directives each with the Match criteria it sits under. +type Config struct { + Path string `json:"path"` + Read bool `json:"read"` + Directives []Directive `json:"-"` + // Missing lists Include patterns that matched no file, and files that + // could not be read. + Missing []string `json:"missing,omitempty"` +} + +// Directive is one keyword line. +type Directive struct { + Key string // lower case + Args []string + File string + Line int + Match []Criterion // nil: global + Block int // index of the Match block (0: global) +} + +// Criterion is one Match criterion ("User", "alice,bob"). +type Criterion struct { + Key, Value string +} + +// Files gives a config reader access to the target's files. +type Files interface { + // Read returns a regular file's content, or nil. + Read(p string) []byte + // Glob returns the files matching an absolute glob pattern, sorted. + Glob(pattern string) []string +} + +// ParseConfig reads an sshd_config and every file it includes, the way +// servconf.c does: relative Include paths are under /etc/ssh, globs expand +// in sorted order, and a Match inside an included file ends with that file. +func ParseConfig(files Files, p string) Config { + c := Config{Path: p} + data := files.Read(p) + if data == nil { + return c + } + c.Read = true + block := 0 + var walk func(file string, data []byte, match []Criterion, depth int) + walk = func(file string, data []byte, match []Criterion, depth int) { + cur := match + curBlock := block + for i, raw := range lines(data) { + args := splitArgs(raw) + if len(args) == 0 { + continue + } + key := strings.ToLower(args[0]) + switch key { + case "match": + block++ + curBlock = block + cur = parseMatch(args[1:]) + continue + case "include": + if depth >= 16 { + c.Missing = append(c.Missing, file+": Include nested too deeply") + continue + } + for _, pat := range args[1:] { + if !strings.HasPrefix(pat, "/") && !strings.HasPrefix(pat, "~") { + pat = path.Join("/etc/ssh", pat) + } + got := files.Glob(pat) + if len(got) == 0 && !hasGlob(pat) { + c.Missing = append(c.Missing, pat) + } + for _, g := range got { + if b := files.Read(g); b != nil { + walk(g, b, cur, depth+1) + } else { + c.Missing = append(c.Missing, g) + } + } + } + continue + } + c.Directives = append(c.Directives, Directive{Key: key, Args: args[1:], File: file, Line: i + 1, Match: cur, Block: curBlock}) + } + } + walk(p, data, nil, 0) + return c +} + +func hasGlob(p string) bool { return strings.ContainsAny(p, "*?[") } + +// splitArgs splits a config line the way servconf.c reads it: the keyword +// ends at whitespace or '=', then words separated by whitespace with double +// quotes grouping, and '#' starting a comment outside quotes. +func splitArgs(line string) []string { + line = strings.TrimLeft(line, " \t\r") + if line == "" || line[0] == '#' { + return nil + } + k := strings.IndexAny(line, " \t\r=") + if k < 0 { + return []string{line} + } + out := []string{line[:k]} + rest := strings.TrimLeft(line[k:], " \t\r") + if strings.HasPrefix(rest, "=") { + rest = rest[1:] + } + var b strings.Builder + in, quoted := false, false + for i := 0; i < len(rest); i++ { + c := rest[i] + switch { + case quoted: + if c == '"' { + quoted = false + } else { + b.WriteByte(c) + } + case c == '"': + quoted, in = true, true + case c == '#': + i = len(rest) + case c == ' ' || c == '\t' || 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 +} + +func parseMatch(args []string) []Criterion { + var out []Criterion + for i := 0; i < len(args); i++ { + k := strings.ToLower(args[i]) + if k == "all" || k == "canonical" || k == "final" || k == "invalid-user" { + out = append(out, Criterion{Key: k}) + continue + } + v := "" + if j := strings.IndexByte(args[i], '='); j > 0 { + k, v = strings.ToLower(args[i][:j]), args[i][j+1:] + } else if i+1 < len(args) { + i++ + v = args[i] + } + out = append(out, Criterion{Key: k, Value: v}) + } + if len(out) == 0 { + out = []Criterion{{Key: "unknown"}} + } + return out +} + +// Tri is a three-valued answer. +type Tri int + +const ( + No Tri = iota + Maybe + Yes +) + +// matches says whether a Match block applies to a connection by user. +func matches(crit []Criterion, acc Account, groups []string) Tri { + res := Yes + for _, c := range crit { + var t Tri + switch c.Key { + case "all": + t = Yes + case "user": + t = boolTri(matchPatternList(acc.Name, c.Value)) + case "group": + t = No + for _, g := range groups { + if matchPatternList(g, c.Value) { + t = Yes + } + } + case "invalid-user": + t = No // the accounts that matter exist + default: + t = Maybe // Address, Host, LocalPort, Exec, Version...: depends on the connection + } + if t == No { + return No + } + if t == Maybe { + res = Maybe + } + } + return res +} + +func boolTri(b bool) Tri { + if b { + return Yes + } + return No +} + +// matchPatternList is OpenSSH's match_pattern_list: comma-separated globs, +// a leading '!' negates and a negated match wins. +func matchPatternList(s, list string) bool { + got := false + for _, p := range strings.Split(list, ",") { + neg := strings.HasPrefix(p, "!") + if neg { + p = p[1:] + } + if p == "" { + continue + } + if globMatch(p, s) { + if neg { + return false + } + got = true + } + } + return got +} + +// globMatch is OpenSSH's match_pattern: '*' and '?' only. +func globMatch(p, s string) bool { + if p == "" { + return s == "" + } + switch p[0] { + case '*': + for i := 0; i <= len(s); i++ { + if globMatch(p[1:], s[i:]) { + return true + } + } + return false + case '?': + return s != "" && globMatch(p[1:], s[1:]) + } + return s != "" && p[0] == s[0] && globMatch(p[1:], s[1:]) +} + +// Values returns every value a single-valued keyword can take for a +// connection by acc: the first value in each Match block that may apply, +// up to the first block that certainly applies, else the global value (the +// first one, as sshd keeps the first value it reads), else def. +func (c Config) Values(key string, acc Account, groups []string, def string) []string { + global := "" + haveGlobal := false + type blk struct { + tri Tri + val string + } + var blocks []blk + seen := map[int]bool{} + for _, d := range c.Directives { + if d.Key != key || len(d.Args) == 0 { + continue + } + val := strings.Join(d.Args, " ") + if d.Match == nil { + if !haveGlobal { + global, haveGlobal = val, true + } + continue + } + if seen[d.Block] { + continue + } + seen[d.Block] = true + if t := matches(d.Match, acc, groups); t != No { + blocks = append(blocks, blk{t, val}) + } + } + var out []string + for _, b := range blocks { + out = appendOnce(out, b.val) + if b.tri == Yes { + return out + } + } + if !haveGlobal { + global = def + } + return appendOnce(out, global) +} + +// Lists returns the patterns of a list keyword (AllowUsers, DenyUsers...) +// for each way a connection by acc can resolve: global lines accumulate, a +// Match block that sets the keyword replaces them. nil entries mean unset. +func (c Config) Lists(key string, acc Account, groups []string) [][]string { + var global []string + set := false + blockVals := map[int][]string{} + var order []int + tri := map[int]Tri{} + for _, d := range c.Directives { + if d.Key != key { + continue + } + if d.Match == nil { + global = append(global, d.Args...) + set = true + continue + } + t := matches(d.Match, acc, groups) + if t == No { + continue + } + if _, ok := blockVals[d.Block]; !ok { + order = append(order, d.Block) + tri[d.Block] = t + } + blockVals[d.Block] = append(blockVals[d.Block], d.Args...) + } + var out [][]string + for _, b := range order { + out = append(out, blockVals[b]) + if tri[b] == Yes { + return out + } + } + if !set { + global = nil + } + return append(out, global) +} + +// Global returns a global-only keyword's value (UsePAM), or def. +func (c Config) Global(key, def string) string { + for _, d := range c.Directives { + if d.Key == key && d.Match == nil && len(d.Args) > 0 { + return d.Args[0] + } + } + return def +} diff --git a/detectors/sshole/internal/assess/fuzz_test.go b/detectors/sshole/internal/assess/fuzz_test.go new file mode 100644 index 0000000..2698402 --- /dev/null +++ b/detectors/sshole/internal/assess/fuzz_test.go @@ -0,0 +1,35 @@ +package assess + +import ( + "testing" + + "github.com/DefectDojo/earlylight/detectors/sshole/internal/testelf" +) + +func FuzzInspect(f *testing.F) { + f.Add(testelf.ELF("/lib/ld-musl-x86_64.so.1", []string{"libpam.so.0"}, testelf.SSHDStrings("10.0p2", "/usr/lib/ssh/sshd-session")...)) + f.Fuzz(func(t *testing.T, b []byte) { Inspect("/usr/sbin/sshd", b) }) +} + +func FuzzAccounts(f *testing.F) { + f.Add("root:x:0:0::/:/bin/sh\nbob:x:1:1::/:/bin/sh\n", "root:$6$rounds=5000$a$b:1::::::\nbob:*:1::::::\n") + f.Fuzz(func(t *testing.T, passwd, shadow string) { + a := ParseAccounts([]byte(passwd), []byte(shadow), []byte(passwd), nil) + d := PickSalt(a) + if len(d.Setting) > 31 { + t.Fatalf("setting longer than sshd's buffer: %q", d.Setting) + } + }) +} + +func FuzzConfig(f *testing.F) { + f.Add("Include x/*.conf\nPasswordAuthentication=no\nMatch User bob,!alice Address 10.*\n PasswordAuthentication \"yes\" # c\n") + f.Fuzz(func(t *testing.T, s string) { + fs := memFiles{"/etc/ssh/sshd_config": s, "/etc/ssh/x/a.conf": s} + c := ParseConfig(fs, "/etc/ssh/sshd_config") + acc := Account{Name: "bob"} + c.Values("passwordauthentication", acc, nil, "yes") + c.Lists("allowusers", acc, nil) + passwordValues(c, acc, nil) + }) +} diff --git a/detectors/sshole/internal/assess/testdata/fuzz/FuzzConfig/b0af9b0046ed84e0 b/detectors/sshole/internal/assess/testdata/fuzz/FuzzConfig/b0af9b0046ed84e0 new file mode 100644 index 0000000..67a1b20 --- /dev/null +++ b/detectors/sshole/internal/assess/testdata/fuzz/FuzzConfig/b0af9b0046ed84e0 @@ -0,0 +1,2 @@ +go test fuzz v1 +string("MAtCh \x96=") diff --git a/detectors/sshole/internal/repo/plan.go b/detectors/sshole/internal/repo/plan.go new file mode 100644 index 0000000..0d743a0 --- /dev/null +++ b/detectors/sshole/internal/repo/plan.go @@ -0,0 +1,211 @@ +package repo + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "unicode" + + "github.com/DefectDojo/earlylight/internal/refs" +) + +// Change is a set of edits to one repository file. +type Change struct { + File string + Edits []Edit + 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 } + +// IsDeclined returns the Declined in err's chain, if any. +func IsDeclined(err error) (*Declined, bool) { + var d *Declined + if errors.As(err, &d) { + return d, true + } + return nil, false +} + +// Plan builds the edit for a finding the scan reported at file:line with +// rule and, for apk findings, props["package"]. It rescans the edited file +// in memory and accepts the edit only when that finding is gone and nothing +// new appeared. already is true when the finding is no longer there. +func Plan(ctx context.Context, root string, f Finding, opts Options) (*Change, bool, error) { + if !f.Fixable || f.edit == nil { + return nil, false, &Declined{Reason: f.Fix} + } + b, err := readFile(root, f.File) + if err != nil { + return nil, false, err + } + lines := strings.Split(string(b), "\n") + e := *f.edit + if e.Line < 1 || e.Line > len(lines) { + return nil, true, nil + } + line := strings.TrimSuffix(lines[e.Line-1], "\r") + if e.Col < 0 || e.Col+len(e.Old) > len(line) || line[e.Col:e.Col+len(e.Old)] != e.Old { + // An earlier edit on the same line moves the word: rescan and take + // the one finding that is still the same word, or decline. + now, err := scanOne(ctx, root, f.File, opts, b) + if err != nil { + return nil, false, err + } + var match *Edit + n := 0 + for _, g := range now { + if g.Rule == f.Rule && g.Line == f.Line && g.edit != nil && g.edit.Old == e.Old && g.Props["spec"] == f.Props["spec"] { + match = g.edit + n++ + } + } + if n != 1 { + return nil, false, &Declined{Reason: fmt.Sprintf("%s:%d no longer reads as scanned", f.File, e.Line)} + } + e = *match + } + newLine := line[:e.Col] + e.New + line[e.Col+len(e.Old):] + ch := &Change{File: f.File, Edits: []Edit{{Line: e.Line, Col: e.Col, Old: line, New: newLine}}, Summary: summary(f)} + + // Rescan the edited file in memory. + edited := append([]string{}, lines...) + cr := "" + if strings.HasSuffix(lines[e.Line-1], "\r") { + cr = "\r" + } + edited[e.Line-1] = newLine + cr + o := opts + o.Overlay = map[string][]byte{f.File: []byte(strings.Join(edited, "\n"))} + before, err := scanOne(ctx, root, f.File, opts, nil) + if err != nil { + return nil, false, err + } + after, err := scanOne(ctx, root, f.File, o, o.Overlay[f.File]) + if err != nil { + return nil, false, err + } + if count(after, f.Rule, e.Line) >= count(before, f.Rule, e.Line) { + return nil, false, &Declined{Reason: "the edit did not clear the finding; change it by hand"} + } + if len(after) > len(before) { + return nil, false, &Declined{Reason: "the edit raised a new finding; change it by hand"} + } + return ch, false, nil +} + +func scanOne(ctx context.Context, root, file string, opts Options, data []byte) ([]Finding, error) { + s := &scanner{ctx: ctx, root: root, opts: opts, bases: map[string]baseInfo{}} + if data == nil { + var err error + if data, err = readFile(root, file); err != nil { + return nil, err + } + } + switch kindOf(file) { + case "dockerfile": + return s.dockerfile(file, string(data)), nil + case "shell": + return s.script(file, string(data)), nil + case "yaml": + return s.yaml(file, string(data)), nil + case "sshd_config": + return s.sshdConfig(file, string(data)), nil + } + return nil, nil +} + +func count(fs []Finding, rule string, line int) int { + n := 0 + for _, f := range fs { + if f.Rule == rule && f.Line == line { + n++ + } + } + return n +} + +func summary(f Finding) string { + switch f.Rule { + case RulePin, RuleUnpinned: + return fmt.Sprintf("Require %s at %s or later, the Alpine release with the *sshole fix", f.Props["package"], f.Props["fixed"]) + case RuleStar: + return "Set the password field to \"*NP*\" instead of \"*\", which keeps key logins and matches no password" + } + return f.Fix +} + +// Apply writes a change after checking each edited line still reads as +// planned. It keeps line endings and the file mode, and writes atomically. +func Apply(root string, ch *Change) error { + p, err := refs.SafePath(root, ch.File) + if err != nil { + return err + } + fi, err := os.Lstat(p) + if err != nil { + return err + } + b, err := readFile(root, ch.File) + if err != nil { + return err + } + lines := strings.Split(string(b), "\n") + for _, e := range ch.Edits { + if e.Line < 1 || e.Line > len(lines) || strings.TrimSuffix(lines[e.Line-1], "\r") != e.Old { + return fmt.Errorf("%s changed since the plan: line %d no longer reads as planned", ch.File, e.Line) + } + cr := "" + if strings.HasSuffix(lines[e.Line-1], "\r") { + cr = "\r" + } + lines[e.Line-1] = e.New + cr + } + tmp, err := os.CreateTemp(filepath.Dir(p), ".earlylight-*") + if err != nil { + return err + } + name := tmp.Name() + if _, err := tmp.WriteString(strings.Join(lines, "\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 is the change as a short unified-style listing. +func Diff(ch *Change) string { + var b strings.Builder + for _, e := range ch.Edits { + fmt.Fprintf(&b, "@@ %s line %d @@\n- %s\n+ %s\n", Printable(ch.File), e.Line, Printable(e.Old), Printable(e.New)) + } + return b.String() +} + +// 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() +} diff --git a/detectors/sshole/internal/repo/repo.go b/detectors/sshole/internal/repo/repo.go new file mode 100644 index 0000000..0231ccd --- /dev/null +++ b/detectors/sshole/internal/repo/repo.go @@ -0,0 +1,908 @@ +// Package repo finds what in a source tree builds or configures an OpenSSH +// server exposed to *sshole, and plans the edits that fix it: +// +// - apk-pin: a Dockerfile on Alpine installs an OpenSSH server package +// pinned to a release without the fix. +// - apk-unpinned: a Dockerfile on Alpine installs one with no floor, so an +// image built before the fix (or from a cached layer) keeps the +// vulnerable package. +// - eol-base: the Alpine release has no fixed package at all. +// - star-account: a Dockerfile, script or Ansible task sets an account's +// password field to "*", the field the bypass logs in to. +// - password-config: something turns PasswordAuthentication on (a note). +// - not-checked: what could not be read or resolved. +package repo + +import ( + "archive/tar" + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "regexp" + "sort" + "strconv" + "strings" + + "github.com/DefectDojo/earlylight/detectors/sshole/internal/assess" + "github.com/DefectDojo/earlylight/internal/refs" +) + +// Rules. +const ( + RulePin = "apk-pin" + RuleUnpinned = "apk-unpinned" + RuleEOL = "eol-base" + RuleStar = "star-account" + RulePassword = "password-config" + RuleNotChecked = "not-checked" +) + +// 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 + Message string `json:"message"` + Fix string `json:"fix,omitempty"` + Fixable bool `json:"fixable"` + Props map[string]string `json:"props,omitempty"` + // edit is the planned replacement, kept for Plan. + edit *Edit +} + +// Skip is a file that was not read, and why. +type Skip struct { + File string `json:"file"` + 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 + // Base resolves an image the tree builds on: whether it is Alpine and + // which branch ("3.22", "edge"). nil: only what the name says. + Base func(ctx context.Context, image string) (alpine bool, branch string, err error) +} + +const ( + maxFileSize = 4 << 20 + maxFiles = 200000 +) + +var skipDirs = map[string]bool{".git": true, "node_modules": true, "vendor": true, ".venv": true, "venv": true, "__pycache__": true, ".tox": true, "bower_components": true} + +// Scan walks root. +func Scan(ctx context.Context, root string, opts Options) (Result, error) { + var res Result + var list []string + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + rel, _ := filepath.Rel(root, p) + res.Skips = append(res.Skips, Skip{File: filepath.ToSlash(rel), Reason: err.Error()}) + return nil + } + if d.IsDir() { + if p != root && skipDirs[d.Name()] { + return filepath.SkipDir + } + return nil + } + if !d.Type().IsRegular() { + return nil + } + rel, err := filepath.Rel(root, p) + if err != nil { + return nil + } + rel = filepath.ToSlash(rel) + if kindOf(rel) == "" { + return nil + } + if len(list) >= maxFiles { + res.Truncated = true + return filepath.SkipAll + } + list = append(list, rel) + return nil + }) + if err != nil { + return res, err + } + for rel := range opts.Overlay { + if kindOf(rel) != "" && !contains(list, rel) { + list = append(list, rel) + } + } + sort.Strings(list) + s := &scanner{ctx: ctx, root: root, opts: opts, bases: map[string]baseInfo{}} + for _, rel := range list { + b, ok := opts.Overlay[rel] + if !ok { + var err error + b, err = readFile(root, rel) + if err != nil { + res.Skips = append(res.Skips, Skip{File: rel, Reason: err.Error()}) + continue + } + } + res.Files++ + switch kindOf(rel) { + case "dockerfile": + res.Findings = append(res.Findings, s.dockerfile(rel, string(b))...) + case "shell": + res.Findings = append(res.Findings, s.script(rel, string(b))...) + case "yaml": + res.Findings = append(res.Findings, s.yaml(rel, string(b))...) + case "sshd_config": + res.Findings = append(res.Findings, s.sshdConfig(rel, string(b))...) + } + } + return res, nil +} + +func contains(xs []string, s string) bool { + for _, x := range xs { + if x == s { + return true + } + } + return false +} + +// kindOf classifies a repository path. +func kindOf(rel string) string { + name := path.Base(rel) + lower := strings.ToLower(name) + switch { + case lower == "dockerfile" || strings.HasPrefix(lower, "dockerfile.") || strings.HasSuffix(lower, ".dockerfile") || + lower == "containerfile" || strings.HasPrefix(lower, "containerfile.") || strings.HasSuffix(lower, ".containerfile"): + return "dockerfile" + case strings.HasSuffix(lower, ".sh") || strings.HasSuffix(lower, ".bash") || strings.HasSuffix(lower, ".ash") || + strings.HasPrefix(lower, "entrypoint") || strings.HasPrefix(lower, "docker-entrypoint"): + return "shell" + case strings.HasSuffix(lower, ".yml") || strings.HasSuffix(lower, ".yaml"): + return "yaml" + case strings.Contains(lower, "sshd_config"): + return "sshd_config" + } + 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", maxFileSize>>20) + } + return os.ReadFile(p) +} + +type baseInfo struct { + alpine, known bool + branch string + why string +} + +type scanner struct { + ctx context.Context + root string + opts Options + bases map[string]baseInfo +} + +// span is a piece of shell text from a file: Text, and the file line each +// byte offset starts on. +type span struct { + text string + lines []int // lines[i] is the 1-based line of byte i + cols []int // cols[i] is the 0-based byte column of byte i on its line +} + +func newSpan(physical []string, firstLine, firstCol int) span { + var b strings.Builder + var lines, cols []int + for i, l := range physical { + col0 := 0 + if i == 0 { + col0 = firstCol + } + for j := 0; j < len(l); j++ { + lines = append(lines, firstLine+i) + cols = append(cols, col0+j) + } + b.WriteString(l) + if i < len(physical)-1 { + b.WriteByte('\n') + lines = append(lines, firstLine+i) + cols = append(cols, col0+len(l)) + } + } + return span{text: b.String(), lines: lines, cols: cols} +} + +// at locates a word: its line and column, and false when it spans lines. +func (sp span) at(w word) (int, int, bool) { + if w.start >= len(sp.lines) || w.end-1 >= len(sp.lines) || w.end <= w.start { + return 0, 0, false + } + l := sp.lines[w.start] + return l, sp.cols[w.start], sp.lines[w.end-1] == l +} + +// Edit replaces Old with New at Col on Line (1-based line, 0-based byte). +type Edit struct { + Line int + Col int + Old string + New string + // Insert, when set, is a whole line inserted after Line instead. + Insert string +} + +// ---- Dockerfiles + +var fromRE = regexp.MustCompile(`(?i)^\s*FROM\s+`) + +type instr struct { + cmd string // upper case + args span + line int + physical []string +} + +func parseDockerfile(text string) []instr { + lines := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") + var out []instr + for i := 0; i < len(lines); i++ { + l := lines[i] + t := strings.TrimLeft(l, " \t") + if t == "" || strings.HasPrefix(t, "#") { + continue + } + start := i + phys := []string{l} + for strings.HasSuffix(strings.TrimRight(lines[i], " \t"), "\\") && i+1 < len(lines) { + i++ + nt := strings.TrimLeft(lines[i], " \t") + if strings.HasPrefix(nt, "#") { + phys = append(phys, "") // Docker drops comment lines inside an instruction + continue + } + phys = append(phys, lines[i]) + } + kw := t + if j := strings.IndexAny(t, " \t"); j >= 0 { + kw = t[:j] + } + cmd := strings.ToUpper(kw) + off := len(l) - len(t) + len(kw) + first := phys[0][off:] + trim := len(first) - len(strings.TrimLeft(first, " \t")) + phys[0] = first[trim:] + in := instr{cmd: cmd, line: start + 1} + // A heredoc body (RUN <= 0 { + name = name[:i] + } + if i := strings.LastIndexByte(name, ':'); i > strings.LastIndexByte(name, '/') { + name, tag = name[:i], name[i+1:] + } + repo := path.Base(name) + switch { + case repo == "alpine": + switch { + case tag == "" || tag == "latest": + return baseInfo{alpine: true, known: true} // branch moves: resolve it + case tag == "edge" || strings.HasPrefix(tag, "20"): + return baseInfo{alpine: true, known: true, branch: "edge"} + } + if br := assess.BranchFromRelease(tag); br != "" { + return baseInfo{alpine: true, known: true, branch: br} + } + return baseInfo{alpine: true, known: true} + case strings.Contains(tag, "alpine"): + if m := alpineTagRE.FindStringSubmatch(tag); m != nil { + return baseInfo{alpine: true, known: true, branch: m[1]} + } + return baseInfo{alpine: true, known: true} + } + for _, glibc := range []string{"wolfi", "chainguard", "debian", "ubuntu", "fedora", "centos", "rockylinux", "almalinux", "amazonlinux", "ubi", "distroless"} { + if strings.Contains(name, glibc) { + return baseInfo{known: true} + } + } + return baseInfo{} +} + +// sshPackages are the Alpine packages that install sshd. +var sshPackages = map[string]bool{"openssh": true, "openssh-server": true, "openssh-server-pam": true, "openssh-server-krb5": true} + +// apk options that take a value. +var apkValueOpts = map[string]bool{"-t": true, "--virtual": true, "-X": true, "--repository": true, "--root": true, "-p": true, + "--arch": true, "--cache-dir": true, "--keys-dir": true, "--repositories-file": true, "--cache-max-age": true, "--timeout": true} + +var specRE = regexp.MustCompile(`^([a-z0-9][a-z0-9._+-]*?)(?:@[A-Za-z0-9_-]+)?(?:(>=|<=|=~|~|=|<|>)(.*))?$`) + +// shell finds apk installs, "*" password fields and PasswordAuthentication +// switches in a piece of shell text. +func (s *scanner) shell(rel string, sp span, b baseInfo, image string, dockerfile bool) []Finding { + var out []Finding + cmds := splitShell(sp.text) + for ci, c := range cmds { + prog, at := c.program() + if at < 0 { + continue + } + args := c.words[at+1:] + // PasswordAuthentication yes, written by sed or echo into a config. + for _, w := range args { + if pwYes.MatchString(w.val) { + l, _, _ := sp.at(w) + out = append(out, Finding{Rule: RulePassword, File: rel, Line: l, Level: "note", + Message: "turns PasswordAuthentication on; with an OpenSSH server on musl that lacks the *sshole fix, accounts with the password field \"*\" are exposed", + Fix: "Use key logins (PasswordAuthentication no) unless passwords are required, and install an OpenSSH package with the fix", + }) + } + } + switch prog { + case "apk": + out = append(out, s.apk(rel, sp, args, b, image, dockerfile)...) + case "usermod", "useradd": + for i := 0; i < len(args); i++ { + v := args[i].val + var pw *word + switch { + case (v == "-p" || v == "--password") && i+1 < len(args): + pw = &args[i+1] + case strings.HasPrefix(v, "--password="): + if strings.TrimPrefix(v, "--password=") == "*" { + w := args[i] + out = append(out, s.star(rel, sp, w, "--password=*", "--password='*NP*'", prog)...) + } + } + if pw != nil && !pw.dynamic && pw.val == "*" { + out = append(out, s.star(rel, sp, *pw, sp.text[pw.start:pw.end], "'*NP*'", prog)...) + } + } + case "chpasswd": + if !hasFlag(args, "-e", "--encrypted") || !c.piped || ci == 0 { + continue + } + for _, w := range feederWords(cmds[ci-1]) { + if starEntry.MatchString(w.val) && !w.dynamic { + raw := sp.text[w.start:w.end] + out = append(out, s.star(rel, sp, w, raw, strings.Replace(raw, ":*", ":*NP*", 1), "chpasswd -e")...) + } + } + case "sed": + if !touchesShadow(args) { + continue + } + for _, w := range args { + if w.dynamic || strings.HasPrefix(w.val, "-") && !strings.HasPrefix(w.val, "-e") { + continue + } + if repl, ok := sedStarReplacement(w.val); ok { + raw := sp.text[w.start:w.end] + fixed := strings.Replace(raw, repl, strings.Replace(repl, "*", "*NP*", 1), 1) + if fixed != raw { + out = append(out, s.star(rel, sp, w, raw, fixed, "sed on /etc/shadow")...) + } + } + } + case "echo", "printf": + for _, r := range c.redirs { + if strings.HasSuffix(r.target.val, "/etc/shadow") && (r.op == ">" || r.op == ">>") { + for _, w := range args { + if shadowLine.MatchString(strings.TrimSuffix(w.val, `\n`)) && !w.dynamic { + raw := sp.text[w.start:w.end] + out = append(out, s.star(rel, sp, w, raw, strings.Replace(raw, ":*:", ":*NP*:", 1), "a line written to /etc/shadow")...) + } + } + } + } + } + } + return out +} + +var ( + starEntry = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_.-]*\$?:\*(\\n)?$`) + shadowLine = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_.-]*\$?:\*:`) + pwYes = regexp.MustCompile(`(?i)(^|[^A-Za-z])PasswordAuthentication\s+yes\b`) +) + +func hasFlag(ws []word, flags ...string) bool { + for _, w := range ws { + for _, f := range flags { + if w.val == f { + return true + } + } + } + return false +} + +// feederWords returns the words of a command that writes chpasswd's input. +func feederWords(c command) []word { + prog, at := c.program() + if prog != "echo" && prog != "printf" { + return nil + } + return c.words[at+1:] +} + +func touchesShadow(ws []word) bool { + for _, w := range ws { + if strings.HasSuffix(w.val, "/etc/shadow") || strings.HasSuffix(w.val, "/etc/tcb") { + return true + } + } + return false +} + +// sedStarReplacement finds an s command whose replacement writes a password +// field of exactly "*" (":*:" or ":*" at the end), and returns that +// replacement. +func sedStarReplacement(script string) (string, bool) { + script = strings.TrimPrefix(script, "-e") + i := strings.Index(script, "s") + for i >= 0 && i+1 < len(script) { + delim := script[i+1] + if delim == '\\' || delim == '\n' || delim == ' ' { + break + } + parts := splitUnescaped(script[i+2:], delim) + if len(parts) >= 2 { + repl := parts[1] + r := strings.ReplaceAll(repl, `\*`, "*") + if strings.Contains(r, ":*:") || strings.HasSuffix(r, ":*") { + return repl, true + } + } + next := strings.Index(script[i+1:], "s") + if next < 0 { + break + } + i += next + 1 + } + return "", false +} + +func splitUnescaped(s string, d byte) []string { + var out []string + var b strings.Builder + for i := 0; i < len(s); i++ { + if s[i] == '\\' && i+1 < len(s) { + b.WriteByte(s[i]) + b.WriteByte(s[i+1]) + i++ + continue + } + if s[i] == d { + out = append(out, b.String()) + b.Reset() + continue + } + b.WriteByte(s[i]) + } + return append(out, b.String()) +} + +func (s *scanner) star(rel string, sp span, w word, raw, fixed, how string) []Finding { + l, col, ok := sp.at(w) + f := Finding{Rule: RuleStar, File: rel, Line: l, Level: "error", + Message: fmt.Sprintf("sets an account's password field to \"*\" (%s); on an OpenSSH server on musl without the *sshole fix, a crafted password logs in to that account", how), + Fix: "Use \"*NP*\" instead of \"*\": it still allows key logins, and no password matches it on any OpenSSH build", + Props: map[string]string{"how": how}} + if ok && raw != fixed && strings.Count(raw, "\n") == 0 { + f.Fixable = true + f.edit = &Edit{Line: l, Col: col, Old: raw, New: fixed} + } + return []Finding{f} +} + +func (s *scanner) apk(rel string, sp span, args []word, b baseInfo, image string, dockerfile bool) []Finding { + var out []Finding + sub := -1 + for i := 0; i < len(args); i++ { + v := args[i].val + if strings.HasPrefix(v, "-") { + if apkValueOpts[v] { + i++ + } + continue + } + sub = i + break + } + if sub < 0 || args[sub].val != "add" { + return nil + } + for i := sub + 1; i < len(args); i++ { + w := args[i] + if strings.HasPrefix(w.val, "-") { + if apkValueOpts[w.val] { + i++ + } + continue + } + if w.dynamic { + continue + } + m := specRE.FindStringSubmatch(w.val) + if m == nil || !sshPackages[m[1]] { + continue + } + if f, ok := s.judgeSpec(rel, sp, w, m[1], m[2], m[3], b, image, dockerfile); ok { + out = append(out, f) + } + } + return out +} + +// judgeSpec decides an apk dependency on an OpenSSH server package. +func (s *scanner) judgeSpec(rel string, sp span, w word, pkg, op, ver string, b baseInfo, image string, dockerfile bool) (Finding, bool) { + l, col, sameLine := sp.at(w) + raw := sp.text[w.start:w.end] + props := map[string]string{"package": pkg, "spec": w.val} + if image != "" { + props["image"] = image + } + if b.branch != "" { + props["branch"] = b.branch + } + f := Finding{File: rel, Line: l, Props: props} + if !b.known { + f.Rule, f.Level = RuleNotChecked, "note" + why := "the base image could not be identified" + if b.why != "" { + why += " (" + b.why + ")" + } + f.Message = fmt.Sprintf("installs %s with apk, but %s, so whether it is Alpine (musl) is not known", w.val, why) + f.Fix = "If this image is Alpine, require " + pkg + " at the fixed release for its branch (" + fixedTable() + ")" + return f, true + } + if !b.alpine { + return f, false // apk on glibc (Wolfi, Chainguard): not affected + } + fixed, haveFixed := assess.AlpineFixedFor(b.branch) + if b.branch != "" && !haveFixed { + f.Rule, f.Level = RuleEOL, "error" + f.Message = fmt.Sprintf("installs %s on Alpine %s (%s), which has no OpenSSH package with the *sshole fix", w.val, b.branch, image) + f.Fix = "Move the base image to an Alpine release with a fixed package (" + fixedTable() + "), or set PasswordAuthentication no and change every \"*\" password field to \"*NP*\"" + return f, true + } + ok, decided := satisfiesFix(op, ver, fixed, haveFixed) + if decided && ok { + return f, false + } + switch { + case op == "" || op == "~" || op == ">=" || op == ">": + f.Rule, f.Level = RuleUnpinned, "warning" + f.Message = fmt.Sprintf("installs %s with no floor at the fixed release; images built before 2026-11-05, or from a cached layer, keep the vulnerable OpenSSH server", w.val) + default: + f.Rule, f.Level = RulePin, "error" + f.Message = fmt.Sprintf("pins %s to a release without the *sshole fix", w.val) + } + if !haveFixed { + f.Fix = "Require " + pkg + " at the fixed release for this image's Alpine branch (" + fixedTable() + ")" + return f, true + } + newSpec := pkg + ">=" + fixed + if op == "=" { + newSpec = pkg + "=" + fixed + } + quoted := "'" + newSpec + "'" + f.Fix = fmt.Sprintf("Require %s (Alpine %s), which rebuilds the layer with the fixed package", newSpec, branchName(b.branch)) + props["fixed"] = fixed + if sameLine && !strings.Contains(raw, "\n") { + f.Fixable = true + f.edit = &Edit{Line: l, Col: col, Old: raw, New: quoted} + } + return f, true +} + +func branchName(b string) string { + if b == "edge" { + return "edge" + } + return b +} + +func fixedTable() string { + var parts []string + for _, br := range assess.AlpineBranches() { + v, _ := assess.AlpineFixedFor(br) + parts = append(parts, br+": "+v) + } + return strings.Join(parts, ", ") +} + +// satisfiesFix says whether every version an apk constraint allows has the +// fix. decided is false when the constraint cannot be judged. +func satisfiesFix(op, ver, fixed string, haveFixed bool) (ok, decided bool) { + if op == "" || !haveFixed { + return false, op == "" + } + c := compareAPK(ver, fixed) + switch op { + case "=": + if st, _, known := apkFixed(ver); known { + return st, true + } + return c >= 0, c != 2 + case ">=": + return c >= 0 && c != 2, c != 2 + case ">": + return c >= 0 && c != 2, c != 2 + case "~", "=~": + return false, true // a fuzzy match still allows older releases from a cache + } + return false, true // < and <= never guarantee the fix +} + +func apkFixed(v string) (bool, string, bool) { + fixed, why, ok := assess.APKFixed(v) + return fixed, why, ok +} + +// compareAPK compares two openssh apk versions: -1, 0, 1, or 2 when either +// cannot be read. +func compareAPK(a, b string) int { + pa, oka := parseV(a) + pb, okb := parseV(b) + if !oka || !okb { + return 2 + } + for i := range pa { + if pa[i] != pb[i] { + if pa[i] < pb[i] { + return -1 + } + return 1 + } + } + return 0 +} + +var apkVerRE = regexp.MustCompile(`^(\d+)\.(\d+)(?:_p(\d+))?(?:-r(\d+))?$`) + +func parseV(v string) ([4]int, bool) { + m := apkVerRE.FindStringSubmatch(v) + if m == nil { + return [4]int{}, false + } + var out [4]int + for i := 1; i <= 4; i++ { + if m[i] != "" { + out[i-1], _ = strconv.Atoi(m[i]) + } + } + return out, true +} + +// ---- scripts, YAML and sshd_config + +func (s *scanner) script(rel, text string) []Finding { + lines := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") + sp := newSpan(lines, 1, 0) + return s.shell(rel, sp, baseInfo{}, "", false) +} + +var yamlStar = regexp.MustCompile(`^(\s*-?\s*(?:password|passwd)\s*:\s*)(["']?)\*(["']?)\s*$`) +var yamlStarInline = regexp.MustCompile(`\bpassword=(["']?)\*(["']?)(\s|$)`) + +func (s *scanner) yaml(rel, text string) []Finding { + var out []Finding + for i, l := range strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") { + if m := yamlStar.FindStringSubmatchIndex(l); m != nil { + old := l[m[2]:] + newl := l[m[2]:m[3]] + `"*NP*"` + out = append(out, Finding{Rule: RuleStar, File: rel, Line: i + 1, Level: "error", Fixable: true, + Message: "sets an account's password field to \"*\" (Ansible or cloud-init); on an OpenSSH server on musl without the *sshole fix, a crafted password logs in to that account", + Fix: "Use \"*NP*\" instead of \"*\": it still allows key logins, and no password matches it", + Props: map[string]string{"how": "yaml"}, + edit: &Edit{Line: i + 1, Col: m[2], Old: old, New: newl}}) + continue + } + if m := yamlStarInline.FindStringSubmatchIndex(l); m != nil { + old := l[m[0]:m[1]] + newl := strings.Replace(old, "*", "*NP*", 1) + out = append(out, Finding{Rule: RuleStar, File: rel, Line: i + 1, Level: "error", Fixable: true, + Message: "sets an account's password field to \"*\" (Ansible); on an OpenSSH server on musl without the *sshole fix, a crafted password logs in to that account", + Fix: "Use \"*NP*\" instead of \"*\"", + Props: map[string]string{"how": "yaml"}, + edit: &Edit{Line: i + 1, Col: m[0], Old: old, New: newl}}) + } + } + return out +} + +func (s *scanner) sshdConfig(rel, text string) []Finding { + var out []Finding + for i, l := range strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") { + t := strings.TrimSpace(l) + if strings.HasPrefix(t, "#") { + continue + } + if pwYes.MatchString(t) { + out = append(out, Finding{Rule: RulePassword, File: rel, Line: i + 1, Level: "note", + Message: "sshd_config turns PasswordAuthentication on; with an OpenSSH server on musl that lacks the *sshole fix, accounts with the password field \"*\" are exposed", + Fix: "Use key logins (PasswordAuthentication no) unless passwords are required, and install an OpenSSH package with the fix"}) + } + } + return out +} + +// ---- base image resolution + +// AlpineOf reads an image's filesystem for /etc/alpine-release. open +// returns the flattened filesystem as a tar stream. +func AlpineOf(open func() (io.ReadCloser, error)) (bool, string, error) { + rc, err := open() + if err != nil { + return false, "", err + } + defer rc.Close() + tr := tar.NewReader(rc) + musl := false + for { + h, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + return false, "", err + } + name := path.Clean("/" + h.Name) + switch { + case name == "/etc/alpine-release" && h.Typeflag == tar.TypeReg: + b, err := io.ReadAll(io.LimitReader(tr, 256)) + if err != nil { + return false, "", err + } + return true, assess.BranchFromRelease(string(b)), nil + case strings.HasPrefix(name, "/lib/ld-musl-"): + musl = true + } + } + if musl { + return true, "", nil // musl without Alpine's release file + } + return false, "", nil +} diff --git a/detectors/sshole/internal/repo/repo_test.go b/detectors/sshole/internal/repo/repo_test.go new file mode 100644 index 0000000..11697a6 --- /dev/null +++ b/detectors/sshole/internal/repo/repo_test.go @@ -0,0 +1,237 @@ +package repo + +import ( + "archive/tar" + "bytes" + "context" + "errors" + "io" + "os" + "path/filepath" + "strings" + "testing" +) + +func write(t *testing.T, root, rel, s string) { + t.Helper() + p := filepath.Join(root, rel) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(s), 0o644); err != nil { + t.Fatal(err) + } +} + +func scan(t *testing.T, root string, opts Options) []Finding { + t.Helper() + res, err := Scan(context.Background(), root, opts) + if err != nil { + t.Fatal(err) + } + return res.Findings +} + +func rules(fs []Finding) map[string]int { + out := map[string]int{} + for _, f := range fs { + out[f.Rule+":"+f.File+":"+itoa(f.Line)]++ + } + return out +} + +func itoa(n int) string { + var b [20]byte + i := len(b) + if n == 0 { + return "0" + } + for n > 0 { + i-- + b[i] = byte('0' + n%10) + n /= 10 + } + return string(b[i:]) +} + +const svc = `FROM alpine:3.22 AS base +RUN apk add --no-cache \ + openssh-server \ + bash +RUN adduser -D bob \ + && usermod -p '*' bob \ + && echo 'carol:*' | chpasswd -e \ + && sed -i 's/^dave:!/dave:*/' /etc/shadow \ + && sed -i 's/#PasswordAuthentication yes/PasswordAuthentication yes/' /etc/ssh/sshd_config +FROM base +RUN apk add openssh-server-pam=10.0_p1-r10 +` + +func TestScan(t *testing.T) { + root := t.TempDir() + write(t, root, "svc/Dockerfile", svc) + write(t, root, "old/Dockerfile", "FROM alpine:3.14\nRUN apk add --no-cache openssh\n") + write(t, root, "arg/Dockerfile", "ARG ALPINE=3.21\nFROM python:3.12-alpine${ALPINE}\nRUN apk add -U --virtual .ssh openssh-server~9.9\n") + write(t, root, "wolfi/Dockerfile", "FROM cgr.dev/chainguard/wolfi-base\nRUN apk add openssh-server\n") + write(t, root, "ok/Dockerfile", "FROM alpine:3.22\nRUN apk add 'openssh-server>=10.0_p1-r11' && apk add openssh-server=10.0_p1-r12\n") + write(t, root, "edge/Containerfile", "FROM alpine:edge\nRUN apk add openssh-server-krb5\n") + write(t, root, "unknown/Dockerfile", "FROM registry.example/base:1\nRUN apk add openssh-server\n") + write(t, root, "ansible/users.yml", "- user:\n name: deploy\n password: '*'\n- shell: usermod name=x password=* other=1\n") + write(t, root, "entrypoint.sh", "#!/bin/sh\necho \"app:*:20000:0:99999:7:::\" >> /etc/shadow\nexec sshd -D\n") + write(t, root, "etc/sshd_config", "# PasswordAuthentication yes\nPasswordAuthentication yes\n") + write(t, root, "node_modules/x/Dockerfile", "FROM alpine:3.22\nRUN apk add openssh\n") + got := rules(scan(t, root, Options{})) + want := []string{ + "apk-unpinned:svc/Dockerfile:3", + "star-account:svc/Dockerfile:6", + "star-account:svc/Dockerfile:7", + "star-account:svc/Dockerfile:8", + "password-config:svc/Dockerfile:9", + "apk-pin:svc/Dockerfile:11", + "eol-base:old/Dockerfile:2", + "apk-unpinned:arg/Dockerfile:3", + "apk-unpinned:edge/Containerfile:2", + "not-checked:unknown/Dockerfile:2", + "star-account:ansible/users.yml:3", + "star-account:ansible/users.yml:4", + "star-account:entrypoint.sh:2", + "password-config:etc/sshd_config:2", + } + for _, w := range want { + if got[w] != 1 { + t.Errorf("missing %s", w) + } + delete(got, w) + } + for k := range got { + t.Errorf("unexpected %s", k) + } +} + +func TestFixRoundTrip(t *testing.T) { + root := t.TempDir() + write(t, root, "svc/Dockerfile", strings.ReplaceAll(svc, "\n", "\r\n")) + write(t, root, "entrypoint.sh", "#!/bin/sh\necho 'app:*:1:0:99999:7:::' > /etc/shadow\n") + write(t, root, "ansible/users.yml", "- user:\n password: \"*\"\n") + write(t, root, "one/Dockerfile", "FROM alpine:3.23\nRUN apk add openssh && usermod -p '*' a && usermod -p \"*\" b\n") + ctx := context.Background() + for _, f := range scan(t, root, Options{}) { + if f.Level == "note" { + continue + } + ch, already, err := Plan(ctx, root, f, Options{}) + if already || err != nil { + t.Fatalf("%s:%d %s: %v %v", f.File, f.Line, f.Rule, already, err) + } + if err := Apply(root, ch); err != nil { + t.Fatal(err) + } + } + left := 0 + for _, f := range scan(t, root, Options{}) { + if f.Level != "note" { + left++ + t.Errorf("left: %s:%d %s %s", f.File, f.Line, f.Rule, f.Message) + } + } + b, _ := os.ReadFile(filepath.Join(root, "svc/Dockerfile")) + s := string(b) + for _, want := range []string{"'openssh-server>=10.0_p1-r11' \\\r\n", "usermod -p '*NP*' bob", "echo 'carol:*NP*' | chpasswd -e", "s/^dave:!/dave:*NP*/", "'openssh-server-pam=10.0_p1-r11'\r\n"} { + if !strings.Contains(s, want) { + t.Errorf("Dockerfile lacks %q:\n%s", want, s) + } + } + if left == 0 && strings.Count(s, "\r\n") != strings.Count(svc, "\n") { + t.Error("line endings changed") + } +} + +func TestPlanDeclines(t *testing.T) { + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine\nRUN apk add openssh-server\n") + fs := scan(t, root, Options{}) + if len(fs) != 1 || fs[0].Fixable { + t.Fatalf("alpine:latest offline should be reported but not fixable: %+v", fs) + } + if _, _, err := Plan(context.Background(), root, fs[0], Options{}); err == nil { + t.Fatal("planned an edit with no branch") + } else if _, ok := IsDeclined(err); !ok { + t.Fatalf("not a decline: %v", err) + } + // With the base resolved, the same line is fixable. + opts := Options{Base: func(context.Context, string) (bool, string, error) { return true, "3.24", nil }} + fs = scan(t, root, opts) + if len(fs) != 1 || !fs[0].Fixable || fs[0].Props["fixed"] != "10.3_p1-r2" { + t.Fatalf("%+v", fs) + } + // A file changed after the scan is not edited. + write(t, root, "Dockerfile", "FROM alpine\nRUN apk add openssh-server-pam\n") + if _, _, err := Plan(context.Background(), root, fs[0], opts); err == nil { + t.Fatal("edited a changed line") + } + // A word that only moved is found again. + write(t, root, "Dockerfile", "FROM alpine\nRUN apk add openssh-server\n") + if ch, _, err := Plan(context.Background(), root, fs[0], opts); err != nil || !strings.Contains(ch.Edits[0].New, "apk add 'openssh-server>=10.3_p1-r2'") { + t.Fatalf("moved word: %v %+v", err, ch) + } + // A failed resolution leaves it unchecked. + bad := Options{Base: func(context.Context, string) (bool, string, error) { return false, "", errors.New("denied") }} + write(t, root, "Dockerfile", "FROM registry.example/x\nRUN apk add openssh-server\n") + if fs := scan(t, root, bad); len(fs) != 1 || fs[0].Rule != RuleNotChecked || !strings.Contains(fs[0].Message, "denied") { + t.Fatalf("%+v", fs) + } +} + +func TestAlpineOf(t *testing.T) { + mk := func(files map[string]string) func() (io.ReadCloser, error) { + var b bytes.Buffer + tw := tar.NewWriter(&b) + for n, c := range files { + tw.WriteHeader(&tar.Header{Name: n, Mode: 0o644, Size: int64(len(c)), Typeflag: tar.TypeReg}) + tw.Write([]byte(c)) + } + tw.Close() + return func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(b.Bytes())), nil } + } + if a, br, err := AlpineOf(mk(map[string]string{"etc/alpine-release": "3.24.3\n"})); err != nil || !a || br != "3.24" { + t.Errorf("alpine: %v %q %v", a, br, err) + } + if a, _, _ := AlpineOf(mk(map[string]string{"lib/ld-musl-x86_64.so.1": ""})); !a { + t.Error("musl without release file") + } + if a, _, _ := AlpineOf(mk(map[string]string{"etc/debian_version": "12"})); a { + t.Error("debian taken for alpine") + } +} + +func TestSplitShell(t *testing.T) { + cmds := splitShell(`FOO=1 sudo apk add "openssh-server" && echo 'a:*' | chpasswd -e; printf '%s\n' x >> /etc/shadow`) + if len(cmds) != 4 { + t.Fatalf("%d commands", len(cmds)) + } + if p, _ := cmds[0].program(); p != "apk" { + t.Errorf("program %q", p) + } + if !cmds[2].piped || cmds[1].piped { + t.Error("pipe") + } + if len(cmds[3].redirs) != 1 || cmds[3].redirs[0].target.val != "/etc/shadow" { + t.Errorf("redirs %+v", cmds[3].redirs) + } +} + +func FuzzScanText(f *testing.F) { + f.Add(svc) + f.Add("RUN apk add 'x\nFROM\n\\") + f.Fuzz(func(t *testing.T, s string) { + sc := &scanner{ctx: context.Background(), bases: map[string]baseInfo{}} + for _, x := range sc.dockerfile("Dockerfile", s) { + if x.edit != nil && x.edit.Line < 1 { + t.Fatal("edit before line 1") + } + } + sc.script("a.sh", s) + sc.yaml("a.yml", s) + splitShell(s) + }) +} diff --git a/detectors/sshole/internal/repo/shell.go b/detectors/sshole/internal/repo/shell.go new file mode 100644 index 0000000..8aaf72c --- /dev/null +++ b/detectors/sshole/internal/repo/shell.go @@ -0,0 +1,199 @@ +package repo + +import "strings" + +// word is one shell word: its value with quotes removed, and where its raw +// text sits in the logical command. +type word struct { + val string + start, end int // byte offsets of the raw word in the logical text + quoted bool + dynamic bool // contains $ or ` outside single quotes: value not literal +} + +// command is a simple command, and whether a pipe feeds it from the +// previous one. +type command struct { + words []word + piped bool + redirs []redir +} + +type redir struct { + op string // ">", ">>", "<" + target word +} + +// splitShell splits shell text into simple commands. It understands quotes, +// backslashes, comments, the separators ; & && || | and newlines, and +// redirections. It is not a full shell: what it cannot follow it keeps as +// literal text, and callers decide only on literal words. +func splitShell(s string) []command { + var out []command + cur := command{} + var w strings.Builder + in := false + var ws word + pendingRedir := "" + flush := func(end int) { + if !in { + return + } + ws.end = end + ws.val = w.String() + if pendingRedir != "" { + cur.redirs = append(cur.redirs, redir{op: pendingRedir, target: ws}) + pendingRedir = "" + } else { + cur.words = append(cur.words, ws) + } + w.Reset() + in = false + ws = word{} + } + endCmd := func(piped bool) { + if len(cur.words) > 0 || len(cur.redirs) > 0 { + out = append(out, cur) + } + cur = command{piped: piped} + } + start := func(i int) { + if !in { + in = true + ws = word{start: i} + } + } + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case c == '\'': + start(i) + ws.quoted = true + j := strings.IndexByte(s[i+1:], '\'') + if j < 0 { + w.WriteString(s[i+1:]) + i = len(s) + continue + } + w.WriteString(s[i+1 : i+1+j]) + i += j + 1 + case c == '"': + start(i) + ws.quoted = true + i++ + for ; i < len(s) && s[i] != '"'; i++ { + if s[i] == '\\' && i+1 < len(s) && strings.IndexByte("$`\"\\\n", s[i+1]) >= 0 { + i++ + if s[i] != '\n' { + w.WriteByte(s[i]) + } + continue + } + if s[i] == '$' || s[i] == '`' { + ws.dynamic = true + } + w.WriteByte(s[i]) + } + case c == '\\': + if i+1 < len(s) && s[i+1] == '\n' { + i++ // line continuation + continue + } + start(i) + if i+1 < len(s) { + i++ + w.WriteByte(s[i]) + } + case c == '#' && !in: + for i < len(s) && s[i] != '\n' { + i++ + } + i-- + case c == ' ' || c == '\t' || c == '\r': + flush(i) + case c == '\n' || c == ';' || c == '(' || c == ')' || c == '{' && !in || c == '}' && !in: + flush(i) + endCmd(false) + case c == '&': + flush(i) + if i+1 < len(s) && s[i+1] == '&' { + i++ + } else if i > 0 && s[i-1] == '>' { + continue + } + endCmd(false) + case c == '|': + flush(i) + if i+1 < len(s) && s[i+1] == '|' { + i++ + endCmd(false) + } else { + endCmd(true) + } + case c == '>' || c == '<': + // A redirection: a leading fd number in the current word is + // dropped with it. + if in && isDigits(w.String()) { + w.Reset() + in = false + ws = word{} + } else { + flush(i) + } + op := string(c) + if c == '>' && i+1 < len(s) && s[i+1] == '>' { + op = ">>" + i++ + } + if i+1 < len(s) && s[i+1] == '&' { + i++ + } + pendingRedir = op + default: + start(i) + if c == '$' || c == '`' { + ws.dynamic = true + } + w.WriteByte(c) + } + } + flush(len(s)) + endCmd(false) + return out +} + +func isDigits(s string) bool { + if s == "" { + return false + } + for _, c := range s { + if c < '0' || c > '9' { + return false + } + } + return true +} + +// program returns the command's program name, past env assignments and +// wrappers like sudo, exec or env. +func (c command) program() (string, int) { + for i := 0; i < len(c.words); i++ { + v := c.words[i].val + if strings.Contains(v, "=") && !strings.HasPrefix(v, "-") && !strings.HasPrefix(v, "=") { + continue + } + switch base(v) { + case "sudo", "doas", "exec", "env", "command", "nohup", "time": + continue + } + return base(v), i + } + return "", -1 +} + +func base(p string) string { + if i := strings.LastIndexByte(p, '/'); i >= 0 { + return p[i+1:] + } + return p +} diff --git a/detectors/sshole/internal/testelf/testelf.go b/detectors/sshole/internal/testelf/testelf.go new file mode 100644 index 0000000..857bf18 --- /dev/null +++ b/detectors/sshole/internal/testelf/testelf.go @@ -0,0 +1,134 @@ +// Package testelf builds the small ELF executables the sshole tests read. +package testelf + +import ( + "bytes" + "encoding/binary" +) + +// ELF builds a little-endian ELF64 executable with an optional +// PT_INTERP, a .dynamic section listing needed libraries, and extra bytes +// (the strings an sshd carries) in a data section. +func ELF(interp string, needed []string, extra ...string) []byte { + le := binary.LittleEndian + var dynstr bytes.Buffer + dynstr.WriteByte(0) + var offs []uint32 + for _, n := range needed { + offs = append(offs, uint32(dynstr.Len())) + dynstr.WriteString(n) + dynstr.WriteByte(0) + } + var dyn bytes.Buffer + for _, o := range offs { + binary.Write(&dyn, le, uint64(1)) // DT_NEEDED + binary.Write(&dyn, le, uint64(o)) + } + binary.Write(&dyn, le, uint64(0)) // DT_NULL + binary.Write(&dyn, le, uint64(0)) + + var data bytes.Buffer + data.WriteByte(0) + for _, e := range extra { + data.WriteString(e) + data.WriteByte(0) + } + shstr := []byte("\x00.interp\x00.dynstr\x00.dynamic\x00.data\x00.shstrtab\x00") + name := func(s string) uint32 { return uint32(bytes.Index(shstr, []byte("\x00"+s+"\x00")) + 1) } + + const ehsize, phsize, shsize = 64, 56, 64 + nph := 1 + if interp != "" { + nph = 2 + } + off := uint64(ehsize + nph*phsize) + interpB := []byte(interp + "\x00") + interpOff := off + if interp != "" { + off += uint64(len(interpB)) + } + dynstrOff := off + off += uint64(dynstr.Len()) + off = (off + 7) &^ 7 + dynOff := off + off += uint64(dyn.Len()) + dataOff := off + off += uint64(data.Len()) + shstrOff := off + off += uint64(len(shstr)) + off = (off + 7) &^ 7 + shOff := off + + var b bytes.Buffer + b.Write([]byte{0x7f, 'E', 'L', 'F', 2, 1, 1, 0}) + b.Write(make([]byte, 8)) + binary.Write(&b, le, uint16(3)) // ET_DYN + binary.Write(&b, le, uint16(62)) // x86-64 + binary.Write(&b, le, uint32(1)) + binary.Write(&b, le, uint64(0)) + binary.Write(&b, le, uint64(ehsize)) + binary.Write(&b, le, shOff) + binary.Write(&b, le, uint32(0)) + binary.Write(&b, le, uint16(ehsize)) + binary.Write(&b, le, uint16(phsize)) + binary.Write(&b, le, uint16(nph)) + binary.Write(&b, le, uint16(shsize)) + binary.Write(&b, le, uint16(6)) + binary.Write(&b, le, uint16(5)) + ph := func(typ uint32, o, size uint64) { + binary.Write(&b, le, typ) + binary.Write(&b, le, uint32(4)) + binary.Write(&b, le, o) + binary.Write(&b, le, o) + binary.Write(&b, le, o) + binary.Write(&b, le, size) + binary.Write(&b, le, size) + binary.Write(&b, le, uint64(8)) + } + if interp != "" { + ph(3, interpOff, uint64(len(interpB))) // PT_INTERP + } + ph(2, dynOff, uint64(dyn.Len())) // PT_DYNAMIC + if interp != "" { + b.Write(interpB) + } + b.Write(dynstr.Bytes()) + for uint64(b.Len()) < dynOff { + b.WriteByte(0) + } + b.Write(dyn.Bytes()) + b.Write(data.Bytes()) + b.Write(shstr) + for uint64(b.Len()) < shOff { + b.WriteByte(0) + } + sh := func(nm, typ uint32, o, size uint64, link uint32, entsize uint64) { + binary.Write(&b, le, nm) + binary.Write(&b, le, typ) + binary.Write(&b, le, uint64(2)) + binary.Write(&b, le, o) + binary.Write(&b, le, o) + binary.Write(&b, le, size) + binary.Write(&b, le, link) + binary.Write(&b, le, uint32(0)) + binary.Write(&b, le, uint64(1)) + binary.Write(&b, le, entsize) + } + b.Write(make([]byte, shsize)) // SHN_UNDEF + if interp != "" { + sh(name(".interp"), 1, interpOff, uint64(len(interpB)), 0, 0) + } else { + sh(name(".interp"), 0, 0, 0, 0, 0) + } + sh(name(".dynstr"), 3, dynstrOff, uint64(dynstr.Len()), 0, 0) + sh(name(".dynamic"), 6, dynOff, uint64(dyn.Len()), 2, 16) + sh(name(".data"), 1, dataOff, uint64(data.Len()), 0, 0) + sh(name(".shstrtab"), 3, shstrOff, uint64(len(shstr)), 0, 0) + return b.Bytes() +} + +// SSHDStrings are what an Alpine 10.0 listener carries. +func SSHDStrings(release string, helpers ...string) []string { + out := []string{"OpenSSH_" + release[:len(release)-2], "OpenSSH_" + release, "OpenSSH_7.4*", "OpenSSH_2*,OpenSSH_3*,OpenSSH_4*", "/etc/ssh/sshd_config", "Server listening on %s port %s."} + return append(out, helpers...) +} diff --git a/detectors/sshole/probe.go b/detectors/sshole/probe.go new file mode 100644 index 0000000..ba9818e --- /dev/null +++ b/detectors/sshole/probe.go @@ -0,0 +1,162 @@ +package sshole + +import ( + "bufio" + "context" + "errors" + "fmt" + "net" + "strings" + "time" + + "golang.org/x/crypto/ssh" + + "github.com/DefectDojo/earlylight/detectors/sshole/internal/assess" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// probeUser is the user name the probe asks about. sshd lists the same +// methods for any name, and the probe never sends a password. +const probeUser = "earlylight-probe" + +// errStop ends authentication once the server has offered password logins. +var errStop = errors.New("stop") + +// glibcVendors are banner comments of distributions that build OpenSSH on +// glibc or a BSD libc: their servers are not affected. +var glibcVendors = []string{"Debian", "Ubuntu", "Raspbian", "FreeBSD", "NetBSD", "OpenBSD", "Fedora", "RHEL", "SUSE"} + +// Probe connects to an SSH server (default port 22), reads its banner and +// asks which authentication methods it offers. It sends no password: when +// the server offers password logins, the client stops there. +func (d *Detector) Probe(ctx context.Context, addr string, timeout time.Duration) (string, int, []engine.Finding, error) { + if timeout <= 0 { + timeout = 10 * time.Second + } + host, port, err := net.SplitHostPort(addr) + portGiven := err == nil + if !portGiven { + host, port = addr, "22" + } + target := net.JoinHostPort(host, port) + dl := net.Dialer{Timeout: timeout} + conn, err := dl.DialContext(ctx, "tcp", target) + if err != nil { + if !portGiven { + return target, 0, nil, fmt.Errorf("%w: no SSH server answered on %s (%v)", engine.ErrNotApplicable, target, err) + } + return target, 0, nil, err + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(timeout)) + + rec := &bannerConn{Conn: conn} + banner, err := rec.peekBanner() + if err != nil || !strings.HasPrefix(banner, "SSH-") { + return target, 0, nil, fmt.Errorf("%w: %s does not speak SSH", engine.ErrNotApplicable, target) + } + + offered := false + cfg := &ssh.ClientConfig{ + User: probeUser, + Auth: []ssh.AuthMethod{ssh.PasswordCallback(func() (string, error) { + offered = true + return "", errStop + })}, + HostKeyCallback: ssh.InsecureIgnoreHostKey(), //nolint:gosec // inspection only: no secret is sent + Timeout: timeout, + } + _, _, _, herr := ssh.NewClientConn(rec, target, cfg) + methodsKnown := offered || herr != nil && strings.Contains(herr.Error(), "unable to authenticate") + + f, ok := judgeBanner(target, banner, offered, methodsKnown) + if !ok { + return target, 1, nil, nil + } + return target, 1, []engine.Finding{f}, nil +} + +// judgeBanner decides what a banner and the offered methods can tell. ok +// is false when the server is not an affected build (not OpenSSH, or a +// glibc distribution's). +func judgeBanner(target, banner string, offered, methodsKnown bool) (engine.Finding, bool) { + soft := strings.TrimPrefix(strings.TrimPrefix(banner, "SSH-2.0-"), "SSH-1.99-") + name, comment, _ := strings.Cut(soft, " ") + if !strings.HasPrefix(name, "OpenSSH_") || strings.HasPrefix(name, "OpenSSH_for_Windows") { + return engine.Finding{}, false + } + for _, v := range glibcVendors { + if strings.Contains(comment, v) { + return engine.Finding{}, false + } + } + v, ok := assess.ParseRelease(name) + f := engine.Finding{Kind: KindHost, Path: target, Method: "ssh-banner", + Facts: map[string]string{"banner": banner, "password_offered": yes(offered)}} + switch { + case !ok: + f.Verdict, f.Reason = engine.Unknown, "the banner's OpenSSH release could not be read" + f.Message = "SSH server " + name + return f, true + case !v.Less(assess.FixedRelease): + f.Verdict, f.Reason = engine.Fixed, "the banner reports OpenSSH "+v.String()+", which has the fix" + f.Message = "OpenSSH " + v.String() + " has the *sshole fix" + return f, true + case v.Less(assess.FirstAffected): + f.Verdict, f.Reason = engine.Fixed, "OpenSSH "+v.String()+" predates 7.3p1 and never borrows another account's salt" + f.Message = "OpenSSH " + v.String() + " is not affected by *sshole" + return f, true + case methodsKnown && !offered: + f.Verdict = engine.Inactive + f.Reason = "the server does not offer password logins to this address (a Match block can still offer them to others)" + f.Message = "OpenSSH " + v.String() + " does not offer password logins" + return f, true + } + f.Verdict = engine.Unknown + f.Reason = "a banner does not show the C library or a vendor backport: scan the host's filesystem (earlylight fs /) to decide" + f.Message = fmt.Sprintf("OpenSSH %s reports a release before 10.6p2", v.String()) + if offered { + f.Message += " and offers password logins" + } + f.Fix = "Scan the host with earlylight fs / --detector sshole. If sshd runs on musl, update OpenSSH to 10.6p2 or a vendor package with the fix, or set PasswordAuthentication no." + f.Severity = "medium" + return f, true +} + +// bannerConn reads the server's identification line before the SSH client +// does, then replays it. +type bannerConn struct { + net.Conn + r *bufio.Reader +} + +func (c *bannerConn) peekBanner() (string, error) { + c.r = bufio.NewReaderSize(c.Conn, 4096) + // RFC 4253 allows other lines before the identification string. + for i := 0; i < 16; i++ { + b, err := c.r.Peek(c.r.Buffered() + 1) + if err != nil && len(b) == 0 { + return "", err + } + all, _ := c.r.Peek(c.r.Buffered()) + for _, line := range strings.Split(string(all), "\n") { + if strings.HasPrefix(line, "SSH-") && strings.Contains(string(all), line+"\n") { + return strings.TrimRight(line, "\r"), nil + } + } + if err != nil { + return "", err + } + if c.r.Buffered() >= 4096 { + break + } + } + return "", errors.New("no SSH identification line") +} + +func (c *bannerConn) Read(p []byte) (int, error) { + if c.r != nil { + return c.r.Read(p) + } + return c.Conn.Read(p) +} diff --git a/detectors/sshole/repo.go b/detectors/sshole/repo.go new file mode 100644 index 0000000..36b9f12 --- /dev/null +++ b/detectors/sshole/repo.go @@ -0,0 +1,190 @@ +package sshole + +import ( + "context" + "fmt" + "io" + "sync" + + "github.com/DefectDojo/earlylight/detectors/sshole/internal/repo" + "github.com/DefectDojo/earlylight/internal/engine" + "github.com/DefectDojo/earlylight/internal/image" + "github.com/DefectDojo/earlylight/internal/source" +) + +// Kind IDs for a source tree. +const ( + KindAPKPin = repo.RulePin + KindAPKFloor = repo.RuleUnpinned + KindEOL = repo.RuleEOL + KindStar = repo.RuleStar + KindPassword = repo.RulePassword + KindNotChecked = repo.RuleNotChecked +) + +func repoKinds() []engine.Kind { + cwe := []string{"CWE-287", "CWE-253"} + return []engine.Kind{ + {ID: KindAPKPin, Title: "Dockerfile pins an Alpine OpenSSH server package without the *sshole fix", Level: "error", SecuritySeverity: "9.8", CWEs: cwe, + Description: "An apk add of openssh, openssh-server, openssh-server-pam or openssh-server-krb5 pinned to a release older than the fixed package for the image's Alpine branch."}, + {ID: KindAPKFloor, Title: "Dockerfile installs an Alpine OpenSSH server with no floor at the *sshole fix", Level: "warning", SecuritySeverity: "6.5", CWEs: cwe, + Description: "An apk add of an OpenSSH server package with no version floor. Images built before 2026-11-05, or rebuilt from a cached layer, keep the vulnerable package; a floor at the fixed release rebuilds the layer and fails the build if the fix is missing."}, + {ID: KindEOL, Title: "OpenSSH server built on an Alpine release with no *sshole fix", Level: "warning", SecuritySeverity: "6.5", CWEs: cwe, + Description: "A Dockerfile stage that installs an OpenSSH server on an Alpine release before 3.16, for which Alpine published no fixed package."}, + {ID: KindStar, Title: "Account password field set to \"*\"", Level: "error", SecuritySeverity: "8.1", CWEs: cwe, + Description: "A Dockerfile, script or Ansible or cloud-init task that sets an account's password field to \"*\" (usermod -p, chpasswd -e, sed on /etc/shadow). On an OpenSSH server on musl without the fix, a crafted password logs in to that account. \"*NP*\" keeps key logins and matches no password on any build."}, + {ID: KindPassword, Title: "PasswordAuthentication turned on", Level: "note", + Description: "Something turns PasswordAuthentication on. With an OpenSSH server on musl that lacks the fix, every account with the password field \"*\" is exposed."}, + {ID: KindNotChecked, Title: "OpenSSH install not checked for the *sshole fix", Level: "note", + Description: "An apk add of an OpenSSH server whose base image could not be identified, or a file that could not be read. It is not known to be safe."}, + } +} + +// ScanRepo checks a source tree. +func (d *Detector) ScanRepo(ctx context.Context, dir string, o engine.Options) *engine.Target { + t := &engine.Target{Name: dir, Type: engine.Repository} + res, err := repo.Scan(ctx, dir, repo.Options{Base: baseResolver(o)}) + 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" + } + for _, f := range res.Findings { + t.Findings = append(t.Findings, repoFinding(f)) + } + for _, s := range res.Skips { + t.Skipped = append(t.Skipped, source.Skip{Path: s.File, Reason: s.Reason}) + } + return t +} + +func repoFinding(f repo.Finding) engine.Finding { + v, reason := engine.Vulnerable, "" + switch f.Rule { + case repo.RuleNotChecked: + v, reason = engine.Unknown, "the base image could not be identified" + case repo.RulePassword: + v, reason = engine.Inactive, "a setting, not a vulnerable build: it matters only with an affected OpenSSH server" + } + facts := map[string]string{} + for k, val := range f.Props { + facts[k] = val + } + out := engine.Finding{Kind: f.Rule, Path: f.File, Line: f.Line, Verdict: v, Reason: reason, Message: f.Message, Method: "source", Facts: facts, Fix: f.Fix} + if f.Level == "warning" { + out.Severity = "medium" + } + return out +} + +// baseResolver reads /etc/alpine-release from the images a tree builds on, +// once each, unless the run is offline. +func baseResolver(o engine.Options) func(context.Context, string) (bool, string, error) { + if o.Offline { + return nil + } + type res struct { + alpine bool + branch string + err error + } + var mu sync.Mutex + cache := map[string]res{} + return func(_ context.Context, ref string) (bool, string, error) { + mu.Lock() + defer mu.Unlock() + if r, ok := cache[ref]; ok { + return r.alpine, r.branch, r.err + } + platform := o.Platform + if platform == "" && len(o.Platforms) > 0 { + platform = o.Platforms[0] + } + a, b, err := repo.AlpineOf(func() (io.ReadCloser, error) { + op, err := image.Open(ref, platform) + if err != nil { + return nil, err + } + return op.FS, nil + }) + cache[ref] = res{a, b, err} + return a, b, err + } +} + +// Fix rewrites what can be fixed: apk constraints to the fixed release and +// "*" password fields to "*NP*". Each edit is rescanned in memory first. +func (d *Detector) Fix(ctx context.Context, dirs []string, o engine.Options, stdout, stderr io.Writer) int { + code := 0 + opts := repo.Options{Base: baseResolver(o)} + for _, dir := range dirs { + res, err := repo.Scan(ctx, dir, opts) + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", repo.Printable(dir), err) + return 2 + } + if res.Truncated { + fmt.Fprintf(stdout, "incomplete %s: the source tree has too many files to walk; what lies past the limit is not checked\n", repo.Printable(dir)) + code = max(code, 1) + } + for _, sk := range res.Skips { + fmt.Fprintf(stdout, "not checked %s %s\n", repo.Printable(sk.File), repo.Printable(sk.Reason)) + code = max(code, 1) + } + for _, f := range res.Findings { + if f.Level == "note" && f.Rule != repo.RuleNotChecked { + continue + } + where := fmt.Sprintf("%s:%d", repo.Printable(f.File), f.Line) + if !f.Fixable { + fmt.Fprintf(stdout, "not fixed %s %s\n %s\n", where, repo.Printable(f.Message), repo.Printable(f.Fix)) + code = max(code, 1) + continue + } + ch, already, err := repo.Plan(ctx, dir, f, opts) + switch { + case already: + continue + case err != nil: + fmt.Fprintf(stdout, "not fixed %s %s\n", where, repo.Printable(err.Error())) + code = max(code, 1) + continue + } + verb := "fixed" + if o.DryRun { + verb = "would fix" + } else if err := repo.Apply(dir, ch); err != nil { + fmt.Fprintf(stderr, "%s: %v\n", repo.Printable(ch.File), err) + return 2 + } + fmt.Fprintf(stdout, "%-10s %s %s\n%s", verb, where, repo.Printable(ch.Summary), indent(repo.Diff(ch))) + } + } + return code +} + +func indent(s string) string { + out := "" + for _, l := range splitLines(s) { + out += " " + l + "\n" + } + return out +} + +func splitLines(s string) []string { + var out []string + start := 0 + for i := 0; i < len(s); i++ { + if s[i] == '\n' { + out = append(out, s[start:i]) + start = i + 1 + } + } + if start < len(s) { + out = append(out, s[start:]) + } + return out +} diff --git a/detectors/sshole/sshole.go b/detectors/sshole/sshole.go new file mode 100644 index 0000000..59dd255 --- /dev/null +++ b/detectors/sshole/sshole.go @@ -0,0 +1,346 @@ +// Package sshole is the detector for *sshole, the OpenSSH password +// authentication bypass on musl libc fixed in OpenSSH 10.6p2 (commit +// 4353fdc43, 2026-11-05) and in Alpine's openssh packages the same day. On +// musl, sshd before the fix compares an account's password field of "*" +// with the "*" that musl's crypt returns when it fails, so a password that +// makes crypt fail logs in to that account. +// +// It finds OpenSSH servers in filesystems and container images, judges each +// by its C library, its release and the apk database, and then checks what +// the target's sshd_config and account files make reachable. It also checks +// live servers (what a banner and the offered methods can tell) and the +// Dockerfiles and scripts in a source tree. +// +// internal/assess knows nothing about the engine; this file adapts it. +package sshole + +import ( + "os" + "path" + "path/filepath" + "sort" + "strings" + + "github.com/DefectDojo/earlylight/detectors/sshole/internal/assess" + "github.com/DefectDojo/earlylight/internal/archive" + "github.com/DefectDojo/earlylight/internal/engine" +) + +// ID is the detector's ID. +const ID = "sshole" + +// Kind IDs. +const ( + KindExposed = assess.KindExposed + KindServer = assess.KindServer + KindHost = "host" +) + +// Detector implements engine.Detector, engine.Reader, engine.Prober, +// engine.RepoScanner and engine.Fixer. +type Detector struct{} + +func init() { engine.Register(&Detector{}) } + +const about = " On musl libc (Alpine, OpenWrt, Void musl, Buildroot and Yocto musl builds), sshd before OpenSSH 10.6p2" + + " compares an account's password field of \"*\" with the \"*\" musl's crypt returns when it fails. When the first" + + " account with a sha256, sha512 or bcrypt hash supplies the salt, a password longer than 256 bytes (or any" + + " password, for bcrypt) logs in to every \"*\" account sshd lets in. Builds that check passwords with PAM" + + " (UsePAM yes) are not affected. Fixed in OpenSSH 10.6p2 and in Alpine's openssh packages of 2026-11-05." + +// Manifest describes the detector. +func (d *Detector) Manifest() engine.Manifest { + cwe := []string{"CWE-287", "CWE-253"} + return engine.Manifest{ + ID: ID, + Title: "*sshole: OpenSSH password authentication bypass on musl libc", + Advisories: []string{ + "https://sshhole.com", + "https://www.openssh.org/releasenotes.html#10.6p2", + "https://github.com/openssh/openssh-portable/commit/4353fdc43ef646c43a8dda7025cc1a898caf1482", + }, + Disclosed: "2026-11-05", + Targets: []engine.TargetKind{engine.Filesystem, engine.Image, engine.Host, engine.Repository}, + Kinds: append([]engine.Kind{ + {ID: KindExposed, Title: "OpenSSH server accepts a crafted password for an account with password field \"*\"", Level: "error", SecuritySeverity: "9.8", CWEs: cwe, + Description: "An OpenSSH server on musl without the fix, whose sshd_config allows password logins for an account with the password field \"*\" while another account's hash makes crypt fail. Anyone who can reach the server can log in as that account." + about}, + {ID: KindServer, Title: "OpenSSH server on musl without the *sshole fix", Level: "warning", SecuritySeverity: "6.5", CWEs: cwe, + Description: "An OpenSSH server on musl without the fix, where the accounts or settings found today do not complete the bypass. A new account with the password field \"*\", a changed sshd_config or a different entrypoint makes it exploitable." + about}, + {ID: KindHost, Title: "Live OpenSSH server that may be exposed to *sshole", Level: "warning", SecuritySeverity: "6.5", CWEs: cwe, + Description: "A live server whose banner reports an OpenSSH release before 10.6p2 and which offers password logins. A banner does not reveal the C library, so scan the host's filesystem to decide." + about}, + }, repoKinds()...), + Tags: []string{"security", "openssh", "musl", "alpine", "*sshole"}, + Data: "OpenSSH releases (fixed in 10.6p2, affected from 7.3p1) and Alpine openssh fixed packages for 3.16 to 3.24 and edge, checked 2026-11-05", + } +} + +// Load has nothing to load: the knowledge is in the code. +func (d *Detector) Load() error { return nil } + +// Wants reads executables (possible sshd binaries) and the few files the +// verdict depends on. +func (d *Detector) Wants(p string, head []byte, _ bool) bool { + return archive.IsExecutable(head) || keep(p) +} + +// keep reports whether a file's content feeds a verdict: account files, +// the apk database, the Alpine release and anything that can be an +// sshd_config or a file one includes. +func keep(p string) bool { + switch p { + case "/etc/passwd", "/etc/shadow", "/etc/group", "/etc/alpine-release", "/etc/os-release", "/usr/lib/os-release", + "/lib/apk/db/installed", "/usr/lib/apk/db/installed": + return true + } + if strings.HasPrefix(p, "/etc/tcb/") && strings.HasSuffix(p, "/shadow") { + return true + } + base := path.Base(p) + return strings.Contains(base, "sshd_config") || strings.Contains(p, "/sshd_config.d/") || + strings.Contains(path.Dir(p), "ssh") && (strings.HasSuffix(base, ".conf") || strings.HasSuffix(base, "config")) +} + +const maxKept = 4 << 20 + +// NewScan starts a filesystem or image scan. +func (d *Detector) NewScan(kind engine.TargetKind) engine.Scan { + return &scan{kind: kind, files: map[string][]byte{}} +} + +type scan struct { + kind engine.TargetKind + binaries []*assess.Binary + files map[string][]byte +} + +func (s *scan) Visit(f engine.File) []engine.Skip { + if f.Member { + return nil // installed servers only, not copies inside archives + } + if keep(f.Path) && len(f.Data) <= maxKept && !archive.IsExecutable(f.Data) { + s.files[f.Path] = f.Data + return nil + } + if b, ok := assess.Inspect(f.Path, f.Data); ok { + s.binaries = append(s.binaries, b) + } + return nil +} + +func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { + if len(s.binaries) == 0 { + return nil + } + fs := &files{kept: s.files, root: ctx.SystemRoot()} + links, _ := ctx.Links() + res := resolver{links: links, exists: func(p string) bool { + if ctx.Exists(p) { + return true + } + return fs.root != "" && fs.diskRegular(p) + }} + acc := assess.ParseAccounts(fs.Read("/etc/passwd"), fs.Read("/etc/shadow"), fs.Read("/etc/group"), fs.tcb()) + owners := map[string]assess.Package{} + for _, db := range []string{"/lib/apk/db/installed", "/usr/lib/apk/db/installed"} { + if b := fs.Read(db); b != nil { + for k, v := range assess.APKOwners(b) { + owners[k] = v + } + } + } + branch := assess.BranchFromRelease(string(fs.Read("/etc/alpine-release"))) + if branch != "" { + ctx.Annotate("alpine_branch", branch) + } + found := assess.Run(assess.Input{ + Binaries: s.binaries, + Owners: owners, + Files: fs, + Accounts: acc, + Resolve: res.resolve, + Branch: branch, + Image: s.kind == engine.Image, + }) + out := make([]engine.Finding, 0, len(found)) + for _, x := range found { + out = append(out, finding(x)) + } + return out +} + +var verdicts = map[assess.Status]engine.Verdict{ + assess.Vulnerable: engine.Vulnerable, + assess.Fixed: engine.Fixed, + assess.Inactive: engine.Inactive, + assess.Undecided: engine.Unknown, +} + +func finding(x assess.Finding) engine.Finding { + v, ok := verdicts[x.Status] + if !ok { + v = engine.Unknown + } + facts := map[string]string{"release": x.Release, "libc": string(x.Libc), "pam_built": yes(x.PAM)} + if x.Package != nil { + facts["package"] = x.Package.Name + " " + x.Package.Version + } + if x.UsePAM != "" { + facts["use_pam"] = x.UsePAM + } + if x.Password != "" { + facts["password_auth"] = x.Password + } + if x.Donor != nil { + facts["salt_from"] = x.Donor.Account + facts["crypt_fails"] = x.Donor.Fails + } + if len(x.Targets) > 0 { + var names []string + for _, t := range x.Targets { + names = append(names, t.Account) + } + facts["accounts"] = strings.Join(names, ",") + } + return engine.Finding{ + Kind: x.Kind, + Path: x.Path, + Verdict: v, + Reason: x.Reason, + Message: x.Message, + Method: "elf", + Facts: facts, + Fix: x.Fix, + Severity: x.Severity, + Details: x, + } +} + +func yes(b bool) string { + if b { + return "yes" + } + return "no" +} + +// files serves kept file contents, and for a walk below a system root, the +// root's own files from disk. +type files struct { + kept map[string][]byte + root string +} + +func (f *files) Read(p string) []byte { + if b, ok := f.kept[p]; ok { + return b + } + if f.root == "" { + return nil + } + return f.disk(p) +} + +func (f *files) diskPath(p string) (string, bool) { + clean := path.Clean("/" + p) + full := filepath.Join(f.root, filepath.FromSlash(clean)) + rel, err := filepath.Rel(f.root, full) + if err != nil || strings.HasPrefix(rel, "..") { + return "", false + } + return full, true +} + +func (f *files) diskRegular(p string) bool { + full, ok := f.diskPath(p) + if !ok { + return false + } + fi, err := os.Stat(full) + return err == nil && fi.Mode().IsRegular() +} + +// disk reads a regular file below the system root, never through a +// symbolic link. +func (f *files) disk(p string) []byte { + full, ok := f.diskPath(p) + if !ok { + return nil + } + fi, err := os.Lstat(full) + if err != nil || !fi.Mode().IsRegular() || fi.Size() > maxKept { + return nil + } + b, err := os.ReadFile(full) + if err != nil { + return nil + } + return b +} + +func (f *files) Glob(pattern string) []string { + seen := map[string]bool{} + var out []string + for p := range f.kept { + if ok, _ := path.Match(pattern, p); ok && !seen[p] { + seen[p] = true + out = append(out, p) + } + } + if f.root != "" { + if full, ok := f.diskPath(pattern); ok { + ms, _ := filepath.Glob(full) + for _, m := range ms { + rel, err := filepath.Rel(f.root, m) + if err != nil { + continue + } + p := "/" + filepath.ToSlash(rel) + if !seen[p] && f.disk(p) != nil { + seen[p] = true + out = append(out, p) + } + } + } + } + sort.Strings(out) + return out +} + +func (f *files) tcb() map[string][]byte { + out := map[string][]byte{} + for _, p := range f.Glob("/etc/tcb/*/shadow") { + out[path.Base(path.Dir(p))] = f.Read(p) + } + return out +} + +// resolver follows symbolic links the way the kernel would, component by +// component, within the target. +type resolver struct { + links map[string]string + exists func(string) bool +} + +func (r resolver) resolve(p string) (string, bool) { + cur := path.Clean("/" + p) + for hops := 0; hops < 40; hops++ { + parts := strings.Split(strings.TrimPrefix(cur, "/"), "/") + changed := false + prefix := "/" + for i, part := range parts { + next := path.Join(prefix, part) + if to, ok := r.links[next]; ok { + if !strings.HasPrefix(to, "/") { + to = path.Join(prefix, to) + } + cur = path.Clean(path.Join(append([]string{to}, parts[i+1:]...)...)) + changed = true + break + } + prefix = next + } + if !changed { + return cur, r.exists(cur) + } + } + return cur, false +} diff --git a/detectors/sshole/sshole_test.go b/detectors/sshole/sshole_test.go new file mode 100644 index 0000000..33c447d --- /dev/null +++ b/detectors/sshole/sshole_test.go @@ -0,0 +1,211 @@ +package sshole_test + +import ( + "bytes" + "context" + "crypto/ed25519" + "crypto/rand" + "encoding/json" + "errors" + "net" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "golang.org/x/crypto/ssh" + + "github.com/DefectDojo/earlylight/detectors/sshole" + "github.com/DefectDojo/earlylight/detectors/sshole/internal/testelf" + "github.com/DefectDojo/earlylight/internal/cli" + "github.com/DefectDojo/earlylight/internal/engine" +) + +var cfg = cli.Config{Tool: "earlylight", Version: "test", Summary: "test"} + +func write(t *testing.T, root, rel string, data []byte, mode os.FileMode) { + t.Helper() + p := filepath.Join(root, rel) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, data, mode); err != nil { + t.Fatal(err) + } +} + +type report struct { + Targets []struct { + Error string `json:"error"` + Findings []engine.Finding `json:"findings"` + } `json:"targets"` +} + +func run(t *testing.T, args ...string) report { + t.Helper() + var out, errb bytes.Buffer + full := append([]string{args[0], args[1], "--format", "json"}, args[2:]...) + cli.Run(cfg, full, &out, &errb) + var r report + if err := json.Unmarshal(out.Bytes(), &r); err != nil { + t.Fatalf("%v\n%s\n%s", err, out.String(), errb.String()) + } + return r +} + +// alpineRoot lays out an Alpine system with an unfixed sshd. +func alpineRoot(t *testing.T, apkVersion string) string { + root := t.TempDir() + sshd := testelf.ELF("/lib/ld-musl-x86_64.so.1", []string{"libc.musl-x86_64.so.1"}, testelf.SSHDStrings("10.0p2", "/usr/lib/ssh/sshd-session", "/usr/lib/ssh/sshd-auth")...) + write(t, root, "usr/sbin/sshd", sshd, 0o755) + write(t, root, "usr/lib/ssh/sshd-session", testelf.ELF("/lib/ld-musl-x86_64.so.1", nil, testelf.SSHDStrings("10.0p2")...), 0o755) + write(t, root, "usr/lib/ssh/sshd-auth", testelf.ELF("/lib/ld-musl-x86_64.so.1", nil, testelf.SSHDStrings("10.0p2")...), 0o755) + write(t, root, "bin/busybox", testelf.ELF("/lib/ld-musl-x86_64.so.1", nil, "busybox"), 0o755) + if err := os.Symlink("/bin/busybox", filepath.Join(root, "bin/sh")); err != nil { + t.Fatal(err) + } + write(t, root, "etc/alpine-release", []byte("3.22.2\n"), 0o644) + write(t, root, "etc/passwd", []byte("root:x:0:0:root:/root:/bin/sh\nalice:x:1000:1000::/home/alice:/bin/sh\nbob:x:1001:1001::/home/bob:/bin/sh\n"), 0o644) + write(t, root, "etc/shadow", []byte("root:*::0:::::\nalice:$6$salt$hash:20762:0:99999:7:::\nbob:*:20762:0:99999:7:::\n"), 0o640) + write(t, root, "etc/ssh/sshd_config", []byte("Include /etc/ssh/sshd_config.d/*.conf\nSubsystem sftp internal-sftp\n"), 0o644) + write(t, root, "lib/apk/db/installed", []byte("P:openssh-server\nV:"+apkVersion+"\nF:usr/sbin\nR:sshd\nF:usr/lib/ssh\nR:sshd-session\nR:sshd-auth\n\n"), 0o644) + return root +} + +func TestScanFS(t *testing.T) { + r := run(t, "scan", "fs", "--detector", "sshole", "--as-root", alpineRoot(t, "10.0_p1-r10")) + fs := r.Targets[0].Findings + if len(fs) != 1 || fs[0].Kind != sshole.KindExposed || fs[0].Verdict != engine.Vulnerable || fs[0].Facts["accounts"] != "bob" { + t.Fatalf("%+v", fs) + } + if !strings.Contains(fs[0].Fix, "10.0_p1-r11") { + t.Errorf("fix %q", fs[0].Fix) + } + r = run(t, "scan", "fs", "--detector", "sshole", "--as-root", alpineRoot(t, "10.0_p1-r11")) + if fs := r.Targets[0].Findings; len(fs) != 1 || fs[0].Verdict != engine.Fixed { + t.Fatalf("%+v", fs) + } +} + +// sshServer runs an in-process SSH server that offers password logins or +// not, and records whether any password arrived. +func sshServer(t *testing.T, passwords bool, version string) (string, *bool) { + t.Helper() + _, key, _ := ed25519.GenerateKey(rand.Reader) + signer, err := ssh.NewSignerFromKey(key) + if err != nil { + t.Fatal(err) + } + got := false + sc := &ssh.ServerConfig{ServerVersion: version} + sc.AddHostKey(signer) + sc.PublicKeyCallback = func(ssh.ConnMetadata, ssh.PublicKey) (*ssh.Permissions, error) { return nil, errors.New("no") } + if passwords { + sc.PasswordCallback = func(ssh.ConnMetadata, []byte) (*ssh.Permissions, error) { + got = true + return nil, errors.New("no") + } + } + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { l.Close() }) + go func() { + for { + c, err := l.Accept() + if err != nil { + return + } + go func() { + defer c.Close() + ssh.NewServerConn(c, sc) + }() + } + }() + return l.Addr().String(), &got +} + +func TestProbe(t *testing.T) { + d := &sshole.Detector{} + cases := []struct { + version string + passwords bool + verdict engine.Verdict + none bool + }{ + {"SSH-2.0-OpenSSH_10.0", true, engine.Unknown, false}, + {"SSH-2.0-OpenSSH_10.0", false, engine.Inactive, false}, + {"SSH-2.0-OpenSSH_10.6p2", true, engine.Fixed, false}, + {"SSH-2.0-OpenSSH_9.2p1 Debian-2+deb12u3", true, "", true}, + {"SSH-2.0-dropbear_2025.88", true, "", true}, + } + for _, c := range cases { + addr, got := sshServer(t, c.passwords, c.version) + _, n, fs, err := d.Probe(context.Background(), addr, 5*time.Second) + if err != nil || n != 1 { + t.Fatalf("%s: %v %d", c.version, err, n) + } + if *got { + t.Fatalf("%s: the probe sent a password", c.version) + } + if c.none { + if len(fs) != 0 { + t.Errorf("%s: %+v", c.version, fs) + } + continue + } + if len(fs) != 1 || fs[0].Verdict != c.verdict { + t.Errorf("%s: %+v", c.version, fs) + } + } +} + +func TestProbeNotSSH(t *testing.T) { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer l.Close() + go func() { + for { + c, err := l.Accept() + if err != nil { + return + } + c.Write([]byte("HTTP/1.1 400 Bad Request\r\n\r\n")) + c.Close() + } + }() + _, _, _, err = (&sshole.Detector{}).Probe(context.Background(), l.Addr().String(), 2*time.Second) + if !errors.Is(err, engine.ErrNotApplicable) { + t.Fatalf("want not applicable, got %v", err) + } + // A host scan where no detector applies fails with the reason. + tg := engine.ScanHost([]engine.Detector{&sshole.Detector{}}, l.Addr().String(), engine.Options{Timeout: 2 * time.Second}) + if tg.Error == "" { + t.Fatal("no error") + } +} + +func TestRepoAndFix(t *testing.T) { + root := t.TempDir() + write(t, root, "Dockerfile", []byte("FROM alpine:3.22\nRUN apk add --no-cache openssh-server && usermod -p '*' bob\n"), 0o644) + r := run(t, "scan", "repo", "--offline", "--detector", "sshole", root) + if n := len(r.Targets[0].Findings); n != 2 { + t.Fatalf("%d findings: %+v", n, r.Targets[0].Findings) + } + var out, errb bytes.Buffer + if code := cli.Run(cfg, []string{"fix", "--offline", "--detector", "sshole", root}, &out, &errb); code != 0 { + t.Fatalf("fix exit %d\n%s%s", code, out.String(), errb.String()) + } + b, _ := os.ReadFile(filepath.Join(root, "Dockerfile")) + if string(b) != "FROM alpine:3.22\nRUN apk add --no-cache 'openssh-server>=10.0_p1-r11' && usermod -p '*NP*' bob\n" { + t.Fatalf("%s", b) + } + r = run(t, "scan", "repo", "--offline", "--detector", "sshole", root) + if n := len(r.Targets[0].Findings); n != 0 { + t.Fatalf("left: %+v", r.Targets[0].Findings) + } +} diff --git a/go.mod b/go.mod index 025fc8f..635bc81 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/klauspost/compress v1.20.3 github.com/knqyf263/go-rpmdb v0.1.1 github.com/ulikunitz/xz v0.5.17 + golang.org/x/crypto v0.58.0 gopkg.in/yaml.v3 v3.0.1 software.sslmate.com/src/go-pkcs12 v0.7.4 ) @@ -23,7 +24,6 @@ require ( github.com/opencontainers/image-spec v1.1.1 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/sirupsen/logrus v1.10.2 // indirect - golang.org/x/crypto v0.58.0 // indirect golang.org/x/sync v0.24.0 // indirect golang.org/x/sys v0.49.0 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect diff --git a/go.sum b/go.sum index 5cbd115..2a7b608 100644 --- a/go.sum +++ b/go.sum @@ -47,6 +47,8 @@ golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= diff --git a/internal/engine/engine.go b/internal/engine/engine.go index aaad129..286ab77 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -9,6 +9,7 @@ package engine import ( "context" + "errors" "fmt" "sort" "time" @@ -182,6 +183,11 @@ type Reader interface { Wants(path string, head []byte, executable bool) bool } +// ErrNotApplicable is what a Prober returns when the address does not run +// the service it checks (no SSH server where a TLS check was asked for). The +// host scan skips that detector, and fails only when every detector did. +var ErrNotApplicable = errors.New("not applicable") + // Prober is implemented by detectors that check live network hosts. type Prober interface { // Probe connects to addr and returns the name it resolved to, how many items diff --git a/internal/engine/run.go b/internal/engine/run.go index fb5688a..4651726 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -400,7 +400,8 @@ func ScanHost(dets []Detector, addr string, opts Options) *Target { addr = u.Host } t := &Target{Name: addr, Type: Host} - ran := false + ran, applied := false, false + var notApplicable []string for _, d := range dets { p, ok := d.(Prober) if !ok || !d.Manifest().Supports(Host) { @@ -408,6 +409,11 @@ func ScanHost(dets []Detector, addr string, opts Options) *Target { } ran = true name, checked, fs, err := p.Probe(context.Background(), addr, opts.Timeout) + if errors.Is(err, ErrNotApplicable) { + notApplicable = append(notApplicable, d.Manifest().ID+": "+err.Error()) + continue + } + applied = true if name != "" { t.Name = name } @@ -424,8 +430,11 @@ func ScanHost(dets []Detector, addr string, opts Options) *Target { t.Read += checked t.Findings = append(t.Findings, check(d.Manifest().ID, fs)...) } - if !ran { + switch { + case !ran: t.Error = "none of the selected detectors check network hosts" + case !applied: + t.Error = strings.Join(notApplicable, "; ") } return t } diff --git a/parity/SSHOLE-RESULTS.md b/parity/SSHOLE-RESULTS.md new file mode 100644 index 0000000..738a50d --- /dev/null +++ b/parity/SSHOLE-RESULTS.md @@ -0,0 +1,16 @@ +# *sshole fixture results + +Generated by `parity/sshole.py`. + +| Case | Result | Findings | +| --- | --- | --- | +| vuln | pass | /usr/sbin/sshd exposed vulnerable critical
/usr/sbin/sshd.pam exposed vulnerable critical | +| fixed | pass | /usr/sbin/sshd sshd fixed
/usr/sbin/sshd.pam sshd fixed | +| pwoff | pass | /usr/sbin/sshd sshd vulnerable medium
/usr/sbin/sshd.pam sshd vulnerable medium | +| usepam | pass | /usr/sbin/sshd exposed vulnerable critical
/usr/sbin/sshd.pam sshd inactive | +| root | pass | /usr/sbin/sshd exposed vulnerable critical | +| matchonly | pass | /usr/sbin/sshd exposed vulnerable high
/usr/sbin/sshd.pam exposed vulnerable high | +| latest | pass | /usr/sbin/sshd sshd fixed | +| debian | pass | none | + +8/8 cases match. diff --git a/parity/sshole.py b/parity/sshole.py new file mode 100644 index 0000000..9a06b2f --- /dev/null +++ b/parity/sshole.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Build the *sshole fixture images and check each verdict. + +usage: python3 parity/sshole.py path/to/earlylight + +Needs Docker. The images are built locally from parity/sshole/*.Dockerfile +(vuln first: other cases build on it) and scanned from `docker save` +archives. Writes parity/SSHOLE-RESULTS.md. +""" +import json +import os +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +CASES = os.path.join(HERE, "sshole") +ORDER = ["vuln", "fixed", "pwoff", "usepam", "root", "matchonly", "latest", "debian"] + + +def main(): + if len(sys.argv) != 2: + sys.exit(__doc__) + tool = os.path.abspath(sys.argv[1]) + expected = json.load(open(os.path.join(CASES, "expected.json"))) + rows, failed = [], 0 + with tempfile.TemporaryDirectory() as tmp: + for case in ORDER: + tag = "earlylight-parity-sshole:" + case + subprocess.run(["docker", "build", "-q", "-t", tag, "-f", os.path.join(CASES, case + ".Dockerfile"), CASES], + check=True, stdout=subprocess.DEVNULL) + tar = os.path.join(tmp, case + ".tar") + subprocess.run(["docker", "save", tag, "-o", tar], check=True) + out = subprocess.run([tool, "scan", "image", "--detector", "sshole", "--format", "json", "docker-archive:" + tar], + capture_output=True, text=True) + report = json.loads(out.stdout) + got = [] + for t in report["targets"]: + if t.get("error"): + got.append(["error", t["error"], "", ""]) + for f in t.get("findings", []): + got.append([f["path"], f["kind"], f["verdict"], f.get("severity", "")]) + want = expected[case] + ok = sorted(got) == sorted(want) + failed += not ok + rows.append((case, ok, got, want)) + with open(os.path.join(HERE, "SSHOLE-RESULTS.md"), "w") as f: + f.write("# *sshole fixture results\n\nGenerated by `parity/sshole.py`.\n\n| Case | Result | Findings |\n| --- | --- | --- |\n") + for case, ok, got, want in rows: + cell = "
".join(" ".join(x for x in g if x) for g in sorted(got)) or "none" + f.write(f"| {case} | {'pass' if ok else 'FAIL (want ' + json.dumps(want) + ')'} | {cell} |\n") + f.write(f"\n{len(rows) - failed}/{len(rows)} cases match.\n") + print(f"{len(rows) - failed}/{len(rows)} cases match") + sys.exit(1 if failed else 0) + + +if __name__ == "__main__": + main() diff --git a/parity/sshole/debian.Dockerfile b/parity/sshole/debian.Dockerfile new file mode 100644 index 0000000..3352ed6 --- /dev/null +++ b/parity/sshole/debian.Dockerfile @@ -0,0 +1,3 @@ +FROM debian:12-slim +RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends openssh-server >/dev/null \ + && useradd -m bob && usermod -p '*' bob && rm -rf /var/lib/apt/lists/* diff --git a/parity/sshole/expected.json b/parity/sshole/expected.json new file mode 100644 index 0000000..08699ea --- /dev/null +++ b/parity/sshole/expected.json @@ -0,0 +1,10 @@ +{ + "vuln": [["/usr/sbin/sshd", "exposed", "vulnerable", "critical"], ["/usr/sbin/sshd.pam", "exposed", "vulnerable", "critical"]], + "fixed": [["/usr/sbin/sshd", "sshd", "fixed", ""], ["/usr/sbin/sshd.pam", "sshd", "fixed", ""]], + "pwoff": [["/usr/sbin/sshd", "sshd", "vulnerable", "medium"], ["/usr/sbin/sshd.pam", "sshd", "vulnerable", "medium"]], + "usepam": [["/usr/sbin/sshd", "exposed", "vulnerable", "critical"], ["/usr/sbin/sshd.pam", "sshd", "inactive", ""]], + "root": [["/usr/sbin/sshd", "exposed", "vulnerable", "critical"]], + "matchonly": [["/usr/sbin/sshd", "exposed", "vulnerable", "high"], ["/usr/sbin/sshd.pam", "exposed", "vulnerable", "high"]], + "latest": [["/usr/sbin/sshd", "sshd", "fixed", ""]], + "debian": [] +} diff --git a/parity/sshole/fixed.Dockerfile b/parity/sshole/fixed.Dockerfile new file mode 100644 index 0000000..38174c9 --- /dev/null +++ b/parity/sshole/fixed.Dockerfile @@ -0,0 +1,4 @@ +FROM alpine:3.22 +RUN apk add --no-cache 'openssh-server>=10.0_p1-r11' 'openssh-server-pam>=10.0_p1-r11' \ + && adduser -D alice && echo 'alice:parity-only-not-secret' | chpasswd -c sha512 \ + && adduser -D bob && sed -i 's/^bob:[^:]*:/bob:*:/' /etc/shadow diff --git a/parity/sshole/latest.Dockerfile b/parity/sshole/latest.Dockerfile new file mode 100644 index 0000000..cc06edc --- /dev/null +++ b/parity/sshole/latest.Dockerfile @@ -0,0 +1,2 @@ +FROM alpine:3.24 +RUN apk add --no-cache openssh-server diff --git a/parity/sshole/matchonly.Dockerfile b/parity/sshole/matchonly.Dockerfile new file mode 100644 index 0000000..73f2f36 --- /dev/null +++ b/parity/sshole/matchonly.Dockerfile @@ -0,0 +1,2 @@ +FROM earlylight-parity-sshole:vuln +RUN printf 'PasswordAuthentication no\nMatch Address 10.0.0.0/8\n PasswordAuthentication yes\n' > /etc/ssh/sshd_config.d/00-match.conf diff --git a/parity/sshole/pwoff.Dockerfile b/parity/sshole/pwoff.Dockerfile new file mode 100644 index 0000000..539c591 --- /dev/null +++ b/parity/sshole/pwoff.Dockerfile @@ -0,0 +1,2 @@ +FROM earlylight-parity-sshole:vuln +RUN echo 'PasswordAuthentication no' > /etc/ssh/sshd_config.d/00-off.conf diff --git a/parity/sshole/root.Dockerfile b/parity/sshole/root.Dockerfile new file mode 100644 index 0000000..36f2667 --- /dev/null +++ b/parity/sshole/root.Dockerfile @@ -0,0 +1,8 @@ +# No "*" account but root (Alpine's default), with PermitRootLogin yes. +FROM alpine:3.22 +RUN arch=$(apk --print-arch) && cd /tmp \ + && for p in openssh-keygen openssh-server-common openssh-server; do \ + wget -q https://dl-cdn.alpinelinux.org/alpine/v3.22/main/$arch/$p-10.0_p1-r10.apk; done \ + && apk add --no-cache /tmp/*.apk && rm /tmp/*.apk \ + && adduser -D alice && echo 'alice:parity-only-not-secret' | chpasswd -c sha512 \ + && echo 'PermitRootLogin yes' > /etc/ssh/sshd_config.d/10-root.conf diff --git a/parity/sshole/usepam.Dockerfile b/parity/sshole/usepam.Dockerfile new file mode 100644 index 0000000..ec73fc6 --- /dev/null +++ b/parity/sshole/usepam.Dockerfile @@ -0,0 +1,2 @@ +FROM earlylight-parity-sshole:vuln +RUN echo 'UsePAM yes' > /etc/ssh/sshd_config.d/00-pam.conf diff --git a/parity/sshole/vuln.Dockerfile b/parity/sshole/vuln.Dockerfile new file mode 100644 index 0000000..83d961a --- /dev/null +++ b/parity/sshole/vuln.Dockerfile @@ -0,0 +1,9 @@ +# Alpine 3.22 with openssh 10.0_p1-r10, the release before the fix: an +# account "bob" with the password field "*" and "alice" with a sha512 hash. +FROM alpine:3.22 +RUN arch=$(apk --print-arch) && cd /tmp \ + && for p in openssh-keygen openssh-server-common openssh-server openssh-server-pam; do \ + wget -q https://dl-cdn.alpinelinux.org/alpine/v3.22/main/$arch/$p-10.0_p1-r10.apk; done \ + && apk add --no-cache linux-pam /tmp/*.apk && rm /tmp/*.apk \ + && adduser -D alice && echo 'alice:parity-only-not-secret' | chpasswd -c sha512 \ + && adduser -D bob && sed -i 's/^bob:[^:]*:/bob:*:/' /etc/shadow From 4723cba87c7cd0ffdf569b4dd6dead0dee806aa8 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Thu, 5 Nov 2026 16:11:14 -0700 Subject: [PATCH 2/8] sshole: bound config includes and globs, guard base-image lookups, refuse symlinked reads Also adds repo.Find and Options.Files for callers that rescan one finding or a pull request's changed files. Co-Authored-By: Claude Opus 5.5 --- .../sshole/internal/assess/assess_test.go | 21 +++++++ detectors/sshole/internal/assess/binary.go | 4 +- detectors/sshole/internal/assess/config.go | 59 ++++++++++++++----- detectors/sshole/internal/repo/plan.go | 40 +++++++++++++ detectors/sshole/internal/repo/repo.go | 19 ++++++ detectors/sshole/internal/repo/repo_test.go | 21 +++++++ detectors/sshole/repo.go | 59 ++++++++++++++++++- detectors/sshole/sshole.go | 27 ++++++++- 8 files changed, 231 insertions(+), 19 deletions(-) diff --git a/detectors/sshole/internal/assess/assess_test.go b/detectors/sshole/internal/assess/assess_test.go index 113a9dd..9172911 100644 --- a/detectors/sshole/internal/assess/assess_test.go +++ b/detectors/sshole/internal/assess/assess_test.go @@ -337,3 +337,24 @@ func TestBranchFromRelease(t *testing.T) { } } } + +func TestGlobMatch(t *testing.T) { + cases := map[[2]string]bool{{"bob", "bob"}: true, {"b*", "bob"}: true, {"*o?", "bob"}: true, {"?", ""}: false, {"*", ""}: true, {"a*b*c", "axxbyyc"}: true, {"a*b*c", "axxbyy"}: false} + for k, want := range cases { + if globMatch(k[0], k[1]) != want { + t.Errorf("%q %q", k[0], k[1]) + } + } + // Linear, not exponential: this would never finish with backtracking recursion. + if globMatch(strings.Repeat("*a", 200)+"b", strings.Repeat("a", 5000)) { + t.Error("matched") + } +} + +func TestIncludeLoop(t *testing.T) { + fs := memFiles{"/etc/ssh/sshd_config": "Include /etc/ssh/a.conf\n", "/etc/ssh/a.conf": "Include /etc/ssh/a.conf /etc/ssh/sshd_config\nPasswordAuthentication no\n"} + c := ParseConfig(fs, "/etc/ssh/sshd_config") + if len(c.Directives) != 1 || len(c.Missing) == 0 { + t.Fatalf("%+v", c) + } +} diff --git a/detectors/sshole/internal/assess/binary.go b/detectors/sshole/internal/assess/binary.go index 22bd620..f1c14a8 100644 --- a/detectors/sshole/internal/assess/binary.go +++ b/detectors/sshole/internal/assess/binary.go @@ -170,8 +170,8 @@ func Inspect(p string, data []byte) (*Binary, bool) { } for _, prog := range f.Progs { - if prog.Type != elf.PT_INTERP { - continue + if prog.Type != elf.PT_INTERP || prog.Filesz > 4096 { + continue // an interpreter path is short: a larger size is a hostile header } buf := make([]byte, prog.Filesz) if _, err := prog.ReadAt(buf, 0); err == nil { diff --git a/detectors/sshole/internal/assess/config.go b/detectors/sshole/internal/assess/config.go index 610b0e6..11c0261 100644 --- a/detectors/sshole/internal/assess/config.go +++ b/detectors/sshole/internal/assess/config.go @@ -50,8 +50,12 @@ func ParseConfig(files Files, p string) Config { } c.Read = true block := 0 + filesRead := 1 + onStack := map[string]bool{} var walk func(file string, data []byte, match []Criterion, depth int) walk = func(file string, data []byte, match []Criterion, depth int) { + onStack[file] = true + defer delete(onStack, file) cur := match curBlock := block for i, raw := range lines(data) { @@ -80,6 +84,15 @@ func ParseConfig(files Files, p string) Config { c.Missing = append(c.Missing, pat) } for _, g := range got { + if onStack[g] { + c.Missing = append(c.Missing, g+": includes itself") + continue + } + if filesRead >= maxIncludes { + c.Missing = append(c.Missing, g+": more than 256 included files; the rest are not read") + break + } + filesRead++ if b := files.Read(g); b != nil { walk(g, b, cur, depth+1) } else { @@ -89,6 +102,10 @@ func ParseConfig(files Files, p string) Config { } continue } + if len(c.Directives) >= maxDirectives { + c.Missing = append(c.Missing, file+": more than 100000 directives; the rest are not read") + return + } c.Directives = append(c.Directives, Directive{Key: key, Args: args[1:], File: file, Line: i + 1, Match: cur, Block: curBlock}) } } @@ -96,6 +113,12 @@ func ParseConfig(files Files, p string) Config { return c } +// Limits on what one sshd_config can make the parser read. +const ( + maxIncludes = 256 + maxDirectives = 100000 +) + func hasGlob(p string) bool { return strings.ContainsAny(p, "*?[") } // splitArgs splits a config line the way servconf.c reads it: the keyword @@ -240,23 +263,31 @@ func matchPatternList(s, list string) bool { return got } -// globMatch is OpenSSH's match_pattern: '*' and '?' only. +// globMatch is OpenSSH's match_pattern: '*' and '?' only. Iterative, with +// one backtrack point, so it runs in time linear in the input for each star. func globMatch(p, s string) bool { - if p == "" { - return s == "" - } - switch p[0] { - case '*': - for i := 0; i <= len(s); i++ { - if globMatch(p[1:], s[i:]) { - return true - } + pi, si := 0, 0 + star, mark := -1, 0 + for si < len(s) { + switch { + case pi < len(p) && (p[pi] == '?' || p[pi] == s[si]): + pi++ + si++ + case pi < len(p) && p[pi] == '*': + star, mark = pi, si + pi++ + case star >= 0: + pi = star + 1 + mark++ + si = mark + default: + return false } - return false - case '?': - return s != "" && globMatch(p[1:], s[1:]) } - return s != "" && p[0] == s[0] && globMatch(p[1:], s[1:]) + for pi < len(p) && p[pi] == '*' { + pi++ + } + return pi == len(p) } // Values returns every value a single-valued keyword can take for a diff --git a/detectors/sshole/internal/repo/plan.go b/detectors/sshole/internal/repo/plan.go index 0d743a0..92ad88f 100644 --- a/detectors/sshole/internal/repo/plan.go +++ b/detectors/sshole/internal/repo/plan.go @@ -209,3 +209,43 @@ func Printable(s string) string { } return b.String() } + +// Find rescans one file and returns the finding with this rule at this +// line. spec, when not empty, picks between several on the line: the apk +// spec or the text the finding's message quotes. gone is true when the file +// has no such finding any more. +func Find(ctx context.Context, root, file string, line int, rule, message string, opts Options) (f *Finding, gone bool, err error) { + fs, err := scanOne(ctx, root, file, opts, nil) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil, true, nil + } + return nil, false, err + } + var at []Finding + for _, g := range fs { + if g.Rule == rule && g.Line == line { + at = append(at, g) + } + } + if len(at) > 1 && message != "" { + var picked []Finding + for _, g := range at { + if strings.Contains(message, g.Message) || g.Props["spec"] != "" && strings.Contains(message, g.Props["spec"]) { + picked = append(picked, g) + } + } + if len(picked) > 0 { + at = picked + } + } + switch len(at) { + case 0: + return nil, true, nil + case 1: + return &at[0], false, nil + } + // Several identical findings on one line: the first; the rest come + // back on the next scan. + return &at[0], false, nil +} diff --git a/detectors/sshole/internal/repo/repo.go b/detectors/sshole/internal/repo/repo.go index 0231ccd..b74456d 100644 --- a/detectors/sshole/internal/repo/repo.go +++ b/detectors/sshole/internal/repo/repo.go @@ -78,6 +78,9 @@ type Options struct { // Base resolves an image the tree builds on: whether it is Alpine and // which branch ("3.22", "edge"). nil: only what the name says. Base func(ctx context.Context, image string) (alpine bool, branch string, err error) + // Files, when set, limits the scan to these repository-relative paths + // (a pull request's changed files). + Files []string } const ( @@ -91,6 +94,15 @@ var skipDirs = map[string]bool{".git": true, "node_modules": true, "vendor": tru func Scan(ctx context.Context, root string, opts Options) (Result, error) { var res Result var list []string + if opts.Files != nil { + for _, rel := range opts.Files { + rel = path.Clean(strings.ReplaceAll(rel, "\\", "/")) + if kindOf(rel) != "" && !contains(list, rel) && rel != ".." && !strings.HasPrefix(rel, "../") && !path.IsAbs(rel) { + list = append(list, rel) + } + } + return scanList(ctx, root, list, opts, res) + } err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { if err != nil { rel, _ := filepath.Rel(root, p) @@ -124,6 +136,10 @@ func Scan(ctx context.Context, root string, opts Options) (Result, error) { if err != nil { return res, err } + return scanList(ctx, root, list, opts, res) +} + +func scanList(ctx context.Context, root string, list []string, opts Options, res Result) (Result, error) { for rel := range opts.Overlay { if kindOf(rel) != "" && !contains(list, rel) { list = append(list, rel) @@ -136,6 +152,9 @@ func Scan(ctx context.Context, root string, opts Options) (Result, error) { if !ok { var err error b, err = readFile(root, rel) + if errors.Is(err, fs.ErrNotExist) && opts.Files != nil { + continue // a changed file the pull request deleted + } if err != nil { res.Skips = append(res.Skips, Skip{File: rel, Reason: err.Error()}) continue diff --git a/detectors/sshole/internal/repo/repo_test.go b/detectors/sshole/internal/repo/repo_test.go index 11697a6..8361767 100644 --- a/detectors/sshole/internal/repo/repo_test.go +++ b/detectors/sshole/internal/repo/repo_test.go @@ -235,3 +235,24 @@ func FuzzScanText(f *testing.F) { splitShell(s) }) } + +func TestFindAndFiles(t *testing.T) { + root := t.TempDir() + write(t, root, "a/Dockerfile", "FROM alpine:3.22\nRUN apk add openssh-server && usermod -p '*' bob\n") + write(t, root, "b/Dockerfile", "FROM alpine:3.22\nRUN apk add openssh\n") + ctx := context.Background() + res, err := Scan(ctx, root, Options{Files: []string{"a/Dockerfile", "gone/Dockerfile", "../x/Dockerfile"}}) + if err != nil || len(res.Findings) != 2 || len(res.Skips) != 0 { + t.Fatalf("%v %+v", err, res) + } + f, gone, err := Find(ctx, root, "a/Dockerfile", 2, RuleStar, "", Options{}) + if err != nil || gone || f == nil || !f.Fixable { + t.Fatalf("%v %v %+v", err, gone, f) + } + if _, gone, _ := Find(ctx, root, "a/Dockerfile", 1, RuleStar, "", Options{}); !gone { + t.Error("a line with no finding is not gone") + } + if _, gone, _ := Find(ctx, root, "missing/Dockerfile", 2, RuleStar, "", Options{}); !gone { + t.Error("a missing file is not gone") + } +} diff --git a/detectors/sshole/repo.go b/detectors/sshole/repo.go index 36b9f12..5c9a473 100644 --- a/detectors/sshole/repo.go +++ b/detectors/sshole/repo.go @@ -4,8 +4,12 @@ import ( "context" "fmt" "io" + "net" + "strings" "sync" + "github.com/google/go-containerregistry/pkg/name" + "github.com/DefectDojo/earlylight/detectors/sshole/internal/repo" "github.com/DefectDojo/earlylight/internal/engine" "github.com/DefectDojo/earlylight/internal/image" @@ -99,6 +103,14 @@ func baseResolver(o engine.Options) func(context.Context, string) (bool, string, if r, ok := cache[ref]; ok { return r.alpine, r.branch, r.err } + if err := registryRef(ref, o.PublicOnly); err != nil { + cache[ref] = res{err: err} + return false, "", err + } + if len(cache) >= maxBases { + err := fmt.Errorf("not resolved: this scan already read %d base images, its limit", maxBases) + return false, "", err + } platform := o.Platform if platform == "" && len(o.Platforms) > 0 { platform = o.Platforms[0] @@ -108,13 +120,58 @@ func baseResolver(o engine.Options) func(context.Context, string) (bool, string, if err != nil { return nil, err } - return op.FS, nil + return limitedReadCloser{io.LimitReader(op.FS, maxBaseBytes), op.FS}, nil }) cache[ref] = res{a, b, err} return a, b, err } } +// Limits on base-image lookups: a source tree may not be yours, so what it +// names cannot make a scan read without bound. +const ( + maxBases = 32 + maxBaseBytes = 2 << 30 +) + +type limitedReadCloser struct { + io.Reader + io.Closer +} + +// registryRef accepts only a registry reference: never a local archive +// (docker-archive:, rootfs:) or any other transport a Dockerfile could +// name, and never a registry on a link-local address (cloud metadata), nor, +// with publicOnly, on a loopback, private or internal one. +func registryRef(ref string, publicOnly bool) 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) + } + r, err := name.ParseReference(ref, name.StrictValidation) + if err != nil { + if r, err = name.ParseReference(ref); err != nil { + return fmt.Errorf("%q is not a valid image reference", ref) + } + } + host := r.Context().RegistryStr() + if h, _, err := net.SplitHostPort(host); err == nil { + host = h + } + ips, err := net.LookupIP(host) + if err != nil { + return fmt.Errorf("resolving %s: %w", host, err) + } + for _, ip := range ips { + if ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsUnspecified() { + return fmt.Errorf("%s resolves to a link-local address, which is never a registry", host) + } + if publicOnly && (ip.IsLoopback() || ip.IsPrivate()) { + return fmt.Errorf("%s resolves to a loopback or private address (--public-registries-only)", host) + } + } + return nil +} + // Fix rewrites what can be fixed: apk constraints to the fixed release and // "*" password fields to "*NP*". Each edit is rescanned in memory first. func (d *Detector) Fix(ctx context.Context, dirs []string, o engine.Options, stdout, stderr io.Writer) int { diff --git a/detectors/sshole/sshole.go b/detectors/sshole/sshole.go index 59dd255..07b0e5e 100644 --- a/detectors/sshole/sshole.go +++ b/detectors/sshole/sshole.go @@ -249,22 +249,45 @@ func (f *files) diskPath(p string) (string, bool) { return full, true } +// diskRegular reports whether a regular file is at p below the system +// root, following symbolic links only while they stay inside it. Nothing is +// read. func (f *files) diskRegular(p string) bool { full, ok := f.diskPath(p) if !ok { return false } - fi, err := os.Stat(full) + real, err := filepath.EvalSymlinks(full) + if err != nil { + return false + } + root, err := filepath.EvalSymlinks(f.root) + if err != nil { + return false + } + if rel, err := filepath.Rel(root, real); err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return false + } + fi, err := os.Stat(real) return err == nil && fi.Mode().IsRegular() } // disk reads a regular file below the system root, never through a -// symbolic link. +// symbolic link in any component of its path. func (f *files) disk(p string) []byte { full, ok := f.diskPath(p) if !ok { return nil } + rel, _ := filepath.Rel(f.root, full) + cur := f.root + for _, part := range strings.Split(rel, string(filepath.Separator)) { + cur = filepath.Join(cur, part) + fi, err := os.Lstat(cur) + if err != nil || fi.Mode()&os.ModeSymlink != 0 { + return nil + } + } fi, err := os.Lstat(full) if err != nil || !fi.Mode().IsRegular() || fi.Size() > maxKept { return nil From e8442c4cd53ac8882dbf53bc4db95f4342c33772 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Thu, 5 Nov 2026 16:13:18 -0700 Subject: [PATCH 3/8] sshole: read base images through the guarded transport Moves netguard from detectors/php2shell/internal to internal, unchanged, and adds image.OpenRegistry, which takes a transport and refuses local archives. Base images a source tree names are now checked against the address policy on every connection and redirect, not before them. Co-Authored-By: Claude Opus 5.5 --- SNAPSHOT | 1 + detectors/php2shell/verbatim.go | 2 +- detectors/sshole/repo.go | 38 ++++++------------- internal/image/image.go | 26 +++++++++++++ .../netguard/netguard.go | 0 .../netguard/netguard_test.go | 0 6 files changed, 39 insertions(+), 28 deletions(-) rename {detectors/php2shell/internal => internal}/netguard/netguard.go (100%) rename {detectors/php2shell/internal => internal}/netguard/netguard_test.go (100%) diff --git a/SNAPSHOT b/SNAPSHOT index 4f790f4..5f73c56 100644 --- a/SNAPSHOT +++ b/SNAPSHOT @@ -7,3 +7,4 @@ Engine-only changes since the copy (port these back to emudhra-scan and php2shel - detectors/php2shell/internal/report/report_test.go: gofmt whitespace only - internal/refs/shell.go and yaml.go (refs moved from detectors/php2shell/internal/refs to internal/refs on 2026-10-27, unchanged, so the brotli detector can read image references too): Dockerfile and Compose variable expansion capped at 8 KiB (a chain of doubling ARGs exhausted memory and time); regression tests expansion_bomb_test.go and dotenv_bomb_test.go - detectors/emudhra/internal/detect/detect_test.go: TestManyBeginsNoEndIsFast checks linear growth instead of a 2 s limit (flaked under -race on slow CI; same fix as defectdojo-scan-and-fix #279) +- internal/netguard (moved from detectors/php2shell/internal/netguard on 2026-11-05, unchanged, so the sshole detector reads base images through the same guarded transport) diff --git a/detectors/php2shell/verbatim.go b/detectors/php2shell/verbatim.go index 9c5cf2a..d7dd4f4 100644 --- a/detectors/php2shell/verbatim.go +++ b/detectors/php2shell/verbatim.go @@ -16,11 +16,11 @@ import ( "strings" "github.com/DefectDojo/earlylight/detectors/php2shell/internal/fix" - "github.com/DefectDojo/earlylight/detectors/php2shell/internal/netguard" "github.com/DefectDojo/earlylight/detectors/php2shell/internal/pkgdb" "github.com/DefectDojo/earlylight/detectors/php2shell/internal/registry" "github.com/DefectDojo/earlylight/detectors/php2shell/internal/report" "github.com/DefectDojo/earlylight/detectors/php2shell/internal/reposcan" + "github.com/DefectDojo/earlylight/internal/netguard" ) // systemDirs are read from the system root on every fs scan, so a scan of one diff --git a/detectors/sshole/repo.go b/detectors/sshole/repo.go index 5c9a473..3821398 100644 --- a/detectors/sshole/repo.go +++ b/detectors/sshole/repo.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "net" "strings" "sync" @@ -13,6 +12,7 @@ import ( "github.com/DefectDojo/earlylight/detectors/sshole/internal/repo" "github.com/DefectDojo/earlylight/internal/engine" "github.com/DefectDojo/earlylight/internal/image" + "github.com/DefectDojo/earlylight/internal/netguard" "github.com/DefectDojo/earlylight/internal/source" ) @@ -103,7 +103,7 @@ func baseResolver(o engine.Options) func(context.Context, string) (bool, string, if r, ok := cache[ref]; ok { return r.alpine, r.branch, r.err } - if err := registryRef(ref, o.PublicOnly); err != nil { + if err := registryRef(ref); err != nil { cache[ref] = res{err: err} return false, "", err } @@ -116,7 +116,11 @@ func baseResolver(o engine.Options) func(context.Context, string) (bool, string, platform = o.Platforms[0] } a, b, err := repo.AlpineOf(func() (io.ReadCloser, error) { - op, err := image.Open(ref, platform) + // The guarded transport refuses link-local addresses (cloud + // metadata) always, and with --public-registries-only every + // loopback, private and internal one, on each connection and + // redirect. + op, err := image.OpenRegistry(ref, platform, netguard.Transport(o.PublicOnly)) if err != nil { return nil, err } @@ -141,33 +145,13 @@ type limitedReadCloser struct { // registryRef accepts only a registry reference: never a local archive // (docker-archive:, rootfs:) or any other transport a Dockerfile could -// name, and never a registry on a link-local address (cloud metadata), nor, -// with publicOnly, on a loopback, private or internal one. -func registryRef(ref string, publicOnly bool) error { +// name. Addresses are checked by the guarded transport when it connects. +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) } - r, err := name.ParseReference(ref, name.StrictValidation) - if err != nil { - if r, err = name.ParseReference(ref); err != nil { - return fmt.Errorf("%q is not a valid image reference", ref) - } - } - host := r.Context().RegistryStr() - if h, _, err := net.SplitHostPort(host); err == nil { - host = h - } - ips, err := net.LookupIP(host) - if err != nil { - return fmt.Errorf("resolving %s: %w", host, err) - } - for _, ip := range ips { - if ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsUnspecified() { - return fmt.Errorf("%s resolves to a link-local address, which is never a registry", host) - } - if publicOnly && (ip.IsLoopback() || ip.IsPrivate()) { - return fmt.Errorf("%s resolves to a loopback or private address (--public-registries-only)", host) - } + if _, err := name.ParseReference(ref); err != nil { + return fmt.Errorf("%q is not a valid image reference", ref) } return nil } diff --git a/internal/image/image.go b/internal/image/image.go index 89c8b15..75de9c5 100644 --- a/internal/image/image.go +++ b/internal/image/image.go @@ -4,6 +4,7 @@ package image import ( "fmt" "io" + "net/http" "strings" "github.com/google/go-containerregistry/pkg/authn" @@ -35,6 +36,10 @@ func Open(ref, platform string) (*Opened, error) { if err != nil { return nil, err } + return opened(img) +} + +func opened(img v1.Image) (*Opened, error) { digest, err := img.Digest() if err != nil { return nil, err @@ -88,15 +93,36 @@ func Platforms(ref string) ([]string, error) { return out, nil } +// OpenRegistry is Open for a registry reference only, with every request +// carried by rt: a caller scanning references it does not trust passes a +// guarded transport (internal/netguard). Local archives are refused. +func OpenRegistry(ref, platform string, rt http.RoundTripper) (*Opened, error) { + if strings.HasPrefix(ref, "docker-archive:") || strings.HasPrefix(ref, "rootfs:") { + return nil, fmt.Errorf("%q: only registry references can be opened here", ref) + } + img, err := loadRemote(ref, platform, rt) + if err != nil { + return nil, err + } + return opened(img) +} + func load(ref, platform string) (v1.Image, error) { if p, ok := strings.CutPrefix(ref, "docker-archive:"); ok { return tarball.ImageFromPath(p, nil) } + return loadRemote(ref, platform, nil) +} + +func loadRemote(ref, platform string, rt http.RoundTripper) (v1.Image, error) { r, err := name.ParseReference(ref) if err != nil { return nil, fmt.Errorf("parsing image reference %q: %w", ref, err) } opts := []remote.Option{remote.WithAuthFromKeychain(authn.DefaultKeychain)} + if rt != nil { + opts = append(opts, remote.WithTransport(rt)) + } if platform != "" { p, err := v1.ParsePlatform(platform) if err != nil { diff --git a/detectors/php2shell/internal/netguard/netguard.go b/internal/netguard/netguard.go similarity index 100% rename from detectors/php2shell/internal/netguard/netguard.go rename to internal/netguard/netguard.go diff --git a/detectors/php2shell/internal/netguard/netguard_test.go b/internal/netguard/netguard_test.go similarity index 100% rename from detectors/php2shell/internal/netguard/netguard_test.go rename to internal/netguard/netguard_test.go From 929ca72ea008a222d7c49ed0886f301efad87554 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Thu, 5 Nov 2026 16:20:02 -0700 Subject: [PATCH 4/8] sshole: read Dockerfile-dev style names and sshd_config.d files in source trees Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/internal/repo/repo.go | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/detectors/sshole/internal/repo/repo.go b/detectors/sshole/internal/repo/repo.go index b74456d..a24a99d 100644 --- a/detectors/sshole/internal/repo/repo.go +++ b/detectors/sshole/internal/repo/repo.go @@ -189,20 +189,34 @@ func kindOf(rel string) string { name := path.Base(rel) lower := strings.ToLower(name) switch { - case lower == "dockerfile" || strings.HasPrefix(lower, "dockerfile.") || strings.HasSuffix(lower, ".dockerfile") || - lower == "containerfile" || strings.HasPrefix(lower, "containerfile.") || strings.HasSuffix(lower, ".containerfile"): + case isDockerfile(lower): return "dockerfile" case strings.HasSuffix(lower, ".sh") || strings.HasSuffix(lower, ".bash") || strings.HasSuffix(lower, ".ash") || strings.HasPrefix(lower, "entrypoint") || strings.HasPrefix(lower, "docker-entrypoint"): return "shell" case strings.HasSuffix(lower, ".yml") || strings.HasSuffix(lower, ".yaml"): return "yaml" - case strings.Contains(lower, "sshd_config"): + case strings.Contains(lower, "sshd_config") || strings.Contains("/"+strings.ToLower(rel), "/sshd_config.d/"): return "sshd_config" } return "" } +// isDockerfile matches the names the image reference finder reads: +// Dockerfile, Dockerfile.dev, Dockerfile-dev, Dockerfile_dev, app.dockerfile +// and the same for Containerfile. +func isDockerfile(lower string) bool { + for _, n := range []string{"dockerfile", "containerfile"} { + if lower == n || strings.HasSuffix(lower, "."+n) { + return true + } + if strings.HasPrefix(lower, n) && strings.ContainsRune("._-", rune(lower[len(n)])) { + return true + } + } + return false +} + func readFile(root, rel string) ([]byte, error) { p, err := refs.SafePath(root, rel) if err != nil { From 6347556cdd45683ec7ca28686fe191258ac73df5 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Thu, 5 Nov 2026 20:48:24 -0700 Subject: [PATCH 5/8] sshole: read the image's command and startup scripts, close source-tree gaps - Images: sshd -o and -f from the container command and startup scripts (entrypoints, s6, cont-init.d, entrypoint.d) change the config judged; a startup script that turns password logins on, sets a "*" field or sets passwords with chpasswd makes an unfixed server exposed (high). The engine passes the image's Entrypoint and Cmd (TargetContext.Command). - OpenWrt's opkg database and its 23.05, 24.10 and 25.12 fixes. - Source trees: apk package lists in ARG and ENV (edited where the value is written), unresolved variables as notes, Ansible apk tasks (fix: state: latest), Buildroot, OpenWrt and Yocto configurations that build OpenSSH on musl, and an end-of-life alpine:3.N base moved to 3.16 as a labelled upgrade. - parity/sshole.py: ten images, all matching. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + README.md | 4 +- detectors/sshole/internal/assess/assess.go | 105 +++++- .../sshole/internal/assess/assess_test.go | 2 + detectors/sshole/internal/assess/config.go | 6 + detectors/sshole/internal/assess/fuzz_test.go | 10 + detectors/sshole/internal/assess/opkg.go | 81 +++++ detectors/sshole/internal/assess/runtime.go | 287 ++++++++++++++++ .../sshole/internal/assess/runtime_test.go | 100 ++++++ detectors/sshole/internal/repo/build.go | 92 ++++++ detectors/sshole/internal/repo/more_test.go | 166 ++++++++++ detectors/sshole/internal/repo/plan.go | 9 +- detectors/sshole/internal/repo/repo.go | 310 +++++++++++++++++- detectors/sshole/sshole.go | 46 ++- internal/engine/engine.go | 3 + internal/engine/run.go | 4 +- internal/image/image.go | 4 + parity/SSHOLE-RESULTS.md | 4 +- parity/sshole.py | 2 +- parity/sshole/cmdline.Dockerfile | 4 + parity/sshole/expected.json | 123 ++++++- parity/sshole/startup.Dockerfile | 8 + 22 files changed, 1333 insertions(+), 38 deletions(-) create mode 100644 detectors/sshole/internal/assess/opkg.go create mode 100644 detectors/sshole/internal/assess/runtime.go create mode 100644 detectors/sshole/internal/assess/runtime_test.go create mode 100644 detectors/sshole/internal/repo/build.go create mode 100644 detectors/sshole/internal/repo/more_test.go create mode 100644 parity/sshole/cmdline.Dockerfile create mode 100644 parity/sshole/startup.Dockerfile diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a318bea..15bcb44 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,6 +31,7 @@ jobs: go test ./detectors/brotli/internal/pins -run '^$' -fuzz '^FuzzPins$' -fuzztime 30s go test ./detectors/sshole/internal/assess -run '^$' -fuzz '^FuzzConfig$' -fuzztime 30s go test ./detectors/sshole/internal/assess -run '^$' -fuzz '^FuzzAccounts$' -fuzztime 30s + go test ./detectors/sshole/internal/assess -run '^$' -fuzz '^FuzzStartup$' -fuzztime 30s go test ./detectors/sshole/internal/repo -run '^$' -fuzz '^FuzzScanText$' -fuzztime 30s for f in FuzzParseDpkgStatus FuzzParseAPKInstalled FuzzParseHeaderBlob FuzzReadBDB FuzzReadNDB FuzzResolver; do go test ./detectors/php2shell/internal/pkgdb -run '^$' -fuzz "^$f\$" -fuzztime 15s diff --git a/README.md b/README.md index c1a0809..c9171fe 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ One engine for DefectDojo's emerging-vulnerability scanners. Each new vulnerabil | `emudhra` | Trust in the eight eMudhra intermediate CA keys compromised in October 2026 ([Mozilla bug 2083449](https://bugzilla.mozilla.org/show_bug.cgi?id=2083449)): trust stores, bundles, keystores and binaries that still trust them, Go binaries without Go's blocklist (CVE-2026-111943), and servers presenting certificates the compromised keys signed | `fs`, `image`, `host` | | `php2shell` | PHP runtimes vulnerable to CVE-2026-109618 and CVE-2026-109619 ("PHP2Shell"), fixed in PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12 ([GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w), [GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp)). A packaged PHP is judged by its vendor's backport data, never by the version it reports. Also checks the images a source tree builds on and deploys, and can rewrite them to fixed images | `fs`, `image`, `repo`, `fix` | | `brotli` | Brotli decoders vulnerable to CVE-2026-111497 ("Node2Shell", "Broccoli2Shell"), Brotli 1.0.3 through 1.2.0, fixed in 1.0.10, 1.1.1 and 1.2.1 ([GHSA-9v8h-qqgm-4m35](https://github.com/advisories/GHSA-9v8h-qqgm-4m35)): system `libbrotlidec` and every copy bundled into other software (Node.js, .NET, Bun, Electron, Envoy and Istio, Python wheels such as Pillow, pyarrow, duckdb, pycurl and PyMuPDF, brotli4j, and more), on Linux, Windows and macOS. A decoder is judged first by the error code the fix added, so vendor backports are recognised without distribution data; a build that strips it by its own version stamp or by its code, which returns that error code only once fixed. In a source tree it finds the Node.js, .NET and Bun releases and the bundling packages a project pins, and `fix` moves each to the fixed release | `fs`, `image`, `repo`, `fix` | -| `sshole` | \*sshole, the OpenSSH password authentication bypass on musl libc fixed in OpenSSH 10.6p2 and in Alpine's openssh packages of November 5, 2026 ([release notes](https://www.openssh.org/releasenotes.html#10.6p2), [writeup](https://sshhole.com)). On musl, sshd from 7.3p1 to 10.6p1 compares an account's password field of `*` with the `*` that crypt returns when it fails, so a crafted password logs in to that account. It judges each installed sshd by its C library, its release and the apk database (Alpine backports keep the release number), then checks what the target's `sshd_config` (Include, Match, PasswordAuthentication, AuthenticationMethods, PermitRootLogin, AllowUsers and the rest) and account files make reachable, and reports the accounts. 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 and anything that sets a password field to `*`, and `fix` adds the fixed release floor and changes `*` to `*NP*` | `fs`, `image`, `host`, `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 `*`. `fix` adds the fixed release floor (in the variable when the list is one), moves an end-of-life `alpine:3.N` base to 3.16 as a labelled upgrade, sets Ansible tasks to `state: latest`, and changes `*` to `*NP*` | `fs`, `image`, `host`, `repo`, `fix` | The detectors ported from standalone scanners also build as standalone binaries under the names people search for: `emudhra-scan` and `php2shell-scan`. They keep their original commands, flags and exit status rules. `brotli` and `sshole` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`). @@ -126,7 +126,7 @@ Every port must give exactly the verdicts of the scanner it came from before it - `parity/parity.py` runs emudhra-scan and Early Light over emudhra-scan's public validation images, directories and live TLS servers ([RESULTS.md](parity/RESULTS.md)). - `parity/brotli.py` has no standalone scanner to compare with, so it checks every decoder in 38 images against the vendor's own fix status: Node.js, .NET, Bun, Envoy and curl images before and after their October 2026 releases, distribution packages pinned to their exact unfixed and backported builds, and the Python wheels ([BROTLI-RESULTS.md](parity/BROTLI-RESULTS.md)). - `parity/brotli_files.py` checks 73 release binaries and packages, unpacked and never run: Node.js, .NET and Bun for Windows and macOS, seven Electron releases, Envoy and Istio, and the packages that bundle the decoder ([BROTLI-FILES-RESULTS.md](parity/BROTLI-FILES-RESULTS.md)). A WebAssembly build of the decoder is the one case it cannot settle: it is reported as unknown. -- `parity/sshole.py` builds eight 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, and Debian) 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/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/php.py` runs php2shell-scan, this repo's php2shell-scan and Early Light over php2shell-scan's validation matrix: official images, distribution packages, source builds and hostile images. Each finding's complete record is compared field by field. It also covers filesystem scans at and below a system root, repository scans, `fix --dry-run`, and every detector at once ([PHP-RESULTS.md](parity/PHP-RESULTS.md)). ## Adding a detector diff --git a/detectors/sshole/internal/assess/assess.go b/detectors/sshole/internal/assess/assess.go index cab4fdb..b7d53b5 100644 --- a/detectors/sshole/internal/assess/assess.go +++ b/detectors/sshole/internal/assess/assess.go @@ -13,6 +13,7 @@ package assess import ( "fmt" + "path" "sort" "strings" "time" @@ -67,6 +68,11 @@ type Finding struct { Password string `json:"password_auth,omitempty"` Donor *Donor `json:"donor,omitempty"` Targets []Target `json:"targets,omitempty"` + // StartedWith names where sshd -o options came from (the container + // command or a startup script). + StartedWith string `json:"started_with,omitempty"` + // AtStart lists startup scripts that change accounts or sshd_config. + AtStart []string `json:"at_start,omitempty"` // Missing lists the conditions that do not hold today. Missing []string `json:"missing,omitempty"` } @@ -85,7 +91,9 @@ type Input struct { // Image is true for container images, whose accounts and configuration // an entrypoint can still change. Image bool - Now time.Time + // Startup is the image's command and startup scripts, for images. + Startup Startup + Now time.Time } // Run assesses every OpenSSH server in the input. @@ -162,7 +170,11 @@ func assessUnit(in Input, u []*Binary) (Finding, bool) { if p, ok := in.Owners[b.Path]; ok && strings.HasPrefix(p.Name, "openssh") { pp := p f.Package = &pp - if fx, w, ok := apkStatus(p.Version); ok { + judge := apkStatus + if p.Format == "opkg" { + judge = opkgStatus + } + if fx, w, ok := judge(p.Version); ok { fixed, why = fx, w } break @@ -196,12 +208,29 @@ func assessUnit(in Input, u []*Binary) (Finding, bool) { if cfgPath == "" { cfgPath = "/etc/ssh/sshd_config" } + scripts := in.Startup.startScripts(in.Resolve) + inv, invoked := pickInvocation(invocations(in.Startup, scripts), u) + if invoked && inv.config != "" { + cfgPath = inv.config + } f.Config = cfgPath cfg := ParseConfig(in.Files, cfgPath) + if invoked && len(inv.opts) > 0 { + cfg.Prepend(inv.opts) + f.StartedWith = inv.where + } if !cfg.Read { f.Status, f.Severity = Vulnerable, "medium" f.Missing = append(f.Missing, cfgPath+" is not in the target, so the password settings are unknown") f.Message = fmt.Sprintf("OpenSSH %s server on musl without the *sshole fix (%s not found)", main.Release, cfgPath) + for _, sc := range scripts { + if strings.Contains(sc.text, "sshd_config") { + f.AtStart = append(f.AtStart, sc.where) + } + } + if len(f.AtStart) > 0 { + f.Message += fmt.Sprintf("; its startup script (%s) writes sshd_config when the container starts", strings.Join(f.AtStart, ", ")) + } f.Reason = why return f, true } @@ -286,9 +315,78 @@ func assessUnit(in Input, u []*Binary) (Finding, bool) { } f.Status, f.Severity = Vulnerable, "medium" f.Message = fmt.Sprintf("OpenSSH %s server on musl without the *sshole fix; not exploitable as configured: %s", main.Release, strings.Join(missing, "; ")) + if sig := startupSignals(scripts); sig.any() { + if t, ok := atStart(in, cfg, donor, sig); ok { + f.Kind, f.Severity = KindExposed, "high" + f.Targets = t + f.AtStart = sig.where + f.Message = fmt.Sprintf("OpenSSH %s server on musl without the *sshole fix is not exposed as the image ships, but its startup script (%s) %s when the container starts, after which a crafted password logs in to %s", + main.Release, strings.Join(sig.where, ", "), sig.describe(), targetNames(t)) + return f, true + } + f.AtStart = sig.where + f.Message += fmt.Sprintf("; its startup script (%s) %s when the container starts, which this scan judges only as far as the image shows", strings.Join(sig.where, ", "), sig.describe()) + } return f, true } +func targetNames(ts []Target) string { + var n []string + for _, t := range ts { + n = append(n, t.Account) + } + return strings.Join(n, ", ") +} + +// pickInvocation finds the command line that starts this server. +func pickInvocation(invs []invocation, u []*Binary) (invocation, bool) { + for _, inv := range invs { + for _, b := range u { + if inv.binary == b.Path || path.Base(inv.binary) == path.Base(b.Path) { + return inv, true + } + } + } + return invocation{}, false +} + +// atStart applies what the startup scripts do (turn password logins on, +// set a password field to "*", set passwords with chpasswd) and returns the +// accounts a crafted password would then reach. +func atStart(in Input, cfg Config, donor Donor, sig signals) ([]Target, bool) { + fails := donor.Fails + if donor.Account == "" && sig.passwords { + fails = "long" // chpasswd writes a sha512 hash, the first one pick_salt sees + } + if fails == "none" || sig.usePAMOn { + return nil, false + } + c := cfg + if sig.passwordOn { + c.Prepend([]Directive{{Key: "passwordauthentication", Args: []string{"yes"}, File: "startup"}}) + } + var out []Target + for _, acc := range in.Accounts.List { + if acc.Field != "*" { + continue + } + if t, _ := reach(in, c, acc); t.Reach != "no" { + t.Reach = "maybe" + out = append(out, t) + } + } + if sig.starSet { + // An account the script creates or changes: an ordinary user with + // a shell. + acc := Account{Name: "(an account the startup script sets to \"*\")", UID: 1000, GID: 1000, Shell: "/bin/sh", Field: "*", Expire: -1} + if t, _ := reach(in, c, acc); t.Reach != "no" { + t.Reach = "maybe" + out = append(out, t) + } + } + return out, len(out) > 0 +} + func hashType(setting string) string { switch { case strings.HasPrefix(setting, "$6$"): @@ -521,6 +619,9 @@ func fixText(in Input, f Finding) string { return fmt.Sprintf("Upgrade %s (apk upgrade --no-cache %s); if this Alpine release has no fixed package, move to a supported Alpine branch. Fixed: %s. %s", name, name, alpineFixedSummary(), mitigate) } + if f.Package != nil && f.Package.Format == "opkg" { + return fmt.Sprintf("Upgrade %s from the OpenWrt packages feed (opkg update && opkg upgrade %s): 23.05 9.8p1-2, 24.10 9.9_p2-2 and 25.12 10.6_p2-1 have the fix; 22.03 and older have none. Restart sshd. %s", f.Package.Name, f.Package.Name, mitigate) + } return "Update OpenSSH to 10.6p2 or later, or rebuild with upstream commit 4353fdc43 (\"avoid password authn bypass\"), and restart sshd. " + mitigate } diff --git a/detectors/sshole/internal/assess/assess_test.go b/detectors/sshole/internal/assess/assess_test.go index 9172911..02b2109 100644 --- a/detectors/sshole/internal/assess/assess_test.go +++ b/detectors/sshole/internal/assess/assess_test.go @@ -195,6 +195,8 @@ func newWorld(release string, pam bool, extra map[string]string) *world { return w } +func (w *world) now() time.Time { return time.Unix(20800*86400, 0) } + func (w *world) run() []Finding { return Run(Input{ Binaries: w.binaries, diff --git a/detectors/sshole/internal/assess/config.go b/detectors/sshole/internal/assess/config.go index 11c0261..368290f 100644 --- a/detectors/sshole/internal/assess/config.go +++ b/detectors/sshole/internal/assess/config.go @@ -376,6 +376,12 @@ func (c Config) Lists(key string, acc Account, groups []string) [][]string { return append(out, global) } +// Prepend puts directives before the file's own, as global ones: sshd -o +// options, which sshd reads before its config file, so they win. +func (c *Config) Prepend(ds []Directive) { + c.Directives = append(append([]Directive(nil), ds...), c.Directives...) +} + // Global returns a global-only keyword's value (UsePAM), or def. func (c Config) Global(key, def string) string { for _, d := range c.Directives { diff --git a/detectors/sshole/internal/assess/fuzz_test.go b/detectors/sshole/internal/assess/fuzz_test.go index 2698402..cf24e17 100644 --- a/detectors/sshole/internal/assess/fuzz_test.go +++ b/detectors/sshole/internal/assess/fuzz_test.go @@ -33,3 +33,13 @@ func FuzzConfig(f *testing.F) { passwordValues(c, acc, nil) }) } + +func FuzzStartup(f *testing.F) { + f.Add("/bin/sh", "-c", "#!/bin/sh\nusermod -p '*' x; exec /usr/sbin/sshd -D -o PasswordAuthentication=yes -f /x") + f.Fuzz(func(t *testing.T, a, b, script string) { + st := Startup{Command: []string{a, b, script}, Scripts: map[string][]byte{"/entrypoint.sh": []byte(script), "/etc/cont-init.d/x": []byte(script)}} + sc := st.startScripts(nil) + invocations(st, sc) + startupSignals(sc).describe() + }) +} diff --git a/detectors/sshole/internal/assess/opkg.go b/detectors/sshole/internal/assess/opkg.go new file mode 100644 index 0000000..3d4e5ec --- /dev/null +++ b/detectors/sshole/internal/assess/opkg.go @@ -0,0 +1,81 @@ +package assess + +import ( + "path" + "strconv" + "strings" +) + +// OpkgOwners parses OpenWrt's opkg database: the status file and the +// per-package file lists (/usr/lib/opkg/info/NAME.list), into a map from +// file path to package. +func OpkgOwners(status []byte, lists map[string][]byte) map[string]Package { + versions := map[string]string{} + for _, rec := range strings.Split(strings.ReplaceAll(string(status), "\r\n", "\n"), "\n\n") { + name, ver, installed := "", "", false + for _, l := range strings.Split(rec, "\n") { + k, v, ok := strings.Cut(l, ": ") + if !ok { + continue + } + switch k { + case "Package": + name = v + case "Version": + ver = v + case "Status": + installed = strings.Contains(v, "installed") && !strings.Contains(v, "not-installed") + } + } + if name != "" && ver != "" && installed { + versions[name] = ver + } + } + out := map[string]Package{} + for name, list := range lists { + v, ok := versions[name] + if !ok { + continue + } + for _, f := range strings.Split(string(list), "\n") { + if f = strings.TrimSpace(f); strings.HasPrefix(f, "/") { + out[path.Clean(f)] = Package{Name: name, Version: v, Format: "opkg"} + } + } + } + return out +} + +// openwrtFixed is the release of each OpenWrt openssh version that carries +// the fix: openwrt/packages "backport security mitigation from 10.6p2" +// (23.05, 24.10) and the 10.6_p2 update (master, 25.12), all 2026-11-05. +// 22.03 and older were not patched. +var openwrtFixed = map[string]int{"9.8p1": 2, "9.9_p2": 2} + +// opkgStatus judges an OpenWrt openssh package version ("9.9_p2-2"). +func opkgStatus(version string) (fixed bool, why string, ok bool) { + i := strings.LastIndexByte(version, '-') + if i < 0 { + return false, "", false + } + pkgver, relStr := version[:i], version[i+1:] + rel, err := strconv.Atoi(relStr) + if err != nil { + return false, "", false + } + up, ok := ParseRelease(strings.Replace(pkgver, "_p", "p", 1)) + if !ok { + return false, "", false + } + if !up.Less(FixedRelease) { + return true, "OpenWrt package " + version + " is OpenSSH " + up.String() + " or later, which has the fix", true + } + f, known := openwrtFixed[pkgver] + switch { + case !known: + return false, "OpenWrt published no fix for openssh " + pkgver + " (fixed: 23.05 9.8p1-2, 24.10 9.9_p2-2, 25.12 10.6_p2-1)", true + case rel >= f: + return true, "OpenWrt package " + version + " carries the backported fix", true + } + return false, "OpenWrt package " + version + " is older than the fixed " + pkgver + "-" + strconv.Itoa(f), true +} diff --git a/detectors/sshole/internal/assess/runtime.go b/detectors/sshole/internal/assess/runtime.go new file mode 100644 index 0000000..06822af --- /dev/null +++ b/detectors/sshole/internal/assess/runtime.go @@ -0,0 +1,287 @@ +package assess + +import ( + "path" + "regexp" + "sort" + "strings" +) + +// Startup is what a container does when it starts: the command its image +// runs and the startup scripts in it. +type Startup struct { + // Command is the image's Entrypoint followed by its Cmd. + Command []string + // Scripts are the image's shell scripts ("#!" files), by path. + Scripts map[string][]byte +} + +// initDirs hold scripts an init system runs at start whatever the command +// (s6-overlay, linuxserver's cont-init, baseimage-docker, entrypoint.d). +var initDirs = []string{"/etc/cont-init.d/", "/etc/s6-overlay/", "/custom-cont-init.d/", "/docker-entrypoint.d/", + "/etc/services.d/", "/etc/my_init.d/", "/etc/runit/", "/entrypoint.d/", "/docker-entrypoint-init.d/", "/etc/entrypoint.d/", "/etc/s6/"} + +// pathDirs is where a command named without a path is looked up. +var pathDirs = []string{"/usr/local/sbin/", "/usr/local/bin/", "/usr/sbin/", "/usr/bin/", "/sbin/", "/bin/"} + +// startScripts returns the scripts that run at start, in a stable order: +// the command's own script (or its sh -c text), one level of scripts it +// names, and the init directories. +func (s Startup) startScripts(resolve func(string) (string, bool)) []script { + var out []script + seen := map[string]bool{} + add := func(p string) { + if seen[p] { + return + } + r := p + if resolve != nil { + if rp, ok := resolve(p); ok { + r = rp + } + } + if !strings.HasPrefix(r, "/") { + for _, d := range pathDirs { + if _, ok := s.Scripts[d+r]; ok { + r = d + r + break + } + } + } + if b, ok := s.Scripts[r]; ok { + seen[p], seen[r] = true, true + out = append(out, script{where: p, text: string(b)}) + } + } + if len(s.Command) > 0 { + c := s.Command + for len(c) > 1 && isWrapper(path.Base(c[0])) { + c = c[1:] + } + if isShell(path.Base(c[0])) { + for i := 1; i < len(c); i++ { + if c[i] == "-c" && i+1 < len(c) { + out = append(out, script{where: "the container command", text: c[i+1]}) + break + } + if strings.HasPrefix(c[i], "/") { + add(c[i]) + break + } + } + } else { + add(c[0]) + } + // One level of scripts the command's scripts name. + for _, sc := range append([]script(nil), out...) { + for _, m := range absPathRE.FindAllString(sc.text, -1) { + add(m) + } + } + } + var dirs []string + for p := range s.Scripts { + for _, d := range initDirs { + if strings.HasPrefix(p, d) { + dirs = append(dirs, p) + } + } + } + sort.Strings(dirs) + for _, p := range dirs { + add(p) + } + return out +} + +type script struct{ where, text string } + +var absPathRE = regexp.MustCompile(`/[A-Za-z0-9_./-]+`) + +func isWrapper(b string) bool { + switch b { + case "tini", "dumb-init", "su-exec", "gosu", "env", "exec", "catatonit", "s6-svscan": + return true + } + return false +} + +func isShell(b string) bool { + switch b { + case "sh", "bash", "ash", "dash", "busybox": + return true + } + return false +} + +// invocation is an sshd command line: the binary, -f and -o. +type invocation struct { + binary string + config string + opts []Directive + where string +} + +// invocations finds sshd command lines in the container command and the +// startup scripts. +func invocations(s Startup, scripts []script) []invocation { + var out []invocation + if inv, ok := parseSSHD(s.Command, "the container command"); ok { + out = append(out, inv) + } + for _, sc := range scripts { + for _, line := range strings.Split(sc.text, "\n") { + for _, part := range splitCommands(line) { + if inv, ok := parseSSHD(fieldsQuoted(part), sc.where); ok { + out = append(out, inv) + } + } + } + } + return out +} + +func splitCommands(line string) []string { + if i := strings.Index(line, "#"); i == 0 || i > 0 && (line[i-1] == ' ' || line[i-1] == '\t') { + line = line[:i] + } + return regexp.MustCompile(`&&|\|\||;|\|`).Split(line, -1) +} + +// fieldsQuoted splits on spaces, keeping quoted words whole and unquoted. +func fieldsQuoted(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 == ' ' || c == '\t' || 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 +} + +// sshd options that take a value, besides -f and -o. +var sshdValueFlags = "CEbcghkpu" // sshd.c getopt "C:E:b:c:f:g:h:k:o:p:u:..." + +func parseSSHD(argv []string, where string) (invocation, bool) { + i := 0 + for i < len(argv) { + b := path.Base(argv[i]) + if b == "sshd" || strings.HasPrefix(b, "sshd.") { + break + } + i++ + } + if i >= len(argv) { + return invocation{}, false + } + inv := invocation{binary: argv[i], where: where} + for j := i + 1; j < len(argv); j++ { + a := argv[j] + if len(a) < 2 || a[0] != '-' { + continue + } + flag := a[1] + val := a[2:] + if val == "" && (flag == 'f' || flag == 'o' || strings.IndexByte(sshdValueFlags, flag) >= 0) && j+1 < len(argv) { + j++ + val = argv[j] + } + switch flag { + case 'f': + inv.config = val + case 'o': + if args := splitArgs(val); len(args) >= 2 { + inv.opts = append(inv.opts, Directive{Key: strings.ToLower(args[0]), Args: args[1:], File: where}) + } + } + } + return inv, true +} + +// Startup signals: what the startup scripts do to sshd's settings and the +// accounts before sshd runs. +var ( + pwOnRE = regexp.MustCompile(`(?i)PasswordAuthentication\s*[= ]\s*["']?yes`) + usePAMOnRE = regexp.MustCompile(`(?i)UsePAM\s*[= ]\s*["']?yes`) + starSetRE = []*regexp.Regexp{ + regexp.MustCompile(`(?:usermod|useradd)\b[^\n]*(?:-p|--password)[ =]\s*(?:'\*'|"\*"|\\\*|\*)(?:\s|$)`), + regexp.MustCompile(`[A-Za-z0-9_$.{}-]+:\*['"]?\s*\|\s*chpasswd\s+(?:-e|--encrypted)`), + regexp.MustCompile(`sed\b[^\n]*:\\?\*[:/][^\n]*/etc/shadow`), + regexp.MustCompile(`[A-Za-z0-9_$.{}-]+:\*:[^\n]*>>?\s*/etc/shadow`), + } + chpasswdRE = regexp.MustCompile(`\bchpasswd\b`) +) + +type signals struct { + passwordOn, starSet, passwords, usePAMOn bool + where []string +} + +func (g signals) describe() string { + var d []string + if g.passwordOn { + d = append(d, "turns PasswordAuthentication on") + } + if g.starSet { + d = append(d, "sets a password field to \"*\"") + } + if g.passwords { + d = append(d, "sets passwords with chpasswd") + } + if g.usePAMOn { + d = append(d, "turns UsePAM on") + } + return strings.Join(d, ", ") +} + +func (g signals) any() bool { return g.passwordOn || g.starSet || g.passwords || g.usePAMOn } + +func startupSignals(scripts []script) signals { + var g signals + for _, sc := range scripts { + hit := false + if pwOnRE.MatchString(sc.text) { + g.passwordOn, hit = true, true + } + if usePAMOnRE.MatchString(sc.text) { + g.usePAMOn, hit = true, true + } + for _, re := range starSetRE { + if re.MatchString(sc.text) { + g.starSet, hit = true, true + } + } + for _, line := range strings.Split(sc.text, "\n") { + if chpasswdRE.MatchString(line) && !strings.Contains(line, "-e") && !strings.Contains(line, "--encrypted") { + g.passwords, hit = true, true // busybox and shadow chpasswd write sha512 hashes by default + } + } + if hit { + g.where = append(g.where, sc.where) + } + } + return g +} diff --git a/detectors/sshole/internal/assess/runtime_test.go b/detectors/sshole/internal/assess/runtime_test.go new file mode 100644 index 0000000..8858254 --- /dev/null +++ b/detectors/sshole/internal/assess/runtime_test.go @@ -0,0 +1,100 @@ +package assess + +import ( + "strings" + "testing" +) + +func runStartup(w *world, st Startup) []Finding { + return Run(Input{ + Binaries: w.binaries, Owners: w.owners, Files: w.files, + Accounts: ParseAccounts(w.files.Read("/etc/passwd"), w.files.Read("/etc/shadow"), w.files.Read("/etc/group"), nil), + Resolve: func(p string) (string, bool) { + _, ok := w.files[p] + return p, ok + }, + Image: true, Startup: st, Now: w.now(), + }) +} + +func TestStartupCommand(t *testing.T) { + // The config turns passwords off, the command turns them back on. + w := newWorld("10.0p2", false, map[string]string{"/etc/ssh/sshd_config.d/00.conf": "PasswordAuthentication no\n"}) + f := one(t, runStartup(w, Startup{Command: []string{"/usr/sbin/sshd", "-D", "-e", "-o", "PasswordAuthentication=yes"}})) + if f.Kind != KindExposed || f.StartedWith != "the container command" { + t.Fatalf("%+v", f) + } + // -f points at another config. + w = newWorld("10.0p2", false, map[string]string{"/srv/sshd.conf": "PasswordAuthentication no\n"}) + f = one(t, runStartup(w, Startup{Command: []string{"tini", "--", "/usr/sbin/sshd", "-D", "-f", "/srv/sshd.conf"}})) + if f.Kind != KindServer || f.Config != "/srv/sshd.conf" { + t.Fatalf("%+v", f) + } + // sh -c text. + w = newWorld("10.0p2", false, map[string]string{"/etc/ssh/sshd_config.d/00.conf": "PasswordAuthentication no\n"}) + f = one(t, runStartup(w, Startup{Command: []string{"/bin/sh", "-c", "ssh-keygen -A && exec /usr/sbin/sshd -D -oPasswordAuthentication=yes"}})) + if f.Kind != KindExposed { + t.Fatalf("%+v", f) + } +} + +func TestStartupScripts(t *testing.T) { + quiet := map[string]string{"/etc/shadow": strings.Replace(stdShadow, "bob:*", "bob:!", 1), "/etc/ssh/sshd_config.d/00.conf": "PasswordAuthentication no\n"} + cases := []struct { + name string + script string + kind string + atStart bool + }{ + {"turns on passwords and sets a star", "#!/bin/sh\nsed -i 's/^#*PasswordAuthentication.*/PasswordAuthentication yes/' /etc/ssh/sshd_config\nusermod -p '*' \"$USER\"\nexec /usr/sbin/sshd -D\n", KindExposed, true}, + {"star but passwords stay off", "#!/bin/sh\necho \"$USER:*\" | chpasswd -e\nexec /usr/sbin/sshd -D\n", KindServer, true}, + {"nothing relevant", "#!/bin/sh\nssh-keygen -A\nexec /usr/sbin/sshd -D\n", KindServer, false}, + {"UsePAM on", "#!/bin/sh\necho 'PasswordAuthentication yes' >> /etc/ssh/sshd_config\necho 'UsePAM yes' >> /etc/ssh/sshd_config\nusermod -p '*' x\n", KindServer, true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + w := newWorld("10.0p2", false, quiet) + f := one(t, runStartup(w, Startup{Command: []string{"/entrypoint.sh"}, Scripts: map[string][]byte{"/entrypoint.sh": []byte(c.script)}})) + if f.Kind != c.kind || (len(f.AtStart) > 0) != c.atStart { + t.Fatalf("%s %+v: %s", f.Kind, f.AtStart, f.Message) + } + if f.Kind == KindExposed && (f.Severity != "high" || !strings.Contains(f.Message, "/entrypoint.sh")) { + t.Errorf("%+v", f) + } + }) + } +} + +func TestStartupDonorFromChpasswd(t *testing.T) { + // No $-hash in the image; the script sets a password with chpasswd + // (sha512), turns passwords on and has a "*" account. + w := newWorld("10.0p2", false, map[string]string{"/etc/shadow": strings.Replace(stdShadow, sha512Alice, "!", 1)}) + script := "#!/bin/sh\necho \"admin:$ADMIN_PASSWORD\" | chpasswd\nexec /usr/sbin/sshd -D\n" + f := one(t, runStartup(w, Startup{Command: []string{"entrypoint"}, Scripts: map[string][]byte{"/usr/local/bin/entrypoint": []byte(script)}})) + if f.Kind != KindExposed || !strings.Contains(f.Message, "sets passwords with chpasswd") { + t.Fatalf("%+v", f) + } +} + +func TestInitDirs(t *testing.T) { + w := newWorld("10.0p2", false, map[string]string{"/etc/ssh/sshd_config.d/00.conf": "PasswordAuthentication no\n"}) + f := one(t, runStartup(w, Startup{Command: []string{"/init"}, Scripts: map[string][]byte{ + "/etc/s6-overlay/s6-rc.d/init-ssh/run": []byte("#!/bin/sh\nif [ \"$PASSWORD_ACCESS\" = true ]; then sed -i '/PasswordAuthentication/c\\\\PasswordAuthentication yes' /etc/ssh/sshd_config; fi\n"), + }})) + if f.Kind != KindExposed || f.AtStart[0] != "/etc/s6-overlay/s6-rc.d/init-ssh/run" { + t.Fatalf("%+v", f) + } +} + +func TestOpkg(t *testing.T) { + status := []byte("Package: openssh-server\nVersion: 9.9_p2-1\nStatus: install user installed\n\nPackage: zlib\nVersion: 1.3-1\nStatus: install user installed\n") + owners := OpkgOwners(status, map[string][]byte{"openssh-server": []byte("/usr/sbin/sshd\n/etc/ssh/sshd_config\n")}) + if p := owners["/usr/sbin/sshd"]; p.Name != "openssh-server" || p.Format != "opkg" { + t.Fatalf("%+v", owners) + } + for v, want := range map[string]bool{"9.9_p2-1": false, "9.9_p2-2": true, "9.8p1-2": true, "9.8p1-1": false, "10.6_p2-1": true, "9.2p1-3": false} { + if fixed, _, ok := opkgStatus(v); !ok || fixed != want { + t.Errorf("%s: %v %v", v, fixed, ok) + } + } +} diff --git a/detectors/sshole/internal/repo/build.go b/detectors/sshole/internal/repo/build.go new file mode 100644 index 0000000..1e179c5 --- /dev/null +++ b/detectors/sshole/internal/repo/build.go @@ -0,0 +1,92 @@ +package repo + +import ( + "fmt" + "regexp" + "strings" +) + +// Build systems that make musl firmware: Buildroot and OpenWrt +// configurations name the package and the C library in one file; Yocto's +// TCLIBC and image contents are joined across the tree in finishBuild. + +var ( + brOpenSSH = regexp.MustCompile(`(?m)^BR2_PACKAGE_OPENSSH=y`) + brServer = regexp.MustCompile(`(?m)^BR2_PACKAGE_OPENSSH_SERVER=(y|n)|^# BR2_PACKAGE_OPENSSH_SERVER is not set`) + brMusl = regexp.MustCompile(`(?m)^BR2_TOOLCHAIN_(USES_MUSL|BUILDROOT_MUSL|EXTERNAL_[A-Z0-9_]*MUSL[A-Z0-9_]*)=y`) + brLibc = regexp.MustCompile(`(?m)^BR2_TOOLCHAIN_(USES_GLIBC|USES_UCLIBC|BUILDROOT_GLIBC|BUILDROOT_UCLIBC)=y`) + brPAM = regexp.MustCompile(`(?m)^BR2_PACKAGE_LINUX_PAM=y`) + owrtServer = regexp.MustCompile(`(?m)^CONFIG_PACKAGE_(openssh-server(?:-pam)?)=[ym]`) + yoctoMusl = regexp.MustCompile(`(?m)^\s*TCLIBC\s*\??\??=\s*["']musl["']`) + yoctoOpenSSH = regexp.MustCompile(`(?m)^[^#\n]*(IMAGE_INSTALL|IMAGE_FEATURES|EXTRA_IMAGE_FEATURES|CORE_IMAGE_EXTRA_INSTALL|RDEPENDS)[^=\n]*=[^\n]*\b(openssh-sshd|openssh|ssh-server-openssh|packagegroup-core-ssh-openssh)\b`) + yoctoSSHGuard = regexp.MustCompile(`(?m)^[^#\n]*\bssh-server-dropbear\b`) +) + +func lineOf(text string, at int) int { return strings.Count(text[:at], "\n") + 1 } + +func (s *scanner) build(rel, text string) { + switch { + case brOpenSSH.MatchString(text): + loc := brOpenSSH.FindStringIndex(text) + if m := brServer.FindStringSubmatch(text); m != nil && m[1] != "y" { + return // the client only + } + pam := "" + if brPAM.MatchString(text) { + pam = " It is built with PAM; setting UsePAM yes in sshd_config also closes the hole." + } + f := Finding{Rule: RuleBuild, File: rel, Line: lineOf(text, loc[0]), Props: map[string]string{"system": "buildroot"}, + Fix: "Buildroot master moved OpenSSH to 10.6p2 on 2026-11-05; the 2025.02.x to 2026.08.x branches had not when this was written. Move to a Buildroot with it, or add upstream commit 4353fdc43 as a patch under BR2_GLOBAL_PATCH_DIR/openssh/." + pam} + switch { + case brMusl.MatchString(text): + f.Level = "error" + f.Message = "Buildroot configuration builds the OpenSSH server against musl; Buildroot releases before 10.6p2 lack the *sshole fix" + case brLibc.MatchString(text): + return + default: + f.Rule, f.Level = RuleNotChecked, "note" + f.Message = "Buildroot configuration builds the OpenSSH server, but its C library is not set in this file; with musl, Buildroot releases before 10.6p2 lack the *sshole fix" + } + s.addBuild(f) + case owrtServer.MatchString(text): + for _, m := range owrtServer.FindAllStringSubmatchIndex(text, -1) { + pkg := text[m[2]:m[3]] + s.addBuild(Finding{Rule: RuleBuild, File: rel, Line: lineOf(text, m[0]), Level: "error", Props: map[string]string{"system": "openwrt", "package": pkg}, + Message: fmt.Sprintf("OpenWrt configuration builds %s (OpenWrt uses musl); its openssh needs the *sshole fix", pkg), + Fix: "Build from an OpenWrt packages feed with the fix: 23.05 9.8p1-2, 24.10 9.9_p2-2, 25.12 and master 10.6_p2-1 (2026-11-05). 22.03 and older have none: move to a supported release, or add upstream commit 4353fdc43 to net/openssh/patches."}) + } + default: + if m := yoctoMusl.FindStringIndex(text); m != nil { + s.yoctoMusl = append(s.yoctoMusl, Finding{File: rel, Line: lineOf(text, m[0])}) + } + for _, m := range yoctoOpenSSH.FindAllStringIndex(text, -1) { + s.yoctoSSH = append(s.yoctoSSH, Finding{File: rel, Line: lineOf(text, m[0])}) + } + } +} + +// pending build findings, returned by finishBuild. +func (s *scanner) addBuild(f Finding) { s.yoctoSSH = append(s.yoctoSSH, f) } + +// finishBuild returns the build-system findings: Buildroot and OpenWrt as +// found, and Yocto images with OpenSSH where the tree sets TCLIBC to musl. +func (s *scanner) finishBuild() []Finding { + var out []Finding + for _, f := range s.yoctoSSH { + if f.Rule != "" { + out = append(out, f) + continue + } + if len(s.yoctoMusl) == 0 { + continue + } + m := s.yoctoMusl[0] + out = append(out, Finding{Rule: RuleBuild, File: f.File, Line: f.Line, Level: "error", Props: map[string]string{"system": "yocto", "tclibc": fmt.Sprintf("%s:%d", m.File, m.Line)}, + Message: fmt.Sprintf("Yocto image installs the OpenSSH server and %s:%d sets TCLIBC to musl; OpenEmbedded's openssh before 10.6p2 lacks the *sshole fix", m.File, m.Line), + Fix: "OpenEmbedded-Core had OpenSSH 10.6p1 when this was written (2026-11-05). Add upstream commit 4353fdc43 as a patch in an openssh .bbappend (SRC_URI += \"file://avoid-password-authn-bypass.patch\"), or set PasswordAuthentication no."}) + } + s.yoctoSSH, s.yoctoMusl = nil, nil + return out +} + +var _ = yoctoSSHGuard diff --git a/detectors/sshole/internal/repo/more_test.go b/detectors/sshole/internal/repo/more_test.go new file mode 100644 index 0000000..b097274 --- /dev/null +++ b/detectors/sshole/internal/repo/more_test.go @@ -0,0 +1,166 @@ +package repo + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +// fixAll plans and applies every fixable finding, rescanning after each, +// and returns what is left. +func fixAll(t *testing.T, root string) []Finding { + t.Helper() + ctx := context.Background() + for round := 0; round < 5; round++ { + changed := false + for _, f := range scan(t, root, Options{}) { + if !f.Fixable { + continue + } + ch, already, err := Plan(ctx, root, f, Options{}) + if already { + continue + } + if err != nil { + t.Fatalf("%s:%d %s: %v", f.File, f.Line, f.Rule, err) + } + if err := Apply(root, ch); err != nil { + t.Fatal(err) + } + changed = true + break // rescan: line numbers may have moved + } + if !changed { + break + } + } + var left []Finding + for _, f := range scan(t, root, Options{}) { + if f.Level != "note" { + left = append(left, f) + } + } + return left +} + +func read(t *testing.T, root, rel string) string { + t.Helper() + b, err := os.ReadFile(filepath.Join(root, rel)) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func TestVariables(t *testing.T) { + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:3.22\nARG PKGS=\"bash openssh-server curl\"\nENV EXTRA openssh-server-pam\nRUN apk add --no-cache $PKGS ${EXTRA} $UNSET\n") + got := rules(scan(t, root, Options{})) + for _, w := range []string{"apk-unpinned:Dockerfile:4", "not-checked:Dockerfile:4"} { + if got[w] == 0 { + t.Errorf("missing %s in %v", w, got) + } + } + if got["apk-unpinned:Dockerfile:4"] != 2 { + t.Errorf("want both variables judged: %v", got) + } + if left := fixAll(t, root); len(left) != 0 { + t.Fatalf("left %+v", left) + } + s := read(t, root, "Dockerfile") + if !strings.Contains(s, `ARG PKGS="bash openssh-server>=10.0_p1-r11 curl"`) || !strings.Contains(s, "ENV EXTRA openssh-server-pam>=10.0_p1-r11") { + t.Fatalf("%s", s) + } +} + +func TestEOLUpgrade(t *testing.T) { + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:3.14\nRUN apk add --no-cache openssh\n") + write(t, root, "py/Dockerfile", "FROM python:3.9-alpine3.14\nRUN apk add openssh\n") + fs := scan(t, root, Options{}) + var fixable, manual int + for _, f := range fs { + if f.Rule == RuleEOL && f.Fixable { + fixable++ + } else if f.Rule == RuleEOL { + manual++ + } + } + if fixable != 1 || manual != 1 { + t.Fatalf("%+v", fs) + } + left := fixAll(t, root) + if len(left) != 1 || left[0].File != "py/Dockerfile" { + t.Fatalf("left %+v", left) + } + if s := read(t, root, "Dockerfile"); s != "FROM alpine:3.16\nRUN apk add --no-cache 'openssh>=9.0_p1-r6'\n" { + t.Fatalf("%q", s) + } +} + +func TestAnsible(t *testing.T) { + root := t.TempDir() + write(t, root, "roles/ssh/tasks/main.yml", `- name: install sshd + community.general.apk: + name: + - openssh-server + - bash + state: present +- name: inline + apk: name=openssh state=present update_cache=yes +- name: no state + apk: + name: openssh-server +- name: already latest + apk: + name: openssh-server + state: latest +- name: other package + apk: name=bash +`) + got := rules(scan(t, root, Options{})) + for _, w := range []string{"ansible-apk:roles/ssh/tasks/main.yml:2", "ansible-apk:roles/ssh/tasks/main.yml:8", "ansible-apk:roles/ssh/tasks/main.yml:10"} { + if got[w] != 1 { + t.Errorf("missing %s: %v", w, got) + } + } + if len(got) != 3 { + t.Errorf("extra findings: %v", got) + } + if left := fixAll(t, root); len(left) != 0 { + t.Fatalf("left %+v", left) + } + s := read(t, root, "roles/ssh/tasks/main.yml") + for _, want := range []string{" state: latest\n- name: inline", "apk: name=openssh state=latest update_cache=yes", " name: openssh-server\n state: latest\n- name: already"} { + if !strings.Contains(s, want) { + t.Errorf("lacks %q:\n%s", want, s) + } + } +} + +func TestBuildSystems(t *testing.T) { + root := t.TempDir() + write(t, root, "configs/board_defconfig", "BR2_aarch64=y\nBR2_TOOLCHAIN_BUILDROOT_MUSL=y\nBR2_PACKAGE_OPENSSH=y\n") + write(t, root, "glibc/board_defconfig", "BR2_TOOLCHAIN_BUILDROOT_GLIBC=y\nBR2_PACKAGE_OPENSSH=y\n") + write(t, root, "client/board_defconfig", "BR2_TOOLCHAIN_BUILDROOT_MUSL=y\nBR2_PACKAGE_OPENSSH=y\n# BR2_PACKAGE_OPENSSH_SERVER is not set\n") + write(t, root, "unknown/board_defconfig", "BR2_PACKAGE_OPENSSH=y\n") + write(t, root, "openwrt/.config", "CONFIG_TARGET_x86=y\nCONFIG_PACKAGE_openssh-server=y\nCONFIG_PACKAGE_dropbear=n\n") + write(t, root, "meta-x/conf/distro/x.conf", "DISTRO = \"x\"\nTCLIBC = \"musl\"\n") + write(t, root, "meta-x/recipes-core/images/x-image.bb", "IMAGE_INSTALL:append = \" openssh bash\"\n") + got := rules(scan(t, root, Options{})) + for _, w := range []string{"build-config:configs/board_defconfig:3", "not-checked:unknown/board_defconfig:1", "build-config:openwrt/.config:2", "build-config:meta-x/recipes-core/images/x-image.bb:1"} { + if got[w] != 1 { + t.Errorf("missing %s: %v", w, got) + } + } + if len(got) != 4 { + t.Errorf("extra findings: %v", got) + } + // Without a musl TCLIBC, a Yocto image with OpenSSH is glibc: nothing. + os.Remove(filepath.Join(root, "meta-x/conf/distro/x.conf")) + if got := rules(scan(t, root, Options{})); got["build-config:meta-x/recipes-core/images/x-image.bb:1"] != 0 { + t.Errorf("glibc Yocto reported: %v", got) + } +} diff --git a/detectors/sshole/internal/repo/plan.go b/detectors/sshole/internal/repo/plan.go index 92ad88f..97f0983 100644 --- a/detectors/sshole/internal/repo/plan.go +++ b/detectors/sshole/internal/repo/plan.go @@ -91,7 +91,7 @@ func Plan(ctx context.Context, root string, f Finding, opts Options) (*Change, b if err != nil { return nil, false, err } - if count(after, f.Rule, e.Line) >= count(before, f.Rule, e.Line) { + if count(after, f.Rule, f.Line) >= count(before, f.Rule, f.Line) { return nil, false, &Declined{Reason: "the edit did not clear the finding; change it by hand"} } if len(after) > len(before) { @@ -117,6 +117,9 @@ func scanOne(ctx context.Context, root, file string, opts Options, data []byte) return s.yaml(file, string(data)), nil case "sshd_config": return s.sshdConfig(file, string(data)), nil + case "build": + s.build(file, string(data)) + return s.finishBuild(), nil } return nil, nil } @@ -137,6 +140,10 @@ func summary(f Finding) string { return fmt.Sprintf("Require %s at %s or later, the Alpine release with the *sshole fix", f.Props["package"], f.Props["fixed"]) case RuleStar: return "Set the password field to \"*NP*\" instead of \"*\", which keeps key logins and matches no password" + case RuleEOL: + return fmt.Sprintf("Moves the base image to %s, the nearest Alpine release with a fixed OpenSSH package. This is an Alpine release upgrade: review it and run your tests before you merge", f.Props["upgrade"]) + case RuleAnsible: + return "Sets the Ansible apk task to state: latest, so every run installs the fixed OpenSSH package from the host's Alpine repositories" } return f.Fix } diff --git a/detectors/sshole/internal/repo/repo.go b/detectors/sshole/internal/repo/repo.go index a24a99d..7d25c51 100644 --- a/detectors/sshole/internal/repo/repo.go +++ b/detectors/sshole/internal/repo/repo.go @@ -10,6 +10,10 @@ // - star-account: a Dockerfile, script or Ansible task sets an account's // password field to "*", the field the bypass logs in to. // - password-config: something turns PasswordAuthentication on (a note). +// - ansible-apk: an Ansible apk task installs an OpenSSH server with +// state present, so hosts set up before the fix keep it. +// - build-config: a Buildroot, OpenWrt or Yocto configuration builds an +// OpenSSH server on musl. // - not-checked: what could not be read or resolved. package repo @@ -40,6 +44,8 @@ const ( RuleStar = "star-account" RulePassword = "password-config" RuleNotChecked = "not-checked" + RuleAnsible = "ansible-apk" + RuleBuild = "build-config" ) // Finding is one thing in the tree. @@ -170,8 +176,11 @@ func scanList(ctx context.Context, root string, list []string, opts Options, res res.Findings = append(res.Findings, s.yaml(rel, string(b))...) case "sshd_config": res.Findings = append(res.Findings, s.sshdConfig(rel, string(b))...) + case "build": + s.build(rel, string(b)) } } + res.Findings = append(res.Findings, s.finishBuild()...) return res, nil } @@ -198,6 +207,10 @@ func kindOf(rel string) string { return "yaml" case strings.Contains(lower, "sshd_config") || strings.Contains("/"+strings.ToLower(rel), "/sshd_config.d/"): return "sshd_config" + case lower == ".config" || lower == "diffconfig" || strings.HasSuffix(lower, "defconfig") || lower == "local.conf" || lower == "auto.conf" || lower == "site.conf" || + strings.HasSuffix(lower, ".bb") || strings.HasSuffix(lower, ".bbappend") || strings.HasSuffix(lower, ".inc") || + strings.HasSuffix(lower, ".conf") && (strings.Contains(rel, "conf/distro/") || strings.Contains(rel, "conf/machine/")): + return "build" } return "" } @@ -246,6 +259,26 @@ type scanner struct { root string opts Options bases map[string]baseInfo + // vars are the current Dockerfile's ARG and ENV values. + vars map[string]varDef + // from is the current stage's FROM instruction. + from fromInfo + // Yocto evidence, joined across files at the end. + yoctoMusl []Finding + yoctoSSH []Finding +} + +// varDef is an ARG or ENV value and where it is written. +type varDef struct { + value string + line, col int // where value starts; line 0: not on one line +} + +// fromInfo is a FROM instruction: the image and where its tag is written. +type fromInfo struct { + image string + line, col int // where tagText starts on the FROM line, line 0: not editable + tagText string // the image as written on the line } // span is a piece of shell text from a file: Text, and the file line each @@ -363,17 +396,30 @@ var heredocRE = regexp.MustCompile(`<<-?\s*["']?([A-Za-z_][A-Za-z0-9_]*)["']?\s* func (s *scanner) dockerfile(rel, text string) []Finding { var out []Finding args := map[string]string{} + s.vars = map[string]varDef{} + defer func() { s.vars = nil }() stages := map[string]baseInfo{} var cur baseInfo curImage := "" for _, in := range parseDockerfile(text) { switch in.cmd { - case "ARG": - for _, a := range strings.Fields(in.args.text) { + case "ARG", "ENV": + legacy := in.cmd == "ENV" && !strings.Contains(strings.Fields(in.args.text + " x")[0], "=") + if legacy { + // ENV KEY value with spaces + k, v, _ := strings.Cut(strings.TrimSpace(in.args.text), " ") + v = strings.TrimSpace(v) + args[k] = v + s.defineVar(k, v, in) + continue + } + for _, a := range fieldsQuotedKV(in.args.text) { k, v, ok := strings.Cut(a, "=") if ok { - args[k] = strings.Trim(v, `"'`) - } else if _, set := args[k]; !set { + v = strings.Trim(v, `"'`) + args[k] = v + s.defineVar(k, v, in) + } else if _, set := args[k]; !set && in.cmd == "ARG" { args[k] = "" } } @@ -397,6 +443,12 @@ func (s *scanner) dockerfile(rel, text string) []Finding { cur = s.base(img) } curImage = img + s.from = fromInfo{image: img} + if len(in.physical) == 1 && img != "" && len(in.args.cols) > 0 { + if i := strings.Index(in.physical[0], img); i >= 0 && strings.Count(in.physical[0], img) == 1 { + s.from = fromInfo{image: img, line: in.line, col: in.args.cols[0] + i, tagText: img} + } + } if as != "" { stages[strings.ToLower(as)] = cur } @@ -695,24 +747,117 @@ func (s *scanner) apk(rel string, sp span, args []word, b baseInfo, image string continue } if w.dynamic { + out = append(out, s.apkVariable(rel, sp, w, b, image, dockerfile)...) continue } m := specRE.FindStringSubmatch(w.val) if m == nil || !sshPackages[m[1]] { continue } - if f, ok := s.judgeSpec(rel, sp, w, m[1], m[2], m[3], b, image, dockerfile); ok { + l, col, same := sp.at(w) + raw := sp.text[w.start:w.end] + if f, ok := s.judgeSpec(rel, specAt{line: l, editLine: l, col: col, raw: raw, val: w.val, editable: same && !strings.Contains(raw, "\n")}, m[1], m[2], m[3], b, image, dockerfile); ok { out = append(out, f) } } return out } +// apkVariable judges an apk add word that is a variable: an ARG or ENV +// value from this Dockerfile, whose packages are judged and edited where +// the value is written; anything else is reported as not checked when the +// image may be Alpine. +func (s *scanner) apkVariable(rel string, sp span, w word, b baseInfo, image string, dockerfile bool) []Finding { + l, _, _ := sp.at(w) + name := "" + if m := varRE.FindStringSubmatch(w.val); m != nil && m[0] == w.val { + name = m[1] + if name == "" { + name = m[3] + } + } + def, ok := s.vars[name] + if !ok { + if b.known && !b.alpine { + return nil + } + return []Finding{{Rule: RuleNotChecked, File: rel, Line: l, Level: "note", Props: map[string]string{"spec": w.val}, + Message: fmt.Sprintf("installs packages named by %s with apk; their value is not set in this file, so whether they include an OpenSSH server without the *sshole fix is not checked", w.val), + Fix: "If the list includes openssh or openssh-server, require it at the fixed release for the image's Alpine branch (" + fixedTable() + ")"}} + } + var out []Finding + off := 0 + for _, tok := range strings.Fields(def.value) { + at := strings.Index(def.value[off:], tok) + off + off = at + len(tok) + m := specRE.FindStringSubmatch(tok) + if m == nil || !sshPackages[m[1]] { + continue + } + loc := specAt{line: l, editLine: def.line, col: def.col + at, raw: tok, val: tok, editable: def.line > 0, via: name} + if f, ok := s.judgeSpec(rel, loc, m[1], m[2], m[3], b, image, dockerfile); ok { + out = append(out, f) + } + } + return out +} + +// specAt is where an apk package spec was found and where it is written. +type specAt struct { + line, editLine, col int + raw, val string + editable bool + via string // the variable it came through +} + +func (s *scanner) defineVar(k, v string, in instr) { + d := varDef{value: v} + if len(in.physical) == 1 && v != "" && len(in.args.cols) > 0 && strings.Count(in.physical[0], v) == 1 { + d.line, d.col = in.line, in.args.cols[0]+strings.Index(in.physical[0], v) + } + s.vars[k] = d +} + +// fieldsQuotedKV splits ARG and ENV arguments, keeping quoted values whole. +func fieldsQuotedKV(s string) []string { + var out []string + var b strings.Builder + var q byte + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case q != 0: + if c == q { + q = 0 + } + b.WriteByte(c) + case c == '"' || c == '\'': + q = c + b.WriteByte(c) + case c == ' ' || c == '\t' || c == '\n' || c == '\\': + if b.Len() > 0 { + out = append(out, b.String()) + b.Reset() + } + default: + b.WriteByte(c) + } + } + if b.Len() > 0 { + out = append(out, b.String()) + } + return out +} + // judgeSpec decides an apk dependency on an OpenSSH server package. -func (s *scanner) judgeSpec(rel string, sp span, w word, pkg, op, ver string, b baseInfo, image string, dockerfile bool) (Finding, bool) { - l, col, sameLine := sp.at(w) - raw := sp.text[w.start:w.end] - props := map[string]string{"package": pkg, "spec": w.val} +func (s *scanner) judgeSpec(rel string, at specAt, pkg, op, ver string, b baseInfo, image string, dockerfile bool) (Finding, bool) { + l, col := at.line, at.col + raw := at.raw + _ = col + props := map[string]string{"package": pkg, "spec": at.val} + if at.via != "" { + props["variable"] = at.via + } if image != "" { props["image"] = image } @@ -726,7 +871,7 @@ func (s *scanner) judgeSpec(rel string, sp span, w word, pkg, op, ver string, b if b.why != "" { why += " (" + b.why + ")" } - f.Message = fmt.Sprintf("installs %s with apk, but %s, so whether it is Alpine (musl) is not known", w.val, why) + f.Message = fmt.Sprintf("installs %s with apk, but %s, so whether it is Alpine (musl) is not known", at.val, why) f.Fix = "If this image is Alpine, require " + pkg + " at the fixed release for its branch (" + fixedTable() + ")" return f, true } @@ -736,8 +881,16 @@ func (s *scanner) judgeSpec(rel string, sp span, w word, pkg, op, ver string, b fixed, haveFixed := assess.AlpineFixedFor(b.branch) if b.branch != "" && !haveFixed { f.Rule, f.Level = RuleEOL, "error" - f.Message = fmt.Sprintf("installs %s on Alpine %s (%s), which has no OpenSSH package with the *sshole fix", w.val, b.branch, image) + f.Message = fmt.Sprintf("installs %s on Alpine %s (%s), which has no OpenSSH package with the *sshole fix", at.val, b.branch, image) f.Fix = "Move the base image to an Alpine release with a fixed package (" + fixedTable() + "), or set PasswordAuthentication no and change every \"*\" password field to \"*NP*\"" + // The official alpine image, tagged on its FROM line, moves to the + // nearest release with a fixed package, as a labelled upgrade. + if s.from.line > 0 && s.from.image == image && officialAlpine(image) { + up := alpineTagged(image, "3.16") + props["upgrade"] = up + f.Fixable = true + f.edit = &Edit{Line: s.from.line, Col: s.from.col, Old: s.from.tagText, New: up} + } return f, true } ok, decided := satisfiesFix(op, ver, fixed, haveFixed) @@ -747,10 +900,13 @@ func (s *scanner) judgeSpec(rel string, sp span, w word, pkg, op, ver string, b switch { case op == "" || op == "~" || op == ">=" || op == ">": f.Rule, f.Level = RuleUnpinned, "warning" - f.Message = fmt.Sprintf("installs %s with no floor at the fixed release; images built before 2026-11-05, or from a cached layer, keep the vulnerable OpenSSH server", w.val) + f.Message = fmt.Sprintf("installs %s with no floor at the fixed release; images built before 2026-11-05, or from a cached layer, keep the vulnerable OpenSSH server", at.val) default: f.Rule, f.Level = RulePin, "error" - f.Message = fmt.Sprintf("pins %s to a release without the *sshole fix", w.val) + f.Message = fmt.Sprintf("pins %s to a release without the *sshole fix", at.val) + } + if at.via != "" { + f.Message += fmt.Sprintf(" (through $%s, set on line %d)", at.via, at.editLine) } if !haveFixed { f.Fix = "Require " + pkg + " at the fixed release for this image's Alpine branch (" + fixedTable() + ")" @@ -761,11 +917,14 @@ func (s *scanner) judgeSpec(rel string, sp span, w word, pkg, op, ver string, b newSpec = pkg + "=" + fixed } quoted := "'" + newSpec + "'" + if at.via != "" { + quoted = newSpec // inside a variable's value the shell never reads > as a redirection + } f.Fix = fmt.Sprintf("Require %s (Alpine %s), which rebuilds the layer with the fixed package", newSpec, branchName(b.branch)) props["fixed"] = fixed - if sameLine && !strings.Contains(raw, "\n") { + if at.editable { f.Fixable = true - f.edit = &Edit{Line: l, Col: col, Old: raw, New: quoted} + f.edit = &Edit{Line: at.editLine, Col: at.col, Old: raw, New: quoted} } return f, true } @@ -861,7 +1020,7 @@ var yamlStar = regexp.MustCompile(`^(\s*-?\s*(?:password|passwd)\s*:\s*)(["']?)\ var yamlStarInline = regexp.MustCompile(`\bpassword=(["']?)\*(["']?)(\s|$)`) func (s *scanner) yaml(rel, text string) []Finding { - var out []Finding + out := s.ansible(rel, strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n")) for i, l := range strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") { if m := yamlStar.FindStringSubmatchIndex(l); m != nil { old := l[m[2]:] @@ -939,3 +1098,122 @@ func AlpineOf(open func() (io.ReadCloser, error)) (bool, string, error) { } return false, "", nil } + +// officialAlpine reports the official alpine image (alpine, library/alpine, +// docker.io/library/alpine) with a tag. +func officialAlpine(img string) bool { + name := img + if i := strings.Index(name, "@"); i >= 0 { + return false // a digest pin: change it by hand + } + i := strings.LastIndexByte(name, ':') + if i < 0 { + return false + } + name = strings.TrimPrefix(strings.TrimPrefix(name[:i], "docker.io/"), "library/") + return name == "alpine" +} + +func alpineTagged(img, tag string) string { + return img[:strings.LastIndexByte(img, ':')+1] + tag +} + +// Ansible apk tasks: `apk: name=... state=present`, or a mapping with +// name and state. state: latest upgrades on every run. +var ( + ansibleModule = regexp.MustCompile(`^(\s*)(?:-\s+)?(?:community\.general\.)?apk:\s*(.*)$`) + ansibleKey = regexp.MustCompile(`^(\s*)(name|state|pkg|package):\s*(.*)$`) + ansibleItem = regexp.MustCompile(`^\s*-\s+["']?([A-Za-z0-9._+-]+)`) +) + +func (s *scanner) ansible(rel string, lines []string) []Finding { + var out []Finding + for i := 0; i < len(lines); i++ { + m := ansibleModule.FindStringSubmatch(lines[i]) + if m == nil { + continue + } + indent := len(m[1]) + var names []string + state, stateLine, stateCol := "", 0, 0 + nameLine := 0 + if inline := strings.TrimSpace(m[2]); inline != "" && strings.Contains(inline, "=") { + for _, kv := range strings.Fields(inline) { + k, v, _ := strings.Cut(kv, "=") + switch k { + case "name", "pkg": + names = append(names, strings.Split(strings.Trim(v, `"'`), ",")...) + case "state": + state = strings.Trim(v, `"'`) + stateLine, stateCol = i+1, strings.Index(lines[i], kv) + } + } + nameLine = i + 1 + } else { + for j := i + 1; j < len(lines); j++ { + l := lines[j] + if strings.TrimSpace(l) == "" { + continue + } + if len(l)-len(strings.TrimLeft(l, " ")) <= indent { + break + } + km := ansibleKey.FindStringSubmatch(l) + if km == nil { + continue + } + switch km[2] { + case "name", "pkg", "package": + nameLine = j + 1 + v := strings.Trim(strings.TrimSpace(km[3]), "[]") + for _, n := range strings.Split(v, ",") { + if n = strings.Trim(strings.TrimSpace(n), `"'`); n != "" { + names = append(names, n) + } + } + for k := j + 1; k < len(lines); k++ { + im := ansibleItem.FindStringSubmatch(lines[k]) + if im == nil || len(lines[k])-len(strings.TrimLeft(lines[k], " ")) <= len(km[1]) && !strings.HasPrefix(strings.TrimSpace(lines[k]), "-") { + break + } + names = append(names, im[1]) + } + case "state": + state = strings.Trim(strings.TrimSpace(km[3]), `"'`) + stateLine, stateCol = j+1, len(km[1]) + } + } + } + pkgs := []string{} + for _, n := range names { + if sm := specRE.FindStringSubmatch(n); sm != nil && sshPackages[sm[1]] { + pkgs = append(pkgs, n) + } + } + if len(pkgs) == 0 || state == "latest" || state == "absent" || state == "removed" { + continue + } + f := Finding{Rule: RuleAnsible, File: rel, Line: i + 1, Level: "warning", Props: map[string]string{"package": strings.Join(pkgs, ",")}, + Message: fmt.Sprintf("Ansible apk task installs %s without state: latest; hosts set up before 2026-11-05 keep an OpenSSH server without the *sshole fix", strings.Join(pkgs, ", ")), + Fix: "Set state: latest on the task (or run apk upgrade on the hosts), so each run installs the fixed package from the host's Alpine repositories"} + switch { + case stateLine > 0 && strings.Contains(lines[stateLine-1], "state=") && state != "": + old := "state=" + state + if c := strings.Index(lines[stateLine-1], old); c >= 0 { + f.Fixable, f.edit = true, &Edit{Line: stateLine, Col: c, Old: old, New: "state=latest"} + } + case stateLine > 0: + l := strings.TrimRight(lines[stateLine-1], "\r") + f.Fixable, f.edit = true, &Edit{Line: stateLine, Col: stateCol, Old: l[stateCol:], New: "state: latest"} + case nameLine > 0 && strings.Contains(lines[nameLine-1], "name=") || nameLine == i+1 && strings.Contains(m[2], "="): + l := strings.TrimRight(lines[i], "\r") + f.Fixable, f.edit = true, &Edit{Line: i + 1, Col: len(l), Old: "", New: " state=latest"} + case nameLine > 0: + l := strings.TrimRight(lines[nameLine-1], "\r") + ind := l[:len(l)-len(strings.TrimLeft(l, " "))] + f.Fixable, f.edit = true, &Edit{Line: nameLine, Col: len(l), Old: "", New: "\n" + ind + "state: latest"} + } + out = append(out, f) + } + return out +} diff --git a/detectors/sshole/sshole.go b/detectors/sshole/sshole.go index 07b0e5e..d91286e 100644 --- a/detectors/sshole/sshole.go +++ b/detectors/sshole/sshole.go @@ -80,16 +80,28 @@ func (d *Detector) Load() error { return nil } // Wants reads executables (possible sshd binaries) and the few files the // verdict depends on. func (d *Detector) Wants(p string, head []byte, _ bool) bool { - return archive.IsExecutable(head) || keep(p) + return archive.IsExecutable(head) || keep(p) || isScript(head) } +// isScript reports a "#!" script: a container's entrypoint or startup step. +func isScript(head []byte) bool { return len(head) > 2 && head[0] == '#' && head[1] == '!' } + +// Limits on the startup scripts kept per target. +const ( + maxScript = 256 << 10 + maxScripts = 64 << 20 +) + // keep reports whether a file's content feeds a verdict: account files, // the apk database, the Alpine release and anything that can be an // sshd_config or a file one includes. func keep(p string) bool { switch p { case "/etc/passwd", "/etc/shadow", "/etc/group", "/etc/alpine-release", "/etc/os-release", "/usr/lib/os-release", - "/lib/apk/db/installed", "/usr/lib/apk/db/installed": + "/lib/apk/db/installed", "/usr/lib/apk/db/installed", "/usr/lib/opkg/status": + return true + } + if strings.HasPrefix(p, "/usr/lib/opkg/info/openssh") && strings.HasSuffix(p, ".list") { return true } if strings.HasPrefix(p, "/etc/tcb/") && strings.HasSuffix(p, "/shadow") { @@ -104,19 +116,25 @@ const maxKept = 4 << 20 // NewScan starts a filesystem or image scan. func (d *Detector) NewScan(kind engine.TargetKind) engine.Scan { - return &scan{kind: kind, files: map[string][]byte{}} + return &scan{kind: kind, files: map[string][]byte{}, scripts: map[string][]byte{}} } type scan struct { - kind engine.TargetKind - binaries []*assess.Binary - files map[string][]byte + kind engine.TargetKind + binaries []*assess.Binary + files map[string][]byte + scripts map[string][]byte + scriptBytes int } func (s *scan) Visit(f engine.File) []engine.Skip { if f.Member { return nil // installed servers only, not copies inside archives } + if isScript(f.Data) && len(f.Data) <= maxScript && s.scriptBytes+len(f.Data) <= maxScripts { + s.scripts[f.Path] = f.Data + s.scriptBytes += len(f.Data) + } if keep(f.Path) && len(f.Data) <= maxKept && !archive.IsExecutable(f.Data) { s.files[f.Path] = f.Data return nil @@ -148,6 +166,15 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { } } } + if st := fs.Read("/usr/lib/opkg/status"); st != nil { + lists := map[string][]byte{} + for _, p := range fs.Glob("/usr/lib/opkg/info/openssh*.list") { + lists[strings.TrimSuffix(path.Base(p), ".list")] = fs.Read(p) + } + for k, v := range assess.OpkgOwners(st, lists) { + owners[k] = v + } + } branch := assess.BranchFromRelease(string(fs.Read("/etc/alpine-release"))) if branch != "" { ctx.Annotate("alpine_branch", branch) @@ -160,6 +187,7 @@ func (s *scan) Finish(ctx engine.TargetContext) []engine.Finding { Resolve: res.resolve, Branch: branch, Image: s.kind == engine.Image, + Startup: assess.Startup{Command: ctx.Command(), Scripts: s.scripts}, }) out := make([]engine.Finding, 0, len(found)) for _, x := range found { @@ -194,6 +222,12 @@ func finding(x assess.Finding) engine.Finding { facts["salt_from"] = x.Donor.Account facts["crypt_fails"] = x.Donor.Fails } + if len(x.AtStart) > 0 { + facts["startup_scripts"] = strings.Join(x.AtStart, ",") + } + if x.StartedWith != "" { + facts["sshd_options_from"] = x.StartedWith + } if len(x.Targets) > 0 { var names []string for _, t := range x.Targets { diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 286ab77..c05a48b 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -142,6 +142,9 @@ type TargetContext interface { Exists(path string) bool // Env is the image configuration's environment ("KEY=value"), nil otherwise. Env() []string + // Command is what the image's container runs (Entrypoint then Cmd), nil + // for anything but an image. + Command() []string // Aliases returns every path that names the same file as p (symlinks, hard // links), p included. Aliases(p string) []string diff --git a/internal/engine/run.go b/internal/engine/run.go index 4651726..f144a63 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -92,6 +92,7 @@ type targetCtx struct { sysRoot string // fs scans below the system root: its OS path seen map[string]bool env []string + cmd []string symlinks map[string]string // absolute path -> target as written hardlinks map[string]string // absolute path -> absolute path it names } @@ -115,6 +116,7 @@ func (c *targetCtx) Annotate(key string, v any) { 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 } func (c *targetCtx) Aliases(p string) []string { out := []string{p} seen := map[string]bool{p: true} @@ -374,7 +376,7 @@ func ScanImage(dets []Detector, ref string, opts Options) *Target { t.Error = err.Error() return t } - rc, t.Digest, t.Platform, w.ctx.env = o.FS, o.Digest, o.Platform, o.Env + rc, t.Digest, t.Platform, w.ctx.env, w.ctx.cmd = o.FS, o.Digest, o.Platform, o.Env, o.Command } defer rc.Close() so := w.sourceOptions(opts) diff --git a/internal/image/image.go b/internal/image/image.go index 75de9c5..ef9b360 100644 --- a/internal/image/image.go +++ b/internal/image/image.go @@ -25,6 +25,9 @@ type Opened struct { Platform string // Env is the image configuration's environment. Env []string + // Command is what the container runs: the configuration's Entrypoint + // followed by its Cmd. + Command []string } // Open resolves ref and returns the image's flattened filesystem. @@ -47,6 +50,7 @@ func opened(img v1.Image) (*Opened, error) { o := &Opened{Digest: digest.String()} if cf, err := img.ConfigFile(); err == nil && cf != nil { o.Env = cf.Config.Env + o.Command = append(append([]string(nil), cf.Config.Entrypoint...), cf.Config.Cmd...) if cf.OS != "" { o.Platform = cf.OS + "/" + cf.Architecture if cf.Variant != "" { diff --git a/parity/SSHOLE-RESULTS.md b/parity/SSHOLE-RESULTS.md index 738a50d..29103ab 100644 --- a/parity/SSHOLE-RESULTS.md +++ b/parity/SSHOLE-RESULTS.md @@ -12,5 +12,7 @@ Generated by `parity/sshole.py`. | matchonly | pass | /usr/sbin/sshd exposed vulnerable high
/usr/sbin/sshd.pam exposed vulnerable high | | latest | pass | /usr/sbin/sshd sshd fixed | | debian | pass | none | +| startup | pass | /usr/sbin/sshd exposed vulnerable high
/usr/sbin/sshd.pam exposed vulnerable high | +| cmdline | pass | /usr/sbin/sshd exposed vulnerable critical
/usr/sbin/sshd.pam sshd vulnerable medium | -8/8 cases match. +10/10 cases match. diff --git a/parity/sshole.py b/parity/sshole.py index 9a06b2f..4652175 100644 --- a/parity/sshole.py +++ b/parity/sshole.py @@ -15,7 +15,7 @@ HERE = os.path.dirname(os.path.abspath(__file__)) CASES = os.path.join(HERE, "sshole") -ORDER = ["vuln", "fixed", "pwoff", "usepam", "root", "matchonly", "latest", "debian"] +ORDER = ["vuln", "fixed", "pwoff", "usepam", "root", "matchonly", "latest", "debian", "startup", "cmdline"] def main(): diff --git a/parity/sshole/cmdline.Dockerfile b/parity/sshole/cmdline.Dockerfile new file mode 100644 index 0000000..2ceee12 --- /dev/null +++ b/parity/sshole/cmdline.Dockerfile @@ -0,0 +1,4 @@ +# Password logins off in sshd_config, on again in the image's command. +FROM earlylight-parity-sshole:vuln +RUN echo 'PasswordAuthentication no' > /etc/ssh/sshd_config.d/00-off.conf +CMD ["/usr/sbin/sshd", "-D", "-e", "-o", "PasswordAuthentication=yes"] diff --git a/parity/sshole/expected.json b/parity/sshole/expected.json index 08699ea..baa7dfe 100644 --- a/parity/sshole/expected.json +++ b/parity/sshole/expected.json @@ -1,10 +1,117 @@ { - "vuln": [["/usr/sbin/sshd", "exposed", "vulnerable", "critical"], ["/usr/sbin/sshd.pam", "exposed", "vulnerable", "critical"]], - "fixed": [["/usr/sbin/sshd", "sshd", "fixed", ""], ["/usr/sbin/sshd.pam", "sshd", "fixed", ""]], - "pwoff": [["/usr/sbin/sshd", "sshd", "vulnerable", "medium"], ["/usr/sbin/sshd.pam", "sshd", "vulnerable", "medium"]], - "usepam": [["/usr/sbin/sshd", "exposed", "vulnerable", "critical"], ["/usr/sbin/sshd.pam", "sshd", "inactive", ""]], - "root": [["/usr/sbin/sshd", "exposed", "vulnerable", "critical"]], - "matchonly": [["/usr/sbin/sshd", "exposed", "vulnerable", "high"], ["/usr/sbin/sshd.pam", "exposed", "vulnerable", "high"]], - "latest": [["/usr/sbin/sshd", "sshd", "fixed", ""]], - "debian": [] + "vuln": [ + [ + "/usr/sbin/sshd", + "exposed", + "vulnerable", + "critical" + ], + [ + "/usr/sbin/sshd.pam", + "exposed", + "vulnerable", + "critical" + ] + ], + "fixed": [ + [ + "/usr/sbin/sshd", + "sshd", + "fixed", + "" + ], + [ + "/usr/sbin/sshd.pam", + "sshd", + "fixed", + "" + ] + ], + "pwoff": [ + [ + "/usr/sbin/sshd", + "sshd", + "vulnerable", + "medium" + ], + [ + "/usr/sbin/sshd.pam", + "sshd", + "vulnerable", + "medium" + ] + ], + "usepam": [ + [ + "/usr/sbin/sshd", + "exposed", + "vulnerable", + "critical" + ], + [ + "/usr/sbin/sshd.pam", + "sshd", + "inactive", + "" + ] + ], + "root": [ + [ + "/usr/sbin/sshd", + "exposed", + "vulnerable", + "critical" + ] + ], + "matchonly": [ + [ + "/usr/sbin/sshd", + "exposed", + "vulnerable", + "high" + ], + [ + "/usr/sbin/sshd.pam", + "exposed", + "vulnerable", + "high" + ] + ], + "latest": [ + [ + "/usr/sbin/sshd", + "sshd", + "fixed", + "" + ] + ], + "debian": [], + "startup": [ + [ + "/usr/sbin/sshd", + "exposed", + "vulnerable", + "high" + ], + [ + "/usr/sbin/sshd.pam", + "exposed", + "vulnerable", + "high" + ] + ], + "cmdline": [ + [ + "/usr/sbin/sshd", + "exposed", + "vulnerable", + "critical" + ], + [ + "/usr/sbin/sshd.pam", + "sshd", + "vulnerable", + "medium" + ] + ] } diff --git a/parity/sshole/startup.Dockerfile b/parity/sshole/startup.Dockerfile new file mode 100644 index 0000000..6d666ca --- /dev/null +++ b/parity/sshole/startup.Dockerfile @@ -0,0 +1,8 @@ +# Password logins off and no "*" account as the image ships; the entrypoint +# turns password logins on and sets a "*" account when the container starts. +FROM earlylight-parity-sshole:vuln +RUN echo 'PasswordAuthentication no' > /etc/ssh/sshd_config.d/00-off.conf \ + && sed -i 's/^bob:\*:/bob:!:/' /etc/shadow \ + && printf '#!/bin/sh\nrm -f /etc/ssh/sshd_config.d/00-off.conf\necho "PasswordAuthentication yes" >> /etc/ssh/sshd_config\necho "$SSH_USER:*" | chpasswd -e\nexec /usr/sbin/sshd -D -e\n' > /entrypoint.sh \ + && chmod +x /entrypoint.sh +ENTRYPOINT ["/entrypoint.sh"] From a73ffe86d8b97bd682afb474dfebb7a03ac58be6 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Thu, 5 Nov 2026 20:51:57 -0700 Subject: [PATCH 6/8] sshole: UsePAM at start protects only PAM builds; read chpasswd's own flags; ignore disagreeing or test-mode sshd command lines Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/internal/assess/assess.go | 43 ++++++++++++++++--- detectors/sshole/internal/assess/runtime.go | 35 +++++++++++++-- .../sshole/internal/assess/runtime_test.go | 38 +++++++++++++++- 3 files changed, 106 insertions(+), 10 deletions(-) diff --git a/detectors/sshole/internal/assess/assess.go b/detectors/sshole/internal/assess/assess.go index b7d53b5..1be61e5 100644 --- a/detectors/sshole/internal/assess/assess.go +++ b/detectors/sshole/internal/assess/assess.go @@ -316,7 +316,7 @@ func assessUnit(in Input, u []*Binary) (Finding, bool) { f.Status, f.Severity = Vulnerable, "medium" f.Message = fmt.Sprintf("OpenSSH %s server on musl without the *sshole fix; not exploitable as configured: %s", main.Release, strings.Join(missing, "; ")) if sig := startupSignals(scripts); sig.any() { - if t, ok := atStart(in, cfg, donor, sig); ok { + if t, ok := atStart(in, cfg, donor, sig, f.PAM); ok { f.Kind, f.Severity = KindExposed, "high" f.Targets = t f.AtStart = sig.where @@ -338,27 +338,58 @@ func targetNames(ts []Target) string { return strings.Join(n, ", ") } -// pickInvocation finds the command line that starts this server. +// pickInvocation finds the command line that starts this server: the +// container command's when it runs sshd, else the startup scripts' when they +// all agree. Command lines that disagree are not applied: options must not +// lower a verdict on a guess. func pickInvocation(invs []invocation, u []*Binary) (invocation, bool) { + var mine []invocation for _, inv := range invs { for _, b := range u { if inv.binary == b.Path || path.Base(inv.binary) == path.Base(b.Path) { - return inv, true + mine = append(mine, inv) + break } } } - return invocation{}, false + if len(mine) == 0 { + return invocation{}, false + } + for _, inv := range mine { + if inv.where == "the container command" { + return inv, true + } + } + for _, inv := range mine[1:] { + if inv.config != mine[0].config || !sameOpts(inv.opts, mine[0].opts) { + return invocation{}, false + } + } + return mine[0], true +} + +func sameOpts(a, b []Directive) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i].Key != b[i].Key || strings.Join(a[i].Args, " ") != strings.Join(b[i].Args, " ") { + return false + } + } + return true } // atStart applies what the startup scripts do (turn password logins on, // set a password field to "*", set passwords with chpasswd) and returns the // accounts a crafted password would then reach. -func atStart(in Input, cfg Config, donor Donor, sig signals) ([]Target, bool) { +func atStart(in Input, cfg Config, donor Donor, sig signals, pamBuilt bool) ([]Target, bool) { fails := donor.Fails if donor.Account == "" && sig.passwords { fails = "long" // chpasswd writes a sha512 hash, the first one pick_salt sees } - if fails == "none" || sig.usePAMOn { + // UsePAM yes protects only a build with PAM in it. + if fails == "none" || sig.usePAMOn && pamBuilt { return nil, false } c := cfg diff --git a/detectors/sshole/internal/assess/runtime.go b/detectors/sshole/internal/assess/runtime.go index 06822af..92e2790 100644 --- a/detectors/sshole/internal/assess/runtime.go +++ b/detectors/sshole/internal/assess/runtime.go @@ -186,6 +186,13 @@ func fieldsQuoted(s string) []string { var sshdValueFlags = "CEbcghkpu" // sshd.c getopt "C:E:b:c:f:g:h:k:o:p:u:..." func parseSSHD(argv []string, where string) (invocation, bool) { + // A line that only prints, tests or looks for sshd does not run it. + if len(argv) > 0 { + switch path.Base(argv[0]) { + case "echo", "printf", "test", "[", "[[", "grep", "pgrep", "pkill", "kill", "which", "command", "type", "ls", "cat", "if", "case": + return invocation{}, false + } + } i := 0 for i < len(argv) { b := path.Base(argv[i]) @@ -197,6 +204,11 @@ func parseSSHD(argv []string, where string) (invocation, bool) { if i >= len(argv) { return invocation{}, false } + for _, a := range argv[i+1:] { + if a == "-t" || a == "-T" || a == "-G" { + return invocation{}, false // a config test, not the server + } + } inv := invocation{binary: argv[i], where: where} for j := i + 1; j < len(argv); j++ { a := argv[j] @@ -225,7 +237,7 @@ func parseSSHD(argv []string, where string) (invocation, bool) { // accounts before sshd runs. var ( pwOnRE = regexp.MustCompile(`(?i)PasswordAuthentication\s*[= ]\s*["']?yes`) - usePAMOnRE = regexp.MustCompile(`(?i)UsePAM\s*[= ]\s*["']?yes`) + usePAMOnRE = regexp.MustCompile(`(?im)^[^#\n]*UsePAM\s*[= ]\s*["']?yes`) starSetRE = []*regexp.Regexp{ regexp.MustCompile(`(?:usermod|useradd)\b[^\n]*(?:-p|--password)[ =]\s*(?:'\*'|"\*"|\\\*|\*)(?:\s|$)`), regexp.MustCompile(`[A-Za-z0-9_$.{}-]+:\*['"]?\s*\|\s*chpasswd\s+(?:-e|--encrypted)`), @@ -275,8 +287,25 @@ func startupSignals(scripts []script) signals { } } for _, line := range strings.Split(sc.text, "\n") { - if chpasswdRE.MatchString(line) && !strings.Contains(line, "-e") && !strings.Contains(line, "--encrypted") { - g.passwords, hit = true, true // busybox and shadow chpasswd write sha512 hashes by default + if !chpasswdRE.MatchString(line) { + continue + } + for _, part := range splitCommands(line) { + words := fieldsQuoted(part) + for i, w := range words { + if path.Base(w) != "chpasswd" { + continue + } + encrypted := false + for _, a := range words[i+1:] { + if a == "-e" || a == "--encrypted" || strings.HasPrefix(a, "-") && !strings.HasPrefix(a, "--") && strings.Contains(a, "e") { + encrypted = true + } + } + if !encrypted { + g.passwords, hit = true, true // busybox and shadow chpasswd write sha512 hashes by default + } + } } } if hit { diff --git a/detectors/sshole/internal/assess/runtime_test.go b/detectors/sshole/internal/assess/runtime_test.go index 8858254..25030bf 100644 --- a/detectors/sshole/internal/assess/runtime_test.go +++ b/detectors/sshole/internal/assess/runtime_test.go @@ -49,7 +49,7 @@ func TestStartupScripts(t *testing.T) { {"turns on passwords and sets a star", "#!/bin/sh\nsed -i 's/^#*PasswordAuthentication.*/PasswordAuthentication yes/' /etc/ssh/sshd_config\nusermod -p '*' \"$USER\"\nexec /usr/sbin/sshd -D\n", KindExposed, true}, {"star but passwords stay off", "#!/bin/sh\necho \"$USER:*\" | chpasswd -e\nexec /usr/sbin/sshd -D\n", KindServer, true}, {"nothing relevant", "#!/bin/sh\nssh-keygen -A\nexec /usr/sbin/sshd -D\n", KindServer, false}, - {"UsePAM on", "#!/bin/sh\necho 'PasswordAuthentication yes' >> /etc/ssh/sshd_config\necho 'UsePAM yes' >> /etc/ssh/sshd_config\nusermod -p '*' x\n", KindServer, true}, + {"UsePAM on without a PAM build", "#!/bin/sh\necho 'PasswordAuthentication yes' >> /etc/ssh/sshd_config\necho 'UsePAM yes' >> /etc/ssh/sshd_config\nusermod -p '*' x\n", KindExposed, true}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { @@ -98,3 +98,39 @@ func TestOpkg(t *testing.T) { } } } + +func TestStartupReviewCases(t *testing.T) { + quiet := map[string]string{"/etc/shadow": strings.Replace(stdShadow, "bob:*", "bob:!", 1), "/etc/ssh/sshd_config.d/00.conf": "PasswordAuthentication no\n"} + // UsePAM yes protects nothing on a build without PAM. + w := newWorld("10.0p2", false, quiet) + script := "#!/bin/sh\necho 'UsePAM yes' >> /etc/ssh/sshd_config\necho 'PasswordAuthentication yes' >> /etc/ssh/sshd_config\nusermod -p '*' x\n" + if f := one(t, runStartup(w, Startup{Command: []string{"/e.sh"}, Scripts: map[string][]byte{"/e.sh": []byte(script)}})); f.Kind != KindExposed { + t.Errorf("non-PAM build with UsePAM: %+v", f) + } + // "-e" elsewhere on the line is not chpasswd's flag. + w = newWorld("10.0p2", false, map[string]string{"/etc/shadow": strings.Replace(stdShadow, sha512Alice, "!", 1)}) + script = "#!/bin/sh\necho -e \"admin:$PW\" | chpasswd\n" + if f := one(t, runStartup(w, Startup{Command: []string{"/e.sh"}, Scripts: map[string][]byte{"/e.sh": []byte(script)}})); f.Kind != KindExposed { + t.Errorf("echo -e | chpasswd: %+v", f) + } + // Two scripts that start sshd differently: their options are not applied. + w = newWorld("10.0p2", false, nil) + scripts := map[string][]byte{"/etc/cont-init.d/a": []byte("#!/bin/sh\n/usr/sbin/sshd -D -o PasswordAuthentication=no\n"), "/etc/cont-init.d/b": []byte("#!/bin/sh\n/usr/sbin/sshd -D\n")} + if f := one(t, runStartup(w, Startup{Scripts: scripts})); f.Kind != KindExposed { + t.Errorf("disagreeing invocations lowered the verdict: %+v", f) + } + // A config test and an echo do not count. + scripts = map[string][]byte{"/etc/cont-init.d/a": []byte("#!/bin/sh\n/usr/sbin/sshd -t -o PasswordAuthentication=no\necho /usr/sbin/sshd -o PasswordAuthentication=no\n")} + if f := one(t, runStartup(w, Startup{Scripts: scripts})); f.Kind != KindExposed { + t.Errorf("test-mode invocation applied: %+v", f) + } +} + +func TestStartupUsePAMOnPAMBuild(t *testing.T) { + quiet := map[string]string{"/etc/shadow": strings.Replace(stdShadow, "bob:*", "bob:!", 1), "/etc/ssh/sshd_config.d/00.conf": "PasswordAuthentication no\n"} + w := newWorld("10.0p2", true, quiet) + script := "#!/bin/sh\necho 'PasswordAuthentication yes' >> /etc/ssh/sshd_config\necho 'UsePAM yes' >> /etc/ssh/sshd_config\nusermod -p '*' x\n" + if f := one(t, runStartup(w, Startup{Command: []string{"/e.sh"}, Scripts: map[string][]byte{"/e.sh": []byte(script)}})); f.Kind != KindServer { + t.Errorf("PAM build with UsePAM yes at start: %+v", f) + } +} From f02c8091430ad45ad0c3603eaefc4d711a96992b Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Thu, 5 Nov 2026 21:13:45 -0700 Subject: [PATCH 7/8] sshole: images a source tree references, deployment command overrides, retag and patch fixes - scan repo pulls the images a tree references through the guarded transport (engine Options.Guarded, at most 20) and judges them with the Compose entrypoint/command or Kubernetes command/args set for them (engine Options.Override; image.Opened keeps Entrypoint and Cmd). - fix: an end-of-life Alpine-suffixed base (python:3.9-alpine3.14) moves to the same tag on the nearest fixed Alpine release once that image is confirmed to be that release; Buildroot and Yocto builds get upstream commit 4353fdc43 as a patch scoped to OpenSSH 8.9p1 to 10.6p1 (applies cleanly to every release in that range; patched 8.9p1, 9.9p2 and 10.6p1 build on musl). Fixes can now add files. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- .../repo/avoid-password-authn-bypass.patch | 189 ++++++++++ detectors/sshole/internal/repo/build.go | 330 ++++++++++++++++-- detectors/sshole/internal/repo/more_test.go | 119 +++++++ detectors/sshole/internal/repo/override.go | 141 ++++++++ detectors/sshole/internal/repo/plan.go | 135 ++++++- detectors/sshole/internal/repo/repo.go | 80 ++++- detectors/sshole/repo.go | 135 ++++++- internal/engine/run.go | 49 ++- internal/image/image.go | 3 + 10 files changed, 1143 insertions(+), 40 deletions(-) create mode 100644 detectors/sshole/internal/repo/avoid-password-authn-bypass.patch create mode 100644 detectors/sshole/internal/repo/override.go diff --git a/README.md b/README.md index c9171fe..6f9ea5a 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ One engine for DefectDojo's emerging-vulnerability scanners. Each new vulnerabil | `emudhra` | Trust in the eight eMudhra intermediate CA keys compromised in October 2026 ([Mozilla bug 2083449](https://bugzilla.mozilla.org/show_bug.cgi?id=2083449)): trust stores, bundles, keystores and binaries that still trust them, Go binaries without Go's blocklist (CVE-2026-111943), and servers presenting certificates the compromised keys signed | `fs`, `image`, `host` | | `php2shell` | PHP runtimes vulnerable to CVE-2026-109618 and CVE-2026-109619 ("PHP2Shell"), fixed in PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12 ([GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w), [GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp)). A packaged PHP is judged by its vendor's backport data, never by the version it reports. Also checks the images a source tree builds on and deploys, and can rewrite them to fixed images | `fs`, `image`, `repo`, `fix` | | `brotli` | Brotli decoders vulnerable to CVE-2026-111497 ("Node2Shell", "Broccoli2Shell"), Brotli 1.0.3 through 1.2.0, fixed in 1.0.10, 1.1.1 and 1.2.1 ([GHSA-9v8h-qqgm-4m35](https://github.com/advisories/GHSA-9v8h-qqgm-4m35)): system `libbrotlidec` and every copy bundled into other software (Node.js, .NET, Bun, Electron, Envoy and Istio, Python wheels such as Pillow, pyarrow, duckdb, pycurl and PyMuPDF, brotli4j, and more), on Linux, Windows and macOS. A decoder is judged first by the error code the fix added, so vendor backports are recognised without distribution data; a build that strips it by its own version stamp or by its code, which returns that error code only once fixed. In a source tree it finds the Node.js, .NET and Bun releases and the bundling packages a project pins, and `fix` moves each to the fixed release | `fs`, `image`, `repo`, `fix` | -| `sshole` | \*sshole, the OpenSSH password authentication bypass on musl libc fixed in OpenSSH 10.6p2 and in Alpine's openssh packages of November 5, 2026 ([release notes](https://www.openssh.org/releasenotes.html#10.6p2), [writeup](https://sshhole.com)). On musl, sshd from 7.3p1 to 10.6p1 compares an account's password field of `*` with the `*` that crypt returns when it fails, so a crafted password logs in to that account. It judges each installed sshd by its C library, its release and the apk database (Alpine backports keep the release number), then checks what the target's `sshd_config` (Include, Match, PasswordAuthentication, AuthenticationMethods, PermitRootLogin, AllowUsers and the rest) and account files make reachable, and reports the accounts. In an image it also reads the command (`sshd -o` and `-f`) and the startup scripts it runs (entrypoints, s6, cont-init.d), and reports a server as exposed when a startup script turns password logins on, sets a `*` field or sets passwords. OpenWrt's opkg database and its backports (23.05, 24.10, 25.12) count like Alpine's. PAM-checked builds (`UsePAM yes`) are not affected. On a live server it reads the banner and the offered methods and never sends a password. In a source tree it finds Dockerfiles that install an OpenSSH server on Alpine without the fix (package lists in `ARG` and `ENV` too), Ansible apk tasks, Buildroot, OpenWrt and Yocto configurations that build one on musl, and anything that sets a password field to `*`. `fix` adds the fixed release floor (in the variable when the list is one), moves an end-of-life `alpine:3.N` base to 3.16 as a labelled upgrade, sets Ansible tasks to `state: latest`, and changes `*` to `*NP*` | `fs`, `image`, `host`, `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` | The detectors ported from standalone scanners also build as standalone binaries under the names people search for: `emudhra-scan` and `php2shell-scan`. They keep their original commands, flags and exit status rules. `brotli` and `sshole` were written here and run through `earlylight` (`--detector brotli`, `--detector sshole`). diff --git a/detectors/sshole/internal/repo/avoid-password-authn-bypass.patch b/detectors/sshole/internal/repo/avoid-password-authn-bypass.patch new file mode 100644 index 0000000..e5334f1 --- /dev/null +++ b/detectors/sshole/internal/repo/avoid-password-authn-bypass.patch @@ -0,0 +1,189 @@ +From 4353fdc43ef646c43a8dda7025cc1a898caf1482 Mon Sep 17 00:00:00 2001 +From: Damien Miller +Date: Thu, 5 Nov 2026 08:18:18 +1100 +Subject: [PATCH] avoid password authn bypass + +This bypass affects some configurations and runtime configurations. +We do not consider the root cause to be within OpenSSH but we are +well equipped to avoid it. +--- + auth-passwd.c | 17 +++++++++++++---- + openbsd-compat/port-uw.c | 16 ++++++++-------- + openbsd-compat/xcrypt.c | 18 +++++++++++++----- + 3 files changed, 34 insertions(+), 17 deletions(-) + +diff --git a/auth-passwd.c b/auth-passwd.c +index 37dba168c..5406e2d55 100644 +--- a/auth-passwd.c ++++ b/auth-passwd.c +@@ -50,6 +50,7 @@ + #include "ssherr.h" + #include "log.h" + #include "misc.h" ++#include "xmalloc.h" + #include "servconf.h" + #include "sshkey.h" + #include "hostfile.h" +@@ -67,6 +68,7 @@ extern login_cap_t *lc; + #define DAY (24L * 60 * 60) /* 1 day in seconds */ + #define TWO_WEEKS (2L * 7 * DAY) /* 2 weeks in seconds */ + ++#define MIN_PASSWORD_HASH_LEN 4 + #define MAX_PASSWORD_LEN 1024 + + /* +@@ -198,16 +200,20 @@ sys_auth_passwd(struct ssh *ssh, const char *password) + Authctxt *authctxt = ssh->authctxt; + struct passwd *pw = authctxt->pw; + char *encrypted_password, *salt = NULL; ++ int ret; + + /* Just use the supplied fake password if authctxt is invalid */ +- char *pw_password = authctxt->valid ? shadow_pw(pw) : pw->pw_passwd; ++ char *pw_password = authctxt->valid ? ++ shadow_pw(pw) : xstrdup(pw->pw_passwd); + + if (pw_password == NULL) + return 0; + + /* Check for users with no password. */ +- if (strcmp(pw_password, "") == 0 && strcmp(password, "") == 0) +- return (1); ++ if (strcmp(pw_password, "") == 0 && strcmp(password, "") == 0) { ++ free(pw_password); ++ return 1; ++ } + + /* + * Encrypt the candidate password using the proper salt, or pass a +@@ -221,7 +227,10 @@ sys_auth_passwd(struct ssh *ssh, const char *password) + * Authentication is accepted if the encrypted passwords + * are identical. + */ +- return encrypted_password != NULL && ++ ret = encrypted_password != NULL && ++ strlen(pw_password) >= MIN_PASSWORD_HASH_LEN && + strcmp(encrypted_password, pw_password) == 0; ++ freezero(pw_password, strlen(pw_password)); ++ return ret; + } + #endif +diff --git a/openbsd-compat/port-uw.c b/openbsd-compat/port-uw.c +index 074f80c8d..5c50ffa0f 100644 +--- a/openbsd-compat/port-uw.c ++++ b/openbsd-compat/port-uw.c +@@ -58,14 +58,17 @@ sys_auth_passwd(struct ssh *ssh, const char *password) + int result; + + /* Just use the supplied fake password if authctxt is invalid */ +- char *pw_password = authctxt->valid ? shadow_pw(pw) : pw->pw_passwd; ++ char *pw_password = authctxt->valid ? ++ shadow_pw(pw) : xstrdup(pw->pw_passwd); + + if (pw_password == NULL) + return 0; + + /* Check for users with no password. */ +- if (strcmp(pw_password, "") == 0 && strcmp(password, "") == 0) +- return (1); ++ if (strcmp(pw_password, "") == 0 && strcmp(password, "") == 0) { ++ free(pw_password); ++ return 1; ++ } + + /* Encrypt the candidate password using the proper salt. */ + salt = (pw_password[0] && pw_password[1]) ? pw_password : "xx"; +@@ -83,11 +86,8 @@ sys_auth_passwd(struct ssh *ssh, const char *password) + #endif /* UNIXWARE_LONG_PASSWORDS */ + result = (strcmp(xcrypt(password, salt), pw_password) == 0); + +-#ifdef USE_LIBIAF +- if (authctxt->valid) +- free(pw_password); +-#endif +- return(result); ++ freezero(pw_password, strlen(pw_password)); ++ return result; + } + + #ifdef UNIXWARE_LONG_PASSWORDS +diff --git a/openbsd-compat/xcrypt.c b/openbsd-compat/xcrypt.c +index 4e0d0d644..80b13a5c4 100644 +--- a/openbsd-compat/xcrypt.c ++++ b/openbsd-compat/xcrypt.c +@@ -25,6 +25,8 @@ + #include "includes.h" + + #include ++#include ++#include + #include + #include + #include +@@ -59,6 +61,8 @@ + # define crypt DES_crypt + # endif + ++#include "xmalloc.h" ++ + #define MINIMUM(a, b) (((a) < (b)) ? (a) : (b)) + + /* +@@ -71,7 +75,7 @@ static const char * + pick_salt(void) + { + struct passwd *pw; +- char *passwd, *p; ++ char *passwd = NULL, *p; + size_t typelen; + static char salt[32]; + +@@ -80,6 +84,8 @@ pick_salt(void) + strlcpy(salt, "xx", sizeof(salt)); + setpwent(); + while ((pw = getpwent()) != NULL) { ++ if (passwd != NULL) ++ freezero(passwd, strlen(passwd)); + if ((passwd = shadow_pw(pw)) == NULL) + continue; + if (passwd[0] == '$' && (p = strrchr(passwd+1, '$')) != NULL) { +@@ -97,6 +103,8 @@ pick_salt(void) + } + } + out: ++ if (passwd != NULL) ++ freezero(passwd, strlen(passwd)); + endpwent(); + return salt; + } +@@ -129,9 +137,8 @@ xcrypt(const char *password, const char *salt) + + /* + * Handle shadowed password systems in a cleaner way for portable +- * version. ++ * version. Caller must free returned value. + */ +- + char * + shadow_pw(struct passwd *pw) + { +@@ -145,7 +152,8 @@ shadow_pw(struct passwd *pw) + # endif + + #ifdef USE_LIBIAF +- return(get_iaf_password(pw)); ++ pw_password = get_iaf_password(pw); ++ return pw_password == NULL ? NULL : xstrdup(pw_password); + #endif + + # if defined(HAVE_GETPWANAM) && !defined(DISABLE_SHADOW) +@@ -159,5 +167,5 @@ shadow_pw(struct passwd *pw) + pw_password = spw->ufld.fd_encrypt; + # endif + +- return pw_password; ++ return pw_password == NULL ? NULL : xstrdup(pw_password); + } +-- +2.50.1 (Apple Git-155) + diff --git a/detectors/sshole/internal/repo/build.go b/detectors/sshole/internal/repo/build.go index 1e179c5..0a7f34c 100644 --- a/detectors/sshole/internal/repo/build.go +++ b/detectors/sshole/internal/repo/build.go @@ -1,14 +1,43 @@ package repo import ( + _ "embed" + "errors" "fmt" + "io/fs" + "os" + "path" "regexp" + "sort" "strings" + + "github.com/DefectDojo/earlylight/internal/refs" ) // Build systems that make musl firmware: Buildroot and OpenWrt // configurations name the package and the C library in one file; Yocto's // TCLIBC and image contents are joined across the tree in finishBuild. +// +// Buildroot and Yocto findings are fixed by adding upstream commit +// 4353fdc43 as a patch, scoped to the OpenSSH versions it applies to (8.9p1 +// to 10.6p1, checked with patch --dry-run on every release, and built on +// musl for 8.9p1, 9.9p2 and 10.6p1), so it never lands on 10.6p2 or later. + +//go:embed avoid-password-authn-bypass.patch +var upstreamPatch []byte + +// PatchName is the file name the fix adds. +const PatchName = "0001-avoid-password-authn-bypass.patch" + +// buildrootVersions are the OpenSSH versions Buildroot's branches from +// 2022.02.x to 2026.08.x ship (checked 2026-11-05); master has 10.6p2. +var buildrootVersions = []string{"8.9p1", "9.0p1", "9.1p1", "9.3p2", "9.6p1", "9.7p1", "9.8p1", "9.9p2", "10.0p1", "10.2p1", "10.5p1", "10.6p1"} + +// yoctoSeries maps an OpenEmbedded release to its OpenSSH version (checked +// 2026-11-05). dunfell (8.2p1) and older are too old for the patch; +// blacksail is left out because its branch and master differ. +var yoctoSeries = map[string]string{"kirkstone": "8.9p1", "langdale": "9.0p1", "mickledore": "9.3p2", "nanbield": "9.5p1", + "scarthgap": "9.6p1", "styhead": "9.8p1", "walnascar": "9.9p2", "whinlatter": "10.2p1", "wrynose": "10.3p1"} var ( brOpenSSH = regexp.MustCompile(`(?m)^BR2_PACKAGE_OPENSSH=y`) @@ -16,60 +45,197 @@ var ( brMusl = regexp.MustCompile(`(?m)^BR2_TOOLCHAIN_(USES_MUSL|BUILDROOT_MUSL|EXTERNAL_[A-Z0-9_]*MUSL[A-Z0-9_]*)=y`) brLibc = regexp.MustCompile(`(?m)^BR2_TOOLCHAIN_(USES_GLIBC|USES_UCLIBC|BUILDROOT_GLIBC|BUILDROOT_UCLIBC)=y`) brPAM = regexp.MustCompile(`(?m)^BR2_PACKAGE_LINUX_PAM=y`) + brPatchDir = regexp.MustCompile(`(?m)^BR2_GLOBAL_PATCH_DIR="([^"]*)"`) + brExtVar = regexp.MustCompile(`^\$\(BR2_EXTERNAL_([A-Za-z0-9_]+)_PATH\)/(.*)$`) owrtServer = regexp.MustCompile(`(?m)^CONFIG_PACKAGE_(openssh-server(?:-pam)?)=[ym]`) yoctoMusl = regexp.MustCompile(`(?m)^\s*TCLIBC\s*\??\??=\s*["']musl["']`) yoctoOpenSSH = regexp.MustCompile(`(?m)^[^#\n]*(IMAGE_INSTALL|IMAGE_FEATURES|EXTRA_IMAGE_FEATURES|CORE_IMAGE_EXTRA_INSTALL|RDEPENDS)[^=\n]*=[^\n]*\b(openssh-sshd|openssh|ssh-server-openssh|packagegroup-core-ssh-openssh)\b`) - yoctoSSHGuard = regexp.MustCompile(`(?m)^[^#\n]*\bssh-server-dropbear\b`) + yoctoSeriesRE = regexp.MustCompile(`(?m)^\s*LAYERSERIES_COMPAT_[A-Za-z0-9_-]+\s*=\s*"([^"]*)"`) + ocoreRecipe = regexp.MustCompile(`(^|/)recipes-connectivity/openssh/openssh_([0-9]+\.[0-9]+p[0-9]+)\.bb$`) ) func lineOf(text string, at int) int { return strings.Count(text[:at], "\n") + 1 } +// readRel reads a repository file, from the overlay first. +func (s *scanner) readRel(rel string) ([]byte, bool) { + if b, ok := s.opts.Overlay[rel]; ok { + return b, true + } + b, err := readFile(s.root, rel) + return b, err == nil +} + +// listDir lists a repository directory's entries, overlay included. +func (s *scanner) listDir(rel string) []string { + seen := map[string]bool{} + if p, err := refs.SafePath(s.root, rel); err == nil { + if es, err := os.ReadDir(p); err == nil { + for _, e := range es { + seen[e.Name()] = true + } + } + } + pre := strings.TrimSuffix(rel, "/") + "/" + for p := range s.opts.Overlay { + if strings.HasPrefix(p, pre) { + seen[strings.SplitN(p[len(pre):], "/", 2)[0]] = true + } + } + out := make([]string, 0, len(seen)) + for n := range seen { + out = append(out, n) + } + sort.Strings(out) + return out +} + +func hasFix(b []byte) bool { return strings.Contains(string(b), "MIN_PASSWORD_HASH_LEN") } + func (s *scanner) build(rel, text string) { switch { case brOpenSSH.MatchString(text): - loc := brOpenSSH.FindStringIndex(text) - if m := brServer.FindStringSubmatch(text); m != nil && m[1] != "y" { - return // the client only - } - pam := "" - if brPAM.MatchString(text) { - pam = " It is built with PAM; setting UsePAM yes in sshd_config also closes the hole." - } - f := Finding{Rule: RuleBuild, File: rel, Line: lineOf(text, loc[0]), Props: map[string]string{"system": "buildroot"}, - Fix: "Buildroot master moved OpenSSH to 10.6p2 on 2026-11-05; the 2025.02.x to 2026.08.x branches had not when this was written. Move to a Buildroot with it, or add upstream commit 4353fdc43 as a patch under BR2_GLOBAL_PATCH_DIR/openssh/." + pam} - switch { - case brMusl.MatchString(text): - f.Level = "error" - f.Message = "Buildroot configuration builds the OpenSSH server against musl; Buildroot releases before 10.6p2 lack the *sshole fix" - case brLibc.MatchString(text): - return - default: - f.Rule, f.Level = RuleNotChecked, "note" - f.Message = "Buildroot configuration builds the OpenSSH server, but its C library is not set in this file; with musl, Buildroot releases before 10.6p2 lack the *sshole fix" - } - s.addBuild(f) + s.buildroot(rel, text) case owrtServer.MatchString(text): for _, m := range owrtServer.FindAllStringSubmatchIndex(text, -1) { pkg := text[m[2]:m[3]] s.addBuild(Finding{Rule: RuleBuild, File: rel, Line: lineOf(text, m[0]), Level: "error", Props: map[string]string{"system": "openwrt", "package": pkg}, Message: fmt.Sprintf("OpenWrt configuration builds %s (OpenWrt uses musl); its openssh needs the *sshole fix", pkg), - Fix: "Build from an OpenWrt packages feed with the fix: 23.05 9.8p1-2, 24.10 9.9_p2-2, 25.12 and master 10.6_p2-1 (2026-11-05). 22.03 and older have none: move to a supported release, or add upstream commit 4353fdc43 to net/openssh/patches."}) + Fix: "Build from an OpenWrt packages feed with the fix: 23.05 9.8p1-2, 24.10 9.9_p2-2, 25.12 and master 10.6_p2-1 (2026-11-05). 22.03 and older have none: move to a supported release, or add upstream commit 4353fdc43 to net/openssh/patches in your feed."}) } default: if m := yoctoMusl.FindStringIndex(text); m != nil { s.yoctoMusl = append(s.yoctoMusl, Finding{File: rel, Line: lineOf(text, m[0])}) } + if strings.HasSuffix(rel, ".bbappend") && strings.HasPrefix(path.Base(rel), "openssh_") && strings.Contains(text, PatchName) { + s.yoctoPatched = append(s.yoctoPatched, rel) + } for _, m := range yoctoOpenSSH.FindAllStringIndex(text, -1) { s.yoctoSSH = append(s.yoctoSSH, Finding{File: rel, Line: lineOf(text, m[0])}) } } } +func (s *scanner) buildroot(rel, text string) { + loc := brOpenSSH.FindStringIndex(text) + if m := brServer.FindStringSubmatch(text); m != nil && m[1] != "y" { + return // the client only + } + if brLibc.MatchString(text) { + return + } + f := Finding{Rule: RuleBuild, File: rel, Line: lineOf(text, loc[0]), Level: "error", Props: map[string]string{"system": "buildroot"}} + pam := "" + if brPAM.MatchString(text) { + pam = " It is built with PAM; UsePAM yes in sshd_config also closes the hole." + } + f.Fix = "Move to a Buildroot with OpenSSH 10.6p2 (master since 2026-11-05; the 2025.02.x to 2026.08.x branches had not moved when this was written), or add upstream commit 4353fdc43 as BR2_GLOBAL_PATCH_DIR/openssh//" + PatchName + "." + pam + if !brMusl.MatchString(text) { + f.Rule, f.Level = RuleNotChecked, "note" + f.Message = "Buildroot configuration builds the OpenSSH server, but its C library is not set in this file; with musl, Buildroot releases before 10.6p2 lack the *sshole fix" + s.addBuild(f) + return + } + f.Message = "Buildroot configuration builds the OpenSSH server against musl; Buildroot releases before 10.6p2 lack the *sshole fix" + dir, line, err := s.buildrootPatchDir(rel, text) + if err == nil && s.patchedIn(dir) { + return // the patch is in place + } + if err != nil { + f.Fix += " (" + err.Error() + ")" + s.addBuild(f) + return + } + f.Fixable = true + f.newFiles = map[string][]byte{} + for _, v := range buildrootVersions { + f.newFiles[path.Join(dir, "openssh", v, PatchName)] = upstreamPatch + } + f.Props["fix_summary"] = fmt.Sprintf("Adds upstream commit 4353fdc43 (the *sshole fix) under %s/openssh// for every OpenSSH version Buildroot's release branches ship (8.9p1 to 10.6p1), so it applies to whichever this Buildroot builds and never to 10.6p2 or later.", dir) + if line != "" { + last := strings.Count(strings.TrimRight(text, "\n"), "\n") + 1 + lines := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") + l := strings.TrimRight(lines[last-1], "\r") + f.edit = &Edit{Line: last, Col: len(l), Old: "", New: "\n" + line} + f.Props["fix_summary"] += " Sets BR2_GLOBAL_PATCH_DIR to that directory." + } + s.addBuild(f) +} + +// buildrootPatchDir finds where the global patch directory is in the +// repository, and the BR2_GLOBAL_PATCH_DIR line to add when none is set. +func (s *scanner) buildrootPatchDir(rel, text string) (dir, line string, err error) { + ext, extName := s.externalTree(rel) + if m := brPatchDir.FindStringSubmatch(text); m != nil && strings.TrimSpace(m[1]) != "" { + first := strings.Fields(m[1])[0] + if v := brExtVar.FindStringSubmatch(first); v != nil { + if ext == "" || !strings.EqualFold(v[1], extName) { + return "", "", errors.New("BR2_GLOBAL_PATCH_DIR names another external tree") + } + return path.Clean(path.Join(ext, v[2])), "", nil + } + if strings.Contains(first, "$") || path.IsAbs(first) { + return "", "", errors.New("BR2_GLOBAL_PATCH_DIR is not a path inside this repository") + } + if _, ok := s.readRel("Config.in"); ok { // a Buildroot tree: paths are from its top + return path.Clean(first), "", nil + } + return "", "", errors.New("BR2_GLOBAL_PATCH_DIR is relative to a Buildroot tree that is not this repository") + } + if ext == "" { + return "", "", errors.New("no BR2_GLOBAL_PATCH_DIR and no BR2_EXTERNAL tree to put one in") + } + dir = path.Join(ext, "patches") + return dir, fmt.Sprintf(`BR2_GLOBAL_PATCH_DIR="$(BR2_EXTERNAL_%s_PATH)/patches"`, extName), nil +} + +var extNameRE = regexp.MustCompile(`(?m)^name:\s*([A-Za-z0-9_]+)`) + +// externalTree is the BR2_EXTERNAL tree holding a defconfig: the nearest +// directory above it with an external.desc. +func (s *scanner) externalTree(rel string) (string, string) { + for d := path.Dir(rel); ; d = path.Dir(d) { + if b, ok := s.readRel(path.Join(d, "external.desc")); ok { + if m := extNameRE.FindSubmatch(b); m != nil { + return path.Clean(d), string(m[1]) + } + return "", "" + } + if d == "." || d == "/" || d == "" { + return "", "" + } + } +} + +// patchedIn reports whether a patch directory already carries the fix for +// openssh, in itself or in a version directory. +func (s *scanner) patchedIn(dir string) bool { + base := path.Join(dir, "openssh") + for _, n := range s.listDir(base) { + p := path.Join(base, n) + if b, ok := s.readRel(p); ok && hasFix(b) { + return true + } + for _, m := range s.listDir(p) { + if b, ok := s.readRel(path.Join(p, m)); ok && hasFix(b) { + return true + } + } + } + return false +} + // pending build findings, returned by finishBuild. func (s *scanner) addBuild(f Finding) { s.yoctoSSH = append(s.yoctoSSH, f) } +// yoctoNeedsTree reports a file whose finding depends on other files. +func (s *scanner) yoctoNeedsTree(rel string) bool { + b := path.Base(rel) + return b != ".config" && b != "diffconfig" && !strings.HasSuffix(b, "defconfig") +} + // finishBuild returns the build-system findings: Buildroot and OpenWrt as -// found, and Yocto images with OpenSSH where the tree sets TCLIBC to musl. +// found, and Yocto images with OpenSSH where the tree sets TCLIBC to musl +// and no openssh bbappend adds the patch. func (s *scanner) finishBuild() []Finding { var out []Finding for _, f := range s.yoctoSSH { @@ -77,16 +243,122 @@ func (s *scanner) finishBuild() []Finding { out = append(out, f) continue } - if len(s.yoctoMusl) == 0 { + if len(s.yoctoMusl) == 0 || len(s.yoctoPatched) > 0 { continue } m := s.yoctoMusl[0] - out = append(out, Finding{Rule: RuleBuild, File: f.File, Line: f.Line, Level: "error", Props: map[string]string{"system": "yocto", "tclibc": fmt.Sprintf("%s:%d", m.File, m.Line)}, + g := Finding{Rule: RuleBuild, File: f.File, Line: f.Line, Level: "error", Props: map[string]string{"system": "yocto", "tclibc": fmt.Sprintf("%s:%d", m.File, m.Line)}, Message: fmt.Sprintf("Yocto image installs the OpenSSH server and %s:%d sets TCLIBC to musl; OpenEmbedded's openssh before 10.6p2 lacks the *sshole fix", m.File, m.Line), - Fix: "OpenEmbedded-Core had OpenSSH 10.6p1 when this was written (2026-11-05). Add upstream commit 4353fdc43 as a patch in an openssh .bbappend (SRC_URI += \"file://avoid-password-authn-bypass.patch\"), or set PasswordAuthentication no."}) + Fix: "OpenEmbedded-Core had OpenSSH 10.6p1 when this was written (2026-11-05). Add upstream commit 4353fdc43 as a patch in an openssh .bbappend for your release's OpenSSH version, or set PasswordAuthentication no."} + s.yoctoFix(&g) + out = append(out, g) } - s.yoctoSSH, s.yoctoMusl = nil, nil + s.yoctoSSH, s.yoctoMusl, s.yoctoPatched = nil, nil, nil return out } -var _ = yoctoSSHGuard +// yoctoFix plans a version-scoped bbappend with the patch in the layer that +// holds the image recipe. The OpenSSH version comes from an +// OpenEmbedded-Core in the repository, else from the layer's single +// LAYERSERIES_COMPAT release. +func (s *scanner) yoctoFix(f *Finding) { + layer := "" + for d := path.Dir(f.File); d != "." && d != "/" && d != ""; d = path.Dir(d) { + if _, ok := s.readRel(path.Join(d, "conf", "layer.conf")); ok { + layer = d + break + } + } + if layer == "" { + f.Fix += " (the recipe is not inside a layer with conf/layer.conf)" + return + } + ver, why := s.yoctoVersion(layer) + if ver == "" { + f.Fix += " (" + why + ")" + return + } + dir := path.Join(layer, "recipes-connectivity", "openssh") + bb := path.Join(dir, "openssh_"+ver+".bbappend") + if _, ok := s.readRel(bb); ok { + f.Fix += " (" + bb + " exists; add the patch to it by hand)" + return + } + f.Fixable = true + f.newFiles = map[string][]byte{ + bb: []byte("# *sshole: OpenSSH password authentication bypass on musl, fixed upstream in\n" + + "# 10.6p2 (commit 4353fdc43). Scoped to " + ver + ": remove it when openssh moves on.\n" + + "FILESEXTRAPATHS:prepend := \"${THISDIR}/files:\"\n" + + "SRC_URI += \"file://" + PatchName + "\"\n"), + path.Join(dir, "files", PatchName): upstreamPatch, + } + f.Props["fix_summary"] = fmt.Sprintf("Adds %s with upstream commit 4353fdc43 (the *sshole fix) for openssh %s. It is scoped to that version, so BitBake reports it when openssh moves on and it can be removed.", bb, ver) +} + +func (s *scanner) yoctoVersion(layer string) (string, string) { + // An OpenEmbedded-Core checked into the repository decides. + var found []string + _ = walkRepo(s.root, func(rel string) { + if m := ocoreRecipe.FindStringSubmatch(rel); m != nil { + found = append(found, m[2]) + } + }) + if len(found) == 1 { + return checkYoctoVersion(found[0]) + } + b, _ := s.readRel(path.Join(layer, "conf", "layer.conf")) + m := yoctoSeriesRE.FindSubmatch(b) + if m == nil { + return "", "the layer does not name its OpenEmbedded release (LAYERSERIES_COMPAT), so the openssh version is not known" + } + vers := map[string]bool{} + for _, series := range strings.Fields(string(m[1])) { + v, ok := yoctoSeries[series] + if !ok { + return "", "the layer supports " + series + ", whose openssh version is not known here" + } + vers[v] = true + } + if len(vers) != 1 { + return "", "the layer supports releases with different openssh versions; add a bbappend for each by hand" + } + for v := range vers { + return checkYoctoVersion(v) + } + return "", "no release" +} + +func checkYoctoVersion(v string) (string, string) { + for _, ok := range buildrootVersions { + if ok == v { + return v, "" + } + } + switch v { + case "9.5p1", "10.3p1": + return v, "" + } + return "", "openssh " + v + " is outside the versions the upstream patch applies to (8.9p1 to 10.6p1)" +} + +// walkRepo calls fn for every regular file's repository-relative path, +// skipping dependency directories, up to maxFiles. +func walkRepo(root string, fn func(string)) error { + n := 0 + return fs.WalkDir(os.DirFS(root), ".", func(p string, d fs.DirEntry, err error) error { + if err != nil { + return nil + } + if d.IsDir() { + if p != "." && skipDirs[d.Name()] { + return fs.SkipDir + } + return nil + } + if n++; n > maxFiles { + return fs.SkipAll + } + fn(p) + return nil + }) +} diff --git a/detectors/sshole/internal/repo/more_test.go b/detectors/sshole/internal/repo/more_test.go index b097274..b9f203a 100644 --- a/detectors/sshole/internal/repo/more_test.go +++ b/detectors/sshole/internal/repo/more_test.go @@ -6,6 +6,8 @@ import ( "path/filepath" "strings" "testing" + + "github.com/DefectDojo/earlylight/internal/refs" ) // fixAll plans and applies every fixable finding, rescanning after each, @@ -164,3 +166,120 @@ func TestBuildSystems(t *testing.T) { t.Errorf("glibc Yocto reported: %v", got) } } + +func TestBuildrootPatchFix(t *testing.T) { + root := t.TempDir() + write(t, root, "br2-acme/external.desc", "name: ACME\ndesc: acme boards\n") + write(t, root, "br2-acme/configs/acme_defconfig", "BR2_aarch64=y\nBR2_TOOLCHAIN_BUILDROOT_MUSL=y\nBR2_PACKAGE_OPENSSH=y\n") + write(t, root, "br2-beta/external.desc", "name: BETA\n") + write(t, root, "br2-beta/configs/beta_defconfig", "BR2_TOOLCHAIN_BUILDROOT_MUSL=y\nBR2_GLOBAL_PATCH_DIR=\"$(BR2_EXTERNAL_BETA_PATH)/board/patches\"\nBR2_PACKAGE_OPENSSH=y\n") + write(t, root, "plain_defconfig", "BR2_TOOLCHAIN_BUILDROOT_MUSL=y\nBR2_PACKAGE_OPENSSH=y\n") + left := fixAll(t, root) + if len(left) != 1 || left[0].File != "plain_defconfig" || left[0].Fixable { + t.Fatalf("left %+v", left) + } + if s := read(t, root, "br2-acme/configs/acme_defconfig"); !strings.HasSuffix(s, "BR2_PACKAGE_OPENSSH=y\nBR2_GLOBAL_PATCH_DIR=\"$(BR2_EXTERNAL_ACME_PATH)/patches\"\n") { + t.Fatalf("%q", s) + } + for _, p := range []string{"br2-acme/patches/openssh/9.9p2/" + PatchName, "br2-acme/patches/openssh/10.6p1/" + PatchName, "br2-beta/board/patches/openssh/10.2p1/" + PatchName} { + if !strings.Contains(read(t, root, p), "MIN_PASSWORD_HASH_LEN") { + t.Errorf("%s lacks the patch", p) + } + } + if _, err := os.Stat(filepath.Join(root, "br2-acme/patches/openssh/10.6p2")); err == nil { + t.Error("patched a fixed version") + } +} + +func TestYoctoPatchFix(t *testing.T) { + root := t.TempDir() + write(t, root, "meta-acme/conf/layer.conf", "BBFILE_COLLECTIONS += \"acme\"\nLAYERSERIES_COMPAT_acme = \"scarthgap\"\n") + write(t, root, "meta-acme/conf/distro/acme.conf", "TCLIBC = \"musl\"\n") + write(t, root, "meta-acme/recipes-core/images/acme-image.bb", "IMAGE_INSTALL:append = \" openssh\"\n") + write(t, root, "meta-two/conf/layer.conf", "LAYERSERIES_COMPAT_two = \"scarthgap walnascar\"\n") + write(t, root, "meta-two/recipes-core/images/two-image.bb", "IMAGE_FEATURES += \"ssh-server-openssh\"\n") + fs := scan(t, root, Options{}) + var acme, two *Finding + for i := range fs { + switch fs[i].File { + case "meta-acme/recipes-core/images/acme-image.bb": + acme = &fs[i] + case "meta-two/recipes-core/images/two-image.bb": + two = &fs[i] + } + } + if acme == nil || !acme.Fixable || two == nil || two.Fixable || !strings.Contains(two.Fix, "different openssh versions") { + t.Fatalf("%+v\n%+v", acme, two) + } + ch, _, err := Plan(context.Background(), root, *acme, Options{}) + if err != nil { + t.Fatal(err) + } + if err := Apply(root, ch); err != nil { + t.Fatal(err) + } + bb := read(t, root, "meta-acme/recipes-connectivity/openssh/openssh_9.6p1.bbappend") + if !strings.Contains(bb, "SRC_URI += \"file://"+PatchName+"\"") || !strings.Contains(read(t, root, "meta-acme/recipes-connectivity/openssh/files/"+PatchName), "MIN_PASSWORD_HASH_LEN") { + t.Fatalf("%s", bb) + } + // With the patch in a bbappend, the tree is no longer reported. + for _, f := range scan(t, root, Options{}) { + if f.Rule == RuleBuild && f.File == acme.File { + t.Errorf("still reported: %+v", f) + } + } +} + +func TestOverrideFor(t *testing.T) { + root := t.TempDir() + write(t, root, "compose.yaml", "services:\n a:\n image: x/a:1\n command: /usr/sbin/sshd -D -o 'PasswordAuthentication yes'\n b:\n image: x/b:1\n entrypoint: [\"/start.sh\"]\n c:\n image: x/c:1\n") + write(t, root, "k8s.yaml", "apiVersion: v1\nkind: Pod\nspec:\n containers:\n - name: s\n image: x/d:1\n args: [\"-D\", \"-e\"]\n---\napiVersion: v1\nkind: Pod\nspec:\n containers:\n - name: t\n image: x/e:1\n command: [\"/usr/sbin/sshd\"]\n") + rs, _, err := refs.Scan(root, refs.Options{}) + if err != nil { + t.Fatal(err) + } + got := map[string]string{} + for _, r := range rs { + o := OverrideFor(root, r, nil) + got[r.Image] = strings.Join(o.Apply([]string{"/init"}, []string{"sshd"}), " ") + } + want := map[string]string{ + "x/a:1": "/init /usr/sbin/sshd -D -o PasswordAuthentication yes", + "x/b:1": "/start.sh", + "x/c:1": "/init sshd", + "x/d:1": "/init -D -e", + "x/e:1": "/usr/sbin/sshd", + } + for k, v := range want { + if got[k] != v { + t.Errorf("%s: %q, want %q", k, got[k], v) + } + } +} + +func TestAlpineRetag(t *testing.T) { + root := t.TempDir() + write(t, root, "Dockerfile", "FROM python:3.9-alpine3.14\nRUN apk add openssh\n") + opts := Options{ + Tags: func(context.Context, string) ([]string, error) { + return []string{"3.9-alpine3.13", "3.9-alpine3.14", "3.9-alpine3.15", "3.9-alpine3.16", "3.9-alpine3.17", "3.10-alpine3.16", "3.9-slim"}, nil + }, + Base: func(_ context.Context, img string) (bool, string, error) { + b := img[strings.LastIndex(img, "alpine")+len("alpine"):] + return true, b, nil + }, + } + fs := scan(t, root, opts) + if len(fs) != 1 || !fs[0].Fixable || fs[0].Props["upgrade"] != "python:3.9-alpine3.16" { + t.Fatalf("%+v", fs) + } + ch, _, err := Plan(context.Background(), root, fs[0], opts) + if err != nil || ch.Edits[0].New != "FROM python:3.9-alpine3.16" { + t.Fatalf("%v %+v", err, ch) + } + // A candidate whose image is not the release its tag says is skipped. + opts.Base = func(_ context.Context, img string) (bool, string, error) { return true, "3.14", nil } + if fs := scan(t, root, opts); fs[0].Fixable { + t.Fatalf("trusted a tag: %+v", fs) + } +} diff --git a/detectors/sshole/internal/repo/override.go b/detectors/sshole/internal/repo/override.go new file mode 100644 index 0000000..2fdf856 --- /dev/null +++ b/detectors/sshole/internal/repo/override.go @@ -0,0 +1,141 @@ +package repo + +import ( + "strings" + + "gopkg.in/yaml.v3" + + "github.com/DefectDojo/earlylight/internal/refs" +) + +// Override is a deployment's replacement for an image's Entrypoint and Cmd: +// Compose entrypoint and command, Kubernetes command and args. A nil field +// keeps the image's own; ClearCmd drops the image's Cmd. +type Override struct { + Entrypoint, Cmd *[]string + ClearCmd bool +} + +// Apply returns the command the container runs. +func (o *Override) Apply(entrypoint, cmd []string) []string { + if o == nil { + return append(append([]string(nil), entrypoint...), cmd...) + } + if o.Entrypoint != nil { + entrypoint = *o.Entrypoint + if o.ClearCmd { + cmd = nil + } + } + if o.Cmd != nil { + cmd = *o.Cmd + } + return append(append([]string(nil), entrypoint...), cmd...) +} + +// OverrideFor reads the command a Compose service or Kubernetes container +// sets next to an image reference. nil when it sets none or the file is not +// one of those. +func OverrideFor(root string, r refs.Ref, overlay map[string][]byte) *Override { + if r.Kind != refs.KindCompose && r.Kind != refs.KindKubernetes { + return nil + } + b, ok := overlay[r.File] + if !ok { + var err error + if b, err = readFile(root, r.File); err != nil { + return nil + } + } + dec := yaml.NewDecoder(strings.NewReader(string(b))) + for i := 0; i < 1000; i++ { + var doc yaml.Node + if err := dec.Decode(&doc); err != nil { + return nil + } + if m := findImageMapping(&doc, r.Line, 0); m != nil { + return overrideOf(m, r.Kind) + } + } + return nil +} + +// findImageMapping finds the mapping whose "image" value sits on line. +func findImageMapping(n *yaml.Node, line, depth int) *yaml.Node { + if n == nil || depth > 64 { + return nil + } + if n.Kind == yaml.MappingNode { + for i := 0; i+1 < len(n.Content); i += 2 { + if n.Content[i].Value == "image" && n.Content[i+1].Line == line { + return n + } + } + } + for _, c := range n.Content { + if m := findImageMapping(c, line, depth+1); m != nil { + return m + } + } + return nil +} + +func overrideOf(m *yaml.Node, kind refs.Kind) *Override { + get := func(key string) (*[]string, bool) { + for i := 0; i+1 < len(m.Content); i += 2 { + if m.Content[i].Value != key { + continue + } + v := m.Content[i+1] + var out []string + switch v.Kind { + case yaml.SequenceNode: + for _, c := range v.Content { + out = append(out, c.Value) + } + case yaml.ScalarNode: + if v.Tag == "!!null" { + return nil, false + } + out = shellWords(v.Value) + default: + return nil, false + } + return &out, true + } + return nil, false + } + o := &Override{} + set := false + switch kind { + case refs.KindCompose: + if e, ok := get("entrypoint"); ok { + o.Entrypoint, o.ClearCmd, set = e, true, true + } + if c, ok := get("command"); ok { + o.Cmd, set = c, true + } + case refs.KindKubernetes: + if e, ok := get("command"); ok { + o.Entrypoint, o.ClearCmd, set = e, true, true + } + if a, ok := get("args"); ok { + o.Cmd, set = a, true + } + } + if !set { + return nil + } + return o +} + +// shellWords splits a command string the way Compose does (shell quoting). +func shellWords(s string) []string { + var out []string + for _, c := range splitShell(s) { + for _, w := range c.words { + out = append(out, w.val) + } + } + return out +} diff --git a/detectors/sshole/internal/repo/plan.go b/detectors/sshole/internal/repo/plan.go index 97f0983..02d947b 100644 --- a/detectors/sshole/internal/repo/plan.go +++ b/detectors/sshole/internal/repo/plan.go @@ -5,7 +5,9 @@ import ( "errors" "fmt" "os" + "path" "path/filepath" + "sort" "strings" "unicode" @@ -17,6 +19,9 @@ type Change struct { File string Edits []Edit Summary string + // NewFiles are files the change adds, by repository-relative path. + // Apply refuses to replace a file that exists with other content. + NewFiles map[string][]byte } // Declined is a plan that proposes no change, with the reason. @@ -38,9 +43,17 @@ func IsDeclined(err error) (*Declined, bool) { // in memory and accepts the edit only when that finding is gone and nothing // new appeared. already is true when the finding is no longer there. func Plan(ctx context.Context, root string, f Finding, opts Options) (*Change, bool, error) { - if !f.Fixable || f.edit == nil { + if !f.Fixable || f.edit == nil && len(f.newFiles) == 0 { return nil, false, &Declined{Reason: f.Fix} } + for p, data := range f.newFiles { + if cur, err := readFile(root, p); err == nil && string(cur) != string(data) { + return nil, false, &Declined{Reason: fmt.Sprintf("%s already exists with other content; add the fix by hand", p)} + } + } + if f.edit == nil { + return planNewFiles(ctx, root, f, opts) + } b, err := readFile(root, f.File) if err != nil { return nil, false, err @@ -72,7 +85,7 @@ func Plan(ctx context.Context, root string, f Finding, opts Options) (*Change, b e = *match } newLine := line[:e.Col] + e.New + line[e.Col+len(e.Old):] - ch := &Change{File: f.File, Edits: []Edit{{Line: e.Line, Col: e.Col, Old: line, New: newLine}}, Summary: summary(f)} + ch := &Change{File: f.File, Edits: []Edit{{Line: e.Line, Col: e.Col, Old: line, New: newLine}}, Summary: summary(f), NewFiles: f.newFiles} // Rescan the edited file in memory. edited := append([]string{}, lines...) @@ -83,6 +96,9 @@ func Plan(ctx context.Context, root string, f Finding, opts Options) (*Change, b edited[e.Line-1] = newLine + cr o := opts o.Overlay = map[string][]byte{f.File: []byte(strings.Join(edited, "\n"))} + for p, data := range f.newFiles { + o.Overlay[p] = data + } before, err := scanOne(ctx, root, f.File, opts, nil) if err != nil { return nil, false, err @@ -100,6 +116,28 @@ func Plan(ctx context.Context, root string, f Finding, opts Options) (*Change, b return ch, false, nil } +// planNewFiles plans a fix that only adds files, checked by rescanning the +// finding's file with the files in place. +func planNewFiles(ctx context.Context, root string, f Finding, opts Options) (*Change, bool, error) { + o := opts + o.Overlay = map[string][]byte{} + for p, data := range f.newFiles { + o.Overlay[p] = data + } + before, err := scanOne(ctx, root, f.File, opts, nil) + if err != nil { + return nil, false, err + } + after, err := scanOne(ctx, root, f.File, o, nil) + if err != nil { + return nil, false, err + } + if count(after, f.Rule, f.Line) >= count(before, f.Rule, f.Line) { + return nil, false, &Declined{Reason: "the added files did not clear the finding; add the fix by hand"} + } + return &Change{File: f.File, Summary: summary(f), NewFiles: f.newFiles}, false, nil +} + func scanOne(ctx context.Context, root, file string, opts Options, data []byte) ([]Finding, error) { s := &scanner{ctx: ctx, root: root, opts: opts, bases: map[string]baseInfo{}} if data == nil { @@ -118,6 +156,21 @@ func scanOne(ctx context.Context, root, file string, opts Options, data []byte) case "sshd_config": return s.sshdConfig(file, string(data)), nil case "build": + // A Yocto finding needs the whole tree (TCLIBC and bbappends live + // in other files): rescan it, keeping this file's findings. + if s.yoctoNeedsTree(file) { + res, err := Scan(ctx, root, opts) + if err != nil { + return nil, err + } + var out []Finding + for _, f := range res.Findings { + if f.File == file { + out = append(out, f) + } + } + return out, nil + } s.build(file, string(data)) return s.finishBuild(), nil } @@ -141,7 +194,9 @@ func summary(f Finding) string { case RuleStar: return "Set the password field to \"*NP*\" instead of \"*\", which keeps key logins and matches no password" case RuleEOL: - return fmt.Sprintf("Moves the base image to %s, the nearest Alpine release with a fixed OpenSSH package. This is an Alpine release upgrade: review it and run your tests before you merge", f.Props["upgrade"]) + return fmt.Sprintf("Moves the base image to %s, on the nearest Alpine release with a fixed OpenSSH package. This is an Alpine release upgrade: review it and run your tests before you merge", f.Props["upgrade"]) + case RuleBuild: + return f.Props["fix_summary"] case RuleAnsible: return "Sets the Ansible apk task to state: latest, so every run installs the fixed OpenSSH package from the host's Alpine repositories" } @@ -150,7 +205,15 @@ func summary(f Finding) string { // Apply writes a change after checking each edited line still reads as // planned. It keeps line endings and the file mode, and writes atomically. +// New files are written first; one that exists already must hold the same +// content. func Apply(root string, ch *Change) error { + if err := writeNewFiles(root, ch.NewFiles); err != nil { + return err + } + if len(ch.Edits) == 0 { + return nil + } p, err := refs.SafePath(root, ch.File) if err != nil { return err @@ -256,3 +319,69 @@ func Find(ctx context.Context, root, file string, line int, rule, message string // back on the next scan. return &at[0], false, nil } + +func writeNewFiles(root string, files map[string][]byte) error { + paths := make([]string, 0, len(files)) + for p := range files { + paths = append(paths, p) + } + sort.Strings(paths) + for _, rel := range paths { + data := files[rel] + // Create the directories one by one, refusing any symbolic link on + // the way, then check the whole path again. + if err := mkdirsNoLinks(root, path.Dir(path.Clean(rel))); err != nil { + return err + } + p, err := refs.SafePath(root, rel) + if err != nil { + return err + } + if fi, err := os.Lstat(p); err == nil { + cur, rerr := os.ReadFile(p) + if !fi.Mode().IsRegular() || rerr != nil || string(cur) != string(data) { + return fmt.Errorf("%s exists with other content", rel) + } + continue + } + f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) + if err != nil { + return err + } + if _, err := f.Write(data); err != nil { + f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + } + return nil +} + +func mkdirsNoLinks(root, dir string) error { + if dir == "." || dir == "" { + return nil + } + if path.IsAbs(dir) || dir == ".." || strings.HasPrefix(dir, "../") { + return fmt.Errorf("%q leaves the repository", dir) + } + cur := root + for _, e := range strings.Split(dir, "/") { + cur = filepath.Join(cur, e) + fi, err := os.Lstat(cur) + switch { + case errors.Is(err, os.ErrNotExist): + if err := os.Mkdir(cur, 0o755); err != nil { + return err + } + case err != nil: + return err + case fi.Mode()&os.ModeSymlink != 0: + return fmt.Errorf("%s passes through a symbolic link", dir) + case !fi.IsDir(): + return fmt.Errorf("%s is not a directory", cur) + } + } + return nil +} diff --git a/detectors/sshole/internal/repo/repo.go b/detectors/sshole/internal/repo/repo.go index 7d25c51..c1b0420 100644 --- a/detectors/sshole/internal/repo/repo.go +++ b/detectors/sshole/internal/repo/repo.go @@ -60,6 +60,9 @@ type Finding struct { Props map[string]string `json:"props,omitempty"` // edit is the planned replacement, kept for Plan. edit *Edit + // newFiles are files the fix adds (a patch, a bbappend), by + // repository-relative path. + newFiles map[string][]byte } // Skip is a file that was not read, and why. @@ -87,6 +90,10 @@ type Options struct { // Files, when set, limits the scan to these repository-relative paths // (a pull request's changed files). Files []string + // Tags lists an image repository's tags, for moving an end-of-life + // Alpine-based image to a tag on a fixed Alpine release. nil: no + // registry lookups. + Tags func(ctx context.Context, image string) ([]string, error) } const ( @@ -264,8 +271,9 @@ type scanner struct { // from is the current stage's FROM instruction. from fromInfo // Yocto evidence, joined across files at the end. - yoctoMusl []Finding - yoctoSSH []Finding + yoctoMusl []Finding + yoctoSSH []Finding + yoctoPatched []string } // varDef is an ARG or ENV value and where it is written. @@ -890,6 +898,15 @@ func (s *scanner) judgeSpec(rel string, at specAt, pkg, op, ver string, b baseIn props["upgrade"] = up f.Fixable = true f.edit = &Edit{Line: s.from.line, Col: s.from.col, Old: s.from.tagText, New: up} + } else if s.from.line > 0 && s.from.image == image { + // Another image built on Alpine ("python:3.9-alpine3.14"): a + // tag of it on the nearest fixed Alpine release, when the + // registry has one and it is that release. + if up := s.alpineRetag(image); up != "" { + props["upgrade"] = up + f.Fixable = true + f.edit = &Edit{Line: s.from.line, Col: s.from.col, Old: s.from.tagText, New: up} + } } return f, true } @@ -1217,3 +1234,62 @@ func (s *scanner) ansible(rel string, lines []string) []Finding { } return out } + +var alpineSuffixRE = regexp.MustCompile(`^(.*alpine)(\d+)\.(\d+)$`) + +// alpineRetag finds a tag of image on the nearest Alpine release with a +// fixed OpenSSH package: same tag with only the Alpine release changed, +// confirmed by reading the candidate's /etc/alpine-release. +func (s *scanner) alpineRetag(image string) string { + if s.opts.Tags == nil || s.opts.Base == nil || strings.Contains(image, "@") { + return "" + } + i := strings.LastIndexByte(image, ':') + if i < 0 || i < strings.LastIndexByte(image, '/') { + return "" + } + name, tag := image[:i], image[i+1:] + m := alpineSuffixRE.FindStringSubmatch(tag) + if m == nil { + return "" + } + tags, err := s.opts.Tags(s.ctx, name) + if err != nil { + return "" + } + type cand struct { + tag string + maj, minor int + } + var cands []cand + for _, t := range tags { + cm := alpineSuffixRE.FindStringSubmatch(t) + if cm == nil || cm[1] != m[1] { + continue + } + branch := cm[2] + "." + cm[3] + if _, ok := assess.AlpineFixedFor(branch); !ok { + continue + } + maj, _ := strconv.Atoi(cm[2]) + min, _ := strconv.Atoi(cm[3]) + cands = append(cands, cand{t, maj, min}) + } + sort.Slice(cands, func(a, b int) bool { + if cands[a].maj != cands[b].maj { + return cands[a].maj < cands[b].maj + } + return cands[a].minor < cands[b].minor + }) + for i, c := range cands { + if i >= 3 { + break + } + img := name + ":" + c.tag + alpine, branch, err := s.opts.Base(s.ctx, img) + if err == nil && alpine && branch == fmt.Sprintf("%d.%d", c.maj, c.minor) { + return img + } + } + return "" +} diff --git a/detectors/sshole/repo.go b/detectors/sshole/repo.go index 3821398..39e895b 100644 --- a/detectors/sshole/repo.go +++ b/detectors/sshole/repo.go @@ -6,13 +6,17 @@ import ( "io" "strings" "sync" + "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/sshole/internal/repo" "github.com/DefectDojo/earlylight/internal/engine" "github.com/DefectDojo/earlylight/internal/image" "github.com/DefectDojo/earlylight/internal/netguard" + "github.com/DefectDojo/earlylight/internal/refs" "github.com/DefectDojo/earlylight/internal/source" ) @@ -39,6 +43,8 @@ func repoKinds() []engine.Kind { Description: "A Dockerfile, script or Ansible or cloud-init task that sets an account's password field to \"*\" (usermod -p, chpasswd -e, sed on /etc/shadow). On an OpenSSH server on musl without the fix, a crafted password logs in to that account. \"*NP*\" keeps key logins and matches no password on any build."}, {ID: KindPassword, Title: "PasswordAuthentication turned on", Level: "note", Description: "Something turns PasswordAuthentication on. With an OpenSSH server on musl that lacks the fix, every account with the password field \"*\" is exposed."}, + {ID: KindImage, Title: "Image the source tree uses runs an OpenSSH server exposed to *sshole", Level: "error", SecuritySeverity: "9.8", CWEs: cwe, + Description: "An image a Dockerfile, Compose file, Kubernetes manifest, Helm values or CI file names holds an OpenSSH server on musl without the fix, judged as scan image does, with the command the file sets for it."}, {ID: KindNotChecked, Title: "OpenSSH install not checked for the *sshole fix", Level: "note", Description: "An apk add of an OpenSSH server whose base image could not be identified, or a file that could not be read. It is not known to be safe."}, } @@ -47,11 +53,14 @@ func repoKinds() []engine.Kind { // 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{Base: baseResolver(o)}) + res, err := repo.Scan(ctx, dir, repoOptions(o)) if err != nil { t.Error = err.Error() return t } + if !o.Offline { + d.scanImages(dir, o, 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" @@ -84,6 +93,128 @@ func repoFinding(f repo.Finding) engine.Finding { return out } +func repoOptions(o engine.Options) repo.Options { + ro := repo.Options{Base: baseResolver(o)} + if !o.Offline { + ro.Tags = tagLister(o) + } + return ro +} + +// KindImage: an image the source tree builds on or deploys holds an +// OpenSSH server exposed to *sshole. +const KindImage = "image" + +// maxRepoImages bounds the images one source-tree scan pulls. +const maxRepoImages = 20 + +// scanImages pulls the images the tree references (Dockerfile FROM, +// Compose, Kubernetes, Helm values, CI) through the guarded transport and +// judges them like scan image does, with the command a Compose service or +// Kubernetes container sets in place of the image's own. +func (d *Detector) scanImages(dir string, o engine.Options, t *engine.Target) { + rs, _, err := refs.Scan(dir, refs.Options{}) + if err != nil { + t.Problems = append(t.Problems, "image references: "+err.Error()) + return + } + type key struct{ image, cmd string } + seen := map[key]bool{} + pulled := 0 + for _, r := range rs { + if r.Image == "" || r.Image == "scratch" || strings.Contains(r.Image, "$") { + continue + } + ov := repo.OverrideFor(dir, r, nil) + k := key{r.Image, fmt.Sprint(ov)} + if ov != nil && ov.Entrypoint != nil { + k.cmd = strings.Join(*ov.Entrypoint, " ") + } + if ov != nil && ov.Cmd != nil { + k.cmd += "|" + strings.Join(*ov.Cmd, " ") + } + if seen[k] { + continue + } + seen[k] = true + if pulled >= maxRepoImages { + t.Skipped = append(t.Skipped, source.Skip{Path: fmt.Sprintf("%s:%d", r.File, r.Line), Reason: fmt.Sprintf("image %s not pulled: this scan already pulled %d images", r.Image, maxRepoImages)}) + continue + } + pulled++ + eo := engine.Options{Platform: o.Platform, MaxFileSize: o.MaxFileSize, Guarded: true, PublicOnly: o.PublicOnly} + if ov != nil { + eo.Override = &engine.CommandOverride{Entrypoint: ov.Entrypoint, Cmd: ov.Cmd, ClearCmd: ov.ClearCmd} + } + it := engine.ScanImage([]engine.Detector{d}, r.Image, eo) + if it.Error != "" { + t.Findings = append(t.Findings, engine.Finding{Kind: KindNotChecked, Path: r.File, Line: r.Line, Verdict: engine.Unknown, + Reason: "the image could not be pulled", Message: fmt.Sprintf("image %s could not be checked for *sshole: %s", r.Image, it.Error), Method: "registry", + Facts: map[string]string{"image": r.Image}}) + continue + } + for _, f := range it.Findings { + if f.Verdict.Cleared() { + continue + } + g := f + g.Kind, g.Path, g.Line, g.Method = KindImage, r.File, r.Line, "registry" + if g.Facts == nil { + g.Facts = map[string]string{} + } + g.Facts["image"], g.Facts["server"] = r.Image, f.Path + via := "" + if ov != nil { + via = " (with the command this file sets)" + g.Facts["command_override"] = "yes" + } + g.Message = fmt.Sprintf("image %s%s: %s: %s", r.Image, via, f.Path, f.Message) + g.Fix = f.Fix + " Use a release of " + r.Image + " built with the fix, or rebuild it; then redeploy." + if f.Kind == KindExposed && g.Severity == "" { + g.Severity = "critical" + } + t.Findings = append(t.Findings, g) + } + } +} + +// 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 + } +} + // baseResolver reads /etc/alpine-release from the images a tree builds on, // once each, unless the run is offline. func baseResolver(o engine.Options) func(context.Context, string) (bool, string, error) { @@ -160,7 +291,7 @@ func registryRef(ref string) error { // "*" password fields to "*NP*". Each edit is rescanned in memory first. func (d *Detector) Fix(ctx context.Context, dirs []string, o engine.Options, stdout, stderr io.Writer) int { code := 0 - opts := repo.Options{Base: baseResolver(o)} + opts := repoOptions(o) for _, dir := range dirs { res, err := repo.Scan(ctx, dir, opts) if err != nil { diff --git a/internal/engine/run.go b/internal/engine/run.go index f144a63..02d6e3b 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -14,6 +14,7 @@ import ( "github.com/DefectDojo/earlylight/internal/archive" "github.com/DefectDojo/earlylight/internal/image" + "github.com/DefectDojo/earlylight/internal/netguard" "github.com/DefectDojo/earlylight/internal/source" ) @@ -83,6 +84,38 @@ type Options struct { PublicOnly bool // contact only public registry addresses Platforms []string // the platforms that are built; empty means every platform DryRun bool // fix: print changes without writing them + // Override replaces the image's Entrypoint or Cmd for detectors that + // read the container's command (a Compose or Kubernetes setting). + Override *CommandOverride + // Guarded opens registry images through the address-checking + // transport (image references from a source tree), honouring + // PublicOnly, and refuses local archives. + Guarded bool +} + +// CommandOverride is a deployment's replacement for an image's Entrypoint +// and Cmd. A nil field keeps the image's own; Compose's entrypoint without +// command also clears Cmd (ClearCmd). +type CommandOverride struct { + Entrypoint, Cmd *[]string + ClearCmd bool +} + +// Apply returns the command the container runs. +func (o *CommandOverride) Apply(entrypoint, cmd []string) []string { + if o == nil { + return append(append([]string(nil), entrypoint...), cmd...) + } + if o.Entrypoint != nil { + entrypoint = *o.Entrypoint + if o.ClearCmd { + cmd = nil + } + } + if o.Cmd != nil { + cmd = *o.Cmd + } + return append(append([]string(nil), entrypoint...), cmd...) } // targetCtx is the TargetContext the engine builds while it walks a target. @@ -359,7 +392,10 @@ func ScanImage(dets []Detector, ref string, opts Options) *Target { t := &Target{Name: ref, Type: Image} w := newWalker(dets, Image, t, opts) var rc io.ReadCloser - if p, ok := strings.CutPrefix(ref, "rootfs:"); ok { + if p, ok := strings.CutPrefix(ref, "rootfs:"); ok && opts.Guarded { + t.Error = fmt.Sprintf("%q: only registry references are opened for a source tree", "rootfs:"+p) + return t + } else if ok { if p == "-" { rc = io.NopCloser(os.Stdin) } else { @@ -371,12 +407,19 @@ func ScanImage(dets []Detector, ref string, opts Options) *Target { rc = f } } else { - o, err := image.Open(ref, opts.Platform) + open := image.Open + if opts.Guarded { + open = func(ref, platform string) (*image.Opened, error) { + return image.OpenRegistry(ref, platform, netguard.Transport(opts.PublicOnly)) + } + } + o, err := open(ref, opts.Platform) if err != nil { t.Error = err.Error() return t } - rc, t.Digest, t.Platform, w.ctx.env, w.ctx.cmd = o.FS, o.Digest, o.Platform, o.Env, o.Command + rc, t.Digest, t.Platform, w.ctx.env = o.FS, o.Digest, o.Platform, o.Env + w.ctx.cmd = opts.Override.Apply(o.Entrypoint, o.Cmd) } defer rc.Close() so := w.sourceOptions(opts) diff --git a/internal/image/image.go b/internal/image/image.go index ef9b360..652d60b 100644 --- a/internal/image/image.go +++ b/internal/image/image.go @@ -28,6 +28,8 @@ type Opened struct { // Command is what the container runs: the configuration's Entrypoint // followed by its Cmd. Command []string + // Entrypoint and Cmd are the configuration's own. + Entrypoint, Cmd []string } // Open resolves ref and returns the image's flattened filesystem. @@ -51,6 +53,7 @@ func opened(img v1.Image) (*Opened, error) { if cf, err := img.ConfigFile(); err == nil && cf != nil { 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 if cf.OS != "" { o.Platform = cf.OS + "/" + cf.Architecture if cf.Variant != "" { From 97dc16fad71aee53117096808593e551f60b8c6d Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Thu, 5 Nov 2026 21:15:28 -0700 Subject: [PATCH 8/8] sshole: export WriteNewFiles Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/internal/repo/plan.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/detectors/sshole/internal/repo/plan.go b/detectors/sshole/internal/repo/plan.go index 02d947b..a1671da 100644 --- a/detectors/sshole/internal/repo/plan.go +++ b/detectors/sshole/internal/repo/plan.go @@ -208,7 +208,7 @@ func summary(f Finding) string { // New files are written first; one that exists already must hold the same // content. func Apply(root string, ch *Change) error { - if err := writeNewFiles(root, ch.NewFiles); err != nil { + if err := WriteNewFiles(root, ch.NewFiles); err != nil { return err } if len(ch.Edits) == 0 { @@ -320,7 +320,9 @@ func Find(ctx context.Context, root, file string, line int, rule, message string return &at[0], false, nil } -func writeNewFiles(root string, files map[string][]byte) error { +// WriteNewFiles writes files a change adds, refusing symbolic links on +// the way and any file that exists with other content. +func WriteNewFiles(root string, files map[string][]byte) error { paths := make([]string, 0, len(files)) for p := range files { paths = append(paths, p)