GHSA-3FQG-8HPF-5682
Package cache-read path skips data-section hash verification allowing cache-poisoning
CVSS:3.1/AV:L/AC:H/PR:L/UI:R/S:C/C:H/I:H/A:H
Fuente: GitHub
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Divulgación | Publicada | GHSA-3FQG-8HPF-5682 divulgada · CVSS 7.5 (GitHub) | |
| Remediación | Parche v1.4.3 | chainguard.dev/apko · 0 d desde divulgación | |
| Remediación | Parche v0.61.0 | chainguard.dev/melange · 0 d desde divulgación | |
| Divulgación | Modificada | Última actualización del registro | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
## Summary
apko's package cache-read path (`cachedPackage`) installs a package's data section from disk without verifying its SHA-256 against the trusted `.PKGINFO` `datahash`. The fix for CVE-2026-54174 / GHSA-fpg8-7664-jc5q (commit `8d34c75`) added this data-section verification only to the network fetch path (`doFetchExpandAndVerify`); the cache-read path — which is reached *before* fetch and is enabled by default — was left unprotected. An attacker with write access to the package cache can substitute arbitrary data-section contents into a genuine package, causing arbitrary attacker-controlled files to be installed into the built image.
## Root Cause
`pkg/apk/apk/package_getter.go` — `cachedPackage` (v1.2.25, lines 441–539):
- The control section IS re-hashed and compared to the signed-index Q1 checksum (`bytes.Equal(checksum, ctlHash)` at :470), which makes `pkgInfo.DataHash` a *trusted* expected value.
- But the data file is then located purely by its content-addressable filename `<DataHash>.dat.tar.gz` (:510) and `exp.PackageHash, _ = hex.DecodeString(pkgInfo.DataHash)` (:519) merely hex-decodes the *expected* hash — the on-disk bytes are never re-hashed with SHA-256 and compared.
- Contrast the fetch path `doFetchExpandAndVerify` (:298): `bytes.Equal(expectedDataHash, exp.PackageHash)`, where `exp.PackageHash` is SHA-256 over the actual bytes.
- `checkSums` is invoked only inside `ExpandApk` (`expandapk.go:505`) = fetch path; the cache path builds the installable `TarFS` directly (:533) and never calls it.
- The file actually served is `<DataHash>.dat.tar`, not the `.tar.gz`: `cachedPackage` sets `exp.TarFile` to the `.gz`-stripped name (:524) and `PackageData()` (`expandapk.go:157`) opens that uncompressed file first, decompressing the `.gz` only when it is absent. The uncompressed tar has no authenticated digest anywhere in the apk format.
## Impact
An attacker who can write to the package cache (shared/CI cache, multi-stage build, co-tenant build infra, `SharedCache`) can overwrite `<cacheDir>/<pkg>/<DataHash>.dat.tar.gz` with a malicious data tar while leaving the control file intact (so its hash still matches the signed index). The poisoned data section is installed verbatim into the built image, giving the attacker arbitrary file content at arbitrary paths in the produced rootfs. This is the same impact and threat model ("poison a cache") described by CVE-2026-54174 / GHSA-fpg8-7664-jc5q, on a code path the fix did not cover.
That primitive reaches code execution two ways, and they have different victims:
- In anything that runs the image. Replacing a binary that will be executed, a library it loads, or the entrypoint — or dropping a file something else acts on, such as `/etc/cron.d/*` or a shell profile — executes attacker code on the consumer's infrastructure whenever the image runs. `apko` itself never executes package content while building: it assembles an image, so an `apko build` alone does not run the attacker's code.
- In the build environment, under melange. melange uses apko to assemble a guest rootfs and then runs its pipelines and build steps inside it, so a poisoned data section is a poisoned build environment and the attacker's code executes *during* the build rather than after it. melange attempts to sandbox that environment, so compromising the build host itself would additionally require escaping the sandbox, which this issue does not provide. Nothing needs to be escaped to affect what melange *produces*: the attacker controls the environment in which packages are compiled and assembled, so the resulting apks can be compromised, and that propagates to everything built from them. This is why melange is affected more sharply than apko alone.
Install scripts and triggers are not reachable through this issue. `.post-install` and trigger definitions come from the control section, which *is* verified against the signed-index Q1 checksum — and the attack depends on leaving the control file intact. The capability is file content in the image, not script injection.
The tampering is persistent, and the write it needs is cheap. Cache entries are content-addressed and never expire — nothing in apko ages or evicts on-disk package files, and only `apko clean` removes them — so a single write poisons every subsequent build that resolves that package, with no further access required and no need for the write to be repeatable. The target path needs no reconnaissance on the victim host either: `datahash` is public in APKINDEX, and the layout is `<cacheDir>/<repo>/<arch>/<datahash>.dat.tar{,.gz}`. A narrow, one-shot write primitive into the cache directory is therefore sufficient to compromise every image that user builds thereafter.
This does not require co-tenancy or a shared CI cache volume. The default cache is the build user's own — an empty `--cache-dir` resolves through `os.UserCacheDir()` to `$XDG_CACHE_HOME` or `~/.cache` — so any process able to drop a file under that directory can persistently backdoor later apko builds by the same user: a malicious dependency in an unrelated tool, a build or test script, a compromised editor plugin. A shared or world-writable cache widens the set of attackers to other uids, but it is not a precondition.
## Proof of Concept
1. Victim builds an image with apko >= 1.2.9 using a cache (default) shared with the attacker (CI cache / NFS / co-tenant).
2. Attacker reads the target package's public `DataHash` from APKINDEX / `.PKGINFO`, e.g. `abc123...`.
3. Attacker crafts `malicious.dat.tar.gz`: a data section with attacker files (e.g. `/usr/bin/foo` backdoor, `/etc/cron.d/x`), each entry given a self-consistent `APK-TOOLS-CHECKSUM` PAX header (SHA-1 of its own body).
4. Attacker overwrites `<cacheDir>/<pkg>/abc123....dat.tar` with the malicious tar, which must be structurally valid. The `.ctl.tar.gz` control file is left intact so its hash still matches the signed index. (Overwriting only the `.dat.tar.gz` is inert on a warm cache, since the uncompressed sibling is preferred.)
5. Victim build runs `GetPackage` → `getPackageImpl` → `cachedPackage` (cache-hit path, before fetch).
6. `cachedPackage` re-hashes ONLY the control file (matches) → `pkgInfo.DataHash = abc123...` treated as trusted.
7. `cachedPackage` locates `abc123....dat.tar.gz`, sets `exp.PackageHash = hexDecode("abc123...")` WITHOUT recomputing SHA-256 over the on-disk bytes → returns `exp` with `err==nil`.
8. `installAPKFiles` installs the attacker's files verbatim; per-file PAX checksums are attacker-authored, never compared to a trusted reference.
9. Malicious files land in the built image, executing when the image is run (or during the build itself, if the image is a melange guest rootfs).
10. The fetch-path `bytes.Equal(expectedDataHash, exp.PackageHash)` that WOULD catch this is never reached.
## Attack Chain
1. Entry / Action: On a warm/shared cache, attacker writes malicious data bytes to `<cacheDir>/<repo>/<arch>/<DH>.dat.tar.gz`, where `<DH>` is the genuine package's `.PKGINFO` `datahash` (used as the cache filename); the control file is left untouched.
- Guard: Control section re-hashed vs signed-index Q1 checksum — `package_getter.go:470`.
- Bypass proof: The attacker never touches the control file, so it still hashes correctly; `.PKGINFO` (incl. the authentic `datahash`) is read from the genuine control section. The guard does not cover the data file at all.
2. Reachability / Action: `getPackageImpl` (`package_getter.go:200`) calls `cachedPackage` first and `return exp, nil` on cache hit, short-circuiting fetch. Cache is on by default (`pkg/build/build.go:303-304`, enabled whenever `os.UserCacheDir()` succeeds).
- Guard: intended guard = SHA-256 of data bytes vs `pkgInfo.DataHash` (as fetch path does at :298), or `checkSums`.
- Bypass proof: `cachedPackage` performs neither. :510 locates `dat` by filename; :519 only `hex.DecodeString`s the hash; :533 `tarfs.New` builds the installable FS directly. `checkSums` appears only in `ExpandApk` (`expandapk.go:505`), never invoked on the cache path.
3. Sink / Action: `exp.TarFS` (built from malicious bytes) returned via `GetPackage` and installed: `installPackage` → `installAPKFiles`/`lazilyInstallAPKFiles` (`implementation.go:1246-1257`) extract files into the image rootfs.
- Guard: per-file PAX checksum at install (`install.go` `installRegularFile` → `checksumFromHeader`).
- Bypass proof: `checksumFromHeader` reads a PAX record embedded in the attacker-authored tar; self-referential, no external trust anchor. Files land on disk.
4. Impact: Arbitrary attacker-chosen file contents installed into the built image while `.PKGINFO`/scripts still match the signed index — supply-chain compromise identical to CVE-2026-54174, reached via the cache instead of the fetch.
## Bypass Evidence
- `git show 8d34c75 -- pkg/apk/apk/package_getter.go` — the data-hash block was added to `getPackageImpl`/`doFetchExpandAndVerify` only; the `cachedPackage` hunk added ONLY the control-hash comparison.
- `git show v1.2.25:pkg/apk/apk/package_getter.go` — `cachedPackage` has `dat := ...pkgInfo.DataHash+".dat.tar.gz"` (~:510) and `exp.PackageHash, _ = hex.DecodeString(pkgInfo.DataHash)` (~:519) with no `bytes.Equal` against a computed data hash and no `checkSums` call.
- `git log v1.2.25..HEAD -- pkg/apk/apk/package_getter.go` is empty (no post-tag fix).
- Fetch path :298 (`bytes.Equal(expectedDataHash, exp.PackageHash)`) shows the exact check the cache path lacks.
- `checkSums` (`expandapk.go`) and install-time PAX checksums are self-referential (attacker authors both the header and the body), providing no protection against data-section substitution.
## Affected Versions
`chainguard.dev/apko` `>= 1.2.9` and `chainguard.dev/melange` `>= 0.50.4`. The gap was introduced by the 1.2.9 fetch-path fix that missed the cache path, and melange 0.50.4 is the release that bumped onto apko 1.2.9, so this advisory and CVE-2026-54174 together cover all versions of both packages.
Requires a disk cache, which is the default: an empty `--cache-dir` resolves through `os.UserCacheDir()` rather than disabling it.
melange consumes `chainguard.dev/apko/pkg/apk/apk` as an ordinary Go module dependency rather than a vendored copy, and is independently affected. It enables the cache unconditionally for every guest build, with no option to disable it.
Fix
Fixed in apko v1.4.3 and melange v0.61.0. Users of either should upgrade; the Mitigation section below covers what limits exposure for anyone who cannot upgrade immediately.
`cachedPackage` verifies the compressed data section against the `datahash` carried in the control section, and then inflates it into an unnamed file and serves that descriptor. The cached uncompressed tar is no longer read at all.
Two properties of the format make the shorter fixes ineffective, and both are worth stating for anyone auditing similar code. `datahash` covers the *compressed* stream, so hashing decompressed bytes against it fails on legitimate packages. And `checkSums` cannot help, for the reason given under Bypass Evidence above: the per-file PAX checksums are inside the attacker-controlled tar and are self-consistent.
Serving an unnamed file rather than the cached tar is deliberate. Verifying a file and then reading it again are two reads of a mutable object: an attacker who overwrites the verified inode in place, without renaming or unlinking it, controls every byte subsequently served. A file with no name cannot be reached to be overwritten.
The write path was also changed to install a freshly verified download over any existing cache entry rather than deferring to it, so that a rejected entry is replaced rather than re-adopted on the next fetch. That is what removes the persistence described under Impact: a poisoned entry is repaired by the first build that rejects it, instead of surviving to affect every later build.
Mitigation before upgrading
Upgrading is the fix; the following only limits exposure in the meantime.
The attack requires a write into the cache directory in use. By default that is the build user's own cache — `$XDG_CACHE_HOME` or `~/.cache` — which is normally not writable by other uids. So against a default configuration the realistic attacker is one already running as the build user, and no permission change helps against that.
What does help is denying persistence. Because cache entries are content-addressed and never expire, an entry poisoned once affects every later build that resolves that package. Pointing `--cache-dir` (melange: `--apk-cache-dir`) at a directory created fresh for each build, or clearing it between builds, means a pre-positioned entry cannot survive to be used by a later one. The cost is re-downloading packages that would otherwise have been cached.
Where a cache directory *is* deliberately shared across a trust boundary — a shared CI cache volume, or any path writable by another uid — that sharing is itself the exposure and is worth removing independently of this issue.
Limitation on non-Linux platforms
Serving the data from a file with no name relies on `O_TMPFILE`, which is Linux-only and is not implemented by every Linux filesystem. On other platforms, and on Linux filesystems without it, apko falls back to creating a temporary file and unlinking it, which briefly publishes a name.
Against a cache writer running as a different uid, build integrity still holds on that fallback: the file is owned by the build and readable only by it, and an attempt to retain a reference to it is detected and refused. Against an attacker already running as the build user it does not hold, and no file-permission arrangement can change that — such an attacker already has every privilege the build process does. Since the default cache is that user's own, this is the more likely of the two.
The fallback also admits a denial of service on those platforms: a writer able to create files in the cache directory can repeatedly trip that detection and fail affected builds.
Closing this fully means verifying the data at the point of use rather than ahead of it, which is tracked as follow-up work.
---
Reported by zx (Jace) — GitHub: @manus-use
Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Desglose de métricas
Rangos afectados
Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
gochainguard.dev/apko |
Corregida | v1.4.3 | 0 d | v1.5.0 no afectada |
gochainguard.dev/melange |
Corregida | v0.61.0 | 0 d | v0.64.1 no afectada |
v0.61.0v1.4.3Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/chainguard-dev/apko/security/advisories/GHSA-3fqg-8hpf-5682Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
