hostedimage: close the payload scan's gaps (allow, scriptlets, nesting)
Task 10 review round 2. Payload detectors ignore inline gitleaks:allow comments and are given no file path, so no gitleaks path allowlist suppresses a finding; only a ScanAllow entry for exact bytes can. Every RPM header value is scanned, scriptlets and triggers included. Archives inside a pinned input are opened (tar, zip and RPM, through gzip, xz, zstd and bzip2) to three containers deep; anything deeper, unsupported, unreadable or over the size limits is a finding.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+637
−120
Makefile+1 −1docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+48 −0internal/hostedimage/hostedimagetest/hostedimagetest.go+65 −2internal/hostedimage/nested.go+281 −0internal/hostedimage/rpm.go+69 −48internal/hostedimage/scan.go+33 −69internal/hostedimage/scan_test.go+140 −0
diff --git a/Makefile b/Makefile| index 149685a3..25a69925 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -228,7 +228,7 @@ gitleaks: |
| # AWS call. .amadan/ci.d/15-hosted-image runs it on CI. |
| hosted-image-check: |
| go run $(GITLEAKS) dir --no-banner --redact --config .gitleaks.toml infra/hosted/image |
| - CGO_ENABLED=0 go test ./internal/hostedimage -run '^(TestManifestPinsEverything|TestBuildReproducible|TestBuildChecksPins|TestImageInputsHaveNoSecrets|TestBuildScansPayload|TestScanAllowExact|TestBuildNeedsGitleaksConfig|TestImageLayoutMatchesContainmentSuite)$$' -count=1 |
| + CGO_ENABLED=0 go test ./internal/hostedimage -run '^(TestManifestPinsEverything|TestBuildReproducible|TestBuildChecksPins|TestImageInputsHaveNoSecrets|TestBuildScansPayload|TestScanAllowExact|TestBuildNeedsGitleaksConfig|TestImageLayoutMatchesContainmentSuite|TestScanIgnoresGitleaksAllowances|TestScanRPMScriptlets|TestScanNestedArchives)$$' -count=1 |
| # Rastrillo v0.30.0's CLI assumes a single internal app directory. The |
| # runner protocol is a second package, so call the same dump.Compute API |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index e40e0060..f2ae2fbb 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -593,3 +593,51 @@ Also run: |
| - `make budget build vet hosted-image-check`: ok (134 directories within budget). |
| - lanes-check, staticcheck v0.7.0 and gitleaks `dir` on the new directories: clean. `detect.Fragment` carries one `lint:ignore SA1019`, because gitleaks v8's `Detect` takes that type. |
| - gofmt and `git diff --check`: clean. |
| + |
| +### Task 10 review round 2 (t10-r2.md: findings 2 to 4 addressed; finding 1's three scanner gaps fixed) |
| + |
| +(a) **Only ScanAllow suppresses.** |
| +- Every payload detector, cached or new, comes from `payloadDetector`, which sets `IgnoreGitleaksAllow`. |
| +- Fragments go to gitleaks with no `FilePath`, and `Allowlist.PathAllowed("")` is false, so no path allowlist (default or repository) suppresses anything. That covers the defaults for `vendor/...`, `node_modules`, `*.bin` and the like. |
| +- Cost: a gitleaks rule scoped to a path no longer fires on payload bytes. ForbiddenPath judges names. |
| +- New TestScanIgnoresGitleaksAllowances warms the cache first, then plants three cases: a token with an inline `gitleaks:allow` in a binary, and an AWS key at `go/src/vendor/golang.org/x/net/`, `go/misc/node_modules/` and `go/misc/data.bin`. |
| + |
| +(b) **RPM header.** Every string and binary value of an RPM's main header is scanned, under the member `rpm-header/<tag>`: scriptlets (%pre, %post, %preun, %postun), triggers, pre- and post-transaction scripts, descriptions and the rest. The signature header is not scanned; it holds digests and signatures, and nothing from it is installed. New TestScanRPMScriptlets has a clean payload and a `%post` that writes an AWS key to `/etc/service.conf`. |
| + |
| +(c) **Nested archives** (`internal/hostedimage/nested.go`). |
| +- The walk opens tar, zip and RPM containers to `maxDepth` (3) levels, counting the pinned input itself. It expands gzip, xz, zstd and bzip2 streams on the way; a tar.gz counts as one level. |
| +- A member's place joins container paths with `!/`. |
| +- Each member is judged by name (ForbiddenPath) and bytes. |
| +- Findings, each allowed only by a ScanAllow entry for those exact bytes: |
| + - a container or compressed stream past the depth: `nested-too-deep`; |
| + - 7z or rar: `unsupported-container`; |
| + - an archive that does not read: `unreadable-container`; |
| + - a member that leaves its archive: `member-leaves-archive`; |
| + - a member over 1 GiB, or an input expanding past 4 GiB: `over-limit`. |
| +- The top-level tarball and RPM go through the same walk. |
| +- New TestScanNestedArchives covers: |
| + - a private key at `go/share/support.tar.gz!/.aws/credentials`, and the forbidden name; |
| + - a token in a zip; |
| + - a key in a zip in a tar; |
| + - a scriptlet of an RPM inside the tarball; |
| + - a fourth tar.gz, a fourth plain tar, and a fourth compression layer; |
| + - a 7z; |
| + - a member claiming more than 1 GiB; |
| + - too-deep and 7z containers passing only with exact-hash allowances. |
| + |
| +Mutation checks. Each was applied by script and run with `CGO_ENABLED=0 go test ./internal/hostedimage -run '^<Test>$' -count=1`. Every run compiled and failed on its assertion; each file was restored and checked by SHA-256. |
| + |
| +45. Path allowlists apply again (`FilePath` passed). TestScanIgnoresGitleaksAllowances: FAIL, `scan_test.go:267: Build = <nil>, want a payload scan refusal`. Restored. |
| +46. Inline `gitleaks:allow` honoured (`IgnoreGitleaksAllow` not set). TestScanIgnoresGitleaksAllowances: FAIL, `scan_test.go:261: Build = <nil>, want a payload scan refusal`. Restored. |
| +47. Cached detectors honour `gitleaks:allow` (the cache branch builds a plain detector). TestScanIgnoresGitleaksAllowances: FAIL, `scan_test.go:261`. Restored. |
| +48. RPM header values not scanned (`_ = tag` in place of the scan; the first form deleted the call and did not compile). TestScanRPMScriptlets: FAIL, `scan_test.go:283: Build = <nil>, want a payload scan refusal`. Restored. |
| +49. Nested containers not opened (bytes only below the input). TestScanNestedArchives: FAIL, `scan_test.go:320: findings [...:go/share/support.tar.gz line 1 (private-key)], want private-key at ...:go/share/support.tar.gz!/.aws/credentials`. Restored. |
| +50. No container depth limit. On its first run it passed, because the compression check also stops a fourth tar.gz. A plain-tar case was added; rerun FAIL, `scan_test.go:326: findings [...:go/a.tar!/b.tar!/c.tar!/k line 1 (private-key)], want nested-too-deep at ...:go/a.tar!/b.tar!/c.tar`. Restored. |
| +51. 7z and rar scanned as bytes. TestScanNestedArchives: FAIL, `scan_test.go:319: Build = <nil>, want a payload scan refusal`. Restored. |
| +52. Member size limit not checked. TestScanNestedArchives: FAIL, `scan_test.go:320: findings [...:go/big.tar.gz (unreadable-container)], want over-limit at ...:go/big.tar.gz!/huge`. Restored. |
| +53. No compression depth limit. TestScanNestedArchives: FAIL, `scan_test.go:326: findings [...:go/k.gz line 1 (private-key)], want nested-too-deep at ...:go/k.gz`. Restored. |
| + |
| +Also run: |
| +- `CGO_ENABLED=0 go test ./internal/hostedimage/... ./internal/isolatedjob/... ./cmd/equipo-hosted-image -count=1`: ok. |
| +- `make budget build vet hosted-image-check`: ok. The make target now runs the three new tests. |
| +- staticcheck v0.7.0, gitleaks `dir` on `internal/hostedimage`, lanes-check, gofmt and `git diff --check`: clean. |
diff --git a/internal/hostedimage/hostedimagetest/hostedimagetest.go b/internal/hostedimage/hostedimagetest/hostedimagetest.go| index 42e5b358..4221b188 100644 |
| --- a/internal/hostedimage/hostedimagetest/hostedimagetest.go |
| +++ b/internal/hostedimage/hostedimagetest/hostedimagetest.go |
| @@ -5,6 +5,7 @@ package hostedimagetest |
| import ( |
| "archive/tar" |
| + "archive/zip" |
| "bytes" |
| "compress/gzip" |
| "encoding/binary" |
| @@ -56,6 +57,18 @@ func mapKeys[V any](m map[string]V) func(func(string) bool) { |
| // compressor ("gzip", "zstd" or "xz"). ghosts are listed in the header |
| // but not carried. |
| func RPM(files map[string][]byte, compressor string, ghosts ...string) []byte { |
| + return RPMScripts(files, compressor, nil, ghosts...) |
| +} |
| + |
| +// Header tags of RPM scriptlets. |
| +const ( |
| + TagPreIn = 1023 |
| + TagPostIn = 1024 |
| +) |
| + |
| +// RPMScripts is RPM with string header values added, such as scriptlets |
| +// (TagPostIn to its shell text). |
| +func RPMScripts(files map[string][]byte, compressor string, scripts map[int]string, ghosts ...string) []byte { |
| var out bytes.Buffer |
| lead := make([]byte, 96) |
| copy(lead, []byte{0xed, 0xab, 0xee, 0xdb, 3, 0}) |
| @@ -73,13 +86,23 @@ func RPM(files map[string][]byte, compressor string, ghosts ...string) []byte { |
| } |
| bases, idx = append(bases, b), append(idx, int32(i)) |
| } |
| - out.Write(header([]entry{ |
| + es := []entry{ |
| {1117, 8, strs(bases...), len(bases)}, |
| {1118, 8, strs(dirs...), len(dirs)}, |
| {1116, 4, ints(idx...), len(idx)}, |
| {1124, 6, strs("cpio"), 1}, |
| {1125, 6, strs(compressor), 1}, |
| - })) |
| + } |
| + for _, tag := range slices.Sorted(func(yield func(int) bool) { |
| + for k := range scripts { |
| + if !yield(k) { |
| + return |
| + } |
| + } |
| + }) { |
| + es = append(es, entry{tag, 6, strs(scripts[tag]), 1}) |
| + } |
| + out.Write(header(es)) |
| var cp bytes.Buffer |
| pad := func() { |
| for cp.Len()%4 != 0 { |
| @@ -157,6 +180,46 @@ func header(es []entry) []byte { |
| return h.Bytes() |
| } |
| +// Tar is an uncompressed tarball of files. |
| +func Tar(files map[string][]byte) []byte { |
| + var b bytes.Buffer |
| + tw := tar.NewWriter(&b) |
| + for _, name := range slices.Sorted(mapKeys(files)) { |
| + _ = tw.WriteHeader(&tar.Header{Name: name, Typeflag: tar.TypeReg, Mode: 0o644, Size: int64(len(files[name]))}) |
| + _, _ = tw.Write(files[name]) |
| + } |
| + _ = tw.Close() |
| + return b.Bytes() |
| +} |
| + |
| +// Zip is a deflated zip of files. |
| +func Zip(files map[string][]byte) []byte { |
| + var b bytes.Buffer |
| + zw := zip.NewWriter(&b) |
| + for _, name := range slices.Sorted(mapKeys(files)) { |
| + w, _ := zw.Create(name) |
| + _, _ = w.Write(files[name]) |
| + } |
| + _ = zw.Close() |
| + return b.Bytes() |
| +} |
| + |
| +// HugeMemberTarGz is a gzip tarball whose one member's header claims |
| +// size bytes but carries none: what a scan must refuse without reading. |
| +func HugeMemberTarGz(name string, size int64) []byte { |
| + var b bytes.Buffer |
| + zw := gzip.NewWriter(&b) |
| + tw := tar.NewWriter(zw) |
| + _ = tw.WriteHeader(&tar.Header{Name: name, Typeflag: tar.TypeReg, Mode: 0o644, Size: size}) |
| + _ = tw.Flush() |
| + _ = zw.Close() |
| + return b.Bytes() |
| +} |
| + |
| +// SevenZip is the start of a 7z archive, a container the scan cannot |
| +// open. |
| +func SevenZip() []byte { return append([]byte("7z\xbc\xaf\x27\x1c\x00\x04"), make([]byte, 32)...) } |
| + |
| // The secret-shaped values the scan tests plant. They are assembled at |
| // run time so this file's own text holds none of them. |
| var ( |
diff --git a/internal/hostedimage/nested.go b/internal/hostedimage/nested.go| new file mode 100644 |
| index 00000000..a36fab59 |
| --- /dev/null |
| +++ b/internal/hostedimage/nested.go |
| @@ -0,0 +1,281 @@ |
| +package hostedimage |
| + |
| +import ( |
| + "archive/tar" |
| + "archive/zip" |
| + "bytes" |
| + "compress/bzip2" |
| + "compress/gzip" |
| + "errors" |
| + "io" |
| + "path" |
| + "strings" |
| + |
| + "github.com/klauspost/compress/zstd" |
| + "github.com/ulikunitz/xz" |
| +) |
| + |
| +// The walk opens what a pinned input holds. A member's place is its path |
| +// inside each container, joined with "!/": a file of a tarball inside |
| +// the Go toolchain is "go/share/support.tar.gz!/.aws/credentials". |
| +const ( |
| + // maxDepth bounds the containers opened one inside another. The |
| + // pinned input itself, when it is a container (the Go tarball, an |
| + // RPM), is the first. |
| + maxDepth = 3 |
| + // maxExpanded bounds the bytes one input expands to, all members |
| + // and decompressed streams together. |
| + maxExpanded = 4 << 30 |
| +) |
| + |
| +// walk is the scan of one pinned input. |
| +type walk struct { |
| + s *scanner |
| + input string |
| + expanded int64 |
| + stopped bool // the expansion limit was reached; nothing more is read |
| +} |
| + |
| +func join(member, name string) string { |
| + if member == "" { |
| + return name |
| + } |
| + return member + "!/" + name |
| +} |
| + |
| +// finding records a structural finding at member: a container that is |
| +// too deep, unreadable, unsupported or over a limit. sum binds a |
| +// ScanAllow entry to the container's exact bytes. |
| +func (w *walk) finding(member, sum, rule string) { |
| + w.s.findings = append(w.s.findings, Finding{Input: w.input, Member: member, SHA256: sum, Rule: rule}) |
| +} |
| + |
| +// spend counts n expanded bytes against maxExpanded. |
| +func (w *walk) spend(member string, n int64) bool { |
| + if w.stopped { |
| + return false |
| + } |
| + w.expanded += n |
| + if w.expanded > maxExpanded { |
| + w.stopped = true |
| + w.finding(member, "", "over-limit") |
| + return false |
| + } |
| + return true |
| +} |
| + |
| +// scanInput scans one pinned input, held in memory. |
| +func (s *scanner) scanInput(input string, b []byte) error { |
| + w := &walk{s: s, input: input} |
| + w.blob("", b, 0) |
| + return nil |
| +} |
| + |
| +// member scans a file found at member inside a container opened at |
| +// level: its name, then its bytes. |
| +func (w *walk) member(member string, body []byte, level int) { |
| + w.s.scanName(w.input, member, sha256Hex(body)) |
| + w.blob(member, body, level) |
| +} |
| + |
| +// The formats the walk knows by their first bytes. |
| +const ( |
| + kindPlain = iota |
| + kindGzip |
| + kindXz |
| + kindZstd |
| + kindBzip2 |
| + kindTar |
| + kindZip |
| + kindRPM |
| + kindUnsupported // 7z, rar |
| +) |
| + |
| +func sniff(b []byte) int { |
| + has := func(off int, magic string) bool { |
| + return len(b) >= off+len(magic) && string(b[off:off+len(magic)]) == magic |
| + } |
| + switch { |
| + case has(0, "\x1f\x8b"): |
| + return kindGzip |
| + case has(0, "\xfd7zXZ\x00"): |
| + return kindXz |
| + case has(0, "\x28\xb5\x2f\xfd"): |
| + return kindZstd |
| + case has(0, "BZh") && has(4, "1AY&SY"): |
| + return kindBzip2 |
| + case has(257, "ustar"): |
| + return kindTar |
| + case has(0, "PK\x03\x04"), has(0, "PK\x05\x06"): |
| + return kindZip |
| + case has(0, string(rpmLeadMagic)): |
| + return kindRPM |
| + case has(0, "7z\xbc\xaf\x27\x1c"), has(0, "Rar!\x1a\x07"): |
| + return kindUnsupported |
| + } |
| + return kindPlain |
| +} |
| + |
| +// blob scans b, found at member below level containers: plain bytes go |
| +// to gitleaks; a compressed stream is expanded and walked again; a |
| +// container is opened, one level down, if level allows. |
| +func (w *walk) blob(member string, b []byte, level int) { |
| + kind := sniff(b) |
| + sum := sha256Hex(b) |
| + switch kind { |
| + case kindPlain: |
| + w.s.scanBytes(w.input, member, b) |
| + return |
| + case kindUnsupported: |
| + w.finding(member, sum, "unsupported-container") |
| + return |
| + case kindGzip, kindXz, kindZstd, kindBzip2: |
| + if level >= maxDepth { |
| + w.finding(member, sum, "nested-too-deep") |
| + return |
| + } |
| + out, ok := w.expand(member, sum, kind, b) |
| + if !ok { |
| + return |
| + } |
| + if sniff(out) == kindTar { |
| + w.blob(member, out, level) // tar.gz and the like: one level |
| + return |
| + } |
| + w.blob(member, out, level+1) |
| + return |
| + } |
| + if level >= maxDepth { |
| + w.finding(member, sum, "nested-too-deep") |
| + return |
| + } |
| + switch kind { |
| + case kindTar: |
| + w.tar(member, sum, b, level+1) |
| + case kindZip: |
| + w.zip(member, sum, b, level+1) |
| + case kindRPM: |
| + w.rpm(member, b, level+1) |
| + } |
| +} |
| + |
| +// expand decompresses b, within maxMember and maxExpanded. |
| +func (w *walk) expand(member, sum string, kind int, b []byte) ([]byte, bool) { |
| + var r io.Reader |
| + var err error |
| + switch kind { |
| + case kindGzip: |
| + r, err = gzip.NewReader(bytes.NewReader(b)) |
| + case kindXz: |
| + r, err = xz.NewReader(bytes.NewReader(b)) |
| + case kindZstd: |
| + var d *zstd.Decoder |
| + if d, err = zstd.NewReader(bytes.NewReader(b)); err == nil { |
| + defer d.Close() |
| + r = d |
| + } |
| + case kindBzip2: |
| + r = bzip2.NewReader(bytes.NewReader(b)) |
| + } |
| + if err != nil { |
| + w.finding(member, sum, "unreadable-container") |
| + return nil, false |
| + } |
| + out, err := io.ReadAll(io.LimitReader(r, maxMember+1)) |
| + if err != nil { |
| + w.finding(member, sum, "unreadable-container") |
| + return nil, false |
| + } |
| + if len(out) > maxMember { |
| + w.finding(member, sum, "over-limit") |
| + return nil, false |
| + } |
| + if !w.spend(member, int64(len(out))) { |
| + return nil, false |
| + } |
| + return out, true |
| +} |
| + |
| +// cleanName is a member name as the image would hold it, or "" when it |
| +// leaves its archive. |
| +func cleanName(name string) string { |
| + n := path.Clean(strings.TrimPrefix(name, "./")) |
| + if path.IsAbs(name) || n == ".." || strings.HasPrefix(n, "../") { |
| + return "" |
| + } |
| + return n |
| +} |
| + |
| +func (w *walk) tar(member, sum string, b []byte, level int) { |
| + tr := tar.NewReader(bytes.NewReader(b)) |
| + for { |
| + h, err := tr.Next() |
| + if errors.Is(err, io.EOF) { |
| + return |
| + } |
| + if err != nil { |
| + w.finding(member, sum, "unreadable-container") |
| + return |
| + } |
| + name := cleanName(h.Name) |
| + if name == "" { |
| + w.finding(join(member, h.Name), sum, "member-leaves-archive") |
| + continue |
| + } |
| + if h.Typeflag != tar.TypeReg { |
| + w.s.scanName(w.input, join(member, name), "") |
| + continue |
| + } |
| + if h.Size > maxMember { |
| + w.finding(join(member, name), "", "over-limit") |
| + continue |
| + } |
| + if !w.spend(join(member, name), h.Size) { |
| + return |
| + } |
| + body, err := io.ReadAll(io.LimitReader(tr, maxMember)) |
| + if err != nil { |
| + w.finding(member, sum, "unreadable-container") |
| + return |
| + } |
| + w.member(join(member, name), body, level) |
| + } |
| +} |
| + |
| +func (w *walk) zip(member, sum string, b []byte, level int) { |
| + zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b))) |
| + if err != nil { |
| + w.finding(member, sum, "unreadable-container") |
| + return |
| + } |
| + for _, f := range zr.File { |
| + name := cleanName(f.Name) |
| + if name == "" { |
| + w.finding(join(member, f.Name), sum, "member-leaves-archive") |
| + continue |
| + } |
| + if f.FileInfo().IsDir() { |
| + w.s.scanName(w.input, join(member, name), "") |
| + continue |
| + } |
| + if f.UncompressedSize64 > maxMember { |
| + w.finding(join(member, name), "", "over-limit") |
| + continue |
| + } |
| + if !w.spend(join(member, name), int64(f.UncompressedSize64)) { |
| + return |
| + } |
| + rc, err := f.Open() |
| + if err != nil { |
| + w.finding(member, sum, "unreadable-container") |
| + return |
| + } |
| + body, err := io.ReadAll(io.LimitReader(rc, maxMember+1)) |
| + rc.Close() |
| + if err != nil || len(body) > maxMember { |
| + w.finding(member, sum, "unreadable-container") |
| + return |
| + } |
| + w.member(join(member, name), body, level) |
| + } |
| +} |
diff --git a/internal/hostedimage/rpm.go b/internal/hostedimage/rpm.go| index 18dc48ef..aae8dbfa 100644 |
| --- a/internal/hostedimage/rpm.go |
| +++ b/internal/hostedimage/rpm.go |
| @@ -9,7 +9,9 @@ import ( |
| "errors" |
| "fmt" |
| "io" |
| + "maps" |
| "path" |
| + "slices" |
| "strconv" |
| "strings" |
| @@ -41,10 +43,11 @@ var ( |
| ) |
| // rpmHeader is one header structure's tags: strings and string arrays |
| -// as []string, int32 arrays as []int32. |
| +// as []string, int32 arrays as []int32, binary values as bytes. |
| type rpmHeader struct { |
| strs map[int32][]string |
| ints map[int32][]int32 |
| + bins map[int32][]byte |
| } |
| // maxRPMHeader bounds a header's index and data. |
| @@ -72,7 +75,7 @@ func readRPMHeader(r io.Reader) (rpmHeader, int, error) { |
| if _, err := io.ReadFull(r, data); err != nil { |
| return rpmHeader{}, 0, err |
| } |
| - h := rpmHeader{strs: map[int32][]string{}, ints: map[int32][]int32{}} |
| + h := rpmHeader{strs: map[int32][]string{}, ints: map[int32][]int32{}, bins: map[int32][]byte{}} |
| for i := range int(n) { |
| e := index[i*16:] |
| tag := int32(binary.BigEndian.Uint32(e[0:4])) |
| @@ -91,6 +94,11 @@ func readRPMHeader(r io.Reader) (rpmHeader, int, error) { |
| for j := range int(count) { |
| h.ints[tag] = append(h.ints[tag], int32(binary.BigEndian.Uint32(d[j*4:]))) |
| } |
| + case 7: // BIN |
| + if uint64(count) > uint64(len(d)) { |
| + return rpmHeader{}, 0, errors.New("header entry outside its data") |
| + } |
| + h.bins[tag] = append(h.bins[tag], d[:count]...) |
| case 6, 8, 9: // STRING, STRING_ARRAY, I18NSTRING |
| if typ == 6 { |
| count = 1 |
| @@ -148,50 +156,61 @@ func payloadReader(compressor string, r io.Reader) (io.Reader, error) { |
| return nil, fmt.Errorf("payload compressor %q is not one the scan reads", compressor) |
| } |
| -func (s *scanner) scanRPM(input string, b []byte) error { |
| - bad := func(format string, a ...any) error { |
| - return fmt.Errorf("hostedimage: %s: "+format, append([]any{input}, a...)...) |
| - } |
| +// rpm scans an RPM found at member: every value of its main header |
| +// (scriptlets, triggers and the rest run or land at install), the names |
| +// it lists, and the files of its payload, each opened in turn at level. |
| +func (w *walk) rpm(member string, b []byte, level int) { |
| + sum := sha256Hex(b) |
| if len(b) < 96 || !bytes.Equal(b[:4], rpmLeadMagic) { |
| - return bad("not an RPM") |
| + w.finding(member, sum, "unreadable-container") |
| + return |
| } |
| r := bytes.NewReader(b[96:]) |
| _, n, err := readRPMHeader(r) |
| - if err != nil { |
| - return bad("signature header: %v", err) |
| - } |
| - if pad := (8 - n%8) % 8; pad > 0 { |
| - if _, err := r.Seek(int64(pad), io.SeekCurrent); err != nil { |
| - return bad("signature header: %v", err) |
| + if err == nil { |
| + if pad := (8 - n%8) % 8; pad > 0 { |
| + _, err = r.Seek(int64(pad), io.SeekCurrent) |
| } |
| } |
| - h, _, err := readRPMHeader(r) |
| - if err != nil { |
| - return bad("main header: %v", err) |
| + var h rpmHeader |
| + if err == nil { |
| + h, _, err = readRPMHeader(r) |
| + } |
| + var files []string |
| + if err == nil { |
| + files, err = h.files() |
| } |
| - files, err := h.files() |
| if err != nil { |
| - return bad("%v", err) |
| + w.finding(member, sum, "unreadable-container") |
| + return |
| + } |
| + for _, tag := range slices.Sorted(maps.Keys(h.strs)) { |
| + w.s.scanBytes(w.input, join(member, fmt.Sprintf("rpm-header/%d", tag)), []byte(strings.Join(h.strs[tag], "\n"))) |
| + } |
| + for _, tag := range slices.Sorted(maps.Keys(h.bins)) { |
| + w.s.scanBytes(w.input, join(member, fmt.Sprintf("rpm-header/%d", tag)), h.bins[tag]) |
| } |
| if f := first(h.strs[rpmTagPayloadFormat]); f != "cpio" && f != "" { |
| - return bad("payload format %q is not one the scan reads", f) |
| + w.finding(member, sum, "unsupported-container") |
| + return |
| } |
| pr, err := payloadReader(first(h.strs[rpmTagPayloadCompressor]), r) |
| if err != nil { |
| - return bad("payload: %v", err) |
| + w.finding(member, sum, "unsupported-container") |
| + return |
| } |
| seen := map[string]bool{} |
| - if err := s.scanCpio(input, bufio.NewReader(pr), seen); err != nil { |
| - return err |
| + if err := w.cpio(member, bufio.NewReader(pr), seen, level); err != nil { |
| + w.finding(member, sum, "unreadable-container") |
| + return |
| } |
| // A name the header lists but the payload does not carry (a %ghost |
| // file) is judged by its name alone. |
| for _, f := range files { |
| if name := strings.TrimPrefix(path.Clean(f), "/"); !seen[name] { |
| - s.scanName(input, name, "") |
| + w.s.scanName(w.input, join(member, name), "") |
| } |
| } |
| - return nil |
| } |
| func first(s []string) string { |
| @@ -201,12 +220,9 @@ func first(s []string) string { |
| return s[0] |
| } |
| -// scanCpio scans each file of a "newc" cpio archive (magic 070701) by |
| -// name and bytes, and marks each name in seen. |
| -func (s *scanner) scanCpio(input string, r io.Reader, seen map[string]bool) error { |
| - bad := func(format string, a ...any) error { |
| - return fmt.Errorf("hostedimage: %s payload: "+format, append([]any{input}, a...)...) |
| - } |
| +// cpio walks each file of a "newc" cpio archive (magic 070701), marking |
| +// each name in seen. |
| +func (w *walk) cpio(member string, r io.Reader, seen map[string]bool, level int) error { |
| var pos int64 |
| skip := func(n int64) error { |
| _, err := io.CopyN(io.Discard, r, n) |
| @@ -217,11 +233,11 @@ func (s *scanner) scanCpio(input string, r io.Reader, seen map[string]bool) erro |
| for { |
| var hdr [110]byte |
| if _, err := io.ReadFull(r, hdr[:]); err != nil { |
| - return bad("cpio header: %v", err) |
| + return err |
| } |
| pos += 110 |
| if string(hdr[:6]) != "070701" { |
| - return bad("cpio magic %q is not newc", hdr[:6]) |
| + return errors.New("cpio magic is not newc") |
| } |
| field := func(i int) (int64, error) { |
| return strconv.ParseInt(string(hdr[6+i*8:14+i*8]), 16, 64) |
| @@ -229,37 +245,42 @@ func (s *scanner) scanCpio(input string, r io.Reader, seen map[string]bool) erro |
| mode, err1 := field(1) |
| size, err2 := field(6) |
| nameSize, err3 := field(11) |
| - if err := errors.Join(err1, err2, err3); err != nil || nameSize < 1 || nameSize > 4096 || size < 0 || size > maxMember { |
| - return bad("cpio header fields") |
| + if err := errors.Join(err1, err2, err3); err != nil || nameSize < 1 || nameSize > 4096 || size < 0 { |
| + return errors.New("cpio header fields") |
| } |
| nameBuf := make([]byte, nameSize) |
| if _, err := io.ReadFull(r, nameBuf); err != nil { |
| - return bad("cpio name: %v", err) |
| + return err |
| } |
| pos += nameSize |
| name := string(bytes.TrimRight(nameBuf, "\x00")) |
| if err := pad4(); err != nil { |
| - return bad("cpio: %v", err) |
| + return err |
| } |
| if name == "TRAILER!!!" { |
| return nil |
| } |
| name = strings.TrimPrefix(path.Clean(strings.TrimPrefix(name, ".")), "/") |
| seen[name] = true |
| - body := make([]byte, size) |
| - if _, err := io.ReadFull(r, body); err != nil { |
| - return bad("cpio data: %v", err) |
| + if size > maxMember { |
| + w.finding(join(member, name), "", "over-limit") |
| + if err := skip(size); err != nil { |
| + return err |
| + } |
| + } else { |
| + body := make([]byte, size) |
| + if _, err := io.ReadFull(r, body); err != nil { |
| + return err |
| + } |
| + pos += size |
| + if mode&0o170000 == 0o100000 { // a regular file |
| + w.member(join(member, name), body, level) |
| + } else { |
| + w.s.scanName(w.input, join(member, name), "") |
| + } |
| } |
| - pos += size |
| if err := pad4(); err != nil { |
| - return bad("cpio: %v", err) |
| - } |
| - if mode&0o170000 == 0o100000 { // a regular file |
| - sum := sha256Hex(body) |
| - s.scanName(input, name, sum) |
| - s.scanBytes(input, name, body) |
| - } else { |
| - s.scanName(input, name, "") |
| + return err |
| } |
| } |
| } |
diff --git a/internal/hostedimage/scan.go b/internal/hostedimage/scan.go| index 223e3f6a..ea4690ad 100644 |
| --- a/internal/hostedimage/scan.go |
| +++ b/internal/hostedimage/scan.go |
| @@ -1,16 +1,11 @@ |
| package hostedimage |
| import ( |
| - "archive/tar" |
| "bytes" |
| - "compress/gzip" |
| "crypto/sha256" |
| "encoding/hex" |
| - "errors" |
| "fmt" |
| - "io" |
| "os" |
| - "path" |
| "path/filepath" |
| "regexp" |
| "slices" |
| @@ -28,17 +23,24 @@ import ( |
| // scans every pinned input before it writes the zip: |
| // |
| // - each plain file (the binaries) whole; |
| -// - each member of the Go tarball, by its name and its bytes; |
| -// - each file of each RPM, by the names its header lists and by the |
| -// bytes of its payload (rpm.go). |
| +// - each member of a tarball or zip, by its name and its bytes; |
| +// - each RPM by every value of its main header (scriptlets, triggers, |
| +// descriptions), the names it lists, and the files of its payload |
| +// (rpm.go); |
| +// - archives inside those, opened in turn (nested.go): tar, zip and |
| +// RPM containers to a depth of maxDepth, through gzip, xz, zstd and |
| +// bzip2. A container nested deeper, a format the scan cannot open |
| +// (7z, rar), an archive that does not read, or a member over the |
| +// size limits is itself a finding. |
| // |
| // Bytes go through gitleaks with the repository's own configuration |
| -// (.gitleaks.toml, extending gitleaks' defaults); names go through |
| -// ForbiddenPath. Nested archives inside a member are scanned as bytes, |
| -// not opened. A finding stops the build unless the manifest's ScanAllow |
| -// names that exact member and its SHA-256 (a reviewed false positive, |
| -// such as a test key in the Go tree's testdata); an allowance that |
| -// matches nothing also stops it, so the list stays exact. |
| +// (.gitleaks.toml, extending gitleaks' defaults), with inline |
| +// "gitleaks:allow" comments ignored and no path given, so no path |
| +// allowlist applies; names go through ForbiddenPath. A finding stops the |
| +// build unless the manifest's ScanAllow names that exact member and its |
| +// SHA-256 (a reviewed false positive, such as a test key in the Go tree's |
| +// testdata); an allowance that matches nothing also stops it, so the |
| +// list stays exact. |
| // ForbiddenPath matches paths that would put a credential, a person's |
| // configuration or a repository in the image: SSH, AWS, Codex, Claude and |
| @@ -99,7 +101,7 @@ func loadDetector(path string) (*detect.Detector, error) { |
| defer gitleaksMu.Unlock() |
| key := sha256Hex(raw) |
| if cfg, ok := gitleaksConfigs[key]; ok { |
| - return detect.NewDetector(cfg), nil |
| + return payloadDetector(cfg), nil |
| } |
| viper.Reset() |
| defer viper.Reset() |
| @@ -119,7 +121,16 @@ func loadDetector(path string) (*detect.Detector, error) { |
| return nil, fmt.Errorf("hostedimage: gitleaks configuration %s has no rules", path) |
| } |
| gitleaksConfigs[key] = cfg |
| - return detect.NewDetector(cfg), nil |
| + return payloadDetector(cfg), nil |
| +} |
| + |
| +// payloadDetector is a detector for the payload scan: an inline |
| +// "gitleaks:allow" in a pinned file suppresses nothing. Only ScanAllow |
| +// may. |
| +func payloadDetector(cfg config.Config) *detect.Detector { |
| + d := detect.NewDetector(cfg) |
| + d.IgnoreGitleaksAllow = true |
| + return d |
| } |
| // scanner collects findings over the inputs. |
| @@ -143,12 +154,11 @@ func (s *scanner) scanBytes(input, member string, b []byte) { |
| seen := map[string]bool{} |
| for start := 0; ; start += scanChunk { |
| end := min(start+scanChunk+scanOverlap, len(b)) |
| - fp := input |
| - if member != "" { |
| - fp += "/" + member |
| - } |
| + // No FilePath: gitleaks' path allowlists (the defaults skip |
| + // vendor/, node_modules/, *.bin and the like) match only a path, |
| + // so with none they suppress nothing. Only ScanAllow may. |
| //lint:ignore SA1019 Detect takes this type in gitleaks v8; v9 renames it. |
| - for _, f := range s.d.Detect(detect.Fragment{Raw: string(b[start:end]), FilePath: fp}) { |
| + for _, f := range s.d.Detect(detect.Fragment{Raw: string(b[start:end])}) { |
| key := f.RuleID + "\x00" + f.Match |
| if seen[key] { |
| continue // the same match in an overlap |
| @@ -163,56 +173,10 @@ func (s *scanner) scanBytes(input, member string, b []byte) { |
| } |
| } |
| -// scanInput scans one pinned input, held in memory: a tarball member by |
| -// member, an RPM by its file names and payload, anything else whole. |
| -func (s *scanner) scanInput(input string, b []byte) error { |
| - switch { |
| - case strings.HasSuffix(input, ".tar.gz"): |
| - return s.scanTarGz(input, b) |
| - case strings.HasSuffix(input, ".rpm"): |
| - return s.scanRPM(input, b) |
| - } |
| - s.scanBytes(input, "", b) |
| - return nil |
| -} |
| - |
| -// maxMember bounds one archive member read into memory. |
| +// maxMember bounds one archive member, or one decompressed stream, read |
| +// into memory. |
| const maxMember = 1 << 30 |
| -func (s *scanner) scanTarGz(input string, b []byte) error { |
| - zr, err := gzip.NewReader(bytes.NewReader(b)) |
| - if err != nil { |
| - return fmt.Errorf("hostedimage: %s is not gzip: %w", input, err) |
| - } |
| - tr := tar.NewReader(zr) |
| - for { |
| - h, err := tr.Next() |
| - if errors.Is(err, io.EOF) { |
| - return nil |
| - } |
| - if err != nil { |
| - return fmt.Errorf("hostedimage: %s: %w", input, err) |
| - } |
| - name := path.Clean(strings.TrimPrefix(h.Name, "./")) |
| - if path.IsAbs(h.Name) || name == ".." || strings.HasPrefix(name, "../") { |
| - return fmt.Errorf("hostedimage: %s: member %q leaves the archive", input, h.Name) |
| - } |
| - if h.Typeflag != tar.TypeReg { |
| - s.scanName(input, name, "") |
| - continue |
| - } |
| - if h.Size > maxMember { |
| - return fmt.Errorf("hostedimage: %s: member %q is over 1 GiB", input, name) |
| - } |
| - body, err := io.ReadAll(io.LimitReader(tr, maxMember)) |
| - if err != nil { |
| - return fmt.Errorf("hostedimage: %s: %w", input, err) |
| - } |
| - s.scanName(input, name, sha256Hex(body)) |
| - s.scanBytes(input, name, body) |
| - } |
| -} |
| - |
| // judge drops the findings allow covers and returns what is left, plus |
| // any allowance that matched nothing. |
| func judge(findings []Finding, allow []ScanAllowed) (left []Finding, unused []ScanAllowed) { |
diff --git a/internal/hostedimage/scan_test.go b/internal/hostedimage/scan_test.go| index 047e257d..87231707 100644 |
| --- a/internal/hostedimage/scan_test.go |
| +++ b/internal/hostedimage/scan_test.go |
| @@ -1,6 +1,8 @@ |
| package hostedimage |
| import ( |
| + "bytes" |
| + "compress/gzip" |
| "errors" |
| "os" |
| "path/filepath" |
| @@ -210,3 +212,141 @@ func TestImageLayoutMatchesContainmentSuite(t *testing.T) { |
| t.Fatal("vm-init is not told to measure the bwrap the suite runs") |
| } |
| } |
| + |
| +// buildFindings builds m and returns the scan's findings, failing unless |
| +// the scan refused. |
| +func buildFindings(t *testing.T, m Manifest) []Finding { |
| + t.Helper() |
| + _, err := Build(m, filepath.Join(t.TempDir(), "image.zip")) |
| + var se *ScanError |
| + if !errors.As(err, &se) { |
| + t.Fatalf("Build = %v, want a payload scan refusal", err) |
| + } |
| + for _, s := range []string{hostedimagetest.AWSKey, hostedimagetest.GitHubToken, "OPENSSH PRIVATE"} { |
| + if strings.Contains(err.Error(), s) { |
| + t.Fatalf("the refusal quotes the secret: %v", err) |
| + } |
| + } |
| + return se.Findings |
| +} |
| + |
| +func hasFinding(fs []Finding, where, rule string) bool { |
| + return slices.ContainsFunc(fs, func(f Finding) bool { |
| + w := f.Input |
| + if f.Member != "" { |
| + w += ":" + f.Member |
| + } |
| + return w == where && f.Rule == rule |
| + }) |
| +} |
| + |
| +const goInput = "go1.26.11.linux-amd64.tar.gz" |
| + |
| +func plantGo(t *testing.T, m *Manifest, files map[string][]byte) { |
| + t.Helper() |
| + files["go/bin/go"] = []byte("fake go\n") |
| + setInput(t, m, goInput, hostedimagetest.TarGz(files)) |
| +} |
| + |
| +// TestScanIgnoresGitleaksAllowances (review round 2): neither an inline |
| +// "gitleaks:allow" nor gitleaks' default path allowlist (vendored |
| +// dependencies, node_modules, *.bin) suppresses a payload finding; only |
| +// ScanAllow does. |
| +func TestScanIgnoresGitleaksAllowances(t *testing.T) { |
| + // A clean build first, so the cases below use the cached |
| + // configuration. |
| + if _, err := Build(fixture(t), filepath.Join(t.TempDir(), "warm.zip")); err != nil { |
| + t.Fatal(err) |
| + } |
| + m := fixture(t) |
| + setInput(t, &m, "codex", []byte("\x7fELF\x00\ntoken = "+hostedimagetest.GitHubToken+" # gitleaks:allow\n")) |
| + if fs := buildFindings(t, m); !hasFinding(fs, "codex", "github-pat") { |
| + t.Fatalf("findings %v, want the inline-allowed token", fs) |
| + } |
| + for _, member := range []string{"go/src/vendor/golang.org/x/net/creds.txt", "go/misc/node_modules/x/creds.txt", "go/misc/data.bin"} { |
| + m := fixture(t) |
| + plantGo(t, &m, map[string][]byte{member: []byte("aws_access_key_id = " + hostedimagetest.AWSKey + "\n")}) |
| + if fs := buildFindings(t, m); !hasFinding(fs, goInput+":"+member, "aws-access-token") { |
| + t.Fatalf("%s: findings %v, want the key", member, fs) |
| + } |
| + } |
| +} |
| + |
| +// TestScanRPMScriptlets (review round 2): a package whose files are clean |
| +// but whose %post writes a credential is refused. |
| +func TestScanRPMScriptlets(t *testing.T) { |
| + m := fixture(t) |
| + post := "#!/bin/sh\nprintf 'aws_access_key_id = " + hostedimagetest.AWSKey + "\\n' > /etc/service.conf\n" |
| + pkg := "pkgs/" + m.Packages[0].Name |
| + setInput(t, &m, pkg, hostedimagetest.RPMScripts(map[string][]byte{"/usr/bin/git": []byte("fake git\n")}, "gzip", |
| + map[int]string{hostedimagetest.TagPostIn: post})) |
| + if fs := buildFindings(t, m); !hasFinding(fs, pkg+":rpm-header/1024", "aws-access-token") { |
| + t.Fatalf("findings %v, want the %%post credential", fs) |
| + } |
| +} |
| + |
| +// TestScanNestedArchives (review round 2): archives inside a pinned input |
| +// are opened, through compression, to maxDepth containers, and their |
| +// members judged by name and bytes. A container nested deeper, one the |
| +// scan cannot open, or a member over the size limit is refused unless |
| +// ScanAllow names its exact bytes. |
| +func TestScanNestedArchives(t *testing.T) { |
| + key := []byte(hostedimagetest.PrivateKey) |
| + for _, c := range []struct { |
| + name string |
| + files map[string][]byte |
| + where, rule string |
| + }{ |
| + {"credentials in a nested tar.gz", map[string][]byte{"go/share/support.tar.gz": hostedimagetest.TarGz(map[string][]byte{".aws/credentials": key})}, |
| + goInput + ":go/share/support.tar.gz!/.aws/credentials", "private-key"}, |
| + {"forbidden name in a nested tar.gz", map[string][]byte{"go/share/support.tar.gz": hostedimagetest.TarGz(map[string][]byte{".aws/credentials": []byte("x\n")})}, |
| + goInput + ":go/share/support.tar.gz!/.aws", "forbidden-path"}, |
| + {"token in a nested zip", map[string][]byte{"go/lib/a.zip": hostedimagetest.Zip(map[string][]byte{"notes.txt": []byte("t = " + hostedimagetest.GitHubToken + "\n")})}, |
| + goInput + ":go/lib/a.zip!/notes.txt", "github-pat"}, |
| + {"key in a zip in a tar in the tarball", map[string][]byte{"go/x.tar": hostedimagetest.Tar(map[string][]byte{"in.zip": hostedimagetest.Zip(map[string][]byte{"k": key})})}, |
| + goInput + ":go/x.tar!/in.zip!/k", "private-key"}, |
| + {"scriptlet of an RPM in the tarball", map[string][]byte{"go/pkg/x.rpm": hostedimagetest.RPMScripts(map[string][]byte{"/a": []byte("a\n")}, "zstd", |
| + map[int]string{hostedimagetest.TagPreIn: "echo " + hostedimagetest.GitHubToken})}, |
| + goInput + ":go/pkg/x.rpm!/rpm-header/1023", "github-pat"}, |
| + {"a fourth container", map[string][]byte{"go/a.tar.gz": hostedimagetest.TarGz(map[string][]byte{"b.tar.gz": hostedimagetest.TarGz(map[string][]byte{"c.tar.gz": hostedimagetest.TarGz(map[string][]byte{"k": key})})})}, |
| + goInput + ":go/a.tar.gz!/b.tar.gz!/c.tar.gz", "nested-too-deep"}, |
| + {"a fourth plain tar", map[string][]byte{"go/a.tar": hostedimagetest.Tar(map[string][]byte{"b.tar": hostedimagetest.Tar(map[string][]byte{"c.tar": hostedimagetest.Tar(map[string][]byte{"k": key})})})}, |
| + goInput + ":go/a.tar!/b.tar!/c.tar", "nested-too-deep"}, |
| + {"a fourth compression layer", map[string][]byte{"go/k.gz": gz(gz(gz(gz(key))))}, |
| + goInput + ":go/k.gz", "nested-too-deep"}, |
| + {"a 7z archive", map[string][]byte{"go/x.7z": hostedimagetest.SevenZip()}, |
| + goInput + ":go/x.7z", "unsupported-container"}, |
| + {"a member over the limit", map[string][]byte{"go/big.tar.gz": hostedimagetest.HugeMemberTarGz("huge", maxMember+1)}, |
| + goInput + ":go/big.tar.gz!/huge", "over-limit"}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + m := fixture(t) |
| + plantGo(t, &m, c.files) |
| + if fs := buildFindings(t, m); !hasFinding(fs, c.where, c.rule) { |
| + t.Fatalf("findings %v, want %s at %s", fs, c.rule, c.where) |
| + } |
| + }) |
| + } |
| + |
| + // A too-deep or unsupported container passes only with an allowance |
| + // for its exact bytes. |
| + deep := hostedimagetest.TarGz(map[string][]byte{"k": []byte("clean\n")}) |
| + m := fixture(t) |
| + plantGo(t, &m, map[string][]byte{"go/a.tar.gz": hostedimagetest.TarGz(map[string][]byte{"b.tar.gz": hostedimagetest.TarGz(map[string][]byte{"c.tar.gz": deep})}), |
| + "go/x.7z": hostedimagetest.SevenZip()}) |
| + m.ScanAllow = []ScanAllowed{ |
| + {Input: goInput, Member: "go/a.tar.gz!/b.tar.gz!/c.tar.gz", SHA256: sum(deep), Reason: "reviewed by hand"}, |
| + {Input: goInput, Member: "go/x.7z", SHA256: sum(hostedimagetest.SevenZip()), Reason: "reviewed by hand"}, |
| + } |
| + if _, err := Build(m, filepath.Join(t.TempDir(), "ok.zip")); err != nil { |
| + t.Fatalf("Build with the containers allowed by hash = %v", err) |
| + } |
| +} |
| + |
| +func gz(b []byte) []byte { |
| + var out bytes.Buffer |
| + w := gzip.NewWriter(&out) |
| + _, _ = w.Write(b) |
| + _ = w.Close() |
| + return out.Bytes() |
| +} |