CWE-789 Variante Brouillon

Memory Allocation with Excessive Size Value

This vulnerability occurs when a program allocates memory based on a user-supplied or untrusted size value without proper validation. If an attacker provides an excessively large number, the…

Définition

What is CWE-789?

This vulnerability occurs when a program allocates memory based on a user-supplied or untrusted size value without proper validation. If an attacker provides an excessively large number, the application can attempt to allocate massive amounts of system memory, leading to a denial-of-service or system instability.
At its core, this flaw is about a missing safety check. When an application accepts a size parameter—like the length of a file to process or the number of records to load—directly from an untrusted source (user input, network data, a file) and passes it to a memory allocation function (like `malloc`, `calloc`, or `new`) without verifying it's reasonable, the system's memory manager tries to fulfill the request. This often results in an out-of-memory crash, exhausting system resources and making the application unavailable. To prevent this, developers must implement strict bounds checking before any allocation. Establish sensible, application-specific limits for all size values derived from external inputs. Compare the requested size against a configured maximum, and reject the request if it's too large. This validation should happen as early as possible, ideally right after the input is received, to ensure the program remains stable and responsive under all conditions.
Impact réel

Real-world CVEs caused by CWE-789

  • Chain: Python library does not limit the resources used to process images that specify a very large number of bands (CWE-1284), leading to excessive memory consumption (CWE-789) or an integer overflow (CWE-190).

  • program uses ::alloca() for encoding messages, but large messages trigger segfault

  • memory consumption and daemon exit by specifying a large value in a length field

  • large value in a length field leads to memory consumption and crash when no more memory is available

  • large key size in game program triggers crash when a resizing function cannot allocate enough memory

  • large Content-Length HTTP header value triggers application crash in instant messaging application due to failure in memory allocation

Comment les attaquants l'exploitent

Parcours de l'attaquant étape par étape

  1. 1

    Consider the following code, which accepts an untrusted size value and allocates a buffer to contain a string of the given size.

  2. 2

    Suppose an attacker provides a size value of:

  3. 3

    ``` 12345678 ```

  4. 4

    This will cause 305,419,896 bytes (over 291 megabytes) to be allocated for the string.

  5. 5

    Consider the following code, which accepts an untrusted size value and uses the size as an initial capacity for a HashMap.

Exemple de code vulnérable

Vulnerable C

Consider the following code, which accepts an untrusted size value and allocates a buffer to contain a string of the given size.

Vulnérable C
unsigned int size = GetUntrustedInt();
```
/* ignore integer overflow (CWE-190) for this example */* 
  
  unsigned int totBytes = size * sizeof(char);
  char *string = (char *)malloc(totBytes);
  InitializeString(string);
Exemple de code sécurisé

Secure C

Sécurisé C
int proc_msg(char *s, int msg_len)
 {

```
  int pre_len = sizeof("preamble: "); // Note space at the end of the string - assume all strings have preamble with space
  if (pre_len <= msg_len) { // Log error; return error_code; }
  char buf[pre_len - msg_len];
  ... Do processing here and set status
  return status;
 } 
 char *s = "preamble: message\n";
 char *sl = strchr(s, ':'); // Number of characters up to ':' (not including space)
 int jnklen = sl == NULL ? 0 : sl - s; // If undefined pointer, use zero length
 int ret_val = proc_msg ("s", jnklen); // Violate assumption of preamble length, end up with negative value, blow out stack
What changed: the unsafe sink is replaced (or the input is validated/escaped) so the same payload no longer triggers the weakness.
Liste de contrôle de prévention

How to prevent CWE-789

  • Implementation / Architecture and Design Perform adequate input validation against any value that influences the amount of memory that is allocated. Define an appropriate strategy for handling requests that exceed the limit, and consider supporting a configuration option so that the administrator can extend the amount of memory to be used if necessary.
  • Operation Run your program using system-provided resource limits for memory. This might still cause the program to crash or exit, but the impact to the rest of the system will be minimized.
Signaux de détection

How to detect CWE-789

Fuzzing High

Fuzz testing (fuzzing) is a powerful technique for generating large numbers of diverse inputs - either randomly or algorithmically - and dynamically invoking the code with those inputs. Even with random inputs, it is often capable of generating unexpected results such as crashes, memory corruption, or resource consumption. Fuzzing effectively produces repeatable test cases that clearly indicate bugs, which helps developers to diagnose the issues.

Automated Static Analysis High

Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without having to execute it. Typically, this is done by building a model of data flow and control flow, then searching for potentially-vulnerable patterns that connect "sources" (origins of input) with "sinks" (destinations where the data interacts with external components, a lower layer such as the OS, etc.)

CWE-789

Don't catalog this weakness. Prove it's reachable.

Plexicus turns CWE catalogs into evidence: every CWE-pattern is matched against your real code graph, reach is proven on a sandbox clone, and verified findings ship as reviewed PRs.

Questions fréquentes

Frequently asked questions

Qu'est-ce que CWE-789 ?

This vulnerability occurs when a program allocates memory based on a user-supplied or untrusted size value without proper validation. If an attacker provides an excessively large number, the application can attempt to allocate massive amounts of system memory, leading to a denial-of-service or system instability.

Quelle est la gravité de CWE-789 ?

MITRE n'a pas publié de note de probabilité d'exploitation pour cette faiblesse. Traitez-la comme un impact moyen jusqu'à ce que votre modèle de menace prouve le contraire.

Quels langages ou plateformes sont affectés par CWE-789 ?

MITRE lists the following affected platforms: C, C++.

Comment puis-je prévenir CWE-789 ?

Perform adequate input validation against any value that influences the amount of memory that is allocated. Define an appropriate strategy for handling requests that exceed the limit, and consider supporting a configuration option so that the administrator can extend the amount of memory to be used if necessary. Run your program using system-provided resource limits for memory. This might still cause the program to crash or exit, but the impact to the rest of the system will be minimized.

Comment Plexicus détecte et corrige CWE-789 ?

Le moteur SAST de Plexicus reconnaît la signature de flux de données de CWE-789 à chaque commit. Lorsqu'une correspondance est trouvée, notre agent Codex Remedium ouvre une PR de correction avec le code corrigé, les tests et un résumé d'une ligne pour le relecteur.

Où puis-je en savoir plus sur CWE-789 ?

MITRE publie la définition canonique à https://cwe.mitre.org/data/definitions/789.html. Vous pouvez également consulter la documentation OWASP et NIST pour des conseils adjacents.

Prêt à valider l'essentiel ?

Prêt à valider ce qui compte.

Plexicus est Proof-Driven AppSec : findings validés, compréhension contextuelle et remédiation relue — ancrée dans la preuve, scopée avec vous.

Qualification

Vérifiez si l'AI Swarm Pentest convient à votre environnement.

Partagez le contexte minimum. Nous vérifierons le périmètre et indiquerons la prochaine étape commerciale.

Avant d'envoyer — vérifiez que vous correspondez

0 / 280

Sans engagement. Si vous ne correspondez pas, nous vous le dirons.

SAMPLE HANDOVER · ILLUSTRATIVE

Sample evidence handover

A trimmed view of what your team receives at the end of an AI Swarm Pentest engagement. Real engagements include full technical evidence, executive narrative, and a remediation plan.

VALIDATED FINDING Evidence attached

Server-Side Request Forgery in webhooks/receiver

demo-project/sample-app · src/webhooks/receiver.py:42

SeverityHigh CVSS 3.18.6 Priority79 Confirmedvia replay

Untrusted caller-supplied URLs reach an internal egress without an allowlist. Replayed in a sandbox against a fresh authorized target — the same control was validated to fail twice.

REVIEWER-READY REMEDIATION Merge-ready PR

Validate the target URL against an allowlist of permitted hostnames. Reject private/internal IP ranges. Enforce HTTPS only.

plexicus/remediation/webhooks-ssrf 3 changed · 0 new files
42resp = requests.get(target_url)
42+if not is_allowed_host(target_url):
43+  raise WebhookRejected(target_url)
44+resp = requests.get(target_url, timeout=5)
Every engagement hands over:
  • Executive briefing
  • Validated findings list
  • Merge-ready PRs
  • Compliance mapping (NIS2 · DORA · CRA)
Tour privé Pour les investisseurs