[Forgot Password]
Login  Register Subscribe












Paid content will be excluded from the download.

Download | Alert*
view XML

Incorrect Calculation of Buffer Size

ID: 131Date: (C)2012-05-14   (M)2020-01-25
Type: weaknessStatus: DRAFT
Abstraction Type: Base


The software does not correctly calculate the size to be used when allocating a buffer, which could lead to a buffer overflow.

Likelihood of Exploit: High to Very High

Applicable Platforms
Language: C
Language: C++

Time Of Introduction

  • Implementation

Related Attack Patterns

Common Consequences

ScopeTechnical ImpactNotes
DoS: crash / exit / restart
Execute unauthorized code or commands
Read memory
Modify memory
If the incorrect calculation is used in the context of memory allocation, then the software may create a buffer that is smaller or larger than expected. If the allocated buffer is smaller than expected, this could lead to an out-of-bounds read or write (CWE-119), possibly causing a crash, allowing arbitrary code execution, or exposing sensitive data.

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 potential errors in buffer calculations. 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.
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.
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.
Manual Analysis
This weakness can be detected using tools and techniques that require manual (human) analysis, such as penetration testing, threat modeling, and interactive tools that allow the tester to record and modify an active session.
Specifically, manual static analysis is useful for evaluating the correctness of allocation calculations. This can be useful for detecting overflow conditions (CWE-190) or similar weaknesses that might have serious security impacts on the program.

Potential Mitigations

 When allocating a buffer for the purpose of transforming, converting, or encoding an input, allocate enough memory to handle the largest possible encoding. For example, in a routine that converts "&" characters to "&" for HTML entity encoding, the output buffer needs to be at least 5 times as large as the input buffer.
 Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [R.131.7]
Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation.
Input Validation
Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range.
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.
 When processing structured incoming data containing a size field followed by raw data, identify and resolve any inconsistencies between the size field and the actual size of the data (CWE-130).
 When allocating memory that uses sentinels to mark the end of a data structure - such as NUL bytes in strings - make sure you also include the sentinel in your calculation of the total amount of memory that must be allocated.
 Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
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).
Additionally, this only addresses potential overflow issues. Resource consumption / exhaustion issues are still possible.
 Use sizeof() on the appropriate data type to avoid CWE-467.
 Use the appropriate type for the desired action. For example, in C/C++, only use unsigned types for values that could never be negative, such as height, width, or other numbers related to quantity. This will simplify sanity checks and will reduce surprises related to unexpected casting.
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.
Use libraries or frameworks that make it easier to handle numbers without unexpected consequences, or buffer allocation routines that automatically track buffer size.
Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [R.131.1]
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.
Environment Hardening
Use a feature like Address Space Layout Randomization (ASLR) [R.131.3] [R.131.5].
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.
Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (NX) or its equivalent [R.131.4] [R.131.5].
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.
Compilation or Build Hardening
Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system.
Architecture and Design
Environment Hardening
Run your code using the lowest privileges that are required to accomplish the necessary tasks [R.131.6]. 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.
Architecture and Design
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.
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.


Related CWETypeViewChain
CWE-131 ChildOf CWE-890 Category CWE-888  

Demonstrative Examples   (Details)

  1. The following code allocates memory for a maximum number of widgets. It then gets a user-specified number of widgets, making sure that the user does not request too many. It then initializes the elements of the array using InitializeWidget(). Because the number of widgets can vary for each request, the code inserts a NULL pointer to signify the location of the last widget. (Demonstrative Example Id DX-20)
  2. The following code attempts to save three different identification numbers into an array. The array is allocated from memory using a call to malloc().
  3. The following code is intended to read an incoming packet from a socket and extract one or more headers. (Demonstrative Example Id DX-21)
  4. The following image processing code allocates a table for images. (Demonstrative Example Id DX-33)
  5. This example applies an encoding procedure to an input string and stores it into a buffer. (Demonstrative Example Id DX-19)

Observed Examples

  1. CVE-2004-1363 : substitution overflow: buffer overflow using environment variables that are expanded after the length check is performed
  2. CVE-2004-0747 : substitution overflow: buffer overflow using expansion of environment variables
  3. CVE-2005-2103 : substitution overflow: buffer overflow using a large number of substitution strings
  4. CVE-2005-3120 : transformation overflow: product adds extra escape characters to incoming data, but does not account for them in the buffer length
  5. CVE-2003-0899 : transformation overflow: buffer overflow when expanding ">" to ">", etc.
  6. CVE-2001-0334 : expansion overflow: buffer overflow using wildcards
  7. CVE-2001-0248 : expansion overflow: long pathname + glob = overflow
  8. CVE-2001-0249 : expansion overflow: long pathname + glob = overflow
  9. CVE-2002-0184 : special characters in argument are not properly expanded
  10. CVE-2004-0434 : small length value leads to heap overflow
  11. CVE-2002-1347 : multiple variants
  12. CVE-2005-0490 : needs closer investigation, but probably expansion-based
  13. CVE-2004-0940 : needs closer investigation, but probably expansion-based
  14. CVE-2008-0599 : Chain: Language interpreter calculates wrong buffer size (CWE-131) by using "size = ptr ? X : Y" instead of "size = (ptr ? X : Y)" expression.

For more examples, refer to CVE relations in the bottom box.

White Box Definitions

Black Box Definitions

Taxynomy Mappings

PLOVER  Other length calculation error
CERT C Secure Coding MEM35-C
Allocate sufficient memory for an object
CERT C++ Secure Coding MEM35-CPP
Allocate sufficient memory for an object


  1. David LeBlanc Niels Dekker .SafeInt.
  2. Jason Lam .Top 25 Series - Rank 18 - Incorrect Calculation of Buffer Size. SANS Software Security Institute. 2010-03-19.
  3. Michael Howard .Address Space Layout Randomization in Windows Vista.
  4. Microsoft .Understanding DEP as a mitigation technology part 1.
  5. .PaX.
  6. Sean Barnum Michael Gegick .Least Privilege. Published on 2005-09-14.
  7. M. Howard D. LeBlanc .Writing Secure Code 2nd Edition. Microsoft. Section:'Chapter 20, "Integer Overflows" Page 620'. Published on 2002.
  8. Michael Howard David LeBlanc John Viega .24 Deadly Sins of Software Security. McGraw-Hill. Section:'"Sin 5: Buffer Overruns." Page 89'. Published on 2010.
  9. Mark Dowd John McDonald Justin Schuh .The Art of Software Security Assessment 1st Edition. Addison Wesley. Section:'Chapter 8, "Incrementing Pointers Incorrectly", Page 401.'. Published on 2006.
CVE    6

© SecPod Technologies