How-To Guide

How to Fuzz Parsers and Decoders

Feed malformed input to parsers automatically so crashes, hangs and wrong-but-accepted output surface before attackers find them.

On this page

  1. Introduction
  2. Why Parsers Need Adversarial Input
  3. Coverage-Guided Fuzzing
  4. Structured Fuzzing
  5. Assertions a Fuzzer Can Check
  6. Running Fuzzing in CI
  7. Limits and Pitfalls
  8. Conclusion

Introduction

Parsers and decoders are where untrusted bytes become structured data, and they are the code most likely to contain a crash, an infinite loop or an unexpected acceptance. Example-based tests only try the inputs the author imagined; malformed input is exactly what the author did not imagine. Fuzzing closes that gap by generating bad input automatically and checking that the parser either handles it or fails cleanly. This article covers coverage-guided fuzzing, structured fuzzing, and how to run a fuzzer continuously in CI without drowning in false positives.

Why Parsers Need Adversarial Input

A parser must handle every byte sequence, including ones that are not valid in the format. The failure modes are not limited to explicit errors: a length field that disagrees with the actual payload can cause an out-of-bounds read; a nesting depth that is unbounded can exhaust the stack; a decoder that accepts an invalid encoding silently produces wrong data that propagates. Each of these is invisible to a test suite that only feeds well-formed input.

Attackers send malformed input deliberately. A crash is a denial of service; a wrong-but-accepted parse is a parser-differential attack that can bypass a security check written against a stricter parser. Fuzzing finds both because it does not assume good faith from the input, which is the posture a parser must take anyway.

Coverage-Guided Fuzzing

A coverage-guided fuzzer watches which branches your code executes for each input and keeps inputs that reach new branches, mutating them further. Over time it explores paths an author would never write a test for. Most languages have a fuzzing engine: libFuzzer and cargo-fuzz for C and Rust, go-fuzz and the native fuzzing support in Go, Atheris for Python, jazzer for the JVM.

package header

import (
	"testing"
	"time"
)

// FuzzParseHeader explores malformed header inputs. The seed corpus gives
// the fuzzer valid starting points; it mutates from there.
func FuzzParseHeader(f *testing.F) {
	f.Add([]byte("Content-Length: 42\r\n"))
	f.Add([]byte("Content-Length: -1\r\n"))
	f.Fuzz(func(t *testing.T, data []byte) {
		done := make(chan struct{})
		go func() {
			defer close(done)
			_, _ = ParseHeader(data) // must not panic
		}()
		select {
		case <-done:
		case <-time.After(2 * time.Second):
			t.Fatal("ParseHeader did not terminate on malformed input")
		}
	})
}

Structured Fuzzing

Byte-level mutation struggles with formats that require internal consistency, such as a length prefix that must match the body length. Structured fuzzing generates values from a grammar or a schema so the inputs are valid at the outer level while the interesting fields are varied. This reaches deep code that random bytes rarely satisfy, and it is the right approach for JSON, protocol buffers, and any length-delimited format.

import atheris
import sys
from myapp.record import decode_record  # raises DecodeError on invalid input

def build_valid_looking_record(data: bytes) -> bytes:
    # Use fuzzer bytes as fields, but assemble a length-prefixed frame so the
    # outer structure is valid and the decoder reaches the inner logic.
    body = data[:32]
    return len(body).to_bytes(2, "big") + body

def test_one_input(data: bytes):
    frame = build_valid_looking_record(data)
    try:
        decode_record(frame)
    except ValueError:
        pass  # a clean rejection is acceptable; a crash is not

atheris.Setup(sys.argv, test_one_input)
atheris.Fuzz()

Assertions a Fuzzer Can Check

A fuzzer is not limited to detecting crashes. Feed the same input to two implementations and assert they agree; that is differential fuzzing and it finds parser-differential bugs. Feed the output back into a serializer and assert the round-trip is stable; that finds decoders that accept input they cannot faithfully re-encode. Record the time each input takes and assert the process does not exceed a bound; that finds algorithmic complexity attacks where a short input triggers quadratic work.

Every assertion must be deterministic and side-effect free, or the fuzzer reports noise. Do not assert on wall-clock duration in a value sense; assert that the call terminates within a generous timeout. Keep the fuzzer’s own randomness out of the code under test by seeding any random source it uses.

Running Fuzzing in CI

Fuzzing finds bugs over time, so run it continuously rather than once. Keep a seed corpus in the repository so new runs start from the interesting inputs found before, and commit newly discovered crash inputs as regression tests. Run a short fuzz session on every pull request touching a parser and a longer session on a schedule.

Distinguish infrastructure flakiness from real findings. A crash that only reproduces with a specific input is real; a failure that depends on timing or environment is noise. Save the exact crashing input, minimize it with the fuzzer’s built-in minimizer, and turn the minimized input into a unit test so the fix is provably permanent. This is the same discipline as any regression test.

Limits and Pitfalls

Fuzzing proves the absence of crashes for the inputs it tried, not for all inputs. A fuzzer that stops early may miss a deep bug, and a corpus that never reaches a code path cannot exercise it. Treat coverage of the parser as the measure of fuzzing quality and keep pushing it up, rather than declaring victory after a fixed number of executions.

Do not fuzz untrusted code without isolation. A fuzzer executes inputs that may cause memory corruption in unsafe languages, so run it in a sandbox or a container, and treat a hang as a bug to bound with a timeout rather than something to wait out. In memory-safe languages a hang is still a denial of service, so the timeout assertion matters regardless.

Conclusion

Fuzzing parsers and decoders replaces the author’s imagination with an automated search for malformed input that breaks them. Use coverage-guided fuzzing with a seed corpus to explore branches, structured generation for formats that need internal consistency, differential and round-trip assertions to catch wrong-but-accepted output, and a terminating-timeout assertion to catch hangs. Run it in CI with committed crash inputs as regressions and minimize findings before fixing them. Then a malformed packet is caught by your pipeline, not by an attacker.

Sources: Go fuzzing, Atheris (Python fuzzing), libFuzzer.

FAQ

How is fuzzing different from property-based testing?
Both generate inputs, but a fuzzer is coverage-guided: it keeps inputs that reach new code paths and mutates them further, which is effective for finding crashes deep in a parser. Property-based testing checks invariants over generated inputs; the two are complementary.
Can I fuzz a parser written in a memory-safe language?
Yes, and it is still worthwhile: memory-safe parsers can still hang, throw unhandled exceptions, or accept invalid input and produce wrong data. Add a timeout assertion for hangs and round-trip or differential assertions for wrong-but-accepted output.

Related Examples