CWE-131 — Incorrect Calculation of Buffer Size
CWE-131: Incorrect Calculation of Buffer Size
MITRE CWE weakness
| Kind | Weakness |
| Abstraction | Base |
| Status | Draft |
| Likelihood of exploit | High |
Description
The product does not correctly calculate the size to be used when allocating a buffer, which could lead to a buffer overflow.
Common consequences
- Integrity, Availability, Confidentiality: DoS: Crash, Exit, or Restart, Execute Unauthorized Code or Commands, Read Memory, Modify Memory
Mitigations
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).
References
- CWE page: https://cwe.mitre.org/data/definitions/131.html
- CWE list: https://cwe.mitre.org/data/index.html