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 out-of-bounds memory operations. 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.
Buffer Access with Incorrect Length Value
This vulnerability occurs when software reads from or writes to a buffer using a loop or sequential operation, but mistakenly calculates or provides an incorrect length value. This incorrect length…
What is CWE-805?
Real-world CVEs caused by CWE-805
-
Chain: large length value causes buffer over-read (CWE-126)
-
Use of packet length field to make a calculation, then copy into a fixed-size buffer
-
Chain: retrieval of length value from an uninitialized memory location
-
Crafted length value in document reader leads to buffer overflow
-
SSL server overflow when the sum of multiple length fields exceeds a given value
-
Language interpreter API function doesn't validate length argument, leading to information exposure
Step-by-step attacker path
- 1
This example takes an IP address from a user, verifies that it is well formed and then looks up the hostname and copies it into a buffer.
- 2
This function allocates a buffer of 64 bytes to store the hostname under the assumption that the maximum length value of hostname is 64 bytes, however there is no guarantee that the hostname will not be larger than 64 bytes. If an attacker specifies an address which resolves to a very large hostname, then the function may overwrite sensitive data or even relinquish control flow to the attacker.
- 3
Note that this example also contains an unchecked return value (CWE-252) that can lead to a NULL pointer dereference (CWE-476).
- 4
In the following example, it is possible to request that memcpy move a much larger segment of memory than assumed:
- 5
If returnChunkSize() happens to encounter an error it will return -1. Notice that the return value is not checked before the memcpy operation (CWE-252), so -1 can be passed as the size argument to memcpy() (CWE-805). Because memcpy() assumes that the value is unsigned, it will be interpreted as MAXINT-1 (CWE-195), and therefore will copy far more memory than is likely available to the destination buffer (CWE-787, CWE-788).
Vulnerable C
This example takes an IP address from a user, verifies that it is well formed and then looks up the hostname and copies it into a buffer.
void host_lookup(char *user_supplied_addr){
struct hostent *hp;
in_addr_t *addr;
char hostname[64];
in_addr_t inet_addr(const char *cp);
```
/*routine that ensures user_supplied_addr is in the right format for conversion */*
validate_addr_form(user_supplied_addr);
addr = inet_addr(user_supplied_addr);
hp = gethostbyaddr( addr, sizeof(struct in_addr), AF_INET);
strcpy(hostname, hp->h_name);} Secure C
However, in the call to strncpy the source character string is used within the sizeof call to determine the number of characters to copy. This will create a buffer overflow as the size of the source character string is greater than the dest character string. The dest character string should be used within the sizeof call to ensure that the correct number of characters are copied, as shown below.
...
char source[21] = "the character string";
char dest[12];
strncpy(dest, source, sizeof(dest)-1);
... How to prevent CWE-805
- Requirements Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
- 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. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
- 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.
- Implementation Consider adhering to the following rules when allocating and managing an application's memory: - Double check that the buffer is as large as specified. - When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. - Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. - If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
- 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.
- 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].
- 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 product or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.
How to detect CWE-805
This weakness can be detected using dynamic tools and techniques that interact with the product using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The product'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.
Plexicus auto-detects CWE-805 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-805?
This vulnerability occurs when software reads from or writes to a buffer using a loop or sequential operation, but mistakenly calculates or provides an incorrect length value. This incorrect length causes the operation to access memory outside the buffer's allocated boundaries.
How serious is CWE-805?
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-805?
MITRE lists the following affected platforms: C, C++, Assembly.
How can I prevent CWE-805?
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is…
How does Plexicus detect and fix CWE-805?
Plexicus's SAST engine matches the data-flow signature for CWE-805 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-805?
MITRE publishes the canonical definition at https://cwe.mitre.org/data/definitions/805.html. You can also reference OWASP and NIST documentation for adjacent guidance.
Weaknesses related to CWE-805
Improper Restriction of Operations within the Bounds of a Memory Buffer
This vulnerability occurs when software accesses a memory buffer but reads from or writes to a location outside its allocated boundary.…
Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
This vulnerability occurs when a program copies data from one memory location to another without first verifying that the source data will…
Write-what-where Condition
A write-what-where condition occurs when an attacker can control both the data written and the exact memory location where it's written,…
Out-of-bounds Read
An out-of-bounds read occurs when software accesses memory outside the boundaries of a buffer, array, or similar data structure, reading…
Improper Handling of Length Parameter Inconsistency
This vulnerability occurs when a program reads a structured data packet or message but fails to properly validate that the declared length…
Return of Pointer Value Outside of Expected Range
This vulnerability occurs when a function returns a memory pointer that points outside the expected buffer range, potentially exposing…
Access of Memory Location Before Start of Buffer
This vulnerability occurs when software attempts to read from or write to a memory location positioned before the official start of a…
Out-of-bounds Write
This vulnerability occurs when software incorrectly writes data outside the boundaries of its allocated memory buffer, either beyond the…
Access of Memory Location After End of Buffer
This vulnerability occurs when software attempts to read from or write to a memory buffer using an index or pointer that points past the…
Further reading
- MITRE — official CWE-805 https://cwe.mitre.org/data/definitions/805.html
- Writing Secure Code https://www.microsoftpressstore.com/store/writing-secure-code-9780735617223
- Address Space Layout Randomization in Windows Vista https://learn.microsoft.com/en-us/archive/blogs/michael_howard/address-space-layout-randomization-in-windows-vista
- Limiting buffer overflows with ExecShield https://archive.is/saAFo
- PaX https://en.wikipedia.org/wiki/Executable_space_protection#PaX
- Top 25 Series - Rank 12 - Buffer Access with Incorrect Length Value https://web.archive.org/web/20100316043717/http://blogs.sans.org:80/appsecstreetfighter/2010/03/11/top-25-series-rank-12-buffer-access-with-incorrect-length-value/
- Safe C String Library v1.0.3 http://www.gnu-darwin.org/www001/ports-1.5a-CURRENT/devel/safestr/work/safestr-1.0.3/doc/safestr.html
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.