top of page

Fuzzing Protocol Parsers in Firmware CI: A Framework That Finds Bugs in Seconds

Writer: Srihari Maddula
Srihari Maddula
6 days ago
15 min read
Lines of source code on a dark screen
Photo: Florian Olivo on Unsplash

The email from the security researcher is polite and short. Sending a particular 40-byte configuration frame to your sensor over its radio makes it reboot. Sending a slightly different one makes it stop reporting until someone power-cycles it. A proof-of-concept file is attached, along with a note that the researcher plans to publish in ninety days.

The engineering team reproduces it in an afternoon. The cause is a length field in the configuration parser that was checked against the buffer size, but not against the space left after the header. Three lines of code fix it. The harder question arrives the next morning: how many more parsers in the firmware have the same kind of bug, and how would anyone know?

There is a standard answer, and it is cheaper than most firmware teams assume. Fuzzing feeds a parser millions of automatically mutated inputs, watches for crashes and memory errors, and keeps any input that reaches new code. Run on a development machine, against the parser code compiled for the host, a fuzzer can try tens of millions of inputs in a minute. Bugs of the kind in the researcher's email tend to fall out in seconds.

The framework in this post is four rules. Separate every parser from the hardware so it compiles on a workstation. Give each parser one small harness. Run it under sanitizers that turn silent memory errors into loud ones. And keep the corpus of interesting inputs in the repository, so continuous integration runs the fuzzer on every change. The worked example is a real run: a small configuration-frame parser with two planted bugs, fuzzed with libFuzzer, that found both in under two seconds.


Where the Bytes Come In

Every parser that reads bytes from outside the device is an attack surface, and an embedded product usually has more of them than its designers list.

Entry point

Example content

Who can send it

Radio frames

LoRa, BLE, Wi-Fi, cellular payloads

Anyone within range

Serial and fieldbus

Modbus, CAN, RS-485 commands

Anyone with physical access to the bus

Configuration frames

Device name, report period, channel lists

Network server, installer tools

Firmware update manifests

Version, size, hash, signature fields

Update server, or anyone who can reach the device

Files

Configuration files, logs, images on SD cards

Anyone who can insert or swap a card

Network messages

MQTT topics and payloads, HTTP bodies, JSON

Brokers, gateways, cloud services

Sensor data

Packets from digital sensors on I2C or SPI

A faulty or counterfeit sensor

The last row is easy to miss. A parser that assumes a sensor always sends well-formed data will one day meet a sensor with a loose connector or a counterfeit chip, and the failure looks exactly like an attack.

Every byte that arrives from outside the processor is untrusted input. A parser that trusts its peer is a parser waiting for a broken peer or a curious attacker.

What Fuzzing Is and Is Not

A coverage-guided fuzzer is a loop. It takes an input from its collection, called the corpus, applies a small random change such as flipping a bit, inserting bytes or splicing two inputs together, and runs the code under test. If the input makes the code take a path it has not taken before, the fuzzer keeps it in the corpus. If the code crashes, hangs or trips a sanitizer, the fuzzer saves the input and stops. Over millions of iterations, the corpus grows into a set of inputs that exercise more and more of the parser.

LLVM's documentation describes libFuzzer as an in-process, coverage-guided, evolutionary fuzzing engine, and the description is precise. It runs inside the same process as the code under test, which makes it fast. It uses compiler instrumentation to see which code each input reaches. And it evolves its corpus towards inputs that reach new code.

Fuzzing is not a proof of correctness. It finds bugs that its inputs happen to reach, and it reports nothing about code they never reach. It is also not a replacement for unit tests, which check that valid inputs produce correct outputs. Fuzzing checks something different and complementary: that no input, however malformed, makes the code misbehave.


The Framework: Four Rules

The framework is short enough to adopt in a week.

Rule

What it means

Why

1. Separate parsers from hardware

Parsing code takes a buffer and a length, returns a result, and touches no registers

It compiles and runs on a workstation at full speed

2. One harness per parser

A few lines that pass the fuzzer's bytes to one parsing function

Each parser gets its own coverage and its own corpus

3. Run under sanitizers

AddressSanitizer and UndefinedBehaviorSanitizer at minimum

Turns silent memory corruption into an immediate, located report

4. Corpus and fuzzer in CI

Seed inputs in the repository; short fuzz runs on every change, longer runs nightly

Bugs are caught when introduced, and regressions stay fixed

The rest of this post takes the rules one at a time, then shows them working on real code.


Rule 1: Separate Parsers From Hardware

Firmware often mixes parsing with everything else. A radio interrupt handler reads bytes from a peripheral register, checks a few fields, updates global state, and writes to another peripheral, all in one function. That code cannot be fuzzed on a workstation, because it needs the hardware.

The fix is a refactor that most teams benefit from anyway. Give each parser a pure interface: a pointer to a buffer, a length, and an output structure. The parser validates and decodes the bytes and returns a status. It does not read registers, call the radio driver, allocate from a global pool or depend on the time of day. The driver that receives the bytes calls the parser; the application that acts on the result reads the output structure.

Once a parser looks like this, it compiles with the host compiler with no changes, alongside a harness. The same source file goes into the firmware build and the fuzz build, so there is no second copy that drifts out of date.

Three things often need small changes to make this work: fixed-width types instead of compiler-specific ones, no assumptions about byte order that hold only on the target, and no reliance on the target's memory layout. Each of these is also a portability bug waiting to happen, so the refactor pays off beyond fuzzing.


Rule 2: One Harness per Parser

A libFuzzer harness is a single function the fuzzer calls with each input. LLVM's documentation shows the shape: a function named LLVMFuzzerTestOneInput that takes a pointer to the data and its size, passes them to the code under test and returns zero. It also states the requirement that matters most: the target must tolerate any kind of input, empty, huge or malformed.

#include <stdint.h>
#include <stddef.h>

int parse_frame(const uint8_t *buf, size_t n, cfg_t *cfg);   /* from the firmware */

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    cfg_t *cfg = (cfg_t *)__builtin_malloc(sizeof(cfg_t));    /* heap: exact bounds for ASan */
    parse_frame(data, size, cfg);
    __builtin_free(cfg);
    return 0;
}

Two details are deliberate. The output structure is allocated on the heap with its exact size, so AddressSanitizer can detect a write even one byte past its end. And the harness does nothing else: no logging, no global state, no randomness. The fuzzer works best when the same input always produces the same behaviour.

Building it is one command with a recent Clang, which includes libFuzzer: compile the parser and the harness with the fuzzer and sanitizer flags, for example -g -O1 -fsanitize=fuzzer,address,undefined, and the result is an executable that fuzzes the parser when run.


Rule 3: Run Under Sanitizers

Most memory bugs in C do not crash immediately. A write one byte past an array lands in the next variable, and the program carries on with corrupted state until something unrelated fails much later. On a microcontroller with no memory protection, that is exactly how a malformed radio frame turns into a device that stops reporting hours afterwards.

Sanitizers change this. They instrument the compiled code so that every memory access and many operations are checked, and the first violation stops the program with a report showing the exact line, the kind of error and the input that caused it. LLVM's libFuzzer documentation recommends combining the fuzzer with AddressSanitizer, UndefinedBehaviorSanitizer or both.

Sanitizer

Finds

Typical firmware bug it catches

AddressSanitizer

Out-of-bounds reads and writes on heap, stack and globals; use after free

A length field used to copy more bytes than the buffer holds

UndefinedBehaviorSanitizer

Out-of-range array indexing, integer overflow, invalid shifts, misaligned access

An off-by-one index inside a structure; a shift by more than the type width

MemorySanitizer

Reads of uninitialised memory

A field returned to the caller that was never written on one path

LeakSanitizer

Memory leaks

A parser that allocates and forgets to free on an error path

Use at least the first two together. The worked example below shows why: one of the two planted bugs was caught only by UndefinedBehaviorSanitizer.


Rule 4: Keep the Corpus and Run in CI

A fuzzer that runs once on an engineer's laptop finds today's bugs. A fuzzer in continuous integration catches tomorrow's.

Start each harness with a seed corpus: a handful of valid inputs, such as real configuration frames captured from a test device, committed to the repository next to the harness. On every pull request, CI builds the fuzz targets and runs each for a short time, a minute or two, starting from the corpus. Nightly, a longer run of an hour or more explores further, and any new interesting inputs it finds are added back to the corpus. Any crash fails the build and attaches the input that caused it.

fuzz:
  stage: test
  script:
    - clang -g -O1 -fsanitize=fuzzer,address,undefined src/cfg_parse.c fuzz/cfg_fuzz.c -o cfg_fuzz
    - ./cfg_fuzz -max_total_time=90 -timeout=5 fuzz/corpus/cfg
  artifacts:
    when: on_failure
    paths: [crash-*, timeout-*]

The corpus also works as a regression test. Running the fuzz executable with the corpus directory and no mutation replays every stored input, so a bug that was fixed and then reintroduced is caught immediately, even before any new fuzzing.

Commit the corpus next to the harness, fuzz briefly on every change and longer every night. A crash input attached to a failed build is the cheapest security review a firmware team will ever get.

A Worked Run: Two Planted Bugs, Found in Seconds

To make this concrete, we wrote a small configuration-frame parser of the kind found in sensor firmware and planted two realistic bugs in it. A frame starts with a sync byte and a length, carries a sequence of records, and ends with a CRC-8 over the payload. Each record has a type, a length and a value: type 1 is the device name, copied into a 16-byte field; type 2 is the report period; type 3 is a list of channel numbers, copied into an 8-byte array.

The first bug is the off-by-one from the opening email: the name length is checked with "greater than" instead of "greater than or equal", so a 16-byte name leaves no room for the terminator, and the code writes the terminator one byte past the field. The second bug is a missing check: the channel list is copied with whatever length the record claims.

The seed corpus held a single valid 20-byte frame. We built two versions, the buggy one and a fixed one, both with -fsanitize=fuzzer,address,undefined, and ran them with Clang 18 on an ordinary development machine.

Run

Result

Time and executions

Buggy parser, run until the first crash

AddressSanitizer: heap-buffer-overflow, a write of 17 bytes in the channel-list copy

1.48 seconds, about 650,000 inputs

Buggy parser, two-minute run

UndefinedBehaviorSanitizer: index out of bounds at the name terminator, plus the heap overflow

Both reported, with the line numbers of each bug

Fixed parser, one minute

No findings

36.1 million inputs in 61 seconds

Fixed parser, replaying the saved crash input

Runs cleanly

Immediate

Three things in the result are worth noticing. The fuzzer passed the CRC check without any help: libFuzzer watches comparisons in the code and uses the values it sees to guide mutations, so a single valid seed frame was enough to get through the checksum. The heap overflow was found in under two seconds, from one seed input. And the fix was verified the same way the bug was found: tens of millions of inputs with no findings, plus a replay of the saved crash file.


The Off-by-One That AddressSanitizer Missed

The device name bug is the more instructive of the two. The write of the terminator lands one byte past the end of the 16-byte name field, but that byte is still inside the configuration structure: it is the first byte of the next field. AddressSanitizer guards the edges of allocations, not the boundaries between fields inside one structure, so to AddressSanitizer this write looks legal.

UndefinedBehaviorSanitizer caught it, because writing to index 16 of a 16-element array is out of bounds for that array, whatever happens to sit after it in memory. The report named the file and the line.

On the device, this bug would have silently overwritten the low byte of the report period with zero whenever a 16-character name was configured. The symptom in the field would have been a device that reports at a strange interval after reconfiguration, which is the kind of fault that takes weeks to trace back to its cause. This is the reason for the rule to run both sanitizers: each catches errors the other cannot see.

Run more than one sanitizer. Memory checks guard allocations; undefined-behaviour checks guard array bounds inside them. A bug that hides between two fields of a structure needs the second.

Writing Bounds Checks That Survive Fuzzing

Fuzzing tends to teach a team a better style for bounds checks, and the lessons are worth adopting before the fuzzer finds them.

Compare lengths, not pointers. A check written as v + rlen > end computes a pointer that may lie beyond the buffer before comparing it, which is undefined behaviour in C if it goes past one element beyond the end. Writing the same check as rlen > (size_t)(end - v) compares two lengths and never forms an invalid pointer.

Check against the space remaining, not the buffer size. The opening email's bug, and many real ones, compare a length with the total buffer size rather than with what is left after the header and earlier records.

Validate before copying, and copy with the destination's size. Every copy into a fixed field should be guarded by a comparison with that field's size, written with sizeof on the destination so a later change to the field cannot silently break it.

Reject, do not truncate, unless the protocol says otherwise. Quietly truncating an oversized field hides malformed input and can create inconsistencies between what was received and what was stored.

Return a specific error code for each failure. Distinct codes make fuzzing reports and field logs easier to read, and they let tests check that each rejection happens for the right reason.


Measuring What the Fuzzer Reaches

A fuzzer that runs without finding anything is either testing good code or not reaching the code at all, and the two look the same from the outside. Coverage reports tell them apart.

Build the harness a second time with source-based coverage instrumentation, replay the corpus through it, and generate a line-by-line report of the parser. Lines the corpus never reached show where the fuzzer is blocked: often behind a checksum, a magic number, a length that must match another field, or a record type that no seed contains. Each blocked region suggests a fix, such as a new seed input, a dictionary entry or a fuzz-build switch that skips a check.

Track two numbers per harness over time: the share of the parser's lines reached by the corpus, and the number of inputs in the corpus. Coverage that climbs and then flattens is normal. Coverage that stays low from the start means the harness or the seeds need work before the results mean much. A parser at high coverage with no findings after a long run has earned some trust; one at low coverage has not, however long the fuzzer ran.


Structured Inputs: Checksums, Lengths and State

Real protocols have structure that can slow a fuzzer down: checksums, length fields that must agree with each other, magic numbers and nested records. The worked example shows that libFuzzer's comparison tracing gets through a CRC-8 easily, but stronger checks, such as a 32-bit CRC or a cryptographic signature, can stop it at the front door.

Three techniques help. A fuzz-build switch can skip checksum and signature verification, so the fuzzer explores the parsing behind them; the verification code itself gets its own separate harness. A dictionary file lists magic values, keywords and field markers that the fuzzer should try, which helps with text formats and protocols with fixed tokens. And a structured-input helper, such as the FuzzedDataProvider class that comes with libFuzzer, lets a harness consume the fuzzer's bytes as typed values, which suits parsers that take several separate arguments rather than one buffer.

For protocols with state, such as a session that requires a handshake before commands are accepted, the harness can treat the input as a sequence of messages: split the bytes into chunks and feed them to the state machine one at a time. The fuzzer then explores sequences of messages, which is how state-machine bugs, such as a command accepted before authentication, are found.


On-Target Fuzzing and When You Need It

Host fuzzing covers parsing logic, which is where most input-handling bugs live. It does not cover bugs that depend on the target: interrupt timing, DMA, peripheral quirks, the real memory layout or a compiler that behaves differently for the target architecture.

For those, there are slower options. Emulators can run the real firmware image with fuzzed inputs injected into the emulated peripherals, which finds bugs in driver and integration code at a fraction of host speed. Hardware-in-the-loop fuzzing sends mutated frames to a real device over its real interface and watches for resets, hangs and watchdog events; it is slow, often a few inputs per second, but it tests the exact product.

A sensible split is host fuzzing for every parser on every change, emulation for the firmware's input paths before releases, and hardware-in-the-loop for the radio and bus interfaces of each new product, run for days rather than minutes.


Triage: The First Week of Findings

A code base that has never been fuzzed usually produces a burst of findings in its first days. Handled badly, that burst becomes a pile of crash files that nobody reads. Handled well, it becomes a short list of fixes.

Start by grouping crashes by their stack trace. Many crash files are the same bug reached by different inputs, and the sanitizer report's top frames identify it. libFuzzer can minimise a crash input to the smallest bytes that still reproduce the failure, which makes the cause easier to see and the regression test easier to read.

Then rank by reachability, not by the sanitizer's wording. A heap overflow in a parser that accepts frames over the air from anyone is urgent; the same overflow in a parser that only reads a file written by the device's own firmware is less so, though still worth fixing. Ask for each finding: who can send these bytes to the device, and what happens on the target if they do?

Group crashes by stack trace, minimise the inputs, and rank by who can reach the parser. Ten crash files are usually two bugs, and only one of them faces the radio.

Fix each bug at its cause, not by catching the crash. Add the minimised input to the regression folder, confirm that the fuzz target replays it cleanly, and run the fuzzer again. A fix that only moves the crash to the next line shows up within minutes.


What Fuzzing Costs to Run

Fuzzing is cheap compared with most security work. The fixed parser in the worked example ran 36.1 million inputs in a minute on a single core of an ordinary machine. A firmware product with a dozen parsers, each fuzzed for 90 seconds per change, adds a few minutes of CI time, which parallel jobs can absorb. A nightly run of an hour per parser on a spare machine or a cloud instance costs very little.

The real cost is engineering time: refactoring parsers to be host-buildable, writing harnesses, and triaging the first wave of findings, which on a mature code base that has never been fuzzed can be substantial. Budget a few days per parser for the first pass, and expect most of the effort to go into fixing what the fuzzer finds rather than into the fuzzer itself.


Where Fuzzing Fits in Secure Development and Compliance

Regulation is moving in the same direction. The EU Cyber Resilience Act requires manufacturers of products with digital elements to handle vulnerabilities and to test the security of their products, and industrial security standards for secure product development include robustness testing with malformed inputs among their verification practices. Fuzzing is one of the most direct ways to show that testing happened, because it produces evidence: the harnesses, the corpus, the CI logs and the record of findings and fixes.

Keep that evidence. A short record per parser, listing the harness, the sanitizers used, total executions and every finding with its fix, fits naturally next to the software bill of materials and the secure boot design in a product's security file. When a customer or an auditor asks how input handling was tested, the answer is a link rather than a promise.


A Rollout Plan for a Firmware Team

  1. List the parsers. Walk the entry-point table above for your product and list every function that interprets bytes from outside the processor.

  2. Pick the riskiest first. Start with parsers that accept input over the air or from a network, then fieldbus, then files.

  3. Refactor one parser to a pure interface. Buffer, length and output structure in; status out; no hardware access.

  4. Write its harness and seed corpus. Capture a few real valid frames as seeds.

  5. Run it locally under sanitizers for an hour. Fix what it finds, and add each crash input to a regression folder.

  6. Add it to CI. A short run per change and a long run nightly, with the corpus committed.

  7. Repeat for the next parser. Most teams find the second and third parsers much faster than the first.

  8. Review quarterly. Check coverage reports for parsers whose fuzzers have stopped finding new paths, and improve their seeds or dictionaries.


When Fuzzing Is the Wrong Tool

Fuzzing finds input-handling bugs. It does not find design flaws, such as a protocol that accepts unauthenticated commands by design, a key stored in plain text or an update path without signature checks. Those need threat modelling and review.

It is also weak where correctness depends on meaning rather than on memory safety. A parser that decodes a temperature with the wrong scaling will never crash, and no fuzzer will notice. Unit tests with known inputs and outputs remain essential.

And it struggles with code that cannot be separated from hardware or timing without a major rewrite. In those cases, start with careful review and emulation, and plan the refactor for the next major version.


Back to the 40-Byte Packet

The researcher's frame was found by a person with a hex editor and patience. A fuzzer with a single valid seed frame and a pair of sanitizers would have found the same class of bug in seconds, before the firmware ever shipped, and would have kept finding the next one every time someone changed the parser. The three-line fix was right. The lasting fix is the harness, the corpus and the line in CI that runs them.


Every parser that reads untrusted bytes deserves the same treatment, starting with the one that faces the radio.

EurthTech is an engineering-first product design and embedded systems company with a development center in Hyderabad. To discuss a project, write to connect@eurthtech.com or see https://www.eurthtech.com/case-studies.

Comments


EurthTech delivers AI-powered embedded systems, IoT product engineering, and smart infrastructure solutions to transform cities, enterprises, and industries with innovation and precision.

Factory:

Plot No: 41,
ALEAP Industrial Estate, Suramapalli,
Vijayawada,

India - 521212.

  • Linkedin
  • Twitter
  • Youtube
  • Facebook
  • Instagram

 

© 2026 by Eurth Techtronics Pvt Ltd.

 

Development Center:

4th Floor, Krishna towers, 100 Feet Rd, Madhapur, Hyderabad, Telangana 500081

Menu

|

Accesibility Statement

bottom of page