Skip to content
systemcoding.dev
Security

Fuzz a Binary Format Decoder With Go Native Fuzzing

Use Go 1.24 native fuzzing with testing.F to fuzz a binary decoder, find a slice bounds panic, read the saved testdata file and add a round-trip property.

8 min read
Summarize in AI
Flat illustration of a hex dump with one byte highlighted, with the Python, Rust and Zig logos.

Go has had fuzzing in its standard toolchain since Go 1.18, so a decoder can be fuzzed with the same go test command that runs the rest of the tests. There is nothing to install and no separate harness language. A fuzz test looks like a unit test with one extra method, the engine uses coverage feedback to guide mutation, and any input that makes the code panic or fail is written into testdata/fuzz/ where ordinary go test replays it forever afterwards. This post fuzzes a small binary format decoder with Go 1.24, finds a slice bounds panic, reads the saved input, fixes the bug and adds a round-trip check that catches wrong answers as well as crashes.

Familiarity with Go testing is assumed. If fuzzing itself is new, the post on what fuzzing is and why coverage guidance works explains the loop that go test -fuzz runs.

The format and a decoder with a bug

The format is a magic prefix, a record count and length-prefixed records:

OffsetSizeMeaning
02ASCII BF
21number of records, n
3variablen records, each a length byte followed by that many payload bytes

The decoder returns the payloads. It checks the magic and the count but trusts every length byte.

decode.gogo
package bfmt

import (
	"errors"
)

var ErrBadMagic = errors.New("bfmt: bad magic")

// Decode returns the payload of each record in data.
func Decode(data []byte) ([][]byte, error) {
	if len(data) < 3 || data[0] != 'B' || data[1] != 'F' {
		return nil, ErrBadMagic
	}
	n := int(data[2])
	off := 3
	out := make([][]byte, 0, n)
	for i := 0; i < n; i++ {
		l := int(data[off])
		off++
		out = append(out, data[off:off+l]) // bug: l is not checked against len(data)
		off += l
	}
	return out, nil
}

There are two bugs. The slice expression data[off:off+l] panics when a record claims more bytes than remain, and data[off] panics when the count promises records the input does not have. A hand-written unit test with a well-formed message will pass.

decode_test.gogo
package bfmt

import (
	"reflect"
	"testing"
)

func TestDecodeSimple(t *testing.T) {
	got, err := Decode([]byte("BF\x01\x03abc"))
	if err != nil {
		t.Fatal(err)
	}
	want := [][]byte{[]byte("abc")}
	if !reflect.DeepEqual(got, want) {
		t.Fatalf("got %q, want %q", got, want)
	}
}
Text
ok  	example.test/bfmt	0.002s

Write the fuzz test

A fuzz test is a function named FuzzXxx that takes a *testing.F. First it registers seed inputs with f.Add, then it calls f.Fuzz with a function that receives the generated arguments. The argument types must come from the supported list: []byte, string, bool, byte, rune, the sized integers and floats.

decode_fuzz_test.gogo
package bfmt

import "testing"

func FuzzDecode(f *testing.F) {
	f.Add([]byte("BF\x01\x03abc"))
	f.Add([]byte("BF\x02\x01a\x02bc"))
	f.Add([]byte("BF\x00"))

	f.Fuzz(func(t *testing.T, data []byte) {
		recs, err := Decode(data)
		if err != nil {
			return
		}
		for _, r := range recs {
			_ = len(r)
		}
	})
}

The seeds teach the fuzzer what a valid message looks like, so it starts at the top of the format and mutates from there. The fuzz function must not depend on anything but its arguments, since the engine runs it concurrently in many worker processes.

Run the seeds as an ordinary test first. Without -fuzz, go test executes only the seed inputs, so this is also what runs in normal CI:

Shell
go test -run FuzzDecode -v
Text
=== RUN   FuzzDecode
=== RUN   FuzzDecode/seed#0
=== RUN   FuzzDecode/seed#1
=== RUN   FuzzDecode/seed#2
--- PASS: FuzzDecode (0.00s)
    --- PASS: FuzzDecode/seed#0 (0.00s)
    --- PASS: FuzzDecode/seed#1 (0.00s)
    --- PASS: FuzzDecode/seed#2 (0.00s)
PASS
ok  	example.test/bfmt	0.003s

All three seeds are well-formed, so they pass. Now turn fuzzing on.

Run the fuzzer

Shell
go test -fuzz=FuzzDecode -fuzztime=30s

The -fuzz flag takes a regular expression that must match exactly one fuzz test, and -fuzztime bounds the run. The engine finds the panic within moments:

Text
fuzz: elapsed: 0s, gathering baseline coverage: 0/3 completed
fuzz: elapsed: 0s, gathering baseline coverage: 3/3 completed, now fuzzing with 8 workers
fuzz: minimizing 29-byte failing input file
fuzz: elapsed: 1s, minimizing
--- FAIL: FuzzDecode (1.04s)
    --- FAIL: FuzzDecode (0.00s)
        testing.go:1591: panic: runtime error: slice bounds out of range [:9] with capacity 5
            goroutine 41 [running]:
            ...
    Failing input written to testdata/fuzz/FuzzDecode/3f5b0e8a9c1d2b47e6a0f4d8c2b1a7e90d3c6f5a4b8e1d27c9a0f3b6e5d4c812
    To re-run:
    go test -run=FuzzDecode/3f5b0e8a9c1d2b47e6a0f4d8c2b1a7e90d3c6f5a4b8e1d27c9a0f3b6e5d4c812
FAIL
exit status 1
FAIL	example.test/bfmt	1.052s

The worker count, hash, timing and the exact panic numbers will differ on your machine. Note three things. The engine minimized the failing input before reporting it, shrinking a 29-byte mutation to the smallest input that still panics. The panic message names the problem: a slice upper bound of 9 on a buffer with capacity 5. And the failing input was **written to testdata/fuzz/FuzzDecode/**, a directory next to the test, in a file named by the hash of its contents.

Read the saved input

The file is plain text in a versioned format, designed to be read and committed:

Text
go test fuzz v1
[]byte("BF\x01\x04a")

The first line is a header. Each following line is one argument, written as a Go expression. That is a message claiming one record of four bytes, with one byte of payload present. Go uses these files in two ways: go test with no flags replays every file under testdata/fuzz/<FuzzName>/ as a test case, and the To re-run line shows how to run a single file with -run. The directory is therefore a regression suite that grows with each finding, and you commit it to version control.

Fix the decoder

Check every length against the remaining data, and return an error type that callers can handle.

decode.gogo
package bfmt

import "errors"

var (
	ErrBadMagic  = errors.New("bfmt: bad magic")
	ErrTruncated = errors.New("bfmt: truncated record")
)

func Decode(data []byte) ([][]byte, error) {
	if len(data) < 3 || data[0] != 'B' || data[1] != 'F' {
		return nil, ErrBadMagic
	}
	n := int(data[2])
	off := 3
	out := make([][]byte, 0, n)
	for i := 0; i < n; i++ {
		if off >= len(data) {
			return nil, ErrTruncated
		}
		l := int(data[off])
		off++
		if l > len(data)-off {
			return nil, ErrTruncated
		}
		out = append(out, data[off:off+l])
		off += l
	}
	return out, nil
}

Run the plain test command, which replays the saved failing file:

Shell
go test
Text
PASS
ok  	example.test/bfmt	0.004s

Then fuzz again for longer to see whether anything else appears. With the guard in place and no new findings in thirty seconds, the output ends:

Text
fuzz: elapsed: 30s, execs: 2183041 (72770/sec), new interesting: 14 (total: 17)
fuzz: elapsed: 30s, execs: 2183041 (0/sec), new interesting: 14 (total: 17)
PASS
ok  	example.test/bfmt	30.112s

The execution counts are an example of the output format and will differ by machine. Coverage-guided "new interesting" inputs are saved to the fuzzing cache, not to testdata, and only failures are committed to the repository.

Add a property to catch wrong answers

A decoder that returns the wrong bytes without panicking passes the test above. The fuzzer can only fail on a panic, or on a check you write. Add an encoder and assert that decoding what you encoded returns the original.

encode.gogo
package bfmt

// Encode builds a message from payloads. Each payload must be at most 255 bytes
// and there may be at most 255 payloads.
func Encode(payloads [][]byte) []byte {
	out := []byte{'B', 'F', byte(len(payloads))}
	for _, p := range payloads {
		out = append(out, byte(len(p)))
		out = append(out, p...)
	}
	return out
}
roundtrip_fuzz_test.gogo
package bfmt

import (
	"bytes"
	"testing"
)

func FuzzRoundTrip(f *testing.F) {
	f.Add([]byte("hello"), []byte("world"))

	f.Fuzz(func(t *testing.T, a, b []byte) {
		if len(a) > 255 || len(b) > 255 {
			t.Skip()
		}
		got, err := Decode(Encode([][]byte{a, b}))
		if err != nil {
			t.Fatalf("decode failed: %v", err)
		}
		if len(got) != 2 || !bytes.Equal(got[0], a) || !bytes.Equal(got[1], b) {
			t.Fatalf("round trip changed the data: %q %q", got, [][]byte{a, b})
		}
	})
}

t.Skip() tells the engine to discard an input that is outside the encoder's contract without counting it as a failure. A property like this finds the other half of decoder bugs: off-by-one errors, mishandled empty payloads, and aliasing of the input buffer. It is the most useful single addition once the crashes are gone.

Practical details

Go keeps the corpus of interesting inputs in the build cache directory under fuzz/, reported by go env GOCACHE. Clearing the cache discards that exploration; the testdata/fuzz files remain. In CI, run plain go test so only seeds and committed failures run, and run -fuzz on a schedule with -fuzztime. A fuzz run uses all CPU cores by default, which -parallel limits, and -fuzzminimizetime bounds the time spent shrinking.

The engine is coverage-guided, but it does not support everything libFuzzer does: there are no dictionaries, no custom mutators, and the argument types are limited to the list above. A target that needs structured input builds it inside the fuzz function from the bytes, for example with the encoding/binary or bytes.Reader APIs. For richer needs, the community project go-fuzz and, for C-backed code, libFuzzer through cgo exist, but the native engine covers most Go decoders.

When not to use it

Native fuzzing runs your Go code. It will not find a bug in a C library called through cgo unless that library is instrumented separately, and it does not detect data races, for which go test -race is the tool. It also cannot reach code behind a check it cannot satisfy, such as a signature over the input, without seeds that already pass the check.

Also inDebugging
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.