tofu Archive Extract

tofu Archive Extract #

INTERNAL - DO NOT FORWARD

Classification: Internal-Only (design of an internal service; no source code, customer data or PII).

Unzips customer zip uploads safely, so each file inside becomes its own document (ENG-6496). A zip is the most hostile input we accept: it can claim any size, any name and any content, and it is decompressed on our hardware. Everything here is built on the assumption that the zip is an attack.

Piece Ticket State
Extraction rules, two-process runner, archive-extract-cli for security testing ENG-9992 Built (apps/tofu-archive-extract)
Queue consumer, S3 staging, bonsapi creating the child documents ENG-9993 Not started
Sandboxing the child further (landlock or seccomp: no file access, network or exec) ENG-10137 Not started; blocks ENG-9993

How to run the CLI, the limits table, the ClamAV test setup and the security checklist live in the crate’s README. This page explains the design and why it is shaped this way.

The one rule #

The extractor never parses an extracted file’s contents. It may decompress, count bytes, compare the first bytes against known signatures, and write bytes out. It may not open PDFs or images, make thumbnails, or read metadata or page counts. “First bytes” means a fixed 8 KiB prefix handed to the shared bonsai-utils MimeTypeDetector. Parsing belongs to the services that already handle untrusted documents; the extractor’s job is only to decide which bytes leave the zip.

Where it sits #

The planned ENG-9993 flow:

upload (zip) → bonsapi → queue → archive worker (ENG-9993)
                                   1. ClamAV scans the whole zip
                                   2. limited child process extracts
                                   3. kept files → S3 staging, under UUID names
                                   4. result message → bonsapi
                                 bonsapi: cleans each name (bonsai_utils::file_name),
                                          creates one document per kept file

ENG-9992 built steps 1–3 as a library plus a CLI that runs the exact same flow against a local file. The library takes a “store this file” closure. The CLI’s closure writes <uuid> files with mode 0600 into an empty --out directory; ENG-9993’s will upload to S3. The security team attacks the CLI before anything is deployed.

Two processes #

PARENT (no OS limits; may use the network)
  ClamAV INSTREAM → spawn child → read frames → re-check them
  → store kept files → wall-clock watchdog → result
        │ zip on stdin                         ▲ frames on stdout
        ▼                                      │
CHILD (same binary, hidden subcommand)
  set limits on itself → open zip → extraction rules → frames

The decompressor (zip and miniz_oxide) is the code most likely to have a bug a hostile zip can reach, so it runs in a child that can do as little harm as possible. Before reading a byte, the child sets on itself:

Limit Value Stops
RLIMIT_AS 512 MiB Memory exhaustion; allocation failure aborts the child
RLIMIT_CPU soft at the time limit (120 s), hard 5 s later CPU spinning; SIGXCPU, then SIGKILL
RLIMIT_FSIZE 0 Writing data to any file
RLIMIT_NOFILE 16 Opening many files
RLIMIT_CORE 0 Core dumps holding customer bytes
not dumpable (PR_SET_DUMPABLE 0) on Core dumps through a piped core_pattern (apport, systemd-coredump), which ignores RLIMIT_CORE
no_new_privs, pdeathsig on Gaining privileges through exec; outliving the parent

These use safe nix wrappers called by the child itself, so there is no pre_exec and no unsafe. RLIMIT_FSIZE only stops writing file data. It does not stop reading or creating files, network access or exec. That gap is accepted until ENG-10137 (T3).

Protocol. The child writes length-prefixed frames to stdout: a JSON header (at most 64 KiB) and, for a kept file, its bytes. Frames are File, Skipped, then exactly one Rejected or Done. Names in frames are cut to 1,024 bytes, so a 64 KiB zip name cannot push a header past its cap.

The parent trusts nothing from the child. It assumes the child may be subverted and checks every frame:

  • each file at most 20 MiB, with its body length matching its header;
  • kept bytes in total at most 200 MiB, and within the expansion ratio;
  • no more frames than the 200-file limit, positions strictly increasing;
  • each body re-sniffed from its first bytes: the type must be kept and match the header;
  • exactly one final frame, with nothing after it;
  • no reason only the parent may decide (malicious, timed_out).

Any violation is an internal error, and the parent deletes every file it already stored. The entry cap and bytes counted from skipped entries cannot be re-checked: they never cross the pipe, so those limits rest on the child (accepted: T2). The parent also kills the child at the wall-clock deadline.

How the child ended decides the outcome:

Child Result
Done, exit 0 processed (some entries may be skipped)
Rejected, exit 0 rejected with the child’s reason
Killed at the deadline, or SIGXCPU rejected, timed_out
Crash (abort from RLIMIT_AS, segfault, SIGXFSZ) internal error
Bad frame or broken limit internal error

A crash is an internal error, not a rejection: it means something we did not expect happened, and someone should look. The one known exception is a zip with a huge central directory, which forces an abort on purpose (T16). On rejection or any error, no staged file survives.

Extraction rules #

In this order:

  1. Open. Bytes before the zip (a self-extractor stub) are accepted; the stub is never run. Not a zip → corrupt. (Accepted: T6.)
  2. Structure, before decompressing anything.
    • More than 2,000 central-directory entries → too_many_files.
    • An entry header that cannot be read → corrupt.
    • A local header that disagrees with the central directory, overlapping entries, or duplicate names → corrupt. Overlap is how the best-known zip bombs reach huge ratios; duplicate names would be undercounted, because the zip crate folds them into one entry. (Accepted risk for real-tool zips: T9.)
  3. First pass, metadata only. Folders and junk (a __MACOSX segment, or any path segment starting with . other than . and ..) are dropped silently. ./a.pdf and ../../a.pdf are real files: they are kept, and their path never reaches the filesystem. More than 200 real files → too_many_files. Every real file encrypted → password_protected.
  4. Second pass, entry by entry:
    • symlink → UNSUPPORTED_TYPE, never read or created;
    • encrypted → ENCRYPTED_FILE, never decrypted;
    • a compression method other than stored or deflate → CORRUPT_FILE;
    • read the first 8 KiB; empty → EMPTY_FILE;
    • sniff it: nested archive → NESTED_ARCHIVE, anything not on the allowlist → UNSUPPORTED_TYPE, and reading stops;
    • a kept type is read to the end in 64 KiB chunks. Once past 20 MiB → FILE_TOO_LARGE, so at most one chunk beyond the limit is read. A read error or a CRC mismatch → CORRUPT_FILE.
  5. Every decompressed byte counts, from kept, skipped and cut-off entries alike. Over 200 MiB total → total_size_exceeded. Over 100× the zip’s size, once 10 MiB has come out → expansion_ratio_exceeded. Both are checked after every read and stop extraction at once.

Nothing from the zip ever becomes a filesystem path.

Outcomes #

The whole zip is rejected for: malicious, password_protected, total_size_exceeded, too_many_files, expansion_ratio_exceeded, timed_out, corrupt.

A single entry is skipped, and the rest still processed, for: FILE_TOO_LARGE, NESTED_ARCHIVE, UNSUPPORTED_TYPE, ENCRYPTED_FILE, EMPTY_FILE, CORRUPT_FILE.

Accepted: a single-file bomb is skipped as FILE_TOO_LARGE when the zip is larger than about 210 KiB, and rejected as expansion_ratio_exceeded when it is smaller (T1 below). 1 GiB of zeros in a 1 MiB zip is skipped with about 21 MB counted and 23 MB peak memory; 100 MiB of zeros in a 100 KB zip is rejected.

Type detection #

Extraction uses the same MimeTypeDetector (infer plus our HTML matcher) as every other upload path, on an 8 KiB prefix. 8 KiB, rather than a few bytes, because the HTML matcher reads 1,000 bytes, the OOXML matchers look for part names near the start, and HEIF needs its whole ftyp box.

Detected Result
PDF, PNG, JPEG, TIFF, BMP, GIF, HEIF/HEIC kept, with that type
Starts with a zip signature, or a known archive type (rar, 7z, gzip, tar, …) NESTED_ARCHIVE
Anything else: executables, HTML, text, unknown UNSUPPORTED_TYPE

Kept types are checked first. infer::is_archive is deliberately not used: infer files PDF under its archive matcher type, so that check would mark every PDF as nested.

Accepted consequences (T4, T5 below):

  • docx, xlsx and odt are skipped as NESTED_ARCHIVE: only PDF and images are kept from a zip, and office files start with a zip signature.
  • A PDF inside an HTML wrapper is UNSUPPORTED_TYPE. The upload path accepts it only when the uploader claimed PDF, and an entry inside a zip has no trusted claim.

Names #

Decoding (in the extractor): the UnicodePath extra field if its CRC matches, then the UTF-8 flag, then raw bytes that are valid UTF-8 (macOS Archive Utility writes UTF-8 without the flag), then CP932 (Windows Explorer on Japanese systems). The zip crate’s own CP437 fallback garbles Japanese names, so it is not used.

Cleaning (bonsai_utils::file_name::clean_file_name, shared so bonsapi applies the same rules in ENG-9993):

  1. keep the last path segment;
  2. normalize to NFC (macOS writes NFD);
  3. remove control characters, direction overrides such as U+202E, zero-width characters and the soft hyphen, which can disguise an extension;
  4. replace <>:"/\|?* with _, and trim whitespace and trailing dots;
  5. append the detected extension unless the name already has it: invoice.exe holding a PDF becomes invoice.exe.pdf;
  6. cap at 255 bytes, keeping the extension;
  7. an empty result falls back to <zip name without .zip>-<n> plus the extension, where n is the entry’s position + 1, and the stem is file if the zip name also cleans to nothing.

The display name never decides the type; the detected type does.

ClamAV #

The parent sends the whole zip to clamd over INSTREAM, using a small client we wrote ourselves rather than a new dependency. Only an exact stream: OK is clean. … FOUND rejects the zip as malicious. Any other reply, a timeout or no daemon is an internal error, so a scan can never pass by accident.

clamd needs AlertEncryptedArchive no. With it on, we expect one encrypted entry to reject the whole zip, so ENCRYPTED_FILE could never happen (still to confirm against 1.4.3). Since encrypted entries are never decrypted, ClamAV not seeing inside them costs nothing. With AlertExceedsMax yes, ClamAV may reject a large bomb as malicious before the extractor’s own limits run. (Accepted: T7, T8.)

No C decompressors #

Only deflate (and stored) is compiled in, through pure-Rust miniz_oxide. bzip2, lzma, xz, zstd, deflate64 and ppmd entries become CORRUPT_FILE (accepted: T10). We expect zips from Finder, Explorer, Drive and Dropbox to use deflate; the real-tool runs below will confirm it.

mise run rust-archive-extract-deps-check, part of rust-check, enforces this in two ways:

  • the crate’s own dependency tree must not contain those decompressors or C zlib;
  • no workspace member may turn on another zip method or a C zlib backend, because the deploy image builds with cargo build --workspace and cargo unifies features across members.

Accepted trade-offs #

Each of these is known and deliberately accepted. Please don’t file them as bugs; if the rationale stops holding, revisit the row.

# Known behaviour Why we accept it Bounded by / revisit when
T1 A single-file bomb is skipped as FILE_TOO_LARGE when the zip is larger than about 210 KiB, and the whole zip is rejected as expansion_ratio_exceeded when it is smaller. The outcome depends on the zip’s size. Both outcomes keep memory, disk and CPU bounded. The ratio check exists for many-entry bombs; making it ignore the entry being read would weaken it. PDFs, JPEGs, PNGs and HEIC barely compress, so real uploads stay far below 100:1. The cost: a small zip holding one large, plain BMP or uncompressed TIFF (over 10 MiB, compressing more than 100:1) is rejected, although harmless. Per-file limit and ratio limit. Revisit if customers report small zips rejected for ratio.
T2 The parent re-checks the expansion ratio on kept bytes only, and cannot re-check the 2,000-entry cap or bytes counted from skipped entries. Skipped bytes and the central directory never leave the child; re-checking them would mean piping that data out. A subverted child is still held by its OS limits and by the parent’s checks on file size, kept total, kept ratio, file count, type and order. ENG-10137.
T3 The child’s OS limits stop writing file data, but not reading files, network access or exec. Landlock or seccomp is separate work. ENG-10137 blocks ENG-9993, so this never reaches production without it.
T4 docx, xlsx and odt are skipped and reported as NESTED_ARCHIVE, although direct upload accepts office files. The ticket keeps only PDF and images from a zip. Office files are not a kept type, so only the skip code is at stake: they start with a zip signature, so they are reported as nested rather than UNSUPPORTED_TYPE. Revisit if zips should keep office files: infer can already name OOXML types from the 8 KiB prefix.
T5 A PDF inside an HTML wrapper is UNSUPPORTED_TYPE, although direct upload can accept it. Direct upload accepts it only when the uploader claimed PDF. An entry inside a zip has no trusted claim, and accepting HTML would mean parsing it. —
T6 Bytes before the zip (a self-extractor stub) are accepted. The stub is never run or staged, and ClamAV is sent the whole file, stub included. Whether clamd scans self-extracting archives is still to confirm against 1.4.3.
T7 clamd runs with AlertEncryptedArchive no, so ClamAV does not see inside encrypted entries. Encrypted entries are never decrypted or staged, so nothing unseen reaches a customer. With it on, we expect one encrypted entry to reject the whole zip (still to confirm). —
T8 With AlertExceedsMax yes, ClamAV rejects a zip that exceeds its scan limits as malicious, even when the content is harmless. Without ClamAV, an oversized entry would only be skipped and the rest kept; with it, the whole zip is rejected and labelled malicious. Failing closed is right for a scanner that could not finish. Kept files will be scanned again one by one by bonsai-doc-convert downstream (ENG-9993). The 1.4.3 scan-limit defaults are still to confirm, and no run has used AlertExceedsMax yes yet. Revisit if real zips trip it.
T9 The strict header check may reject some real-tool zips as corrupt. It stops overlap bombs and duplicate-name undercounting before any byte is decompressed. Zips from Python zipfile, the zip crate and streamed (data-descriptor) writers pass. Real-tool runs. If they fail: reject only overlap and duplicates up front, and skip mismatched entries as CORRUPT_FILE.
T10 bzip2, lzma, zstd, deflate64 and ppmd entries are reported as CORRUPT_FILE, though they are not damaged. Only pure-Rust deflate is compiled in, and the skip codes are fixed by the ticket. We expect customer tools to use deflate. Real-tool runs confirm deflate.
T11 Reading can go up to one 64 KiB chunk past the 20 MiB per-file limit before FILE_TOO_LARGE. Checking per chunk keeps the read loop simple. The overshoot is bounded and counted. —
T12 The child holds each kept file in memory (up to about 20 MiB) before sending it. A file whose CRC fails is never sent or stored. RLIMIT_AS of 512 MiB.
T13 An unflagged name whose bytes are valid UTF-8 is read as UTF-8, so a rare CP932 name that is also valid UTF-8 is misread. macOS writes UTF-8 without the flag, and CP932 multibyte text is almost never valid UTF-8. Only the display name is affected. —
T14 Cleaned names do not guard Windows reserved names such as CON. Names are display data only, never a path or an object key. —
T15 The deadline kill has no automated test, and SIGXCPU and SIGXFSZ have never been triggered. A deadline test would be slow and flaky (CLAUDE.md test-cost rule); it was run by hand on 2026-11-26 (checklist). SIGXCPU and SIGXFSZ are backstops: the single-threaded child cannot use more CPU time than wall time, so the watchdog kill comes first, and the child never writes files. —
T16 A zip with a huge central directory makes the child abort, an internal error rather than a rejection. The zip crate reads the whole directory before the 2,000-entry check runs: 1 million empty entries (98 MB zip) are still rejected as too_many_files, 1.5 million (147 MB) abort while allocating 204 MB. Checking first would mean our own parser for the end records on hostile input. The abort is bounded (512 MiB, under 3 s), and nothing is staged. ENG-9993: treat a child crash as final rather than retrying it. A zip-size cap prevents it only below about 59 MB: with minimal 47-byte entries, 1.25 million (58.75 MB) are rejected cleanly and 1.5 million (70.5 MB) abort (measured 2026-11-26). A zip that only declares millions of entries but holds a few is rejected as corrupt (tested up to 100 million declared, including counts below the directory’s offset such as 7 million declared after 8 MB of padding), so the directory really has to be that large.
T17 The extractor has no zip-size limit of its own. A zip larger than clamd’s StreamMaxLength fails the scan, an internal error: the dev-stack clamd, on default settings, dropped the connection on a 147 MB zip (2026-11-26). With the recommended StreamMaxLength 250M, it takes a zip over 250 MB. The upload size belongs to the upload path, which knows the product limit. ENG-9993: cap uploads below StreamMaxLength.
T18 A name without the UTF-8 flag that is not valid UTF-8 is decoded as CP932, whoever sent it. A CP437 or CP1252 name (Café.pdf zipped by Windows Explorer on an English system) or a GBK name comes out garbled. The right codepage is the sender’s Windows locale, which the zip does not record. The extractor has no entity to ask; the worker will. ASCII names, flagged UTF-8 names (7-Zip and most current tools) and macOS names are unaffected, the file is still kept, and only the display name is wrong. ENG-9993: take the legacy codepage from an entity setting, CP932 for the Japan preset.

Decisions and rejected alternatives #

Decision Why Rejected
Child process with rlimits, frames over a pipe A decompressor bug stays inside a process that cannot write files and has bounded memory and CPU Extracting in-process; the child writing files itself
Parent checks every frame against the limits it can see The child is the part that may be compromised Trusting the child’s frames
Reject overlap and header mismatch up front Stops overlap bombs before any byte is decompressed Relying only on byte counting
Shared MimeTypeDetector Extraction and direct upload agree on what a file is A separate signature table
Name cleaning in bonsai-utils bonsapi runs the same function in ENG-9993 A copy in each service
Hand-written INSTREAM client Small, with our own strict reply parsing Adding a ClamAV client crate

Status of verification #

Done (2026-11-25):

  • 44 fast unit and integration tests in the crate, building every hostile zip in memory; nothing hostile is committed;
  • the CLI against a live ClamAV 1.4.3: clean zip processed, EICAR rejected malicious with nothing written, daemon unreachable → internal error;
  • a 3 GB, 150-entry zip → total_size_exceeded; the 1 GiB single-file bomb in a 1 MiB zip → FILE_TOO_LARGE; 100 MiB of zeros in a 100 KB zip → expansion_ratio_exceeded (2026-11-26); time limit → timed_out; child out of memory → internal error; a streamed (data-descriptor) zip processed;
  • on 2026-11-26: a child killed at the deadline while still decompressing → timed_out with --out empty; a 1.5-million-entry central directory → internal error with no core dump (T16).

Still open:

  • zips from real tools (Finder, Windows Explorer, 7-Zip, Drive and Dropbox folder downloads), run by the security team at sign-off;
  • the real “42” nested bomb and an lzma entry;
  • ClamAV 1.4.3 behaviour listed in the README (encrypted entries, StreamMaxLength and MaxScanTime defaults, self-extracting archives).

Follow-ups #

  • ENG-10137: landlock or seccomp in the child. Blocks ENG-9993.
  • ENG-9993:
    • deploy clamd with AlertEncryptedArchive no;
    • cap the zip size below clamd’s StreamMaxLength (T17);
    • treat a child crash as final, not something to retry (T16);
    • take the legacy name codepage from an entity setting, CP932 for the Japan preset (T18);
    • bonsai-mq pulls in zstd-sys through reqwest, so the consumer must pass the dependency gate;
    • the child must stay free of tokio, telemetry and logging to stdout, because stdout is the frame pipe and extra threads do not mix with RLIMIT_AS.