CWE-131: Incorrect Calculation of Buffer Size (Base)

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




Applicable Platforms: ::LANGUAGE NAME:C:LANGUAGE PREVALENCE:Undetermined::LANGUAGE NAME:C++:LANGUAGE PREVALENCE:Undetermined::

Modes of Introduction: ::PHASE:Implementation::



Common Consequences: ::SCOPE:Integrity:SCOPE:Availability:SCOPE:Confidentiality:IMPACT:DoS: Crash, Exit, or Restart:IMPACT:Execute Unauthorized Code or Commands:IMPACT:Read Memory:IMPACT:Modify Memory:NOTE: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: ::METHOD:Automated Static Analysis:DESCRIPTION: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.:EFFECTIVENESS:High::METHOD:Automated Dynamic Analysis:DESCRIPTION: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::METHOD:Manual Analysis:DESCRIPTION: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.::METHOD:Manual Analysis:DESCRIPTION: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.:EFFECTIVENESS:High::METHOD:Automated Static Analysis - Binary or Bytecode:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Bytecode Weakness Analysis - including disassembler + source code weakness analysis Binary Weakness Analysis - including disassembler + source code weakness analysis:EFFECTIVENESS:High::METHOD:Manual Static Analysis - Binary or Bytecode:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Cost effective for partial coverage: Binary / Bytecode disassembler - then use manual analysis for vulnerabilities & anomalies:EFFECTIVENESS:SOAR Partial::METHOD:Manual Static Analysis - Source Code:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Cost effective for partial coverage: Focused Manual Spotcheck - Focused manual analysis of source Manual Source Code Review (not inspections):EFFECTIVENESS:SOAR Partial::METHOD:Automated Static Analysis - Source Code:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Source code Weakness Analyzer Context-configured Source Code Weakness Analyzer Cost effective for partial coverage: Source Code Quality Analyzer:EFFECTIVENESS:High::METHOD:Architecture or Design Review:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Formal Methods / Correct-By-Construction Cost effective for partial coverage: Inspection (IEEE 1028 standard) (can apply to requirements, design, source code, etc.):EFFECTIVENESS:High::

Potential Mitigations: ::PHASE:Implementation:DESCRIPTION: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 &amp; for HTML entity encoding, the output buffer needs to be at least 5 times as large as the input buffer.::PHASE:Implementation:DESCRIPTION: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. [REF-7] Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation.::PHASE:Implementation:STRATEGY:Input Validation:DESCRIPTION: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.::PHASE:Architecture and Design:DESCRIPTION: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:Implementation:DESCRIPTION: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).::PHASE:Implementation:DESCRIPTION: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.::PHASE:Implementation:DESCRIPTION:Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.:EFFECTIVENESS:Moderate::PHASE:Implementation:DESCRIPTION:Use sizeof() on the appropriate data type to avoid CWE-467.::PHASE:Implementation:DESCRIPTION: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 validation and will reduce surprises related to unexpected casting.::PHASE:Architecture and Design:STRATEGY:Libraries or Frameworks:DESCRIPTION: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++). [REF-106]::PHASE:Operation Build and Compilation:STRATEGY:Environment Hardening:DESCRIPTION: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.:EFFECTIVENESS:Defense in Depth::PHASE:Operation Build and Compilation:STRATEGY:Environment Hardening:DESCRIPTION: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 modules, in a process known as rebasing (for Windows) and prelinking (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].:EFFECTIVENESS:Defense in Depth::PHASE:Operation:STRATEGY:Environment Hardening:DESCRIPTION: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].:EFFECTIVENESS:Defense in Depth::PHASE:Implementation:STRATEGY:Compilation or Build Hardening:DESCRIPTION: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.::PHASE:Architecture and Design Operation:STRATEGY:Environment Hardening:DESCRIPTION:Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. 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.::PHASE:Architecture and Design Operation:STRATEGY:Sandbox or Jail:DESCRIPTION: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::

Observed Examples: ::REFERENCE:CVE-2020-17087:DESCRIPTION:Chain: integer truncation (CWE-197) causes small buffer allocation (CWE-131) leading to out-of-bounds write (CWE-787) in kernel pool, as exploited in the wild per CISA KEV.:LINK:https://www.cve.org/CVERecord?id=CVE-2020-17087::REFERENCE:CVE-2004-1363:DESCRIPTION:substitution overflow: buffer overflow using environment variables that are expanded after the length check is performed:LINK:https://www.cve.org/CVERecord?id=CVE-2004-1363::REFERENCE:CVE-2004-0747:DESCRIPTION:substitution overflow: buffer overflow using expansion of environment variables:LINK:https://www.cve.org/CVERecord?id=CVE-2004-0747::REFERENCE:CVE-2005-2103:DESCRIPTION:substitution overflow: buffer overflow using a large number of substitution strings:LINK:https://www.cve.org/CVERecord?id=CVE-2005-2103::REFERENCE:CVE-2005-3120:DESCRIPTION:transformation overflow: product adds extra escape characters to incoming data, but does not account for them in the buffer length:LINK:https://www.cve.org/CVERecord?id=CVE-2005-3120::REFERENCE:CVE-2003-0899:DESCRIPTION:transformation overflow: buffer overflow when expanding > to &gt;, etc.:LINK:https://www.cve.org/CVERecord?id=CVE-2003-0899::REFERENCE:CVE-2001-0334:DESCRIPTION:expansion overflow: buffer overflow using wildcards:LINK:https://www.cve.org/CVERecord?id=CVE-2001-0334::REFERENCE:CVE-2001-0248:DESCRIPTION:expansion overflow: long pathname + glob = overflow:LINK:https://www.cve.org/CVERecord?id=CVE-2001-0248::REFERENCE:CVE-2001-0249:DESCRIPTION:expansion overflow: long pathname + glob = overflow:LINK:https://www.cve.org/CVERecord?id=CVE-2001-0249::REFERENCE:CVE-2002-0184:DESCRIPTION:special characters in argument are not properly expanded:LINK:https://www.cve.org/CVERecord?id=CVE-2002-0184::REFERENCE:CVE-2004-0434:DESCRIPTION:small length value leads to heap overflow:LINK:https://www.cve.org/CVERecord?id=CVE-2004-0434::REFERENCE:CVE-2002-1347:DESCRIPTION:multiple variants:LINK:https://www.cve.org/CVERecord?id=CVE-2002-1347::REFERENCE:CVE-2005-0490:DESCRIPTION:needs closer investigation, but probably expansion-based:LINK:https://www.cve.org/CVERecord?id=CVE-2005-0490::REFERENCE:CVE-2004-0940:DESCRIPTION:needs closer investigation, but probably expansion-based:LINK:https://www.cve.org/CVERecord?id=CVE-2004-0940::REFERENCE:CVE-2008-0599:DESCRIPTION:Chain: Language interpreter calculates wrong buffer size (CWE-131) by using size = ptr ? X : Y instead of size = (ptr ? X : Y) expression.:LINK:https://www.cve.org/CVERecord?id=CVE-2008-0599::



Notes: ::TYPE:Maintenance:NOTE:This is a broad category. Some examples include: simple math errors, incorrectly updating parallel counters, not accounting for size differences when transforming one input to another format (e.g. URL canonicalization or other transformation that can generate a result that's larger than the original input, i.e. expansion). This level of detail is rarely available in public reports, so it is difficult to find good examples.::TYPE:Maintenance:NOTE:This weakness may be a composite or a chain. It also may contain layering or perspective differences. This issue may be associated with many different types of incorrect calculations (CWE-682), although the integer overflow (CWE-190) is probably the most prevalent. This can be primary to resource consumption problems (CWE-400), including uncontrolled memory allocation (CWE-789). However, its relationship with out-of-bounds buffer access (CWE-119) must also be considered.::