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.
Incorrect Calculation of Buffer Size
This vulnerability occurs when a program miscalculates the amount of memory needed for a buffer, potentially leading to a buffer overflow that can crash the software or allow attackers to execute…
What is CWE-131?
Real-world CVEs caused by CWE-131
-
Font rendering library does not properly handle assigning a signed short value to an unsigned long (CWE-195), leading to an integer wraparound (CWE-190), causing too small of a buffer (CWE-131), leading to an out-of-bounds write (CWE-787).
-
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.
-
substitution overflow: buffer overflow using environment variables that are expanded after the length check is performed
-
substitution overflow: buffer overflow using expansion of environment variables
-
substitution overflow: buffer overflow using a large number of substitution strings
-
transformation overflow: product adds extra escape characters to incoming data, but does not account for them in the buffer length
-
transformation overflow: buffer overflow when expanding ">" to ">", etc.
-
expansion overflow: buffer overflow using wildcards
Step-by-step attacker path
- 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.
- 2
However, this code contains an off-by-one calculation error (CWE-193). It allocates exactly enough space to contain the specified number of widgets, but it does not include the space for the NULL pointer. As a result, the allocated buffer is smaller than it is supposed to be (CWE-131). So if the user ever requests MAX_NUM_WIDGETS, there is an out-of-bounds write (CWE-787) when the NULL is assigned. Depending on the environment and compilation settings, this could cause memory corruption.
- 3
The following image processing code allocates a table for images.
- 4
This code intends to allocate a table of size num_imgs, however as num_imgs grows large, the calculation determining the size of the list will eventually overflow (CWE-190). This will result in a very small list to be allocated instead. If the subsequent code operates on the list as if it were num_imgs long, it may result in many types of out-of-bounds problems (CWE-119).
- 5
This example applies an encoding procedure to an input string and stores it into a buffer.
Vulnerable C
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.
int i;
unsigned int numWidgets;
Widget **WidgetList;
numWidgets = GetUntrustedSizeValue();
if ((numWidgets == 0) || (numWidgets > MAX_NUM_WIDGETS)) {
ExitError("Incorrect number of widgets requested!");
}
WidgetList = (Widget **)malloc(numWidgets * sizeof(Widget *));
printf("WidgetList ptr=%p\n", WidgetList);
for(i=0; i<numWidgets; i++) {
WidgetList[i] = InitializeWidget();
}
WidgetList[numWidgets] = NULL;
showWidgets(WidgetList); Secure pseudo
// Validate, sanitize, or use a safe API before reaching the sink.
function handleRequest(input) {
const safe = validateAndEscape(input);
return executeWithGuards(safe);
} How to prevent CWE-131
- Implementation 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.
- Implementation 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.
- Implementation 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.
- Implementation 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).
- Implementation 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.
- Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
- Implementation Use sizeof() on the appropriate data type to avoid CWE-467.
How to detect CWE-131
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 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.
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.
According to SOAR [REF-1479], 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
According to SOAR [REF-1479], the following detection techniques may be useful: ``` Cost effective for partial coverage: ``` Binary / Bytecode disassembler - then use manual analysis for vulnerabilities & anomalies
Plexicus auto-detects CWE-131 and opens a fix PR in under 60 seconds.
Codex Remedium scans every commit, identifies this exact weakness, and ships a reviewer-ready pull request with the patch. No tickets. No hand-offs.
Frequently asked questions
What is CWE-131?
This vulnerability occurs when a program miscalculates the amount of memory needed for a buffer, potentially leading to a buffer overflow that can crash the software or allow attackers to execute malicious code.
How serious is CWE-131?
MITRE rates the likelihood of exploit as High — this weakness is actively exploited in the wild and should be prioritized for remediation.
What languages or platforms are affected by CWE-131?
MITRE lists the following affected platforms: C, C++.
How can I prevent CWE-131?
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,…
How does Plexicus detect and fix CWE-131?
Plexicus's SAST engine matches the data-flow signature for CWE-131 on every commit. When a match is found, our Codex Remedium agent opens a fix PR with the corrected code, tests, and a one-line summary for the reviewer.
Where can I learn more about CWE-131?
MITRE publishes the canonical definition at https://cwe.mitre.org/data/definitions/131.html. You can also reference OWASP and NIST documentation for adjacent guidance.
Weaknesses related to CWE-131
Incorrect Calculation
This vulnerability occurs when software performs a calculation that produces wrong or unexpected results, which are then used to make…
Wrap-around Error
A wrap-around error happens when a variable exceeds the maximum value its data type can hold, causing it to unexpectedly reset to a very…
Incorrect Bitwise Shift of Integer
This vulnerability occurs when a program attempts to shift an integer's bits by an invalid amount—either a negative number or a value…
Insufficient Precision or Accuracy of a Real Number
This vulnerability occurs when a program uses a data type or algorithm that cannot accurately represent or calculate the fractional part…
Incorrect Calculation of Multi-Byte String Length
This vulnerability occurs when software incorrectly measures the length of strings containing multi-byte or wide characters, leading to…
Integer Overflow or Wraparound
Integer overflow or wraparound occurs when a calculation produces a numeric result that exceeds the maximum value a variable can hold.…
Integer Underflow (Wrap or Wraparound)
Integer underflow occurs when a subtraction operation results in a value smaller than the data type's minimum limit, causing the value to…
Off-by-one Error
An off-by-one error occurs when a program incorrectly calculates a boundary, such as a loop counter or array index, by being one unit too…
Divide By Zero
A divide-by-zero error occurs when software attempts to perform a division operation where the denominator is zero.
Further reading
- MITRE — official CWE-131 https://cwe.mitre.org/data/definitions/131.html
- SafeInt https://github.com/dcleblanc/SafeInt/
- Top 25 Series - Rank 18 - Incorrect Calculation of Buffer Size https://www.sans.org/blog/top-25-series-rank-18-incorrect-calculation-of-buffer-size
- Address Space Layout Randomization in Windows Vista https://learn.microsoft.com/en-us/archive/blogs/michael_howard/address-space-layout-randomization-in-windows-vista
- Understanding DEP as a mitigation technology part 1 https://msrc.microsoft.com/blog/2009/06/understanding-dep-as-a-mitigation-technology-part-1/
- PaX https://en.wikipedia.org/wiki/Executable_space_protection#PaX
- Least Privilege https://web.archive.org/web/20211209014121/https://www.cisa.gov/uscert/bsi/articles/knowledge/principles/least-privilege
Don't Let Security
Weigh You Down.
Stop choosing between AI velocity and security debt. Plexicus is the only platform that runs Vibe Coding Security and ASPM in parallel — one workflow, every codebase.