CWE

Common Weakness Enumeration

A Community-Developed Dictionary of Software Weakness Types

Common Weakness Scoring System
Common Weakness Risk Analysis Framework
Home > CWE List > CWE- Individual Dictionary Definition (2.9)  

Presentation Filter:

CWE-805: Buffer Access with Incorrect Length Value

 
Buffer Access with Incorrect Length Value
Weakness ID: 805 (Weakness Base)Status: Incomplete
+ Description

Description Summary

The software uses a sequential operation to read or write a buffer, but it uses an incorrect length value that causes it to access memory that is outside of the bounds of the buffer.

Extended Description

When the length value exceeds the size of the destination, a buffer overflow could occur.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C: (Often)

C++: (Often)

Assembly

+ Common Consequences
ScopeEffect
Integrity
Confidentiality
Availability

Technical Impact: Execute unauthorized code or commands

Buffer overflows often can be used to execute arbitrary code, which is usually outside the scope of a program's implicit security policy. This can often be used to subvert any other security service.

Availability

Technical Impact: DoS: crash / exit / restart; DoS: resource consumption (CPU)

Buffer overflows generally lead to crashes. Other attacks leading to lack of availability are possible, including putting the program into an infinite loop.

+ Likelihood of Exploit

Medium to High

+ Detection Methods

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.

Effectiveness: 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.

Effectiveness: Moderate

Without visibility into the code, black box methods may not be able to sufficiently distinguish this weakness from others, requiring manual methods to diagnose the underlying problem.

Manual Analysis

Manual analysis can be useful for finding this weakness, but it might not achieve desired code coverage within limited time constraints. This becomes difficult for weaknesses that must be considered for all inputs, since the attack surface can be too large.

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

(Bad Code)
Example Language:
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 under the assumption that the maximum length value of hostname is 64 bytes, 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).

Example 2

In the following example, it is possible to request that memcpy move a much larger segment of memory than assumed:

(Bad Code)
Example Language:
int returnChunkSize(void *) {
/* if chunk info is valid, return the size of usable memory,
* else, return -1 to indicate an error
*/
...
}
int main() {
...
memcpy(destBuf, srcBuf, (returnChunkSize(destBuf)-1));
...
}

If returnChunkSize() happens to encounter an error it will return -1. Notice that the return value is not checked before the memcpy operation (CWE-252), so -1 can be passed as the size argument to memcpy() (CWE-805). Because memcpy() assumes that the value is unsigned, it will be interpreted as MAXINT-1 (CWE-195), and therefore will copy far more memory than is likely available to the destination buffer (CWE-787, CWE-788).

Example 3

In the following example, the source character string is copied to the dest character string using the method strncpy.

(Bad Code)
Example Languages: C and C++ 
...
char source[21] = "the character string";
char dest[12];
strncpy(dest, source, sizeof(source)-1);
...

However, in the call to strncpy the source character string is used within the sizeof call to determine the number of characters to copy. This will create a buffer overflow as the size of the source character string is greater than the dest character string. The dest character string should be used within the sizeof call to ensure that the correct number of characters are copied, as shown below.

(Good Code)
Example Languages: C and C++ 
...
char source[21] = "the character string";
char dest[12];
strncpy(dest, source, sizeof(dest)-1);
...

Example 4

In this example, the method outputFilenameToLog outputs a filename to a log file. The method arguments include a pointer to a character string containing the file name and an integer for the number of characters in the string. The filename is copied to a buffer where the buffer size is set to a maximum size for inputs to the log file. The method then calls another method to save the contents of the buffer to the log file.

(Bad Code)
Example Languages: C and C++ 
#define LOG_INPUT_SIZE 40

// saves the file name to a log file
int outputFilenameToLog(char *filename, int length) {
int success;

// buffer with size set to maximum size for input to log file
char buf[LOG_INPUT_SIZE];

// copy filename to buffer
strncpy(buf, filename, length);

// save to log file
success = saveToLogFile(buf);

return success;
}

However, in this case the string copy method, strncpy, mistakenly uses the length method argument to determine the number of characters to copy rather than using the size of the local character string, buf. This can lead to a buffer overflow if the number of characters contained in character string pointed to by filename is larger then the number of characters allowed for the local character string. The string copy method should use the buf character string within a sizeof call to ensure that only characters up to the size of the buf array are copied to avoid a buffer overflow, as shown below.

(Good Code)
Example Languages: C and C++ 
...
// copy filename to buffer
strncpy(buf, filename, sizeof(buf)-1);
...
+ Observed Examples
ReferenceDescription
Chain: large length value causes buffer over-read (CWE-126)
Use of packet length field to make a calculation, then copy into a fixed-size buffer
Chain: retrieval of length value from an uninitialized memory location
Crafted length value in document reader leads to buffer overflow
SSL server overflow when the sum of multiple length fields exceeds a given value
Language interpreter API function doesn't validate length argument, leading to information exposure
+ Potential Mitigations

Phase: Requirements

Strategy: 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.

Phase: Architecture and Design

Strategy: 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.805.6], and the Strsafe.h library from Microsoft [R.805.7]. 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.

Phase: Build and Compilation

Strategy: 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.

Effectiveness: 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.

Phase: 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.

Phase: Architecture and Design

For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.

Phase: Operation

Strategy: Environment Hardening

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) [R.805.2] [R.805.4] and Position-Independent Executables (PIE) [R.805.10].

Effectiveness: 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.

Phase: Operation

Strategy: Environment Hardening

Use a CPU and operating system that offers Data Execution Protection (NX) or its equivalent [R.805.3] [R.805.6].

Effectiveness: 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.

Phases: Architecture and Design; Operation

Strategy: Environment Hardening

Run your code using the lowest privileges that are required to accomplish the necessary tasks [R.805.9]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.

Phases: Architecture and Design; Operation

Strategy: Sandbox or Jail

Run the code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by the software.

OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows the software to specify restrictions on file operations.

This may not be a feasible solution, and it only limits the impact to the operating system; the rest of the application may still be subject to compromise.

Be careful to avoid CWE-243 and other weaknesses related to jails.

Effectiveness: Limited

The effectiveness of this mitigation depends on the prevention capabilities of the specific sandbox or jail being used and might only help to reduce the scope of an attack, such as restricting the attacker to certain system calls or limiting the portion of the file system that can be accessed.

+ Weakness Ordinalities
OrdinalityDescription
Resultant
(where the weakness is typically related to the presence of some other weaknesses)
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class119Improper Restriction of Operations within the Bounds of a Memory Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory740CERT C Secure Coding Section 06 - Arrays (ARR)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory8022010 Top 25 - Risky Resource Management
Weaknesses in the 2010 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)800
ChildOfCategoryCategory8672011 Top 25 - Weaknesses On the Cusp
Weaknesses in the 2011 CWE/SANS Top 25 Most Dangerous Software Errors (primary)900
ChildOfCategoryCategory874CERT C++ Secure Coding Section 06 - Arrays and the STL (ARR)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ParentOfWeakness VariantWeakness Variant806Buffer Access Using Size of Source Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
CanFollowWeakness VariantWeakness Variant130Improper Handling of Length Parameter Inconsistency
Research Concepts1000
+ Affected Resources
  • Memory
+ Causal Nature

Explicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CERT C++ Secure CodingARR33-CPPGuarantee that copies are made into storage of sufficient size
CERT C Secure CodingARR33-CGuarantee that copies are made into storage of sufficient size
+ References
[R.805.1] [REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 6, "Why ACLs Are Important" Page 171. 2nd Edition. Microsoft. 2002.
[R.805.2] [REF-22] 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>.
[R.805.3] Arjan van de Ven. "Limiting buffer overflows with ExecShield". <http://www.redhat.com/magazine/009jul05/features/execshield/>.
[R.805.4] [REF-29] "PaX". <http://en.wikipedia.org/wiki/PaX>.
[R.805.5] Jason Lam. "Top 25 Series - Rank 12 - Buffer Access with Incorrect Length Value". SANS Software Security Institute. 2010-03-11. <http://blogs.sans.org/appsecstreetfighter/2010/03/11/top-25-series-rank-12-buffer-access-with-incorrect-length-value/>.
[R.805.6] [REF-26] Matt Messier and John Viega. "Safe C String Library v1.0.3". <http://www.zork.org/safestr/>.
[R.805.7] [REF-27] Microsoft. "Using the Strsafe.h Functions". <http://msdn.microsoft.com/en-us/library/ms647466.aspx>.
[R.805.8] [REF-25] 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>.
[R.805.9] [REF-31] Sean Barnum and Michael Gegick. "Least Privilege". 2005-09-14. <https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html>.
[R.805.10] [REF-37] Grant Murphy. "Position Independent Executables (PIE)". Red Hat. 2012-11-28. <https://securityblog.redhat.com/2012/11/28/position-independent-executables-pie/>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2010-01-15MITREInternal CWE Team
Modifications
Modification DateModifierOrganizationSource
2010-04-05CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2010-06-21CWE Content TeamMITREInternal
updated Common_Consequences, Potential_Mitigations, References
2010-09-27CWE Content TeamMITREInternal
updated Potential_Mitigations
2010-12-13CWE Content TeamMITREInternal
updated Potential_Mitigations
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-06-27CWE Content TeamMITREInternal
updated Demonstrative_Examples, Observed_Examples, Relationships
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Potential_Mitigations, References, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-02-18CWE Content TeamMITREInternal
updated Potential_Mitigations, References
2014-06-23CWE Content TeamMITREInternal
updated Demonstrative_Examples
Page Last Updated: December 08, 2015