Finding Bugs in Parsers
Vulnerability Discovery Case Studies · VR Analysis & Discovery track
9 min read
In this module
Why Parsers Are Vulnerability Magnets
Parsers consistently account for a disproportionate share of security vulnerabilities. Image decoders, network protocol handlers, document processors, archive extractors, certificate parsers, font renderers — these components show up in virtually every major vulnerability disclosure. Understanding why parsers are so reliably exploitable, and how to find their bugs efficiently, is foundational to practical vulnerability research.
The Parser Vulnerability Triangle
Three factors combine to make parsers especially dangerous:
Complex untrusted input - parsers must handle input formats with intricate structure: nested containers, variable-length fields, multiple encoding schemes, recursive definitions, and interdependent sections. Each piece of complexity is an opportunity for the parser to make an incorrect assumption.
Performance pressure - parsers are often in the hot path. Image decoders must handle millions of pixels per second. Network protocol parsers must handle thousands of packets per second. This pressure leads developers to optimise validation away ("we can skip this check for performance") or use unsafe but fast functions.
Specification ambiguity - most file format and protocol specifications leave edge cases undefined or underspecified. What happens when a length field is zero? When a chunk type is unknown? When two fields contradict each other? Different implementations handle these cases differently, and the differences often contain vulnerabilities.
Common Parser Bug Patterns
Certain vulnerability patterns appear again and again in parser code:
Trusting length fields - the most common parser vulnerability. The input contains a field that specifies the length of subsequent data, and the parser trusts it without validating against the actual remaining input:
// VULNERABLE: trusts chunk_length from fileuint32_t chunk_length = read_u32(input);char *chunk_data = malloc(chunk_length);memcpy(chunk_data, input + 4, chunk_length); // Over-read if chunk_length > remainingInteger overflow in compound calculations - when dimensions, counts, or sizes from the input are multiplied together:
// VULNERABLE: width * height can overflowuint32_t width = read_u32(input);uint32_t height = read_u32(input);uint32_t bpp = read_u32(input);size_t buffer_size = width * height * bpp; // Overflow -> small allocationuint8_t *buffer = malloc(buffer_size);decode_pixels(input, buffer, width, height, bpp); // Writes past allocationState confusion in multi-pass parsing - when a parser makes multiple passes over the input and assumptions from pass 1 are violated in pass 2:
// Pass 1: count elementsint count = 0;while (has_more_elements(input)) { skip_element(input); count++;}
// Allocate array based on countelement *elements = malloc(count * sizeof(element));
// Pass 2: parse elements - but what if the input changes between passes?// Or what if skip_element and parse_element disagree on element boundaries?reset_input(input);for (int i = 0; i < count; i++) { parse_element(input, &elements[i]); // May overrun if boundaries differ}Off-by-one in null termination - string handling in parsers often has subtle off-by-one errors:
// VULNERABLE: reads exactly 'length' bytes but needs space for null terminatorchar name[64];uint8_t length = read_u8(input);if (length > 64) return ERROR; // Should be > 63!memcpy(name, input + 1, length);name[length] = '\0'; // Off-by-one write if length == 64Here's the start of a PNG with every length-like field picked out. The IHDR chunk is honest. The tEXt chunk after it claims about 4 GB of text, and then the file ends ten bytes later. Click each field and put the four questions from the callout below to it.
A PNG that ends early
Click a coloured byte or a field name to decode it
When auditing parsers, every length field in the input is a potential vulnerability. For each one, ask: (1) Is it validated against remaining input? (2) Is it validated against allocation sizes? (3) Can it overflow when used in arithmetic? (4) Is it consistent with other length/count fields? A single missed validation on a length field has been responsible for hundreds of CVEs across the software ecosystem.
Differential Testing
Differential testing is one of the most effective techniques for finding parser bugs. The idea is simple: feed the same input to two or more independent implementations of the same format and compare their behaviour. When they disagree, at least one has a bug.
# Differential testing script for image decodersimport hashlibimport subprocess
def test_input(input_file): results = {}
# Test with multiple decoders decoders = [ ("libpng", ["./decode_libpng", input_file]), ("stb_image", ["./decode_stb", input_file]), ("lodepng", ["./decode_lodepng", input_file]), ]
for name, cmd in decoders: try: result = subprocess.run(cmd, capture_output=True, timeout=5) results[name] = { "returncode": result.returncode, "output_hash": hashlib.sha256(result.stdout).hexdigest(), "crashed": result.returncode < 0, } except subprocess.TimeoutExpired: results[name] = {"returncode": None, "output_hash": None, "timeout": True}
# Disagreement 1: decoders differ on accept/reject/crash/timeout return_codes = set(r["returncode"] for r in results.values()) # Disagreement 2: every decoder succeeded but the pixels differ all_ok = return_codes == {0} output_hashes = set(r["output_hash"] for r in results.values())
if len(return_codes) > 1 or (all_ok and len(output_hashes) > 1): print(f"DISAGREEMENT on {input_file}:") for name, r in results.items(): print(f" {name}: return={r['returncode']} output={r['output_hash']}") return True
return FalseDisagreements worth investigating:
- One decoder crashes, others succeed - the crashing decoder likely has a vulnerability
- One decoder rejects, others accept - the accepting decoders may be too permissive (accepting malformed input that exercises untested code)
- All succeed but produce different output - at least one decoder is parsing the format incorrectly, which may indicate a vulnerable code path
Fuzzing Parsers Effectively
Combine the fuzzing techniques from Advanced Fuzzing Techniques with parser-specific strategies:
Dictionary-driven fuzzing - create a dictionary of format-specific tokens:
# png.dict"\x89PNG" # Magic bytes"\x00\x00\x00\x0d" # Standard IHDR length"IHDR" # Image header chunk type"IDAT" # Image data chunk"IEND" # End chunk"tEXt" # Text chunk"pHYs" # Physical dimensions"\x00" # Color type: grayscale"\x02" # Color type: RGB"\x06" # Color type: RGBAStructure-aware mutation - write a custom mutator that understands the chunk format:
// Mutate a PNG-like chunk formatsize_t mutate_chunks(uint8_t *data, size_t size, size_t max_size) { size_t offset = 8; // Skip file header
while (offset + 8 <= size) { uint32_t length = read_u32_be(data + offset); // Randomly mutate this chunk int action = rand() % 5; switch (action) { case 0: // Corrupt the length field write_u32_be(data + offset, rand() % 0x10000); break; case 1: // Corrupt the type field data[offset + 4 + (rand() % 4)] ^= (1 << (rand() % 8)); break; case 2: // Corrupt chunk data if (length > 0 && offset + 8 + length <= size) { size_t pos = rand() % length; data[offset + 8 + pos] = rand() % 256; } break; case 3: // Duplicate this chunk (if space allows) // ... break; case 4: // Delete this chunk // ... break; } // Fix up the CRC (over type + data), or the decoder rejects the // chunk before the interesting code ever sees it. Skip it if the // chunk now runs past the end of the buffer. uint32_t new_len = read_u32_be(data + offset); if (offset + 8 + new_len + 4 <= size) { uint32_t crc = crc32(0, data + offset + 4, 4 + new_len); // zlib write_u32_be(data + offset + 8 + new_len, crc); }
offset += 8 + length + 4; // Move to next chunk } return size;}Edge-case seed generation - create seeds that exercise boundary conditions:
- Minimum-size valid file (1x1 pixel, no optional chunks)
- Maximum-dimension file (65535x65535 but tiny file size)
- Files with every optional chunk type
- Files with unusual but valid colour types and bit depths
- Files with multiple identical chunks (if the format allows it)
Real Parser Vulnerability Discoveries
libpng CVE-2014-9495 and CVE-2015-0973 - a pair of heap buffer overflows fixed in libpng 1.5.21 and 1.6.16. Both come from very large image widths taken from the IHDR chunk: CVE-2014-9495 is in png_combine_row with very wide interlaced images on 64-bit systems, and CVE-2015-0973 is in png_read_IDAT_data. It's the same size-calculation pattern this module keeps coming back to: a dimension from the file feeding arithmetic that nobody checked.
libtiff multiple CVEs - TIFF's complex format with hundreds of tag types and multiple compression schemes has produced dozens of vulnerabilities over the years. Many were found by fuzzing with AFL, which excels at exploring the many code paths activated by different tag combinations.
libxml2 CVEs - XML parsing vulnerabilities including billion-laughs attacks (exponential entity expansion, a resource exhaustion problem rather than memory corruption), XXE (XML External Entity) injection, which is a logic bug, and various buffer overflows in attribute parsing, which are genuine memory corruption.
The common thread: complex formats with abundant optional features and edge cases, processed by C code under performance pressure. That combination reliably produces vulnerabilities. Source-sink analysis, pattern matching, format-aware fuzzing, differential testing — these are the proven methods for surfacing them.