Articles / Security

  • go
  • zip-bomb
  • uploads
  • denial-of-service
  • security
  • archive-zip

How to Stop a Zip Upload Filling Your Disk When the Headers Lie

A 20 MiB upload limit says nothing about how much lands on disk once you unzip it. The archive does declare an uncompressed size for each file, but whoever built the archive typed that number.

The fix is to count the bytes as you write them and stop when your own budget runs out. Around that you need a few more limits, because a zip can exhaust other things besides bytes.

Compressed size tells you almost nothing

DEFLATE tops out at a ratio of roughly 1032:1, so 20 MiB of input can expand to about 20 GiB with perfectly honest headers.

David Fifield's non-recursive zip bomb makes many entries overlap the same compressed data, which beats that ratio without nesting archives. The 42 kB example expands to 5.5 GB, and the 10 MB one to 281 TB.

So you need limits on:

  • compressed upload size
  • number of entries
  • bytes written per file
  • bytes written across the whole archive
  • directory depth
  • number of extractions running at once

Go checks a lying header, but not your budget

Quick detour, because this surprised people I would expect to know it, or at least the opposite is easy to assume. What does Go's archive/zip do if an entry claims to be 1,000 bytes and inflates to 10 MiB?

In the Go 1.27.4 source, the reader returned by File.Open keeps a running count. Once it passes UncompressedSize64 you get zip.ErrFormat; if the data ends short, you get io.ErrUnexpectedEOF. An under-declared size fails the read.

Nice, but the check only holds each entry to its own claim. A truthful claim of 4 GiB passes, as do thousands of modest entries that add up to something silly. File.OpenRaw skips the check entirely, and other zip libraries make their own choices.

You can reject large declared sizes early as a courtesy. Just don't let that be the guard, and be careful summing attacker-chosen 64-bit numbers, since the total can wrap round.

Extract with a running budget

This extractor unpacks into a fresh directory and deletes the lot on any failure. It needs Go 1.25 or later for Root.MkdirAll.

package unzip

import (
	"archive/zip"
	"errors"
	"fmt"
	"io"
	"os"
	"strings"
)

const (
	maxEntries = 1000
	maxDepth   = 8
	maxFile    = 50 << 20  // 50 MiB
	maxTotal   = 200 << 20 // 200 MiB
)

var errLimit = errors.New("archive exceeds extraction limits")

// Extract unpacks zr into a new directory under parent and returns its path.
// On any error the directory is removed.
func Extract(zr *zip.Reader, parent string) (dir string, err error) {
	if len(zr.File) > maxEntries {
		return "", fmt.Errorf("%w: %d entries", errLimit, len(zr.File))
	}
	tmp, err := os.MkdirTemp(parent, "unzip-*")
	if err != nil {
		return "", err
	}
	defer func() {
		if err != nil {
			err = errors.Join(err, os.RemoveAll(tmp))
		}
	}()
	root, err := os.OpenRoot(tmp)
	if err != nil {
		return "", err
	}
	defer root.Close()

	remaining := int64(maxTotal)
	for _, f := range zr.File {
		if strings.Count(f.Name, "/") > maxDepth {
			return "", fmt.Errorf("%w: path too deep", errLimit)
		}
		if f.Mode().IsDir() {
			continue // parents are created along with their files
		}
		if !f.Mode().IsRegular() {
			return "", fmt.Errorf("%q: not a regular file", f.Name)
		}
		n, err := extractFile(root, f, min(maxFile, remaining))
		if err != nil {
			return "", fmt.Errorf("%q: %w", f.Name, err)
		}
		remaining -= n
	}
	return tmp, nil
}

// extractFile writes at most limit+1 bytes, whatever the headers claim.
func extractFile(root *os.Root, f *zip.File, limit int64) (n int64, err error) {
	src, err := f.Open()
	if err != nil {
		return 0, err
	}
	defer src.Close()

	if i := strings.LastIndex(f.Name, "/"); i >= 0 {
		if err := root.MkdirAll(f.Name[:i], 0o700); err != nil {
			return 0, err
		}
	}
	dst, err := root.OpenFile(f.Name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
	if err != nil {
		return 0, err
	}
	defer func() { err = errors.Join(err, dst.Close()) }()

	n, err = io.Copy(dst, io.LimitReader(src, limit+1))
	if err == nil && n > limit {
		err = errLimit
	}
	return n, err
}

Why limit+1?

The extra byte is how you tell "exactly at the limit" from "too big". A plain io.LimitReader(src, limit) returns a clean EOF at the cap, so you would silently keep a truncated file and call it success.

For files within the limit, the copy still reaches the real end of the entry, so the size and checksum checks in archive/zip still get to run.

What the other checks are for

  • os.Root refuses names that escape the directory, such as ../evil.
  • O_EXCL makes a duplicate name an error, so a later entry cannot overwrite an earlier one.
  • The regular-file check rejects symlinks and other oddities.
  • The entry and depth caps limit how many files and directories get created.

Side-path on that last one, because it's fun. A thousand empty files cost nothing against a byte budget, yet each uses an inode. One entry called a/a/a/a/.../f can demand a long chain of directories too. You can run out of inodes with plenty of space free, which makes for a baffling "No space left on device".

Cap the request before you open the archive

The handler limits the body first, then rations how many extractions run together. Four slots at 200 MiB each means about 800 MiB of file data in flight, which you can plan around.

package unzip

import (
	"archive/zip"
	"log/slog"
	"net/http"
)

const maxUpload = 20 << 20 // 20 MiB of compressed input

var slots = make(chan struct{}, 4) // concurrent extractions

func upload(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, maxUpload)
	file, hdr, err := r.FormFile("archive")
	if err != nil {
		http.Error(w, "bad or oversized upload", http.StatusBadRequest)
		return
	}
	defer r.MultipartForm.RemoveAll()
	defer file.Close()

	select {
	case slots <- struct{}{}:
		defer func() { <-slots }()
	default:
		http.Error(w, "busy, try again", http.StatusServiceUnavailable)
		return
	}

	zr, err := zip.NewReader(file, hdr.Size)
	if err != nil {
		http.Error(w, "not a usable zip", http.StatusBadRequest)
		return
	}
	dir, err := Extract(zr, "/srv/unpack")
	if err != nil {
		slog.Warn("extraction rejected", "err", err)
		http.Error(w, "archive rejected", http.StatusUnprocessableEntity)
		return
	}
	slog.Info("extracted", "dir", dir)
	w.WriteHeader(http.StatusCreated)
}

The slot is taken after the upload has arrived, so a slow client cannot sit on one while dribbling bytes. You still want server read timeouts, and the slots do not limit how many uploads are being received.

zip.NewReader loads the whole central directory before you can count entries. The upload cap is what bounds that memory, so don't raise it casually.

Successful extractions stay on disk. Delete them when you have finished with them, or your carefully limited uploads will fill the volume at a more leisurely pace.

Put a filesystem limit behind the code

Give extraction its own filesystem, so the damage from a bug stops at a failed upload and your database stays alive. On Linux, a size-limited tmpfs is a quick way to do it (replace app with your service's user and group):

sudo mount -t tmpfs \
  -o size=1g,nr_inodes=20k,mode=0700,uid=app,gid=app \
  tmpfs /srv/unpack
df -h /srv/unpack
df -i /srv/unpack

The two df commands confirm the byte and inode limits. This mount does not survive a reboot unless you add it to your boot configuration. tmpfs also uses RAM and swap; use a dedicated volume or a filesystem quota if that is a poor trade.

Multipart parsing may spill the upload itself into TMPDIR, which is a different location, so account for that space as well.

Prove it rejects a liar

You can forge a header in a test: build a normal zip, then overwrite the uncompressed size in its central directory record. That field sits 24 bytes after the PK\x01\x02 signature.

package unzip

import (
	"archive/zip"
	"bytes"
	"encoding/binary"
	"errors"
	"os"
	"testing"
)

func build(t *testing.T, size int) []byte {
	var buf bytes.Buffer
	w := zip.NewWriter(&buf)
	f, err := w.Create("zeros")
	if err != nil {
		t.Fatal(err)
	}
	if _, err := f.Write(make([]byte, size)); err != nil {
		t.Fatal(err)
	}
	if err := w.Close(); err != nil {
		t.Fatal(err)
	}
	return buf.Bytes()
}

func TestRejects(t *testing.T) {
	lie := build(t, 10<<20)
	i := bytes.LastIndex(lie, []byte("PK\x01\x02"))
	binary.LittleEndian.PutUint32(lie[i+24:], 1000)

	for _, tc := range []struct {
		data []byte
		want error
	}{
		{build(t, maxFile+1), errLimit},
		{lie, zip.ErrFormat},
	} {
		zr, err := zip.NewReader(bytes.NewReader(tc.data), int64(len(tc.data)))
		if err != nil {
			t.Fatal(err)
		}
		parent := t.TempDir()
		if _, err := Extract(zr, parent); !errors.Is(err, tc.want) {
			t.Fatalf("got %v, want %v", err, tc.want)
		}
		left, err := os.ReadDir(parent)
		if err != nil || len(left) != 0 {
			t.Fatalf("leftovers: %v, %v", left, err)
		}
	}
}

The first case is an honest file one byte over the limit. The second is the liar. Both must return an error and leave nothing behind.

This does not cover archives inside archives. The extractor writes an inner zip as an ordinary file. If you later decide to unpack it automatically, it has to draw from the same total budget and entry count, with a nesting limit, or each layer gets a fresh allowance.