Class · High

CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer

The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected m...

CWE-119 · Class Level ·19 CVEs ·7 Mitigations

Description

The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.

Potential Impact

Integrity, Confidentiality, Availability

Execute Unauthorized Code or Commands, Modify Memory

Availability, Confidentiality

Read Memory, DoS: Crash, Exit, or Restart, DoS: Resource Consumption (CPU), DoS: Resource Consumption (Memory)

Confidentiality

Read Memory

Demonstrative Examples

This example takes an IP address from a user, verifies that it is well formed and then looks up the hostname and copies it into a buffer.
Bad
void host_lookup(char *user_supplied_addr){
                        struct hostent *hp;in_addr_t *addr;char hostname[64];in_addr_t inet_addr(const char *cp);
                           
                           /*routine that ensures user_supplied_addr is in the right format for conversion */
                           
                           validate_addr_form(user_supplied_addr);addr = inet_addr(user_supplied_addr);hp = gethostbyaddr( addr, sizeof(struct in_addr), AF_INET);strcpy(hostname, hp->h_name);
                     }
This function allocates a buffer of 64 bytes to store the hostname, however there is no guarantee that the hostname will not be larger than 64 bytes. If an attacker specifies an address which resolves to a very large hostname, then the function may overwrite sensitive data or even relinquish control flow to the attacker.
Note that this example also contains an unchecked return value (CWE-252) that can lead to a NULL pointer dereference (CWE-476).
This example applies an encoding procedure to an input string and stores it into a buffer.
Bad
char * copy_input(char *user_supplied_string){
                        int i, dst_index;char *dst_buf = (char*)malloc(4*sizeof(char) * MAX_SIZE);if ( MAX_SIZE <= strlen(user_supplied_string) ){die("user string too long, die evil hacker!");}dst_index = 0;for ( i = 0; i < strlen(user_supplied_string); i++ ){
                              if( '&' == user_supplied_string[i] ){dst_buf[dst_index++] = '&';dst_buf[dst_index++] = 'a';dst_buf[dst_index++] = 'm';dst_buf[dst_index++] = 'p';dst_buf[dst_index++] = ';';}else if ('<' == user_supplied_string[i] ){
                                       /* encode to &lt; */
                                       
                                 }else dst_buf[dst_index++] = user_supplied_string[i];
                           }return dst_buf;
                     }
The programmer attempts to encode the ampersand character in the user-controlled string, however the length of the string is validated before the encoding procedure is applied. Furthermore, the programmer assumes encoding expansion will only expand a given character by a factor of 4, while the encoding of the ampersand expands by 5. As a result, when the encoding procedure expands the string it is possible to overflow the destination buffer if the attacker provides a string of many ampersands.
The following example asks a user for an offset into an array to select an item.
Bad
int main (int argc, char **argv) {char *items[] = {"boat", "car", "truck", "train"};int index = GetUntrustedOffset();printf("You selected %s\n", items[index-1]);}
The programmer allows the user to specify which element in the list to select, however an attacker can provide an out-of-bounds offset, resulting in a buffer over-read (CWE-126).
In the following code, the method retrieves a value from an array at a specific array index location that is given as an input parameter to the method
Bad
int getValueFromArray(int *array, int len, int index) {
                        
                           int value;
                           
                           // check that the array index is less than the maximum
                           
                           
                           // length of the array
                           if (index < len) {
                              
                                 // get the value at the specified index of the array
                                 value = array[index];
                           }
                           // if array index is invalid then output error message
                           
                           // and return value indicating error
                           else {printf("Value is: %d\n", array[index]);value = -1;}
                           return value;
                     }
However, this method only verifies that the given array index is less than the maximum length of the array but does not check for the minimum value (CWE-839). This will allow a negative value to be accepted as the input array index, which will result in reading data before the beginning of the buffer (CWE-127) and may allow access to sensitive memory. The input array index should be checked to verify that is within the maximum and minimum range required for the array (CWE-129). In this example the if statement should be modified to include a minimum range check, as shown below.
Good
...
                     
                     // check that the array index is within the correct
                     
                     
                     // range of values for the array
                     if (index >= 0 && index < len) {
                     ...

Mitigations & Prevention

Requirements

Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to ove

Architecture and Design

Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.

OperationBuild and Compilation Defense in Depth

Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.

Implementation

Consider adhering to the following rules when allocating and managing an application's memory:

OperationBuild and Compilation Defense in Depth

Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other mo

Operation Defense in Depth

Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].

Implementation Moderate

Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.

Detection Methods

  • Automated Static Analysis High — This weakness can often be detected using automated static analysis tools. Many modern tools use data flow analysis or constraint-based techniques to minimize the number of false positives. Automated static analysis generally does not account for environmental considerations when
  • Automated Dynamic Analysis — This weakness can be detected using dynamic tools and techniques that interact with the software using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The software's operation may slow down, but it should not become unstable, crash
  • Automated Dynamic Analysis Moderate — Use tools that are integrated during compilation to insert runtime error-checking mechanisms related to memory safety errors, such as AddressSanitizer (ASan) for C/C++ [REF-1518].
  • Automated Static Analysis - Binary or Bytecode SOAR Partial — According to SOAR [REF-1479], the following detection techniques may be useful:
  • Manual Static Analysis - Binary or Bytecode SOAR Partial — According to SOAR [REF-1479], the following detection techniques may be useful:
  • Dynamic Analysis with Automated Results Interpretation SOAR Partial — According to SOAR [REF-1479], the following detection techniques may be useful:

Real-World CVE Examples

CVE IDDescription
CVE-2021-22991Incorrect URI normalization in application traffic product leads to buffer overflow, as exploited in the wild per CISA KEV.
CVE-2025-47153Chain: build process for JavaScript runtime environment can have inconsistent sizes for off_t (CWE-1102), allowing out-of-bounds access / segmentation fault (CWE-119)
CVE-2020-29557Buffer overflow in Wi-Fi router web interface, as exploited in the wild per CISA KEV.
CVE-2009-2550Classic stack-based buffer overflow in media player using a long entry in a playlist
CVE-2009-2403Heap-based buffer overflow in media player using a long entry in a playlist
CVE-2009-0689large precision value in a format string triggers overflow
CVE-2009-0690negative offset value leads to out-of-bounds read
CVE-2009-1532malformed inputs cause accesses of uninitialized or previously-deleted objects, leading to memory corruption
CVE-2009-1528chain: lack of synchronization leads to memory corruption
CVE-2021-29529Chain: machine-learning product can have a heap-based buffer overflow (CWE-122) when some integer-oriented bounds are calculated by using ceiling() and floor() on floating point values
CVE-2009-0558attacker-controlled array index leads to code execution
CVE-2009-0269chain: -1 value from a function call was intended to indicate an error, but is used as an array index instead.
CVE-2009-0566chain: incorrect calculations lead to incorrect pointer dereference and memory corruption
CVE-2009-1350product accepts crafted messages that lead to a dereference of an arbitrary pointer
CVE-2009-0191chain: malformed input causes dereference of uninitialized memory

Showing 15 of 19 observed examples.

Taxonomy Mappings

  • OWASP Top Ten 2004: A5 — Buffer Overflows
  • CERT C Secure Coding: ARR00-C — Understand how arrays work
  • CERT C Secure Coding: ARR30-C — Do not form or use out-of-bounds pointers or array subscripts
  • CERT C Secure Coding: ARR38-C — Guarantee that library functions do not form invalid pointers
  • CERT C Secure Coding: ENV01-C — Do not make assumptions about the size of an environment variable
  • CERT C Secure Coding: EXP39-C — Do not access a variable through a pointer of an incompatible type
  • CERT C Secure Coding: FIO37-C — Do not assume character data has been read
  • CERT C Secure Coding: STR31-C — Guarantee that storage for strings has sufficient space for character data and the null terminator
  • CERT C Secure Coding: STR32-C — Do not pass a non-null-terminated character sequence to a library function that expects a string
  • WASC: 7 — Buffer Overflow
  • Software Fault Patterns: SFP8 — Faulty Buffer Access

Frequently Asked Questions

What is CWE-119?

CWE-119 (Improper Restriction of Operations within the Bounds of a Memory Buffer) is a software weakness identified by MITRE's Common Weakness Enumeration. It is classified as a Class-level weakness. The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected m...

How can CWE-119 be exploited?

Attackers can exploit CWE-119 (Improper Restriction of Operations within the Bounds of a Memory Buffer) to execute unauthorized code or commands, modify memory. This weakness is typically introduced during the Implementation phase of software development.

How do I prevent CWE-119?

Key mitigations include: Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory

What is the severity of CWE-119?

CWE-119 is classified as a Class-level weakness (High abstraction). It has been observed in 19 real-world CVEs.