Files
Kelx/zip_preflight.go
2026-11-30 16:32:37 +00:00

436 lines
18 KiB
Go

package main
// Bounded central-directory preflight for the in-process zip extraction path.
//
// adpanel:zip-cd-dos - archive/zip's zip.NewReader parses the ENTIRE central
// directory before returning: Reader.init walks every real central-directory
// header and allocates a File struct plus Name/Extra/Comment strings per
// entry, and only afterwards can a caller-side check (like the
// maxExtractFiles post-check in extractZipSafeFrom) run. Two strategies
// defeat any check that runs only after the parse:
//
// - the declared entry count can be inflated (the zip64 EOCD carries a
// 64-bit count), and
// - the declared count can be kept SMALL while physically packing millions
// of real central-directory headers: init's parse loop iterates over the
// actual headers (not the declared count) and only fails a mod-65536
// comparison after parsing and allocating for all of them.
//
// Fat headers make it worse: each parsed entry allocates the name/comment
// strings (copied) plus the name+extra+comment scratch buffer, so ~5600
// entries carrying 64KB extra fields already burn ~1.8 GB of heap from ~1 GB
// of header bytes - far below the 100k-entry count cap.
//
// This file therefore mirrors archive/zip's EOCD location (readDirectoryEnd)
// and central-directory parse loop (init + readDirectoryHeader) from Go
// 1.26.9 and counts the REAL headers, with an early stop at the same caps
// the extractor enforces afterwards. Policy:
//
// - FAIL-OPEN on everything archive/zip itself would reject BEFORE parsing
// (no EOCD, invalid comment length, zip64 errors, sanity failures): the
// preflight returns nil so zip.NewReader produces its authentic error;
// those paths never reach a large allocation.
// - FAIL-CLOSED on cap exceedance only: the confirmed entry count or the
// confirmed central-directory byte total crossing the caps.
//
// Every decision point mirrors the stdlib because the preflight must find
// the same EOCD (and hence the same directory) zip.NewReader will parse; a
// crafted multi-EOCD or SFX-prefix file must not make us judge a different
// directory than the stdlib does.
import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"io"
)
// maxZipCentralDirBytes bounds the central-directory bytes the preflight will
// walk, and with it the per-entry allocations zip.NewReader's parse will
// perform. A legitimate maxExtractFiles-entry archive has a ~15-20MB central
// directory; 64MB leaves headroom for long paths. Retained heap after the
// stdlib parse is roughly double the counted bytes (Name/Comment are copied
// while Extra keeps the shared scratch buffer alive) plus ~200B per File
// struct - so ~150MB worst case here versus the multi-GB spike this file
// exists to prevent.
const maxZipCentralDirBytes = 64 << 20
// Signatures and record lengths mirrored from archive/zip/struct.go (they are
// unexported there); verified against go1.26.9.
const (
zipCDHeaderSignature = 0x02014b50 // directoryHeaderSignature
zipCDEOCDSignature = 0x06054b50 // directoryEndSignature
zipCDEOCD64LocSignature = 0x07064b50 // directory64LocSignature
zipCDEOCD64Signature = 0x06064b50 // directory64EndSignature
zipCDHeaderLen = 46 // directoryHeaderLen: fixed part, + name + extra + comment
zipCDEOCDLen = 22 // directoryEndLen: fixed part, + comment
zipCDEOCD64LocLen = 20 // directory64LocLen
zipCDEOCD64Len = 56 // directory64EndLen
zipCDZip64ExtraID = 0x0001 // zip64ExtraID
)
// Mirror-only errors: they never leave the preflight (it turns them into a
// pass so zip.NewReader produces the authentic error), they just reproduce
// the stdlib's internal error paths so the control flow reads the same.
var (
errZipCDFormat = errors.New("zip: not a valid zip file")
errZipCDCommentLength = errors.New("zip: invalid comment length")
)
// zipCentralDirectoryPlan is the outcome of locating the end-of-central-
// directory record exactly the way archive/zip's readDirectoryEnd does.
type zipCentralDirectoryPlan struct {
Found bool // an EOCD was located where archive/zip looks for one
Start int64 // absolute offset of the first central-directory header (baseOffset + directoryOffset)
Records uint64 // declared entry count after zip64 resolution
}
// planZipCentralDirectory mirrors archive/zip/reader.go's readDirectoryEnd
// (go1.26.9) decision for decision: same scan windows, same
// findSignatureInBlock semantics (including the truncated-comment stage
// abort), same zip64 trigger and resolution, same sanity checks, same
// baseOffset math and SFX fallback. A returned error means "the stdlib
// errors before parsing any header on this exact path" - the caller must
// pass through so zip.NewReader produces its authentic error.
func planZipCentralDirectory(f io.ReaderAt, size int64) (zipCentralDirectoryPlan, error) {
if size < 0 {
// The extractor's size comes from fstat and cannot be negative;
// treat the file as unparsable rather than replicate zip.NewReader's
// panic on a negative size.
return zipCentralDirectoryPlan{}, nil
}
// Look for the EOCD signature in the last 1k, then in the last 65k.
var buf []byte
var directoryEndOffset int64
for i, bLen := range []int64{1024, 65 * 1024} {
if bLen > size {
bLen = size
}
buf = make([]byte, int(bLen))
if _, err := f.ReadAt(buf, size-bLen); err != nil && err != io.EOF {
return zipCentralDirectoryPlan{}, err
}
if p := findZipCDEOCDInBlock(buf); p >= 0 {
buf = buf[p:]
directoryEndOffset = size - bLen + int64(p)
break
}
if i == 1 || bLen == size {
// Go returns ErrFormat here; report not-found so the caller
// passes through to zip.NewReader's authentic error.
return zipCentralDirectoryPlan{}, nil
}
}
// Read header into struct (little-endian, after the 4-byte signature):
// diskNbr u16, dirDiskNbr u16, dirRecordsThisDisk u16, directoryRecords
// u16, directorySize u32, directoryOffset u32, commentLen u16.
b := buf[4:]
directoryRecords := uint64(binary.LittleEndian.Uint16(b[6:8]))
directorySize := uint64(binary.LittleEndian.Uint32(b[8:12]))
directoryOffset := uint64(binary.LittleEndian.Uint32(b[12:16]))
commentLen := int(binary.LittleEndian.Uint16(b[16:18]))
b = b[18:]
if commentLen > len(b) {
return zipCentralDirectoryPlan{}, errZipCDCommentLength
}
// These values mean that the file can be a zip64 file. Note Go uses
// 0xffff (not 0xffffffff) for directorySize here.
if directoryRecords == 0xffff || directorySize == 0xffff || directoryOffset == 0xffffffff {
p, err := findZipCDirectory64End(f, directoryEndOffset)
if err == nil && p >= 0 {
directoryEndOffset = p
var rec zipCD64Record
if err = readZipCDirectory64End(f, p, &rec); err == nil {
directoryRecords = rec.directoryRecords
directorySize = rec.directorySize
directoryOffset = rec.directoryOffset
}
}
if err != nil {
return zipCentralDirectoryPlan{}, err
}
}
maxInt64 := uint64(1<<63 - 1)
if directorySize > maxInt64 || directoryOffset > maxInt64 {
return zipCentralDirectoryPlan{}, errZipCDFormat
}
baseOffset := directoryEndOffset - int64(directorySize) - int64(directoryOffset)
// Make sure directoryOffset points to somewhere in our file.
if o := baseOffset + int64(directoryOffset); o < 0 || o >= size {
return zipCentralDirectoryPlan{}, errZipCDFormat
}
// SFX/prefix fallback: if the EOCD implies a non-zero baseOffset but a
// valid central-directory header sits at the RAW directoryOffset, Go
// assumes baseOffset 0. Use the same validator as the walk so the
// decision cannot diverge from the stdlib's.
if baseOffset > 0 {
off := int64(directoryOffset)
rs := io.NewSectionReader(f, off, size-off)
if _, ok := parseZipCDHeader(rs); ok {
baseOffset = 0
}
}
return zipCentralDirectoryPlan{
Found: true,
Start: baseOffset + int64(directoryOffset),
Records: directoryRecords,
}, nil
}
// findZipCDEOCDInBlock mirrors archive/zip's findSignatureInBlock: scan
// backward starting at len(b)-22; the first PK\x05\x06 wins, but if its
// comment length does not fit within the buffer the whole stage is abandoned
// (-1), not skipped-past. That truncated-comment quirk is load-bearing: it
// decides which EOCD - and hence which central directory - the stdlib parses.
func findZipCDEOCDInBlock(b []byte) int {
for i := len(b) - zipCDEOCDLen; i >= 0; i-- {
if b[i] == 'P' && b[i+1] == 'K' && b[i+2] == 0x05 && b[i+3] == 0x06 {
// n is length of comment
n := int(b[i+zipCDEOCDLen-2]) | int(b[i+zipCDEOCDLen-1])<<8
if n+zipCDEOCDLen+i > len(b) {
// Truncated comment. Some parsers (such as Info-ZIP) ignore
// the truncated comment rather than treating it as a hard
// error; Go abandons the stage and so do we.
return -1
}
return i
}
}
return -1
}
// zipCD64Record holds the fields readDirectory64End substitutes into the
// directory end.
type zipCD64Record struct {
directoryRecords uint64
directorySize uint64
directoryOffset uint64
}
// findZipCDirectory64End mirrors archive/zip's findDirectory64End: it tries
// to read the zip64 locator just before the directory end and returns the
// offset of the zip64 directory end if found. (-1, nil) means "no zip64";
// a ReadAt error is propagated (the stdlib treats it as a hard error too).
func findZipCDirectory64End(f io.ReaderAt, directoryEndOffset int64) (int64, error) {
locOffset := directoryEndOffset - zipCDEOCD64LocLen
if locOffset < 0 {
return -1, nil // no need to look for a header outside the file
}
buf := make([]byte, zipCDEOCD64LocLen)
if _, err := f.ReadAt(buf, locOffset); err != nil {
return -1, err
}
if binary.LittleEndian.Uint32(buf[0:4]) != zipCDEOCD64LocSignature {
return -1, nil
}
if binary.LittleEndian.Uint32(buf[4:8]) != 0 { // number of the disk with the start of the zip64 EOCD
return -1, nil // the file is not a valid zip64-file
}
p := binary.LittleEndian.Uint64(buf[8:16]) // relative offset of the zip64 EOCD record
if binary.LittleEndian.Uint32(buf[16:20]) != 1 { // total number of disks
return -1, nil // the file is not a valid zip64-file
}
return int64(p), nil
}
// readZipCDirectory64End mirrors archive/zip's readDirectory64End: it reads
// the zip64 directory end and returns the directory values to substitute.
func readZipCDirectory64End(f io.ReaderAt, offset int64, rec *zipCD64Record) error {
buf := make([]byte, zipCDEOCD64Len)
if _, err := f.ReadAt(buf, offset); err != nil {
return err
}
if binary.LittleEndian.Uint32(buf[0:4]) != zipCDEOCD64Signature {
return errZipCDFormat
}
// After the signature skip 12 bytes (record size u64 + version-made u16 +
// version-needed u16), then diskNbr u32, dirDiskNbr u32,
// dirRecordsThisDisk u64, directoryRecords u64, directorySize u64,
// directoryOffset u64.
rec.directoryRecords = binary.LittleEndian.Uint64(buf[32:40])
rec.directorySize = binary.LittleEndian.Uint64(buf[40:48])
rec.directoryOffset = binary.LittleEndian.Uint64(buf[48:56])
return nil
}
// parseZipCDHeader mirrors archive/zip's readDirectoryHeader error paths so
// the walk stops exactly where init's parse loop would stop. It returns the
// total header size (46 + name + extra + comment) when the stdlib would
// accept the entry, and ok=false on every path where readDirectoryHeader
// returns an error (short read, bad signature, short zip64 extra for a
// needed value, unmet compressed-size/header-offset).
//
// Deliberately not mirrored (the stdlib has no error paths there): UTF-8
// detection, the ntfs/unix/ext-time extra fields, and an unmet
// uncompressed-size (tolerated so ancient zip32 shards like 42.zip still
// parse - see the stdlib's note).
func parseZipCDHeader(r io.Reader) (headerSize int64, ok bool) {
var fixed [zipCDHeaderLen]byte
if _, err := io.ReadFull(r, fixed[:]); err != nil {
return 0, false
}
if binary.LittleEndian.Uint32(fixed[0:4]) != zipCDHeaderSignature {
return 0, false
}
compressedSize := binary.LittleEndian.Uint32(fixed[20:24])
uncompressedSize := binary.LittleEndian.Uint32(fixed[24:28])
nameLen := int(binary.LittleEndian.Uint16(fixed[28:30]))
extraLen := int(binary.LittleEndian.Uint16(fixed[30:32]))
commentLen := int(binary.LittleEndian.Uint16(fixed[32:34]))
headerOffset := binary.LittleEndian.Uint32(fixed[42:46])
tail := make([]byte, nameLen+extraLen+commentLen)
if _, err := io.ReadFull(r, tail); err != nil {
return 0, false
}
needUSize := uncompressedSize == ^uint32(0)
needCSize := compressedSize == ^uint32(0)
needHeaderOffset := headerOffset == ^uint32(0)
extra := tail[nameLen : nameLen+extraLen]
for len(extra) >= 4 { // need at least tag and size
fieldTag := binary.LittleEndian.Uint16(extra[0:2])
fieldSize := int(binary.LittleEndian.Uint16(extra[2:4]))
if len(extra)-4 < fieldSize {
break // malformed extra field: the stdlib breaks out, not an error
}
fieldBuf := extra[4 : 4+fieldSize]
extra = extra[4+fieldSize:]
if fieldTag != zipCDZip64ExtraID {
continue // other extra tags have no error paths
}
// zip64 extra: update the directory values the 32-bit fields maxed
// out for; too short for a needed value is ErrFormat in the stdlib.
if needUSize {
needUSize = false
if len(fieldBuf) < 8 {
return 0, false
}
}
if needCSize {
needCSize = false
if len(fieldBuf) < 8 {
return 0, false
}
}
if needHeaderOffset {
needHeaderOffset = false
if len(fieldBuf) < 8 {
return 0, false
}
}
}
// An unmet uncompressed size is tolerated (42.zip); an unmet compressed
// size or header offset is not.
if needCSize || needHeaderOffset {
return 0, false
}
return int64(zipCDHeaderLen + nameLen + extraLen + commentLen), true
}
// zipCentralDirectoryScan reports what the bounded walk observed before it
// stopped. The walk mirrors init's parse loop - it starts at plan.Start with
// the same transport (bufio over a section of the file) and parses headers
// with the same error semantics - so its confirmed prefix is exactly the
// prefix zip.NewReader would parse and allocate for. Whether the stdlib then
// succeeds, fails the mod-65536 comparison, or fails on a truncated tail is
// irrelevant to the preflight: within the caps it passes through either way.
type zipCentralDirectoryScan struct {
Entries int // complete central-directory headers parsed before stopping
Bytes int64 // central-directory bytes consumed for those headers
}
type zipCentralDirViolation int
const (
zipCentralDirWithinCaps zipCentralDirViolation = iota
zipCentralDirViolatedFileCount
zipCentralDirViolatedBytes
)
// scanZipCentralDirectory walks the central directory from plan.Start,
// counting real headers (not the declared count) and stopping early - without
// scanning further - as soon as a cap would be exceeded. Note that the
// declared count alone cannot be trusted: archives exist that declare a tiny
// record count while physically packing millions of headers.
func scanZipCentralDirectory(f io.ReaderAt, plan zipCentralDirectoryPlan, size int64, maxFiles int, maxDirBytes int64) (zipCentralDirectoryScan, zipCentralDirViolation) {
rs := io.NewSectionReader(f, plan.Start, size-plan.Start)
br := bufio.NewReader(rs)
var scan zipCentralDirectoryScan
for {
headerSize, ok := parseZipCDHeader(br)
if !ok {
// The stdlib's loop stops here too (ErrFormat or
// ErrUnexpectedEOF break the loop; any other error fails init
// outright). The confirmed prefix is complete either way.
return scan, zipCentralDirWithinCaps
}
scan.Entries++
scan.Bytes += headerSize
if scan.Entries > maxFiles {
return scan, zipCentralDirViolatedFileCount
}
if scan.Bytes > maxDirBytes {
return scan, zipCentralDirViolatedBytes
}
}
}
// preflightZipCentralDirectory counts the real central-directory headers of
// the zip at f before zip.NewReader is allowed to parse them, and rejects
// only on cap exceedance. maxFiles and maxDirBytes are parameters so tests
// can inject small caps; extractZipSafeFrom goes through
// preflightZipCentralDirectoryBounded, which binds the production caps.
//
// It fails open on anything the stdlib rejects before parsing (unparsable
// EOCD, zip64 errors, sanity failures, no EOCD at all) so zip.NewReader
// produces its authentic error, and fails closed on the two exceedances.
func preflightZipCentralDirectory(f io.ReaderAt, size int64, maxFiles int, maxDirBytes int64) error {
plan, err := planZipCentralDirectory(f, size)
if err != nil {
// FAIL-OPEN: the stdlib errors before parsing any header on this
// exact path; let zip.NewReader produce its authentic error.
return nil
}
if !plan.Found {
// FAIL-OPEN: no EOCD where the stdlib looks for one.
return nil
}
// Fast path: the declared (zip64-resolved) count alone already exceeds
// the cap - reject before walking. Deliberately stricter than the stdlib,
// which only compares the declared count mod 65536 after parsing: no
// legitimate writer declares more entries than it stores, while the
// declared count is also what drives zip.NewReader's upfront
// []*File preallocation, so an inflated declaration is rejected here
// without touching the directory at all.
if plan.Records > uint64(maxFiles) {
return fmt.Errorf("too many files in archive: %d (max %d)", plan.Records, maxFiles)
}
scan, violation := scanZipCentralDirectory(f, plan, size, maxFiles, maxDirBytes)
switch violation {
case zipCentralDirViolatedFileCount:
return fmt.Errorf("too many files in archive: %d (max %d)", scan.Entries, maxFiles)
case zipCentralDirViolatedBytes:
return fmt.Errorf("zip central directory too large: %d bytes (max %d)", scan.Bytes, maxDirBytes)
}
return nil
}
// preflightZipCentralDirectoryBounded binds the production caps for the
// extract path.
func preflightZipCentralDirectoryBounded(f io.ReaderAt, size int64) error {
return preflightZipCentralDirectory(f, size, maxExtractFiles, maxZipCentralDirBytes)
}