The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. Certain languages allow direct addressing of memory locations and do not automatically ensure that these locations are valid for the memory buffer that is being referenced. This can cause read or write operations to be performed on memory locations that may be associated with other variables, data structures, or internal program data. As a result, an attacker may be able to execute arbitrary code, alter the intended control flow, read sensitive information, or cause the system to crash. 1000 699 Weakness ChildOf 118 700 699 Weakness ChildOf 20 711 Category ChildOf 726 631 Category ChildOf 633 734 Category ChildOf 740 734 Category ChildOf 741 734 Category ChildOf 742 734 Category ChildOf 743 734 Category ChildOf 744 750 Category ChildOf 752 868 Category ChildOf 874 868 Category ChildOf 875 868 Category ChildOf 876 868 Category ChildOf 877 868 Category ChildOf 878 888 Category ChildOf 890 It is possible in many programming languages to attempt an operation outside of the bounds of a memory buffer, but the consequences will vary widely depending on the language, platform, and chip architecture. Memory Corruption The generic term "memory corruption" is often used to describe the consequences of writing to memory outside the bounds of a buffer, when the root cause is something other than a sequential copies of excessive data from a fixed starting location (i.e., classic buffer overflows or CWE-120). This may include issues such as incorrect pointer arithmetic, accessing invalid pointers due to incomplete initialization or memory release, etc. Architecture and Design Implementation Operation High Integrity Confidentiality Availability Execute unauthorized code or commands Modify memory If the memory accessible by the attacker can be effectively controlled, it may be possible to execute arbitrary code, as with a standard buffer overflow. If the attacker can overwrite a pointer's worth of memory (usually 32 or 64 bits), he can redirect a function pointer to his own malicious code. Even when the attacker can only modify a single byte arbitrary code execution can be possible. Sometimes this is because the same problem can be exploited repeatedly to the same effect. Other times it is because the attacker can overwrite security-critical application-specific data -- such as a flag indicating whether the user is an administrator. Availability Confidentiality Read memory DoS: crash / exit / restart DoS: resource consumption (CPU) DoS: resource consumption (memory) Out of bounds memory access will very likely result in the corruption of relevant memory, and perhaps instructions, possibly leading to a crash. Other attacks leading to lack of availability are possible, including putting the program into an infinite loop. Confidentiality Read memory In the case of an out-of-bounds read, the attacker may have access to sensitive information. If the sensitive information contains system details, such as the current buffers position in memory, this knowledge can be used to craft further attacks, possibly with more severe consequences. Automated Static Analysis 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 reporting out-of-bounds memory operations. This can make it difficult for users to determine which warnings should be investigated first. For example, an analysis tool might report buffer overflows that originate from command line arguments in a program that is not expected to run with setuid or other special privileges. High Detection techniques for buffer-related errors are more mature than for most other weakness types. 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, or generate incorrect results. Requirements Language Selection 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 overflows, even if the language itself is theoretically safe. Architecture and Design Libraries or Frameworks 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 [R.119.3], and the Strsafe.h library from Microsoft [R.119.2]. These libraries provide safer versions of overflow-prone string-handling functions. This is not a complete solution, since many buffer overflows are not related to strings. Build and Compilation Compilation or Build Hardening Run or compile the software using features or extensions that automatically provide a protection mechanism that mitigates or eliminates buffer overflows. For example, certain compilers and extensions provide automatic buffer overflow detection mechanisms that are built into the compiled code. Examples include the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice. Defense in Depth This is not necessarily a complete solution, since these mechanisms can only detect certain types of overflows. In addition, an attack could still cause a denial of service, since the typical response is to exit the application. Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that your buffer is as large as you specify. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure you are not in danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Operation Environment Hardening Use a feature like Address Space Layout Randomization (ASLR) [R.119.4] [R.119.6]. Defense in Depth This is not a complete solution. However, it forces the attacker to guess an unknown value that changes every program execution. In addition, an attack could still cause a denial of service, since the typical response is to exit the application. Operation Environment Hardening Use a CPU and operating system that offers Data Execution Protection (NX) or its equivalent [R.119.6] [R.119.7]. Defense in Depth This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Moderate This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). 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. C 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 we 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. C 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; 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. C 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 C 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 a out of bounds read (CWE-125) 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. C ... // check that the array index is within the correct // range of values for the array if (index <= 0 && index < len) { ... CVE-2009-2550 Classic stack-based buffer overflow in media player using a long entry in a playlist CVE-2009-2403 Heap-based buffer overflow in media player using a long entry in a playlist CVE-2009-0689 large precision value in a format string triggers overflow CVE-2009-0690 negative offset value leads to out-of-bounds read CVE-2009-1532 malformed inputs cause accesses of uninitialized or previously-deleted objects, leading to memory corruption CVE-2009-1528 chain: lack of synchronization leads to memory corruption CVE-2009-0558 attacker-controlled array index leads to code execution CVE-2009-0269 chain: -1 value from a function call was intended to indicate an error, but is used as an array index instead. CVE-2009-0566 chain: incorrect calculations lead to incorrect pointer dereference and memory corruption CVE-2009-1350 product accepts crafted messages that lead to a dereference of an arbitrary pointer CVE-2009-0191 chain: malformed input causes dereference of uninitialized memory CVE-2008-4113 OS kernel trusts userland-supplied length value, allowing reading of sensitive information Memory M. Howard D. LeBlanc Writing Secure Code Chapter 5, "Public Enemy #1: The Buffer Overrun" Page 127; Chapter 14, "Prevent I18N Buffer Overruns" Page 441 2nd Edition Microsoft 2002 Microsoft Using the Strsafe.h Functions http://msdn.microsoft.com/en-us/library/ms647466.aspx Matt Messier John Viega Safe C String Library v1.0.3 http://www.zork.org/safestr/ Michael Howard Address Space Layout Randomization in Windows Vista http://blogs.msdn.com/michael_howard/archive/2006/05/26/address-space-layout-randomization-in-windows-vista.aspx Arjan van de Ven Limiting buffer overflows with ExecShield http://www.redhat.com/magazine/009jul05/features/execshield/ PaX http://en.wikipedia.org/wiki/PaX Microsoft Understanding DEP as a mitigation technology part 1 http://blogs.technet.com/b/srd/archive/2009/06/12/understanding-dep-as-a-mitigation-technology-part-1.aspx Mark Dowd John McDonald Justin Schuh The Art of Software Security Assessment Chapter 5, "Memory Corruption", Page 167. 1st Edition Addison Wesley 2006 Mark Dowd John McDonald Justin Schuh The Art of Software Security Assessment Chapter 5, "Protection Mechanisms", Page 189. 1st Edition Addison Wesley 2006 Buffer Overflows A5 Exact Understand how arrays work ARR00-C Guarantee that copies are made into storage of sufficient size ARR33-C Ensure that array types in expressions are compatible ARR34-C Do not allow loops to iterate beyond the end of an array ARR35-C Do not make assumptions about the size of an environment variable ENV01-C Do not assume character data has been read FIO37-C Do not assume memory allocation routines initialize memory MEM09-C Guarantee that storage for strings has sufficient space for character data and the null terminator STR31-C Null-terminate byte strings as required STR32-C Size wide character strings correctly STR33-C Buffer Overflow 7 Understand when to prefer vectors over arrays ARR00-CPP Guarantee that array and vector indices are within the valid range ARR30-CPP Guarantee that copies are made into storage of sufficient size ARR33-CPP Do not allow loops to iterate beyond the end of an array or container ARR35-CPP Guarantee that storage for character arrays has sufficient space for character data and the null terminator STR31-CPP Null-terminate character arrays as required STR32-CPP Do not assume memory allocation routines initialize memory MEM09-CPP Do not assume character data has been read FIO37-CPP Do not make assumptions about the size of an environment variable ENV01-CPP 10 100 14 24 42 44 45 46 47 8 9 PLOVER Eric Dalci Cigital 2008-07-01 updated Time_of_Introduction Veracode 2008-08-15 Suggested OWASP Top Ten 2004 mapping CWE Content Team MITRE 2008-09-08 updated Description, Relationships, Taxonomy_Mappings CWE Content Team MITRE 2008-10-14 updated Relationships CWE Content Team MITRE 2008-11-24 updated Relationships, Taxonomy_Mappings CWE Content Team MITRE 2009-01-12 updated Applicable_Platforms, Common_Consequences, Demonstrative_Examples, Likelihood_of_Exploit, Name, Potential_Mitigations, References, Relationships CWE Content Team MITRE 2009-03-10 updated Potential_Mitigations CWE Content Team MITRE 2009-05-27 updated Demonstrative_Examples CWE Content Team MITRE 2009-07-27 updated Observed_Examples CWE Content Team MITRE 2009-10-29 updated Applicable_Platforms, Common_Consequences, Demonstrative_Examples, Description, Relationships, Time_of_Introduction CWE Content Team MITRE 2009-12-28 updated Common_Consequences, Demonstrative_Examples, Detection_Factors, Observed_Examples CWE Content Team MITRE 2010-02-16 updated Alternate_Terms, Applicable_Platforms, Demonstrative_Examples, Detection_Factors, Potential_Mitigations, References, Relationships, Taxonomy_Mappings CWE Content Team MITRE 2010-06-21 updated Potential_Mitigations CWE Content Team MITRE 2010-09-27 updated Potential_Mitigations, Relationships CWE Content Team MITRE 2010-12-13 updated Name CWE Content Team MITRE 2011-03-29 updated Relationships CWE Content Team MITRE 2011-06-01 updated Common_Consequences, Relationships CWE Content Team MITRE 2011-09-13 updated Relationships, Taxonomy_Mappings CWE Content Team MITRE 2012-05-11 updated Demonstrative_Examples, Potential_Mitigations, References, Relationships CWE Content Team MITRE 2012-10-30 updated Potential_Mitigations Buffer Errors Failure to Constrain Operations within the Bounds of an Allocated Memory Buffer Failure to Constrain Operations within the Bounds of a Memory Buffer