TExcelTAD

Binary Formats with struct

Network protocols, file formats and malware configuration blobs are binary: fixed-size fields, big- or little-endian integers, and length fields that say how many bytes follow. Parsing them is where many of the worst vulnerabilities in history were born. Heartbleed (CVE-2014-0160) was an OpenSSL handler that believed a length field sent by the peer and copied that many bytes back, leaking up to 64 KiB of server memory per request. In Python such a bug cannot read stray memory, but it can still crash your tool, loop forever or produce a wrong report. This lesson parses binary data with struct and checks every length before trusting it.

Definitions

  • struct.unpack(fmt, data) turns bytes into a tuple of numbers according to a format string; struct.pack does the reverse. struct.calcsize(fmt) gives the size.
  • Byte order prefix: ! or > big-endian ("network order", used by IP, TCP, DNS, TLS), < little-endian (x86, most file formats on Windows). Without a prefix, struct uses the machine's native order and alignment: never use that for wire formats.
  • Codes: B unsigned 8-bit, H unsigned 16-bit, I unsigned 32-bit, Q 64-bit, lowercase for signed, 4s four raw bytes.
  • TLV: type–length–value, the common shape of options and extensions (TLS extensions, DHCP options, TCP options).

An IPv4 header from bytes

The 20 bytes below are a lab packet from 10.10.0.5 to 10.10.0.10 (the layout is taught in The IPv4 Header Byte by Byte). The parser unpacks the fixed part, checks the version and header length against the data it actually has, and verifies the header checksum (RFC 791: the ones' complement of the ones' complement sum of the 16-bit words).

python · try it yourself
import struct, ipaddress

hdr = bytes.fromhex("4500003c1c46400040060a540a0a00050a0a000a")

def checksum(data):
    total = sum(struct.unpack(f"!{len(data)//2}H", data))
    while total > 0xFFFF:
        total = (total & 0xFFFF) + (total >> 16)
    return ~total & 0xFFFF

def parse_ipv4(data):
    if len(data) < 20:
        raise ValueError(f"truncated: {len(data)} bytes, need 20")
    ver_ihl, tos, total_len, ident, flags_frag, ttl, proto, csum, src, dst = \
        struct.unpack("!BBHHHBBH4s4s", data[:20])
    version, ihl = ver_ihl >> 4, (ver_ihl & 0x0F) * 4
    if version != 4 or ihl < 20 or ihl > len(data):
        raise ValueError(f"bad version/IHL: {version}/{ihl}")
    return {"src": str(ipaddress.ip_address(src)), "dst": str(ipaddress.ip_address(dst)),
            "ttl": ttl, "proto": proto, "total_len": total_len,
            "df": bool(flags_frag & 0x4000), "csum_ok": checksum(data[:ihl]) == 0}

print(struct.calcsize("!BBHHHBBH4s4s"))
print(parse_ipv4(hdr))
tampered = hdr[:8] + bytes([1]) + hdr[9:]            # change the TTL to 1
print("tampered checksum ok:", parse_ipv4(tampered)["csum_ok"])
for bad in [hdr[:12], bytes([0x4F]) + hdr[1:]]:
    try:
        parse_ipv4(bad)
    except ValueError as e:
        print("rejected:", e)
20
{'src': '10.10.0.5', 'dst': '10.10.0.10', 'ttl': 64, 'proto': 6, 'total_len': 60, 'df': True, 'csum_ok': True}
tampered checksum ok: False
rejected: truncated: 12 bytes, need 20
rejected: bad version/IHL: 4/60

The checksum over a correct header (including its own checksum field) comes out as 0, so csum_ok is True; changing one byte breaks it. The two bad inputs are refused with a reason instead of an IndexError deep in the code: one is too short, the other claims a 60-byte header (IHL 15) in 20 bytes of data.

Lengths that lie

A TLV stream is a loop: read type and length, take length bytes, repeat. A malicious peer controls the length. The safe parser checks that the value fits in what remains, and that the loop always moves forward.

python · try it yourself
import struct

def parse_tlv(data, limit=64):
    out, pos = [], 0
    while pos < len(data):
        if len(out) >= limit:
            raise ValueError("too many records")
        if len(data) - pos < 3:
            raise ValueError(f"truncated header at offset {pos}")
        t, n = struct.unpack_from("!BH", data, pos)
        pos += 3
        if n > len(data) - pos:
            raise ValueError(f"record type {t} claims {n} bytes, only {len(data) - pos} left")
        out.append((t, data[pos:pos + n]))
        pos += n
    return out

good = struct.pack("!BH", 1, 5) + b"alice" + struct.pack("!BH", 2, 2) + b"\x00\x2a"
print(parse_tlv(good))
lying = struct.pack("!BH", 1, 0x4000) + b"hi"        # claims 16384 bytes, sends 2
for data in [lying, good[:6]]:
    try:
        parse_tlv(data)
    except ValueError as e:
        print("rejected:", e)
[(1, b'alice'), (2, b'\x00*')]
rejected: record type 1 claims 16384 bytes, only 2 left
rejected: record type 1 claims 5 bytes, only 3 left

Slicing in Python never reads past the end (data[pos:pos+n] just returns fewer bytes), which is exactly why the check matters: without it, the parser would accept a record that is shorter than it claims and report it as complete. In C, the same missing check reads whatever lies after the buffer, which is Heartbleed.

How such bugs are detected

  • Fuzzing: feed the parser truncated, extended and bit-flipped versions of valid input and watch for exceptions other than your own ValueError, hangs and huge memory use. The testing lesson builds a small one.
  • Differential checks: parse the same pcap with your tool and with tshark and compare fields.
  • Code review of every place a length or count from the input is used: allocation sizes, loop bounds, slice ends, offsets.

How they are prevented

  1. Check remaining >= needed before every read, using struct.unpack_from with an explicit offset.
  2. Cap counts and sizes (limit=64 records, a maximum message size) so that a valid-looking input cannot make the tool allocate gigabytes.
  3. Make progress mandatory: every loop iteration must advance pos, or a zero-length record can spin forever in formats where the length includes the header.
  4. Raise one exception type for malformed input and catch it at the tool's edge, where it becomes a finding.
  5. Use a maintained parser (Scapy, dpkt, cryptography's X.509) when one exists; write your own only for formats you own or to learn.

Pitfalls

  • Native byte order. struct.unpack("HH", ...) on x86 is little-endian with alignment padding: wrong for every network protocol.
  • Signed versus unsigned. h turns 0xFFFF into -1; a negative length then makes data[pos:pos+n] an empty slice, or, once pos+n is negative, a slice counted from the end of the data, and pos += n moves backwards.
  • Header length versus total length. IPv4 has both, TLS records and handshake messages each have their own: check each against the bytes that are really there.

Practice

1. What do struct.unpack("!H", b"\x01\x02") and struct.unpack("<H", b"\x01\x02") return?

(258,) big-endian (0x0102) and (513,) little-endian (0x0201).

2. A TLV format's length counts the 3-byte header too. Which extra check does the parser need?

Reject n < 3: otherwise n = 0 would give pos += n - 3, moving backwards, and an infinite loop or a negative slice. Then check n - 3 <= remaining.

3. Extend parse_ipv4 to report the options length. For which IHL values are there options?

Options length is ihl - 20; there are options when the IHL field is 6 to 15 (24 to 60 bytes). Check that ihl <= len(data) (already done) and return data[20:ihl] as the options.

Test yourself

Which struct prefix means network byte order?

  1. <
  2. !
  3. @
  4. =

What was the root cause of Heartbleed?

  1. A weak cipher
  2. Trusting a length field from the peer and copying that many bytes back
  3. A buffer on the heap that was too large
  4. A missing TLS certificate

In Python, data[pos:pos+n] with n larger than what remains:

  1. raises IndexError
  2. reads past the end of the buffer
  3. returns fewer bytes than n without complaint
  4. returns None

The checksum function returns 0 for the original header. Why?

  1. The header is empty
  2. Summing a header that includes a correct checksum field gives 0xFFFF, whose complement is 0
  3. The function is broken
  4. IPv4 has no checksum