Secrets, cryptography and supply chain · 5 MIN READ

Fuzz the parsers that read untrusted bytes, and bound what they may allocate or inflate

Write a native Go fuzz test with seed inputs and real invariants for a binary parser, harden the parser against what it finds, and cap decompressed size with io.LimitReader.

Every parser that reads bytes from outside the process is attack surface: upload formats, binary protocols, compressed bodies, custom headers. Unit tests check the inputs you thought of. Go's built-in fuzzer mutates seed inputs, guided by coverage, to find the ones you did not, such as a length field that points past the end or a non-canonical encoding that breaks a round trip.

security · A MAP OF THE IDEA

  1. Seed with real inputs
  2. Assert invariants
  3. Fuzz, minimize, commit
  4. Cap lengths and inflation

Useful when

  • Finds inputs you did not think of, often within seconds for small formats.
  • Saved failures become permanent regression tests that run with go test.

Watch out

  • Invariants define what fuzzing can find; a target that only parses finds only panics.
  • A limit on compressed size does not limit decompressed size.

Implementation & operation cost: A fuzz test per parser, CPU time for scheduled fuzzing runs and committed corpus files; the hardening itself costs a few comparisons per field.

01

Where parsers break

Parsers fail in a few recurring ways. They trust a declared length and slice past the end of the buffer, which in Go is a panic rather than memory corruption; but an unrecovered panic in a background goroutine stops the whole process, and even net/http, which recovers handler panics, drops the connection. They allocate whatever a length field asks for, so a five-byte message can request gigabytes. They accept several encodings of the same value, so two components that parse the same bytes disagree, which matters when one of them checks a signature or a policy. And decompressors turn a small input into a huge output. Each of these failures corresponds to an invariant a fuzzer can check on every input.

02

A hardened parser, its seeds and a gzip bomb

The record format is a field count followed by tag, uvarint length and value for each field. Parse checks every length before slicing, caps the number and size of fields, rejects non-minimal varints and trailing bytes, and copies values so callers never alias the input buffer. The program runs Parse on the seeds a fuzz test would start from, shows the panic a naive parser hits, and inflates a gzip bomb through a size limit.

go
package main

import (
	"bytes"
	"compress/gzip"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
)

const (
	maxFields   = 8
	maxValueLen = 256
)

var errMalformed = errors.New("malformed record")

type Field struct {
	Tag   byte
	Value []byte
}

// Parse decodes: count(1) then per field tag(1) || uvarint(len) || value.
// Every length is checked before it is used, and only canonical
// encodings are accepted, so Encode(Parse(b)) == b whenever Parse succeeds.
func Parse(b []byte) ([]Field, error) {
	if len(b) == 0 || b[0] > maxFields {
		return nil, fmt.Errorf("%w: field count", errMalformed)
	}
	count, b := int(b[0]), b[1:]
	fields := make([]Field, 0, count)
	for range count {
		if len(b) == 0 {
			return nil, fmt.Errorf("%w: truncated tag", errMalformed)
		}
		tag := b[0]
		n, k := binary.Uvarint(b[1:])
		switch {
		case k <= 0:
			return nil, fmt.Errorf("%w: bad length", errMalformed)
		case k != len(binary.AppendUvarint(nil, n)):
			return nil, fmt.Errorf("%w: non-minimal length", errMalformed)
		case n > maxValueLen:
			return nil, fmt.Errorf("%w: value too long", errMalformed)
		case uint64(len(b)-1-k) < n:
			return nil, fmt.Errorf("%w: truncated value", errMalformed)
		}
		b = b[1+k:]
		fields = append(fields, Field{tag, bytes.Clone(b[:n])})
		b = b[n:]
	}
	if len(b) != 0 {
		return nil, fmt.Errorf("%w: trailing bytes", errMalformed)
	}
	return fields, nil
}

func Encode(fields []Field) []byte {
	out := []byte{byte(len(fields))}
	for _, f := range fields {
		out = append(out, f.Tag)
		out = binary.AppendUvarint(out, uint64(len(f.Value)))
		out = append(out, f.Value...)
	}
	return out
}

// naiveParse trusts the declared length, the bug fuzzing finds first.
func naiveParse(b []byte) (value []byte, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("panic: %v", r)
		}
	}()
	n, k := binary.Uvarint(b[2:])
	return b[2+k : 2+k+int(n)], nil
}

// readAtMost refuses to inflate more than limit bytes.
func readAtMost(r io.Reader, limit int64) ([]byte, error) {
	data, err := io.ReadAll(io.LimitReader(r, limit+1))
	if err != nil {
		return nil, err
	}
	if int64(len(data)) > limit {
		return nil, fmt.Errorf("decompressed body exceeds %d bytes", limit)
	}
	return data, nil
}

func main() {
	seeds := [][]byte{
		{2, 'n', 3, 'a', 'd', 'a', 'r', 1, 'x'},
		{1, 'n', 5, 'a', 'd'},
		{1, 'n', 0x80, 0x00},
		{1, 'n', 0xff, 0xff, 0xff, 0xff, 0x0f},
		{1, 'n', 1, 'a', 'z'},
		{9},
	}
	for i, s := range seeds {
		fields, err := Parse(s)
		if err != nil {
			fmt.Printf("seed %d: %v\n", i, err)
			continue
		}
		fmt.Printf("seed %d: %d fields, round trip %t\n", i, len(fields), bytes.Equal(Encode(fields), s))
	}
	_, err := naiveParse(seeds[1])
	fmt.Println("naive parser:", err)

	var bomb bytes.Buffer
	zw := gzip.NewWriter(&bomb)
	zw.Write(make([]byte, 16<<20)) // 16 MiB of zeros
	zw.Close()
	fmt.Println("compressed under 64 KiB:", bomb.Len() < 64<<10)
	zr, err := gzip.NewReader(&bomb)
	if err != nil {
		panic(err)
	}
	_, err = readAtMost(zr, 1<<20)
	fmt.Println("inflate with 1 MiB limit:", err)
}
Read the code

Seed 0 parses and re-encodes to identical bytes. Seed 1 declares five value bytes but carries two. Seed 2 encodes the length 0 as 0x80 0x00, which binary.Uvarint accepts but Encode never produces. Seed 3 asks for about four billion bytes and is refused before any allocation. Seed 4 has a trailing byte and seed 5 claims nine fields. naiveParse trusts the length, and the recovered panic shows the slice bound it hit. The bomb is 16 MiB of zeros that compresses to well under 64 KiB; readAtMost reads through io.LimitReader with limit+1 bytes, so it can tell a body exactly at the limit from one over it, and refuses the latter.

03

The fuzz test: seeds plus invariants

A fuzz test is a function FuzzXxx(*testing.F) in a _test.go file. f.Add registers seed inputs, and f.Fuzz receives the target, whose parameters after *testing.T must match the seed types. The target does not know the right answer for a random input; it states what must hold for every input. For a parser, three invariants catch most bugs: it never panics, its output is bounded by its input and its limits, and a successful parse re-encodes to exactly the same bytes.

go
package record

import (
	"bytes"
	"testing"
)

func FuzzParse(f *testing.F) {
	f.Add([]byte{2, 'n', 3, 'a', 'd', 'a', 'r', 1, 'x'}) // valid
	f.Add([]byte{1, 'n', 0x80, 0x00})                    // non-minimal length
	f.Add([]byte{1, 'n', 5, 'a', 'd'})                   // truncated value
	f.Add([]byte{})
	f.Fuzz(func(t *testing.T, data []byte) {
		fields, err := Parse(data) // invariant 1: never panics
		if err != nil {
			return
		}
		total := 0
		for _, fl := range fields {
			total += len(fl.Value)
		}
		// invariant 2: bounded output, never larger than the input
		if len(fields) > maxFields || total > len(data) {
			t.Fatalf("%d fields, %d value bytes from %d input bytes", len(fields), total, len(data))
		}
		// invariant 3: canonical round trip
		if enc := Encode(fields); !bytes.Equal(enc, data) {
			t.Fatalf("round trip changed %x into %x", data, enc)
		}
	})
}
Read the code

This _test.go fragment sits next to Parse and Encode in a package named record; run it with go test in your own environment. Without -fuzz, go test runs only the seeds and any files under testdata/fuzz/FuzzParse, so the fuzz test doubles as a cheap regression test. A panic anywhere in Parse fails the target, which is invariant one. The byte-count check fails if a bug ever reports more value bytes than were read. The round-trip check is the strongest of the three, and it holds only because Parse accepts canonical encodings alone.

04

Run it and keep what it finds

Fuzz one target at a time: -fuzz takes a regular expression that must match exactly one fuzz test in exactly one package. As an experiment, remove the non-minimal check from Parse and the matching seed from the test: on a laptop the fuzzer found the round-trip failure in under a second, minimized it, and wrote it to testdata/fuzz/FuzzParse, from where plain go test replays it. Commit those files; they are the regression tests for the bugs you fixed. Run the seeds on every commit, a short fuzzing budget on a schedule, and longer sessions after parser changes.

bash
# Seeds and saved failures only, as in every CI run:
go test ./record -run=FuzzParse

# Generate new inputs for a fixed budget:
go test ./record -run='^$' -fuzz=FuzzParse -fuzztime=60s

# Replay one saved failure while fixing it:
go test ./record -run=FuzzParse/c8edd71d506c459a
Read the code

Run these in your own module. The first command replays seeds and saved corpus files without generating anything. The second fuzzes for 60 seconds across all CPUs; inputs that expand coverage are cached under $GOCACHE/fuzz, not in the repository. In the experiment the report read: round trip changed 01308000 into 013000, that is count 1, tag 0x30 and the two-byte encoding of length zero that Encode shortens to one byte. The saved file starts with the line go test fuzz v1 followed by the input as a Go literal; the hash in its name will differ on your machine.

05

Bound decompression and allocation everywhere

Limits belong at every layer that can expand data. http.MaxBytesReader caps the compressed request body, but a gzip body inflates after that check, so wrap the decompressor in a LimitReader as readAtMost does and treat hitting the limit as an error rather than silently truncating. The net/http Transport transparently decompresses gzip responses it asked for, so outbound response bodies need the same cap. For zip archives, the sizes in the headers are claims made by whoever built the archive: limit the number of entries and the bytes read per entry and in total, and leave entry names to the path-traversal lesson. Never preallocate from a declared length without a cap. Fuzzing proves nothing about inputs it never reached, so check the seed run with go test -coverprofile and add seeds for the branches it misses.

TAKE THIS WITH YOU

Give every parser of untrusted input a fuzz test with seeds and invariants (no panic, bounded output, canonical round trip), commit the failures it finds, and cap every declared length and every decompressed byte.

Check your understanding

Which invariant in a parser's fuzz target catches a non-canonical length encoding that the other checks miss?

Go to the source

Progress stays in this browser. No account needed.