CWEweakness

CWE-131 Incorrect Calculation of Buffer Size

High Official page ↗
Abstraction
Base
Structure
Simple
Status
Draft
Likelihood of exploit
High
Languages
C, C++, Memory-Unsafe
CWE version
5.0

Description

The product does not correctly calculate the size to be used when allocating a buffer.

Common consequences

• Integrity, Availability, Confidentiality: DoS: Crash, Exit, or 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.

Potential 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). • [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. • [Implementation] 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. • [Architecture and Design] Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid [REF-1482]. 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] • [Operation, Build and Compilation] 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. • [Operation, Build and Compilation] 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]. • [Operation] 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]. • [Implementation] 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, Operation] 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. • [Architecture and Design, Operation] 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.

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. • Automated Dynamic Analysis: Use tools that are integrated during compilation to insert runtime error-checking mechanisms related to memory safety errors, such as AddressSanitizer (ASan) for C/C++ [REF-1518]. • 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. • Automated Static Analysis - Binary or Bytecode: 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 • Manual Static Analysis - Binary or Bytecode: 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 • Manual Static Analysis - Source Code: According to SOAR [REF-1479], 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) • Automated Static Analysis - Source Code: According to SOAR [REF-1479], 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 • Architecture or Design Review: According to SOAR [REF-1479], 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.)

Observed examples

• CVE-2025-46687: Chain: Javascript engine code does not perform a length check (CWE-1284) leading to integer overflow (CWE-190) causing allocation of smaller buffer than expected (CWE-131) resulting in a heap-based buffer overflow (CWE-122) • CVE-2025-27363: 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). • CVE-2020-17087: 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. • CVE-2004-1363: substitution overflow: buffer overflow using environment variables that are expanded after the length check is performed • CVE-2004-0747: substitution overflow: buffer overflow using expansion of environment variables • CVE-2005-2103: substitution overflow: buffer overflow using a large number of substitution strings • CVE-2005-3120: transformation overflow: product adds extra escape characters to incoming data, but does not account for them in the buffer length • CVE-2003-0899: transformation overflow: buffer overflow when expanding ">" to ">", etc. • CVE-2001-0334: expansion overflow: buffer overflow using wildcards • CVE-2001-0248: expansion overflow: long pathname + glob = overflow • CVE-2001-0249: expansion overflow: long pathname + glob = overflow • CVE-2002-0184: special characters in argument are not properly expanded • CVE-2004-0434: small length value leads to heap overflow • CVE-2002-1347: multiple variants • CVE-2005-0490: needs closer investigation, but probably expansion-based • CVE-2004-0940: needs closer investigation, but probably expansion-based • 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.

Related

Attack pattern · CAPEC (2)

  • CAPEC-100 Overflow Buffers attack pattern
  • CAPEC-47 Buffer Overflow via Parameter Expansion attack pattern

Observed example · CVE (17)

  • CVE-2025-46687 quickjs-ng through 0.9.0 has a missing length check in JS_ReadString for a string, leading to a heap-based buffer overflow. vulnerability
  • CVE-2025-27363 An out of bounds write exists in FreeType versions 2.13.0 and below (newer versions of FreeType are not vulnerable) when attempting to… vulnerability
  • CVE-2020-17087 Windows Kernel Local Elevation of Privilege Vulnerability vulnerability
  • CVE-2008-0599 The init_request_info function in sapi/cgi/cgi_main.c in PHP before 5.2.6 does not properly consider operator precedence when calculating… vulnerability
  • CVE-2005-3120 Stack-based buffer overflow in the HTrjis function in Lynx 2.8.6 and earlier allows remote NNTP servers to execute arbitrary code via… vulnerability
  • CVE-2005-2103 Buffer overflow in the AIM and ICQ module in Gaim before 1.5.0 allows remote attackers to cause a denial of service (application crash) and… vulnerability
  • CVE-2005-0490 Multiple stack-based buffer overflows in libcURL and cURL 7.12.1, and possibly other versions, allow remote malicious web servers to… vulnerability
  • CVE-2004-0940 Buffer overflow in the get_tag function in mod_include for Apache 1.3.x to 1.3.32 allows local users who can create SSI documents to… vulnerability
  • CVE-2004-0747 Buffer overflow in Apache 2.0.50 and earlier allows local users to gain apache privileges via a .htaccess file that causes the overflow… vulnerability
  • CVE-2004-1363 Buffer overflow in extproc in Oracle 10g allows remote attackers to execute arbitrary code via environment variables in the library name,… vulnerability
  • CVE-2004-0434 k5admind (kadmind) for Heimdal allows remote attackers to execute arbitrary code via a Kerberos 4 compatibility administration request… vulnerability
  • CVE-2003-0899 Buffer overflow in defang in libhttpd.c for thttpd 2.21 to 2.23b1 allows remote attackers to execute arbitrary code via requests that… vulnerability
  • CVE-2002-1347 Multiple buffer overflows in Cyrus SASL library 2.1.9 and earlier allow remote attackers to cause a denial of service and possibly execute… vulnerability
  • CVE-2002-0184 Sudo before 1.6.6 contains an off-by-one error that can result in a heap-based buffer overflow that may allow local users to gain root… vulnerability
  • CVE-2001-0334 FTP service in IIS 5.0 and earlier allows remote attackers to cause a denial of service via a wildcard sequence that generates a long… vulnerability
  • CVE-2001-0248 Buffer overflow in FTP server in HPUX 11 allows remote attackers to execute arbitrary commands by creating a long pathname and calling the… vulnerability
  • CVE-2001-0249 Heap overflow in FTP daemon in Solaris 8 allows remote attackers to execute arbitrary commands by creating a long pathname and calling the… vulnerability

Can precede · CWE (1)

  • CWE-119 Improper Restriction of Operations within the Bounds of a Memory Buffer weakness

Child of · CWE (1)

  • CWE-682 Incorrect Calculation weakness

Referenced by CAPEC · weakness (2)

  • CAPEC-100 Overflow Buffers attack pattern
  • CAPEC-47 Buffer Overflow via Parameter Expansion attack pattern

Referenced by CVE · weakness (254)

  • CVE-2026-107590 An out-of-bounds write vulnerability in the Qt QTextCodec iconv-based encoding of the Qt 5 Compatibility APIs module (Qt Core in Qt 5 and… vulnerability
  • CVE-2026-112709 A heap-based buffer overflow vulnerability in the Fireware OS authentication service allows an attacker who controls or intercepts traffic… vulnerability
  • CVE-2026-112710 A heap-based buffer overflow vulnerability exists in the Fireware OS authentication service allows an attacker who controls or intercepts… vulnerability
  • CVE-2026-57192 Asterisk is an open source private branch exchange and telephony toolkit. vulnerability
  • CVE-2026-116737 libphdi through 20260902 contains a heap out-of-bounds read vulnerability in libphdi_data_files_get_extent_data_file_path that uses the… vulnerability
  • CVE-2026-82944 SOEM version 2.0.0 and earlier contains a vulnerability in multi-segment data transfers where a malicious device can overflow memory… vulnerability
  • CVE-2026-97631 EDK2 contains a vulnerability in BIOS where a user may cause “Out-of-bounds Write”, Classic Buffer Overflow, and “Incorrect Calculation of… vulnerability
  • CVE-2020-37287 Vyper before 0.2.6 contains a call stack corruption vulnerability that causes incorrect function outputs when complex types with non-base… vulnerability
  • CVE-2026-95111 A memory-protected ThreadX module's queue request reaches the Module Manager's dispatch layer, which decides how much of the module's… vulnerability
  • CVE-2026-112008 libmng through 2.0.3 contains a heap-based buffer overflow vulnerability in mng_read_ordr() that allows attackers to corrupt heap memory… vulnerability
  • CVE-2026-102027 An Incorrect Calculation of Buffer Size vulnerability in the routing protocol daemon (rpd) of Juniper Networks Junos OS and Junos OS… vulnerability
  • CVE-2026-86563 A flaw was found in DPDK lib/vhost. vulnerability
  • CVE-2026-92156 F´ (F Prime) is a framework that enables development and deployment of spaceflight and other embedded software applications. vulnerability
  • CVE-2026-106574 ImageMagick is free and open-source software used for editing and manipulating digital images. vulnerability
  • CVE-2026-104424 Zebra before 6.1.0 contains an incorrect calculation vulnerability in its ZIP-317 block template selector that omits header and… vulnerability
  • CVE-2026-102505 Imager versions before 1.037 for Perl overflow a heap buffer fetching float samples from a paletted image in i_gsampf_fp. vulnerability
  • CVE-2026-47578 NVIDIA GPU Display Driver for Windows contains a vulnerability in the kernel mode layer where an attacker could cause an incorrect buffer… vulnerability
  • CVE-2026-102729 `gx_binres_theme_load()` sizes its theme buffer for the theme it was asked for, and allocates it even when the resource holds no theme with… vulnerability
  • CVE-2026-95509 Strings optimized for Latin-1 displaying Latin-1 characters cause incorrect String.arg() formatting by an incorrect buffer size… vulnerability
  • CVE-2026-13466 Incorrect calculation of buffer size vulnerability in Altera Trusted Firmware on HPS allows Overflow Buffers. vulnerability
  • CVE-2026-88355 An incorrect buffer size calculation vulnerability exists in tinyexpr commit 4a7456e in new_expr(). vulnerability
  • CVE-2026-88830 A unit confusion in BusyBox TLS Montgomery reduction buffer allocation causes a pre-authentication heap buffer overflow when processing a… vulnerability
  • CVE-2026-67549 OpenImageIO is a toolset for reading, writing, and manipulating image files of any image file format relevant to VFX / animation. vulnerability
  • CVE-2026-84448 libheif is a HEIF and AVIF file format decoder and encoder. vulnerability
  • CVE-2026-54692 SAIL is a cross-platform library for loading and saving images with support for animation, metadata, and ICC profiles. vulnerability
  • CVE-2026-91962 FreeRDP before 3.31.0 contains an integer overflow in the audin Apple backends when processing FramesPerPacket values from MSG_SNDIN_OPEN… vulnerability
  • CVE-2026-47773 ArduinoBLE enables Bluetooth Low Energy connectivity on certain Arduino models. vulnerability
  • CVE-2026-22590 eprosima Fast DDS is a C++ implementation of the DDS (Data Distribution Service) standard of the OMG (Object Management Group). vulnerability
  • CVE-2026-69598 Incorrect calculation of buffer size in Windows iSCSI allows an unauthorized attacker to execute code over a network. vulnerability
  • CVE-2026-78221 An incorrect buffer size calculation in the Windows Interactive Service in OpenVPN 2.7_alpha1 through 2.7.6 allows local authenticated… vulnerability
Show all 254 ›

Referenced by CWE · child of (1)

  • CWE-467 Use of sizeof() on a Pointer Type weakness

Referenced by CWE · has member (1)