Section 4.4

Buffer overflow

Definition

A buffer overflow is a write that goes past the end of the buffer it was meant to stay inside. A buffer is a block of memory of fixed size that holds data, such as an array §14.5 of 64 bytes. The bytes that do not fit land in whatever lies next to the buffer and replace what was there. The cause is a missing or wrong check: the program did not correctly compare the position and number of the bytes it writes with the size of the buffer.

The idea

C does not check where a write lands. If a program stores into element 10 of an array that has 8 elements, the processor writes at the address where element 10 would be, and that address belongs to something else. Take a buffer of 8 bytes that holds a name, followed directly by a 1-byte flag that says whether the user is an administrator. A name of 9 letters puts its ninth letter on the flag, so whoever supplies the name chooses the value of the flag.

A paper form with one box per letter is a fair picture. A name longer than its row of boxes runs into the boxes of the next field, and the clerk reads those letters as the value of that field. The picture stops being accurate in one respect. On paper the damage is visible. In memory the next field simply holds a new value.

How it works

Number the bytes of a buffer from 0. A buffer with a capacity of CC bytes has positions 0 to C−1C - 1.

  1. The program writes ww bytes starting at position pp. The write covers positions pp to p+w−1p + w - 1.

  2. If p+wp + w is greater than CC, the bytes meant for positions CC and above land outside the buffer.

  3. What they hit depends on where the buffer is. Next to a local variable lie other local variables and the return address, the stored location at which the calling function will resume. An attacker who overwrites the return address chooses where the function returns to, and so which code runs next. Next to a block obtained from the allocator, the library code that hands out memory, lie other blocks and the records of the allocator.

  4. The processor reports nothing as long as the memory that is hit can be written. The damage shows later, in code that had nothing to do with the write.

The size error behind an overflow has one of four usual forms, and a length check must cover all of them.

Worked example

A buffer has a capacity of 16 bytes. The code writes a 3-byte header, then nn elements of 2 bytes each, then a 1-byte terminator. The number of bytes needed is 3+2n+13 + 2n + 1. The room left for elements is 16−3−1=1216 - 3 - 1 = 12 bytes, which holds 12/2=612 / 2 = 6 elements. For n=6n = 6 the code writes 3+12+1=163 + 12 + 1 = 16 bytes, positions 0 to 15, an exact fit.

A request arrives with n=7n = 7. The code needs 3+14+1=183 + 14 + 1 = 18 bytes and writes positions 0 to 17. Positions 16 and 17 are outside the buffer: an overflow of 2 bytes. Three possible checks give three verdicts.

A check that counts everything can still fail when the arithmetic wraps around. Take a second buffer with a capacity of 64 bytes, an 8-byte header, no terminator and elements of 4 bytes each, so that the check is 8+4n≤648 + 4n \le 64. Suppose sizes are unsigned 32-bit integers, as they are on a typical 32-bit microcontroller §6.1, a small computer on a single chip. An attacker sends n=1,073,741,825n = 1{,}073{,}741{,}825. The true product 4n4n is 4,294,967,3004{,}294{,}967{,}300. A 32-bit integer keeps only the remainder after division by 232=4,294,967,2962^{32} = 4{,}294{,}967{,}296, and that remainder is 4. The program computes 8+4=128 + 4 = 12, the check 12≤6412 \le 64 passes, and the copying loop then writes nn elements, far past the end of the buffer. Dividing avoids the problem. The room for elements is 64−8=5664 - 8 = 56 bytes, and the check n≤56/4=14n \le 56 / 4 = 14 never multiplies the number that the attacker chose. It rejects this nn.

Stated precisely

Let CC be the capacity of the buffer in bytes, hh the number of header bytes, zz the number of terminator bytes (0 if there is no terminator), nn the number of elements, and kk the size of one element in bytes, with k≥1k \ge 1. All five are whole numbers that are not negative, stored in unsigned integers of one width. The write stays inside the buffer exactly when h+n×k+z≤C,h + n \times k + z \le C, where the left side is computed as an ordinary whole number, without wrapping around. Machine integers cannot represent every whole number, so the test is made in two steps. First check that h≤Ch \le C and that z≤C−hz \le C - h. Then check that n≤⌊C−h−zk⌋,n \le \left\lfloor \frac{C - h - z}{k} \right\rfloor, where ⌊x⌋\lfloor x \rfloor means xx rounded down to a whole number. No step can wrap around: each subtraction is made only after a comparison has shown that its result is not negative, and the count nn is compared and never multiplied. For whole numbers the second check is true exactly when n×k≤C−h−zn \times k \le C - h - z.

The C standard makes a write outside an array undefined behavior §4.12, which means that the standard places no requirement on what the program does. A buffer overflow is also called a buffer overrun. A write that lands before position 0 is the mirror case, called a buffer underwrite, and the name out-of-bounds write covers both directions. A read outside the buffer is an out-of-bounds read §4.5. Some authors use the name buffer overflow for all of these.

Limits and common mistakes

The check must use the capacity of the destination. Common wrong capacities are the size of a larger area that contains the buffer and the length of the source data.

A signed length can turn into a huge one. If a length and the capacity are both held in signed integers and an attacker makes the length negative, the test len <= capacity passes. The copying function memcpy takes an unsigned length, so −1-1 becomes 4,294,967,2954{,}294{,}967{,}295 on a system with 32-bit sizes.

The call malloc(n * k) can wrap around silently. The function malloc allocates the number of bytes it is given, and the multiplication happens before malloc sees the result, so a wrapped product yields a block that is far too small. The function calloc(n, k), which allocates room for nn elements of kk bytes each, receives both numbers, and the edition of the C standard published in 2024 requires it to report failure when their product does not fit [309].

Hardware memory protection works on regions, not on objects. A memory protection unit §6.8, a hardware feature that blocks access to chosen address ranges, can stop a write that leaves a permitted range. It cannot see the border between two variables inside the same range.

A stack overflow §4.10 is a different error. A stack overflow means that the stack, the memory area that holds the local variables of running functions, has run out of space. A buffer overflow in a local variable is called a stack-based buffer overflow. Some authors call that error a stack overflow as well, so the meaning has to be checked.

Questions answered

Does a length check include headers, terminators, and multiplication by element size?

A correct length check includes all three, and a check that leaves any of them out does not prevent a buffer overflow, which is a write past the end of a buffer. The check must compare the capacity of the destination buffer with the total number of bytes that the code will write: the header bytes, plus the number of elements multiplied by the size of one element, plus any terminator, such as the zero byte that ends a C string. Every byte left out of the count is a byte that can land outside the buffer.

Two further conditions make the check reliable. The total must be computed so that it cannot wrap around, because a sum or product that is too large for its unsigned integer type silently becomes a smaller number. The safe form first checks that the fixed parts fit, subtracts them from the capacity, and then compares the element count with the remaining room divided by the element size. And the check must run before the first byte is written.

Related entries: Overflow-safe range check (§4.17), Integer promotion and conversion (§4.18), Stack overflow (§4.10), Out-of-bounds read (§4.5), Unsigned modular arithmetic (§4.16), Spatial memory safety (§2.28). Further reading: [78, 309].