CWE-404 Clase Borrador 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…

Definición

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.
Impacto en el mundo real

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

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  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.

Ejemplo de código vulnerable

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.

Vulnerable Java
private void processFile(string fName)
  {
  	BufferReader fil = new BufferReader(new FileReader(fName));
  	String line;
  	while ((line = fil.ReadLine()) != null)
  	{
  		processLine(line);
  	}
  }
Ejemplo de código seguro

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.

Seguro 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.
Lista de prevención

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.
Señales de detección

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

Auto-corrección de Plexicus

Plexicus detecta automáticamente CWE-404 y abre un PR de corrección en menos de 60 segundos.

Codex Remedium escanea cada commit, identifica esta debilidad concreta y entrega un pull request listo para revisión con el parche. Sin tickets. Sin traspasos.

Preguntas frecuentes

Frequently asked questions

¿Qué es 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.

¿Qué gravedad tiene CWE-404?

MITRE califica la probabilidad de explotación como Media — la explotación es realista pero suele requerir condiciones específicas.

¿Qué lenguajes o plataformas se ven afectados por CWE-404?

MITRE no ha especificado plataformas afectadas para esta CWE — puede aplicar a la mayoría de los stacks de aplicaciones.

¿Cómo puedo prevenir 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…

¿Cómo detecta y corrige Plexicus CWE-404?

El motor SAST de Plexicus detecta la firma de flujo de datos para CWE-404 en cada commit. Cuando hay coincidencia, nuestro agente Codex Remedium abre un PR de corrección con el código corregido, las pruebas y un resumen de una línea para el revisor.

¿Dónde puedo aprender más sobre CWE-404?

MITRE publica la definición canónica en https://cwe.mitre.org/data/definitions/404.html. También puedes consultar la documentación de OWASP y NIST para guías relacionadas.

Debilidades relacionadas

Weaknesses related to CWE-404

CWE-664 Padre

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 Hermano

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 Hermano

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 Hermano

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 Hermano

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 Hermano

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 Hermano

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 Hermano

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 Hermano

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…

Listo cuando tú lo estés

Deja de pagar por desarrollador.
Empieza a cerrar el bucle.

Plexicus es el ASPM nativo de IA que escanea, filtra, corrige, pentestea y explica — de forma autónoma. Desarrolladores ilimitados, repos ilimitados, acciones de IA de uso justo. Nivel gratuito real, €269/mo anual cuando estés listo.