CWE
Home > CWE List > CWE- Individual Dictionary Definition (1.4)  

CWE-119: Failure to Constrain Operations within the Bounds of a Memory Buffer

Individual Definition in a New Window
Failure to Constrain Operations within the Bounds of a Memory Buffer
Status: Draft
Weakness ID: 119 (Weakness Class)
+ Description
Summary

The software may potentially allow operations, such as reading or writing, to be performed at addresses not intended by the developer.

Extended Description

When software permits read or write operations on memory located outside of an allocated range, an attacker may be able to access/modify sensitive information, cause the system to crash, alter the intended control flow, or execute arbitrary code.

+ Time of Introduction
* Architecture and Design
* Implementation
+ Applicable Platforms
Languages
All
Platform Notes

It is possible in many languages to attempt an operation outside of the bounds of a memory buffer, but the consequences will vary widely depending on the language and platform.

+ Common Consequences
Confidentiality
Integrity

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

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.

+ Likelihood of Exploit

High

+ Demonstrative Examples
Example 1:

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 Example:
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_supply_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.

Example 2:

This example applies an encoding procedure to an input string and stores it into a buffer.

C Example:
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 3, while the encoding of the ampersand expands by 4. 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.

Example 3:

The following example asks a user for an offset into an array to select an item.

C Example:
 
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).

+ Potential Mitigations
Requirements

Use a language with features that can automatically mitigate or eliminate buffer overflows.

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

Use languages, libraries, or frameworks that make it easier to manage buffers without exceeding their boundaries.

Examples include the Safe C String Library (SafeStr) by Messier and Viega, and the Strsafe.h library from Microsoft. 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

Run or compile your 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.

This is not necessarily a complete solution, since these mechanisms can only detect certain types of overflows. In addition, a buffer overflow attack can still cause a denial of service, since the typical response is to exit the application.

Implementation

Programmers should adhere to the following rules when allocating and managing their 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 calling this function 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.

Testing

Use automated static analysis tools that target this type of weakness. Many modern techniques use data flow analysis to minimize the number of false positives. This is not a perfect solution, since 100% accuracy and coverage are not feasible.

Testing

Use 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.

Operation

Use a feature like Address Space Layout Randomization (ASLR). This is not a complete solution. However, it forces the attacker to guess an unknown value that changes every program execution.

Operation

Use a CPU and operating system that offers Data Execution Protection (NX) or its equivalent. 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.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness ClassWeakness Class118Improper Access of Indexable Resource ('Range Error')
Research Concepts (primary)1000
ChildOfWeakness ClassWeakness ClassWeakness Class20Improper Input Validation
Development Concepts (primary)699
Seven Pernicious Kingdoms (primary)700
ChildOfCategoryCategory726OWASP Top Ten 2004 Category A5 - Buffer Overflows
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory633Weaknesses that Affect Memory
Resource-specific Weaknesses (primary)631
ChildOfCategoryCategory740CERT C Secure Coding Section 06 - Arrays (ARR)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory741CERT C Secure Coding Section 07 - Characters and Strings (STR)
Weaknesses Addressed by the CERT C Secure Coding Standard734
ChildOfCategoryCategory742CERT C Secure Coding Section 08 - Memory Management (MEM)
Weaknesses Addressed by the CERT C Secure Coding Standard734
ChildOfCategoryCategory743CERT C Secure Coding Section 09 - Input Output (FIO)
Weaknesses Addressed by the CERT C Secure Coding Standard734
ChildOfCategoryCategory744CERT C Secure Coding Section 10 - Environment (ENV)
Weaknesses Addressed by the CERT C Secure Coding Standard734
ChildOfCategoryCategory752Risky Resource Management
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
ParentOfWeakness VariantWeakness VariantWeakness Variant121Stack-based Buffer Overflow
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness VariantWeakness Variant122Heap-based Buffer Overflow
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness BaseWeakness Base123Write-what-where Condition
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness BaseWeakness Base124Boundary Beginning Violation ('Buffer Underwrite')
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness BaseWeakness Base125Out-of-bounds Read
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness BaseWeakness Base128Wrap-around Error
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness BaseWeakness Base129Unchecked Array Indexing
Development Concepts (primary)699
Research Concepts (primary)1000
CanFollowWeakness BaseWeakness BaseWeakness Base131Incorrect Calculation of Buffer Size
Development Concepts699
Research Concepts1000
CanFollowWeakness BaseWeakness BaseWeakness Base193Off-by-one Error
Research Concepts1000
ParentOfWeakness BaseWeakness BaseWeakness Base466Return of Pointer Value Outside of Expected Range
Research Concepts (primary)1000
ParentOfCompound Element: CompositeCompound Element: Composite120Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
Development Concepts (primary)699
Research Concepts (primary)1000
+ Affected Resources
* Memory
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
OWASP Top Ten 2004A5ExactBuffer Overflows
CERT C Secure CodingARR00-C Understand how arrays work
CERT C Secure CodingARR33-C Guarantee that copies are made into storage of sufficient size
CERT C Secure CodingARR34-C Ensure that array types in expressions are compatible
CERT C Secure CodingARR35-C Do not allow loops to iterate beyond the end of an array
CERT C Secure CodingENV01-C Do not make assumptions about the size of an environment variable
CERT C Secure CodingFIO37-C Do not assume character data has been read
CERT C Secure CodingMEM09-C Do not assume memory allocation routines initialize memory
CERT C Secure CodingSTR31-C Guarantee that storage for strings has sufficient space for character data and the null terminator
CERT C Secure CodingSTR32-C Null-terminate byte strings as required
CERT C Secure CodingSTR33-C Size wide character strings correctly
+ References
Microsoft. "Using the Strsafe.h Functions". <http://msdn.microsoft.com/en-us/library/ms647466.aspx>.
Matt Messier and John Viega. "Safe C String Library v1.0.3". <http://www.zork.org/safestr/>.
Arjan van de Ven. "Limiting buffer overflows with ExecShield". <http://www.redhat.com/magazine/009jul05/features/execshield/>.
+ Content History
Modifications
Eric Dalci. Cigital. 2008-07-01. (External)
updated Time_of_Introduction
Veracode. 2008-08-15. (External)
Suggested OWASP Top Ten 2004 mapping
CWE Content Team. MITRE. 2008-09-08. (Internal)
updated Description, Relationships, Taxonomy_Mappings
CWE Content Team. MITRE. 2008-10-14. (Internal)
updated Relationships
CWE Content Team. MITRE. 2008-11-24. (Internal)
updated Relationships, Taxonomy_Mappings
CWE Content Team. MITRE. 2009-01-12. (Internal)
updated Applicable_Platforms, Common_Consequences, Demonstrative_Examples, Likelihood_of_Exploit, Name, Potential_Mitigations, References, Relationships
CWE Content Team. MITRE. 2009-03-10. (Internal)
updated Potential_Mitigations
CWE Content Team. MITRE. 2009-05-27. (Internal)
updated Demonstrative_Examples
Previous Entry Names
* Buffer Errors (changed 2008-04-11)
* Failure to Constrain Operations within the Bounds of an Allocated Memory Buffer (changed 2009-01-12)
Page Last Updated: May 26, 2009