Section 4.31

Type-length-value (TLV)

Definition

Type-length-value (TLV) is a pattern for encoding a sequence of fields in which each field has three parts: a type, a code that says what the field means; a length, the number of bytes in the value; and the value itself. A reader can skip a field of unknown type by its length. A value can itself be a sequence of TLV fields, so the pattern nests. TLV is a family of formats, not one standard: each format fixes the widths of type and length and what the length counts.

The idea

Formats change over time. A newer sender adds a field that an older receiver has never heard of, and optional fields appear in some messages and not in others. With fixed positions, every new field breaks every old reader. TLV makes every field announce its own kind and size, so a reader takes the fields it knows and steps over the rest. Many formats use it: the encodings of ASN.1 (Abstract Syntax Notation One), which write a tag, a length and the contents and which public-key certificates use; the options of DHCP (Dynamic Host Configuration Protocol) and of TCP (Transmission Control Protocol); and, with the length written first, Bluetooth advertising data.

The price is that every length is a number the sender wrote. Nesting adds a second constraint: a field inside a container must end inside the container. Boxes packed in a crate are the picture: a box inside the crate cannot be longer than the crate, whatever its label says. The parser enforces this by never letting a nested parse see beyond the end of its container.

How it works

A TLV format must state:

Parse a sequence that occupies the positions from ss up to but not including ee, the half-open interval §14.12 [s,e)[s, e). Let hh be the number of bytes of type and length together.

  1. Set the position pp to ss.

  2. While p<ep < e, let R=e−pR = e - p be the bytes left in the enclosing sequence. If R<hR < h, reject: the header is cut off. Otherwise read the type and the declared value length LL.

  3. If L>R−hL > R - h, reject: the value would run past the end of the enclosing sequence.

  4. The value occupies [p+h,p+h+L)[p + h, p + h + L). Decode it within that interval only. If the type is a container, parse its value with this same procedure, with [p+h,p+h+L)[p + h, p + h + L) as the new [s,e)[s, e) and the nesting depth increased by one, and reject if the depth exceeds a fixed limit. If the type is unknown, skip the field or reject the message, as the format says.

  5. Advance pp to p+h+Lp + h + L, header included, and repeat from step 2.

When the loop ends, p=ep = e exactly.

Three details carry the safety. The test L>R−hL > R - h runs only after R≥hR \ge h is known, so the subtraction cannot go below zero, and the sum p+h+Lp + h + L is formed only after the test, so it cannot overflow. The nested parse receives its container’s interval, not the whole packet. And every field advances pp by at least hh bytes, even a field with an empty value, so the loop ends after at most (e−s)/h(e - s) / h fields. Limits on the number of fields and on the nesting depth also bound the work and the depth of recursion, which would otherwise risk a stack overflow §4.10, the call stack outgrowing its memory.

Worked example

Use a 1-byte type and a 1-byte length that counts only the value, so h=2h = 2. Type 10 is a container, type 02 a name, type 04 a flag with an empty value and type 20 a 2-byte number. A 13-byte packet holds a container followed by a number; its bytes sit at positions 0 to 12:

10 07 02 03 61 62 63 04 00 20 02 AA BB

Top level, [0,13)[0, 13). At p=0p = 0: R=13R = 13, type 10, L=7L = 7, and 7≤13−2=117 \le 13 - 2 = 11. The container’s value is [2,9)[2, 9), and pp becomes 0+2+7=90 + 2 + 7 = 9. At p=9p = 9: R=13−9=4R = 13 - 9 = 4, type 20, L=2L = 2, and 2≤4−2=22 \le 4 - 2 = 2. The value [11,13)[11, 13) is AA BB, and pp becomes 9+2+2=139 + 2 + 2 = 13, which equals ee.

Inside the container, [2,9)[2, 9). At p=2p = 2: R=9−2=7R = 9 - 2 = 7, type 02, L=3L = 3, and 3≤7−2=53 \le 7 - 2 = 5. The value [4,7)[4, 7) is 61 62 63, the text "abc", and pp becomes 2+2+3=72 + 2 + 3 = 7. At p=7p = 7: R=2R = 2, type 04, L=0L = 0, and 0≤2−2=00 \le 2 - 2 = 0. The value is empty, and pp becomes 7+2+0=97 + 2 + 0 = 9, which equals ee.

A lying nested length. Change the byte at position 3 from 03 to 08. Inside the container at p=2p = 2, L=8L = 8 and R−h=5R - h = 5. Since 8>58 > 5, the parser rejects the packet. A parser that checked against the packet instead would see 13−4=913 - 4 = 9 bytes after the name’s header, accept L=8L = 8, and take positions 4 to 11 as the name. That name swallows the flag 04 00 and 3 bytes of the next field, 20 02 AA, which lie outside the container.

An empty value. A parser that advanced by LL alone, forgetting the header, would misread every field after the first. At a field with L=0L = 0, such as the flag, it would not move at all and would loop forever.

Stated precisely

Let the enclosing sequence occupy [s,e)[s, e), let pp be the current position, h≥1h \ge 1 the header size and LL the declared value length, all in bytes. The parser keeps the invariant s≤p≤es \le p \le e. It accepts a field at pp only when h≤e−pand thenL≤(e−p)−h,h \le e - p \quad\text{and then}\quad L \le (e - p) - h, and it then sets the new position p′=p+h+Lp' = p + h + L, so that p<p′≤ep < p' \le e. The field’s value is [p+h,p+h+L)[p + h, p + h + L), which lies inside [s,e)[s, e). A nested parse of that value is given exactly that interval, so every nested interval lies inside every interval that encloses it.

Since pp grows by at least hh per field, a sequence of e−se - s bytes holds at most ⌊(e−s)/h⌋\lfloor (e - s) / h \rfloor fields, where ⌊x⌋\lfloor x \rfloor means xx rounded down to a whole number. The sequence is accepted only when the loop ends with p=ep = e; between 1 and h−1h - 1 leftover bytes form a cut-off header and cause rejection. A depth limit DD bounds the recursion: a container nested more than DD levels deep is rejected.

Limits and common mistakes

Checking against the packet is not enough. A nested length that fits the packet can still cross its container’s end, as the worked example shows. Each parse checks against its own enclosing interval.

The same mistake in practice. Heartbleed, a flaw disclosed in 2014 in OpenSSL, a widely used open-source TLS (Transport Layer Security) library, was a nested length that was never compared with its container [339]. A heartbeat request carried a 2-byte payload length inside a TLS record. The code copied that many bytes into its reply without comparing the payload length with the size of the record that held it. A request with a 1-byte payload that declared 65,535 bytes got back about 64 KiB of the server’s memory, which could include private keys. The repair discards a request when 1+2+payload length+161 + 2 + \text{payload length} + 16 exceeds the record length: 1 byte of message type, 2 bytes of length, the payload, and at least 16 bytes of padding.

Skipping an unknown field still needs the length check. An unknown type is skipped by its length, so that length must pass the same test. Some formats also mark types that a reader must understand, because skipping them would change the message’s meaning. IPv6 (Internet Protocol version 6), for example, encodes in the two highest bits of each option type what a node must do when it does not recognize the option.

Repeated types are ambiguous unless the format says otherwise. If one reader takes the first of two fields of the same type and another reader takes the last, the same bytes mean two things to them.

Several encodings of one value break signatures and comparisons. The BER (Basic Encoding Rules) of ASN.1 allow a length to be written in more than one way, including an open-ended form closed by an end marker. The DER (Distinguished Encoding Rules) allow only the shortest definite form, so every value has exactly one encoding; certificates, which are signed, use DER for that reason.

TLV does not authenticate. A message authentication code §5.7 must cover every field, including fields that the receiver skips, and the receiver must act on the same bytes it verified.

Questions answered

What prevents nested lengths from exceeding the enclosing record?

Only the parser’s own check prevents nested lengths from exceeding the enclosing record; the format cannot, because every length is a number the sender wrote. The parser gives each nested parse the exact interval of its container’s value, [s,e)[s, e), meaning from position ss up to but not including ee. Before reading a field at position pp with hh header bytes and declared value length LL, it requires first h≤e−ph \le e - p and then L≤(e−p)−hL \le (e - p) - h. Testing in that order means no subtraction goes below zero and the sum p+h+Lp + h + L is formed only after it is known to fit, so no overflow can hide a bad length. Each accepted field advances pp by h+Lh + L, so the nested fields can never pass ee, the end of their container. Comparing a nested length with the end of the whole packet is not enough: in the worked example a name that declared 8 bytes inside a container of 7 bytes fitted the 13-byte packet but crossed into the next field. Limits on nesting depth and on the number of fields complete the protection. Heartbleed, in which a declared payload length was never compared with the length of its record, shows the cost of omitting the check.

Related entries: Overflow-safe range check (§4.17), Length-prefix framing (§4.30), Deserialization (§4.29), Half-open interval (§14.12), Out-of-bounds read (§4.5). Further reading: [339].