Section 15.32

zlib module

Full name: zlib: the name of the compression library by Jean-loup Gailly and Mark Adler that this module wraps, used as a plain name.

Definition

The zlib module is the Python §12.23 standard-library module that compresses and decompresses data with the zlib library. The compressed format is DEFLATE, the method of RFC 1951 [392], optionally wrapped in the zlib container of RFC 1950 [393], which adds a 2-byte header and an Adler-32 checksum §4.32, or in the gzip container of RFC 1952 [394], which adds a header and a 32-bit cyclic redundancy check (CRC-32). Its decompression objects take input in pieces and can stop after a stated number of output bytes, which makes bounded decompression possible.

The idea

A service accepts compressed uploads of up to 100,000 bytes and decompresses each one into memory. The size limit on the upload looks like protection, but it limits the wrong number. DEFLATE replaces each repeated stretch of bytes with a short reference to an earlier copy, so it can describe a long run of identical bytes in a few bits, and 97,209 compressed bytes can expand to 100,000,000 bytes, as the worked example below shows. The memory the service needs is set by the output, which the sender chooses, not by the input, which the service limited. A small input built to expand enormously is called a compression bomb, or zip bomb.

The core idea is to count the output while it is produced and to stop at a budget, instead of decompressing first and measuring afterwards. That needs an interface that hands out output in limited portions. A one-shot call such as zlib.decompress(data) has no such limit: it returns everything or fails. A decompression object with a max_length argument does have one.

How it works

The parts of the Python interface that bounded decompression uses:

Let BB be the output budget in bytes and TT the output produced so far, starting at 0.

  1. Read the compressed input in pieces of a fixed size, for example 65,536 bytes, and cap the total compressed input as well.

  2. For each piece, call d.decompress(piece, B - T + 1). The extra 1 does two jobs: the argument is never 0, which would mean no limit, and a stream that needs even one byte more than BB shows itself.

  3. Add the length of the returned bytes to TT. If T>BT > B, stop and reject the input.

  4. Pass the returned bytes on, then call d.decompress(d.unconsumed_tail, B - T + 1) again, repeating until a call returns no bytes. The decompressor can keep input in internal buffers, so an empty unconsumed_tail alone does not show that a piece is finished. Then read the next piece.

  5. After the last piece, require d.eof; without it the stream was cut short. Then inspect d.unused_data. Reject it unless the format defines what follows the stream, as gzip does when several compressed members follow each other, and in that case handle it on purpose.

  6. Never call zlib.decompress or d.flush() on untrusted data, since neither has an output limit.

The decompressor’s own memory is small and fixed. The zlib documentation puts it at the window size, 32,768 bytes by default, plus about 7 kilobytes for the decompressor’s state, so about 40 kilobytes in all. With the output bounded, the remaining memory cost is the output the program keeps. The processor time of decompression grows in proportion to the input read plus the output written, so caps on both also bound the time.

Worked example

With zlib 1.3 at compression level 9, a run of 100,000,000 zero bytes compresses to 97,209 bytes, a ratio of 100,000,000/97,209≈1028.7100{,}000{,}000 / 97{,}209 \approx 1028.7. The zlib documentation gives 1032 to 1 as the theoretical limit of the format: one length-and-distance code of as little as 2 bits can stand for 258 output bytes, and 258×8/2=1032258 \times 8 / 2 = 1032 output bytes per input byte.

Take the budget B=1,000,000B = 1{,}000{,}000 bytes, and for simplicity treat all 97,209 compressed bytes as one piece. The first call is d.decompress(c, 1000001), where c holds the 97,209 compressed bytes, since B−T+1=1,000,000−0+1=1,000,001B - T + 1 = 1{,}000{,}000 - 0 + 1 = 1{,}000{,}001. It returns 1,000,001 bytes and leaves 96,224 bytes in d.unconsumed_tail, so it consumed only 97,209−96,224=98597{,}209 - 96{,}224 = 985 compressed bytes. Now T=1,000,001>BT = 1{,}000{,}001 > B, and the input is rejected. The program held at most 1,000,001 bytes of output, about 0.95 MiB, instead of 100,000,000 bytes, about 95.4 MiB.

A limit per call is not a limit on the stream. Calling d.decompress(d.unconsumed_tail, 65536) in a loop, without adding up the output, returns at most 65,536 bytes each time but carries on until the stream ends. ⌈100,000,000/65,536⌉=1526\lceil 100{,}000{,}000 / 65{,}536 \rceil = 1526 calls return output, where ⌈x⌉\lceil x \rceil means xx rounded up to a whole number, and together they return all 100,000,000 bytes. A program that keeps those pieces holds the whole 95.4 MiB.

Stated precisely

Let BB be the budget, TkT_k the output total after kk calls, with T0=0T_0 = 0, and ckc_k the number of bytes returned by call kk. Call kk is made only while Tk−1≤BT_{k-1} \le B, with max_length set to B−Tk−1+1B - T_{k-1} + 1, which is at least 1. The module guarantees ck≤B−Tk−1+1c_k \le B - T_{k-1} + 1, hence Tk=Tk−1+ck≤B+1T_k = T_{k-1} + c_k \le B + 1. The program rejects as soon as Tk>BT_k > B, which can only mean Tk=B+1T_k = B + 1. Therefore:

The bound rests on three assumptions.

  1. Every output byte comes from d.decompress with a positive max_length; no call to flush, zlib.decompress or another unbounded function produces output.

  2. The module honors its documented promise that a call returns no more than max_length bytes.

  3. The program’s own use of the output is bounded per byte. If it parses the output into larger structures, those structures need their own limit.

The compressed input is a separate resource: unconsumed_tail can hold up to one input piece, so the piece size and the total input need caps of their own.

Limits and common mistakes

A checksum is not authentication §1.6. Adler-32, a checksum built from two running sums of the bytes, and CRC-32 detect accidental corruption, but anyone who changes the data can recompute them, so a stream whose checksum matches can still come from an attacker. Showing who produced the data needs a message authentication code §5.7 or a digital signature §5.14 over the compressed or the decompressed bytes.

Sizes declared by the sender are claims. The gzip trailer stores the uncompressed size modulo 2322^{32}, meaning the remainder after division by 2322^{32}, so the field wraps for data of 4 GiB or more, and a program that reads it before decompressing is trusting the sender. Archive formats state member sizes in headers that the sender also writes. Size memory by the budget BB, not by a declared size.

Nesting multiplies. A compressed file inside another compressed file can multiply the factor of about 1,000 again at each layer. Apply a budget to every layer, or one budget to the total across all layers.

Trailing data needs a decision. A gzip file may hold several members one after another, and d.unused_data shows the bytes after the first. Silently ignoring those bytes, or decompressing them as a second stream without a shared budget, lets two programs read different contents from the same file.

The +1+1 matters. With max_length set to B−TB - T, a stream that fills the budget exactly makes the next argument 0, which the module reads as no limit, and the next call returns everything that is left.

Bounding the output is not checking it. The BB bytes that pass can still be malformed, malicious or unauthorized.

Questions answered

How is decompressed output bounded against a compression bomb?

Decompressed output is bounded by counting the output while it is produced and stopping at a fixed budget, never by trusting the compressed size or a size the sender declares. A compression bomb is a small compressed input that expands to a huge output; with the zlib library, 97,209 bytes can expand to 100,000,000 bytes. In Python:

  1. create d = zlib.decompressobj() and feed it the compressed input in fixed-size pieces, with a cap on the total input;

  2. on every call pass max_length =B−T+1= B - T + 1, where BB is the budget and TT the output so far; the +1+1 keeps the argument above 0, which would mean no limit;

  3. add each result’s length to TT and reject as soon as T>BT > B;

  4. feed d.unconsumed_tail back in until a call returns nothing;

  5. at the end require d.eof, which shows that the stream is complete and its checksum matched, and decide on purpose what to do with d.unused_data.

Never use zlib.decompress or d.flush() on untrusted data, because neither has an output limit. A cap on each call alone is not enough, since many capped calls still add up to the whole output. With these rules at most B+1B + 1 bytes are ever produced. The checksum inside the stream only detects accidental damage; it does not show who made the data.

Related entries: Overflow-safe range check (§4.17), Algorithmic complexity attack (§15.35), Archive path traversal (§15.18), Message authentication code (MAC) (§5.7), Checksum versus CRC (§4.32), Resource cap versus resource reservation (§13.22). Further reading: [145, 392, 393, 394].