Section 4.29

Deserialization

Definition

Deserialization is the conversion of a sequence of bytes back into structured values, such as the fields of a record, according to a format; it is the reverse of serialization §4.28. Its core is a parser, the code that finds where each field starts and ends and reads its value. For bytes from outside the program, deserialization also validates: it checks that every byte it reads is present, that each value is in its permitted range and that the requested memory and work are affordable, and it rejects the input otherwise.

The idea

Deserialization is usually the first code that turns bytes chosen by someone else into numbers the program acts on. A received count becomes the size of a memory request; a received position becomes an index into a table; a received code chooses which function runs. Whoever wrote the bytes, possibly an attacker, chooses those numbers. Many memory-safety bugs start here: an out-of-bounds read §4.5 past the end of the input, a buffer overflow §4.4 caused by an index that was never checked, a size calculation that overflows, or a memory request so large that the device runs out of memory.

A loading dock is a fair picture. A delivery note says “20 boxes, 16 kilograms each”. Before any box enters the warehouse, the dock counts the boxes actually on the truck, checks that 20 boxes are allowed and that the floor holds 20×16=32020 \times 16 = 320 kilograms, and checks who sent them. The note is a claim; counting and weighing are the checks. The picture stops in one place: a dock can send a wrong delivery back, but a program cannot undo an effect, such as exhausted memory, that happened before a check failed.

This leads to the principle that language-theoretic security (LangSec), a line of research on safe input handling, calls full recognition before processing: decide whether the whole input is valid before acting on any part of it. Its opposite, which the same research calls shotgun parsing, scatters checks through the code that acts on the data, so some effects happen before the input is known to be valid.

How it works

A deserializer runs on bytes that nobody has checked yet, so every step below must be safe for any input. Each check comes before the first use it protects.

  1. Presence. Before reading a field of kk bytes at offset oo in an input of nn bytes, check that o≤no \le n and k≤n−ok \le n - o. The test k≤n−ok \le n - o cannot overflow, because it subtracts only after o≤no \le n is known; the sum o+ko + k can overflow when oo and kk are large, so comparing o+ko + k with nn can let a huge kk through. The overflow-safe range check §4.17 entry treats this in full.

  2. Syntax. Decode each field by the format’s rule, such as a 4-byte big-endian §4.21 unsigned number, and check the structure: a known version and type, nested lengths that stay inside their enclosing field, and no unexpected bytes after the end.

  3. Ranges. Check each value against the range the application permits, which is usually far smaller than the range the field can hold.

  4. Resources. Before memory is reserved, check that the requested amount fits a budget, with arithmetic that cannot overflow. Before an index is used, check that it is below the length of the table. Before descending into a nested structure, check the nesting depth. Limit the total number of fields and the total work.

  5. Authentication §1.6. Verify the message’s tag, for example a message authentication code §5.7, over the exact bytes that will be used. Some bounded parsing, such as finding where the tag sits, has to come before this step, which is why steps 1 to 4 must be safe on unauthenticated input.

  6. Authorization §1.7. Decide whether this sender may perform this operation on this target now.

  7. Effect. Only now build the trusted value and hand it to the code that acts on it.

The point where unchecked bytes start to steer the program is a trust boundary §1.3: a place where data from a less trusted party starts to drive a more trusted part. Each step above establishes one more fact about the input, and no fact implies the next. Strict parsing §1.48, which rejects every input the format does not allow instead of guessing what the sender meant, keeps all components that read the same bytes in agreement.

Some deserializers go further and let the input name a type to create or a function to call. Python’s §12.23 pickle module and Java’s built-in object serialization work this way, and an attacker who controls the bytes can make them run code that the program never meant to run. The Common Weakness Enumeration (CWE), a public catalog of software weaknesses, lists this as CWE-502, deserialization of untrusted data. A deserializer for untrusted input creates only values of types that the format fixes in advance, and it checks any code in the input that selects a function against a fixed list of allowed functions.

Worked example

A format has 5 bytes: a tag of 1 byte, then a count as a 4-byte big-endian unsigned number. Tag 1 asks the receiver to prepare count records of 16 bytes each. The application allows at most 1000 records and has a budget of 16,000 bytes for them.

Valid input 01 00 00 01 02. Presence: 5 bytes arrived and 5 are needed. Syntax: tag 1 is known, and the count is 0×2563+0×2562+1×256+2=2580 \times 256^3 + 0 \times 256^2 + 1 \times 256 + 2 = 258. Range: 258≤1000258 \le 1000. Resources: 258×16=4128258 \times 16 = 4128 bytes, which fits the 16,000-byte budget. The input passes steps 1 to 4. Authentication and authorization still come before the records are produced.

Truncated input 01 00 00. Only 3 bytes arrived, and the count needs bytes 1 to 4. The presence check fails, so the parser rejects the input without reading past byte 2. Reading on would take whatever bytes happen to lie next in memory, an out-of-bounds read.

Overflowing count 01 10 00 00 01. The count is 0x10000001, which is 268,435,457. A parser that computes the memory size in 32-bit unsigned arithmetic gets 268,435,457×16=4,294,967,312268{,}435{,}457 \times 16 = 4{,}294{,}967{,}312, which exceeds 232=4,294,967,2962^{32} = 4{,}294{,}967{,}296 by 16. Unsigned arithmetic in C keeps only the remainder modulo 2322^{32}, so the computed size is 16 bytes. The program reserves 16 bytes and then writes 268 million records into them, a buffer overflow on the heap. The correct order compares first: ⌊16,000/16⌋=1000\lfloor 16{,}000 / 16 \rfloor = 1000, and 268,435,457>1000268{,}435{,}457 > 1000, so the input is rejected before any multiplication. The format can carry this count; the application must still refuse it.

Unknown operation 09 00 00 00 01. All 5 bytes are present, but tag 9 is not a known operation, so the syntax check rejects the input.

Stated precisely

Let the input be nn bytes long. Reading kk bytes at offset oo is allowed exactly when o≤no \le n and k≤n−ok \le n - o. Let cc be a requested count, s>0s > 0 the bytes needed per item and BB the budget in bytes, all whole numbers. The resource condition c×s≤Bc \times s \le B holds exactly when c≤⌊B/s⌋c \le \lfloor B / s \rfloor, where ⌊x⌋\lfloor x \rfloor means xx rounded down to a whole number. The second form needs no product, so it cannot overflow. It is exact because cc is a whole number: c×s≤Bc \times s \le B means c≤B/sc \le B / s, and a whole number is at most B/sB / s exactly when it is at most ⌊B/s⌋\lfloor B / s \rfloor. With a budget of 31 bytes and 16-byte items, ⌊31/16⌋=1\lfloor 31 / 16 \rfloor = 1: one item fits, and two would need 32 bytes.

A deserializer for untrusted input meets this contract. For every byte string it either rejects or returns a value that satisfies every rule of the format and every range the application sets. It reads no byte outside the input, and its memory, time and nesting depth stay below limits fixed in advance. No allocation, index, call or change of state uses a field before the check that bounds that field. Each check establishes a separate fact: presence that the bytes exist, range that a value is permitted, resources that the request is affordable, authentication that a key holder produced the bytes, and authorization that the request is allowed. A passed check never stands in for a missing one.

Limits and common mistakes

A memory-safe language moves the checks; it does not remove them. A memory-safe language, such as Rust outside its unsafe blocks, Java or Python, prevents a program from reading or writing memory outside a live object. For array §14.5 indexes it mainly inserts a runtime bounds check §2.27, omitted only where the compiler proves the index in range, and a failed check stops the program or raises an error instead of corrupting memory. Such a language still allows a huge memory request, a wrong limit, a misread field or a skipped authorization, and a crash on a failed check is a denial of service §1.28. Rust’s integer arithmetic wraps around silently in default release builds, and unsafe code and calls into C libraries lie outside the guarantee.

Well formed is not acceptable, and authentic is not authorized. A message can follow the format exactly and still ask for a billion records. A message with a valid tag can still request an operation that its sender may not perform.

A late check cannot undo an early effect. Effects that happen before a failed check remain: exhausted memory, a written log entry, a partial change of state.

Two parsers of one format must agree. When a gateway checks a message with one parser and the target acts on it with another, any disagreement about repeated fields, unknown fields, trailing bytes or number syntax lets one byte string mean two things. Such a disagreement is called a parser differential.

Read shared input once. A parser that reads a length from memory that another processor or program can change, checks it, and then reads it again to use it may use a different value from the one it checked, a time-of-check to time-of-use §9.26 (TOCTOU) error. Copy the input into private memory first, or read each field exactly once.

Questions answered

Which validation occurs before allocation, indexing, or native calls?

Every check that bounds a value occurs before the first use of that value: presence, syntax, range and resource checks first, then authentication and authorization before any effect. In detail:

Steps that only locate the tag, such as reading a bounded header, may come before authentication, but they must be safe for any input, and no field read before authentication may cause an effect. In the worked example, a count of 268,435,457 is rejected because it exceeds ⌊16,000/16⌋=1000\lfloor 16{,}000 / 16 \rfloor = 1000, before a 32-bit multiplication could wrap it to 16 bytes.

Related entries: Length-prefix framing (§4.30), Type-length-value (TLV) (§4.31), Authorization (§1.7), Trust boundary (§1.3), Overflow-safe range check (§4.17), Robustness principle and strict parsing (§1.48).