CWE-787 Base Draft High likelihood

Out-of-bounds Write

This vulnerability occurs when software incorrectly writes data outside the boundaries of its allocated memory buffer, either beyond the end or before the beginning.

Definition

What is CWE-787?

This vulnerability occurs when software incorrectly writes data outside the boundaries of its allocated memory buffer, either beyond the end or before the beginning.
An out-of-bounds write happens when a program fails to properly validate the target location for a write operation, such as copying data, assigning a value, or modifying memory. This can corrupt adjacent data structures, crash the application, or alter critical program logic, often leading to unpredictable behavior. It's a fundamental memory safety flaw commonly arising from incorrect pointer arithmetic, off-by-one errors, or using unsafe functions that don't check buffer sizes. Attackers frequently exploit this weakness to execute arbitrary code, escalate privileges, or cause denial-of-service. To prevent it, developers should use secure, bounds-checked functions, employ modern safe languages or libraries, and rigorously validate all indices and offsets before performing write operations. Static and dynamic analysis tools are also essential for catching these dangerous errors before deployment.
Vulnerability Diagram CWE-787
Out-of-Bounds Write arr[8] 01234567 adjacent: function ptr / metadata arr[12] = 0xDEADBEEF write past end Writing outside the array overwrites neighbouring memory or vtables.
Auswirkungen in der Praxis

Real-world CVEs caused by CWE-787

  • 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).

  • The reference implementation code for a Trusted Platform Module does not implement length checks on data, allowing for an attacker to write 2 bytes past the end of a buffer.

  • Chain: insufficient input validation (CWE-20) in browser allows heap corruption (CWE-787), as exploited in the wild per CISA KEV.

  • GPU kernel driver allows memory corruption because a user can obtain read/write access to read-only pages, as exploited in the wild per CISA KEV.

  • 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.

  • Out-of-bounds write in kernel-mode driver, as exploited in the wild per CISA KEV.

  • Escape from browser sandbox using out-of-bounds write due to incorrect bounds check, as exploited in the wild per CISA KEV.

  • Memory corruption in web browser scripting engine, as exploited in the wild per CISA KEV.

Wie Angreifer es ausnutzen

Angreiferpfad Schritt für Schritt

  1. 1

    The following code attempts to save four different identification numbers into an array.

  2. 2

    Since the array is only allocated to hold three elements, the valid indices are 0 to 2; so, the assignment to id_sequence[3] is out of bounds.

  3. 3

    In the following code, it is possible to request that memcpy move a much larger segment of memory than assumed:

  4. 4

    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).

  5. 5

    This code takes an IP address from the user and verifies that it is well formed. It then looks up the hostname and copies it into a buffer.

Verwundbares Codebeispiel

Vulnerable C

The following code attempts to save four different identification numbers into an array.

Verwundbar C
int id_sequence[3];
  /* Populate the id array. */
  id_sequence[0] = 123;
  id_sequence[1] = 234;
  id_sequence[2] = 345;
  id_sequence[3] = 456;
Sicheres Codebeispiel

Secure pseudo

Sicher pseudo
// Validate, sanitize, or use a safe API before reaching the sink.
function handleRequest(input) {
  const safe = validateAndEscape(input);
  return executeWithGuards(safe);
}
What changed: the unsafe sink is replaced (or the input is validated/escaped) so the same payload no longer triggers the weakness.
Präventions-Checkliste

How to prevent CWE-787

  • 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.
  • 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 Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Erkennungssignale

How to detect CWE-787

Automated Static Analysis High

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.

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.

Plexicus Auto-Fix

Plexicus erkennt CWE-787 automatisch und öffnet in unter 60 Sekunden einen Fix-PR.

Codex Remedium scannt jeden Commit, identifiziert genau diese Schwachstelle und liefert einen reviewer-ready Pull Request mit dem Patch. Keine Tickets. Keine Hand-offs.

Häufig gestellte Fragen

Frequently asked questions

Was ist CWE-787?

This vulnerability occurs when software incorrectly writes data outside the boundaries of its allocated memory buffer, either beyond the end or before the beginning.

Wie gravierend ist CWE-787?

MITRE stuft die Exploit-Wahrscheinlichkeit als hoch ein — diese Schwachstelle wird aktiv in freier Wildbahn ausgenutzt und sollte priorisiert behoben werden.

Welche Sprachen oder Plattformen sind von CWE-787 betroffen?

MITRE lists the following affected platforms: C, C++, Assembly, ICS/OT.

Wie kann ich CWE-787 verhindern?

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…

Wie erkennt und behebt Plexicus CWE-787?

Die SAST-Engine von Plexicus erkennt die Datenfluss-Signatur von CWE-787 bei jedem Commit. Bei einem Treffer öffnet unser Codex-Remedium-Agent einen Fix-PR mit korrigiertem Code, Tests und einer einzeiligen Zusammenfassung für den Reviewer.

Wo erfahre ich mehr über CWE-787?

MITRE veröffentlicht die kanonische Definition unter https://cwe.mitre.org/data/definitions/787.html. Für ergänzende Hinweise kannst du auch die OWASP- und NIST-Dokumentation heranziehen.

Verwandte Schwachstellen

Weaknesses related to CWE-787

CWE-119 Parent

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.…

CWE-120 Sibling

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…

CWE-123 Sibling

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,…

CWE-125 Sibling

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…

CWE-130 Sibling

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…

CWE-466 Sibling

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…

CWE-786 Sibling

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…

CWE-788 Sibling

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…

CWE-805 Sibling

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…

Bereit, wenn du es bist

Schluss mit dem Bezahlen pro Entwickler.
Schließ den Kreislauf.

Plexicus ist die KI-native ASPM, die scannt, filtert, fixt, pentestet und erklärt — autonom. Unbegrenzte Entwickler, unbegrenzte Repos, Fair-Use-KI-Aktionen. Echter kostenloser Tarif, €269/mo jährlich, wenn du bereit bist.