CWE-404 Classe Brouillon Medium likelihood

Improper Resource Shutdown or Release

This vulnerability occurs when a program fails to properly close or release a system resource—like a file handle, database connection, or memory block—after it's no longer needed, preventing its…

Définition

What is CWE-404?

This vulnerability occurs when a program fails to properly close or release a system resource—like a file handle, database connection, or memory block—after it's no longer needed, preventing its reuse.
Developers must actively manage a resource's entire lifecycle, from allocation to release. This means ensuring cleanup happens not just in the main success path, but also in every possible error or exception scenario. Missing a single code path can leave resources permanently locked, leading to gradual performance degradation or sudden application crashes. Tracking these leaks across complex, distributed systems is challenging. While SAST tools can flag the pattern, Plexicus uses AI to analyze context and suggest precise code fixes—such as adding finally blocks or implementing try-with-resources—automating remediation and saving hours of manual debugging.
Impact réel

Real-world CVEs caused by CWE-404

  • Does not shut down named pipe connections if malformed data is sent.

  • Sockets not properly closed when attacker repeatedly connects and disconnects from server.

  • Chain: Return values of file/socket operations are not checked (CWE-252), allowing resultant consumption of file descriptors (CWE-772).

Comment les attaquants l'exploitent

Parcours de l'attaquant étape par étape

  1. 1

    The following method never closes the new file handle. Given enough time, the Finalize() method for BufferReader should eventually call Close(), but there is no guarantee as to how long this action will take. In fact, there is no guarantee that Finalize() will ever be invoked. In a busy environment, the Operating System could use up all of the available file handles before the Close() function is called.

  2. 2

    The good code example simply adds an explicit call to the Close() function when the system is done using the file. Within a simple example such as this the problem is easy to see and fix. In a real system, the problem may be considerably more obscure.

  3. 3

    This code attempts to open a connection to a database and catches any exceptions that may occur.

  4. 4

    If an exception occurs after establishing the database connection and before the same connection closes, the pool of database connections may become exhausted. If the number of available connections is exceeded, other users cannot access this resource, effectively denying access to the application.

  5. 5

    Under normal conditions the following C# code executes a database query, processes the results returned by the database, and closes the allocated SqlConnection object. But if an exception occurs while executing the SQL or processing the results, the SqlConnection object is not closed. If this happens often enough, the database will run out of available cursors and not be able to execute any more SQL queries.

Exemple de code vulnérable

Vulnerable Java

The following method never closes the new file handle. Given enough time, the Finalize() method for BufferReader should eventually call Close(), but there is no guarantee as to how long this action will take. In fact, there is no guarantee that Finalize() will ever be invoked. In a busy environment, the Operating System could use up all of the available file handles before the Close() function is called.

Vulnérable Java
private void processFile(string fName)
  {
  	BufferReader fil = new BufferReader(new FileReader(fName));
  	String line;
  	while ((line = fil.ReadLine()) != null)
  	{
  		processLine(line);
  	}
  }
Exemple de code sécurisé

Secure Java

The good code example simply adds an explicit call to the Close() function when the system is done using the file. Within a simple example such as this the problem is easy to see and fix. In a real system, the problem may be considerably more obscure.

Sécurisé Java
private void processFile(string fName)
  {
  	BufferReader fil = new BufferReader(new FileReader(fName));
  	String line;
  	while ((line = fil.ReadLine()) != null)
  	{
  		processLine(line);
  	}
  	fil.Close();
  }
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-404

  • Requirements Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, languages such as Java, Ruby, and Lisp perform automatic garbage collection that releases memory for objects that have been deallocated.
  • Implementation It is good practice to be responsible for freeing all resources you allocate and to be consistent with how and where you free memory in a function. If you allocate memory that you intend to free upon completion of the function, you must be sure to free the memory at all exit points for that function including error conditions.
  • Implementation Memory should be allocated/freed using matching functions such as malloc/free, new/delete, and new[]/delete[].
  • Implementation When releasing a complex object or structure, ensure that you properly dispose of all of its member components, not just the object itself.
Signaux de détection

How to detect CWE-404

Automated Dynamic Analysis Moderate

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. Resource clean up errors might be detected with a stress-test by calling the software simultaneously from a large number of threads or processes, and look for evidence of any unexpected behavior. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results.

Manual Dynamic Analysis

Identify error conditions that are not likely to occur during normal usage and trigger them. For example, run the product under low memory conditions, run with insufficient privileges or permissions, interrupt a transaction before it is completed, or disable connectivity to basic network services such as DNS. Monitor the software for any unexpected behavior. If you trigger an unhandled exception or similar error that was discovered and handled by the application's environment, it may still indicate unexpected conditions that were not handled by the application itself.

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

Correction automatique Plexicus

Plexicus détecte automatiquement CWE-404 et ouvre une PR de correction en moins de 60 secondes.

Codex Remedium analyse chaque commit, identifie cette faiblesse précise et livre une pull request prête à être relue avec le correctif. Pas de tickets. Pas de transferts.

Questions fréquentes

Frequently asked questions

Qu'est-ce que CWE-404 ?

This vulnerability occurs when a program fails to properly close or release a system resource—like a file handle, database connection, or memory block—after it's no longer needed, preventing its reuse.

Quelle est la gravité de CWE-404 ?

MITRE évalue la probabilité d'exploitation comme Moyenne — l'exploitation est réaliste mais nécessite généralement des conditions spécifiques.

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

MITRE n'a pas spécifié les plateformes affectées pour ce CWE — il peut s'appliquer à la plupart des stacks applicatives.

Comment puis-je prévenir CWE-404 ?

Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, languages such as Java, Ruby, and Lisp perform automatic garbage collection that releases memory for objects that have been deallocated. It is good practice to be responsible for freeing all resources you allocate and to be consistent with how and where you free memory in a function. If you allocate memory that you intend to free upon completion of the…

Comment Plexicus détecte et corrige CWE-404 ?

Le moteur SAST de Plexicus reconnaît la signature de flux de données de CWE-404 à 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-404 ?

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

Faiblesses associées

Weaknesses related to CWE-404

CWE-664 Parent

Improper Control of a Resource Through its Lifetime

This vulnerability occurs when software fails to properly manage a resource throughout its entire lifecycle—from creation and active use…

CWE-118 Frère

Incorrect Access of Indexable Resource ('Range Error')

This vulnerability occurs when software fails to properly check the boundaries of an indexed resource, like an array, buffer, or file,…

CWE-1229 Frère

Creation of Emergent Resource

This vulnerability occurs when a system's normal operations unintentionally create new, exploitable resources that attackers can use to…

CWE-1250 Frère

Improper Preservation of Consistency Between Independent Representations of Shared State

This vulnerability occurs when a system with multiple independent components (like distributed services or separate hardware units) each…

CWE-1329 Frère

Reliance on Component That is Not Updateable

This vulnerability occurs when a product depends on a component that cannot be updated or patched to fix security flaws or critical bugs.

CWE-221 Frère

Information Loss or Omission

This weakness occurs when an application fails to log critical security events or records them inaccurately, which can misguide security…

CWE-372 Frère

Incomplete Internal State Distinction

This vulnerability occurs when an application fails to accurately track its own operational state. The system incorrectly assumes it's in…

CWE-400 Frère

Uncontrolled Resource Consumption

This vulnerability occurs when an application fails to properly manage a finite resource, allowing an attacker to exhaust it and cause a…

CWE-410 Frère

Insufficient Resource Pool

This vulnerability occurs when a system's resource pool is too small to handle maximum usage. Attackers can exploit this by making a high…

Prêt quand vous l'êtes

Arrêtez de payer par développeur.
Commencez à fermer la boucle.

Plexicus est l'ASPM natif IA qui scanne, filtre, corrige, penteste et explique — de façon autonome. Développeurs illimités, dépôts illimités, actions IA à usage équitable. Vrai niveau gratuit, €269/mo annuel quand vous êtes prêt.