Issue
A buffer is a fixed-size area of memory used to hold data. A buffer overflow occurs when software reads or writes outside the buffer’s valid bounds. This article focuses on writes past the end of a buffer, sometimes called an out-of-bounds write. A read past the end is a related but distinct memory-safety flaw.
For example, a program might reserve 16 bytes for a name but copy 20 bytes into that space. The extra bytes can overwrite other memory. The result depends on what is nearby and how the program uses it.
Buffers can be stored on the stack, the heap, or in global memory. A stack-based buffer overflow affects a local variable or other stack memory. It is different from stack exhaustion, which happens when a program uses up its call stack, often through excessive recursion. MITRE’s CWE-121 describes stack-based buffer overflows; CWE-120 covers a classic case where a copy does not check whether the input fits.
Common causes include:
- Copying data into a fixed-size buffer without checking its length.
- Trusting a length supplied by a caller or included in a file or network message.
- Calculating a buffer size incorrectly, including integer overflow or off-by-one errors.
- Forgetting space for a string’s terminating null character.
- Using an index or loop bound that allows access beyond the allocated space.
A long input or a crash can be an indicator of a possible flaw. It does not, by itself, prove that a buffer overflow occurred. Confirmation requires evidence such as a sanitizer report, a debugger trace showing an out-of-bounds write, or a reproducible failure tied to a specific invalid memory access.
Examples
The first C example copies input without checking capacity; the second validates the destination size before copying.
Unsafe example
#include <string.h>
void set_name(const char *input) {
char name[16];
strcpy(name, input); // No check that input fits in name
}
strcpy copies through the terminating null character and does not know the destination’s capacity. If the input string is too long, the copy writes past name.
Safer example
#include <stddef.h>
#include <string.h>
int copy_name(char *dst, size_t dst_capacity,
const char *src, size_t src_length) {
if (dst == NULL || src == NULL || dst_capacity == 0) {
return -1;
}
/* Reserve one byte for the terminating null character. */
if (src_length >= dst_capacity) {
return -1;
}
memcpy(dst, src, src_length);
dst[src_length] = '\\0';
return 0;
}
This function rejects inputs that cannot fit, including the null terminator. The caller must still provide a valid source pointer and an accurate src_length; the check cannot make an incorrect length trustworthy. For binary data that is not a string, do not add a null terminator—check that the byte count is no greater than the destination capacity before copying.
Impact
An out-of-bounds write can corrupt program data, cause a crash, or change how the program behaves. In some circumstances, an attacker may be able to influence control flow or execute code. That outcome depends on details such as the affected memory, the input path, the target platform, and the protections enabled. A crash alone supports a denial-of-service concern; it does not demonstrate code execution, data theft, or authentication bypass.
Exploit-mitigation features such as stack protection, address space layout randomization (ASLR), and non-executable memory can make some attacks harder or detect certain corruption. They do not correct the underlying bounds error or guarantee that the program is safe. MITRE notes that these protections cover only subsets of overflow cases.
Testing
1. Check whether oversized input causes memory corruption
In a controlled build, increase input size around documented limits and observe process behavior with a memory-safety tool. Keep a normal input as the baseline.
Example: A crash can have several causes. A sanitizer report or debugger evidence is needed to identify an out-of-bounds write.
POST /api/parse HTTP/1.1
Host: app.example.test
Content-Type: application/json
{"name":"TEST_INPUT_AT_BOUNDARY"}
2. Compare boundaries and parser paths
Test lengths just below, at, and above the relevant limit across supported fields or file formats. Record the process result and any sanitizer report.
Example: A 256-byte buffer and its terminator need careful handling. Test the actual code path and configured limits.
POST /api/parse HTTP/1.1
Host: app.example.test
Content-Type: application/json
{"name":"TEST_INPUT_OVER_BOUNDARY"}
3. Review native code and protections
Inspect copy operations, length calculations, integer conversions, and compiler or runtime protections. Confirm any suspected fault using reproducible inputs and debug information.
Example: A rejected long request is not a buffer overflow. It may show that an input limit is working.
Common false positives and limits
- A crash after oversized input is a lead, not proof; other faults may cause the crash.
- A sanitizer report is strong evidence for the reported invalid access in the tested build, but it does not establish remote exploitability or impact in production.
- A clean sanitizer run is not proof of safety. The relevant path may not have run, or the code may not have been instrumented.
- A scanner warning about a risky function is not proof that an overflow is reachable. Review the actual buffer capacity, input length, and checks.
Mitigation
Primary fixes
- Keep the destination capacity with the buffer. Pass the capacity to functions that write into it, and verify the requested length against that capacity before copying.
- Validate lengths before arithmetic or allocation. Check that a length is within an approved limit and that calculations such as
count * element_sizecannot overflow. - Account for string terminators. When storing a C string, reserve space for the terminating null byte as well as the character data. CERT C’s STR31-C rule covers this requirement.
- Use APIs that express bounds clearly. A function with a length parameter is not automatically safe: the caller must supply the correct length, and the function must enforce the destination limit. In particular, replacing
strcpywithstrncpyalone can leave strings unterminated or preserve incorrect size calculations. Review the behavior and error handling of the chosen API. MITRE’s CWE-120 guidance discusses these limitations. - Prefer memory-safe languages where practical. Languages with automatic bounds checks can prevent many out-of-bounds writes. Review native interfaces and foreign-function boundaries separately, since unsafe code or incorrect length handling there can reintroduce the flaw.
Additional defensive measures
- Enable compiler and platform protections, such as stack protection and ASLR, where supported. Treat these as layers that may detect or hinder some attacks, not as substitutes for correct bounds checks. Microsoft documents /GS as a buffer security check.
- Run sanitizer-enabled builds and boundary-focused tests in development or CI. Add a regression case for each confirmed flaw and verify that oversized or malformed input is rejected safely.
- Run the program with only the privileges it needs, so that a separate flaw has less opportunity to affect the rest of the system.
After a fix, repeat the boundary tests and run the affected paths under a sanitizer-enabled build. Confirm that valid inputs still work, oversized inputs follow the documented rejection behavior, and no out-of-bounds access is reported. A clean retest applies to the tested build and paths; continue reviewing adjacent code and other input routes that use the same buffer logic.