CWE-404 Classe Rascunho 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…

Definição

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

Como os atacantes a exploram

Trajeto do atacante passo a passo

  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.

Exemplo de código vulnerável

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.

Vulnerável Java
private void processFile(string fName)
  {
  	BufferReader fil = new BufferReader(new FileReader(fName));
  	String line;
  	while ((line = fil.ReadLine()) != null)
  	{
  		processLine(line);
  	}
  }
Exemplo 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 verificação de prevenção

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.
Sinais de deteção

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

Correção automática do Plexicus

O Plexicus deteta automaticamente o CWE-404 e abre um PR de correção em menos de 60 segundos.

O Codex Remedium analisa cada commit, identifica esta fraqueza exata e entrega um pull request pronto para revisão com o patch. Sem tickets. Sem transferências.

Perguntas frequentes

Frequently asked questions

O que é o 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.

Qual a gravidade do CWE-404?

A MITRE classifica a probabilidade de exploração como Média — a exploração é realista mas normalmente requer condições específicas.

Que linguagens ou plataformas são afetadas pelo CWE-404?

A MITRE não especificou as plataformas afetadas por este CWE — pode aplicar-se à maioria das stacks de aplicações.

Como posso prevenir o 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…

Como é que o Plexicus deteta e corrige o CWE-404?

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-404 em cada commit. Quando é encontrada uma correspondência, o nosso agente Codex Remedium abre um PR de correção com o código corrigido, testes e um resumo de uma linha para o revisor.

Onde posso saber mais sobre o CWE-404?

A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/404.html. Pode também consultar a documentação da OWASP e do NIST para orientações adjacentes.

Fraquezas relacionadas

Weaknesses related to CWE-404

CWE-664 Pai

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 Irmão

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 Irmão

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 Irmão

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 Irmão

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 Irmão

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 Irmão

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 Irmão

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 Irmão

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…

Pronto quando você estiver

Pare de pagar por desenvolvedor.
Comece a fechar o ciclo.

O Plexicus é o ASPM nativo de IA que verifica, filtra, corrige, pentesta e explica — de forma autónoma. Programadores ilimitados, repos ilimitados, ações de IA de utilização justa. Nível gratuito real, €269/mo anual quando estiver pronto.