CWE-1341 Base Incompleto

Multiple Releases of Same Resource or Handle

This vulnerability occurs when a program incorrectly tries to close or release the same system resource—like memory, a file, or a network connection—more than once. This double-free or double-close…

Definición

What is CWE-1341?

This vulnerability occurs when a program incorrectly tries to close or release the same system resource—like memory, a file, or a network connection—more than once. This double-free or double-close violates the API's contract and leads to unpredictable and often dangerous behavior.
Modern software constantly acquires and releases resources such as memory blocks, file handles, and socket connections. APIs like `free()`, `delete()`, or `close()` are designed to manage this lifecycle, but they typically assume the developer will call them exactly once per resource. When the same release function is called a second time on an already-freed resource, the underlying system management structures can become corrupted. This corruption can directly cause crashes, memory leaks, or even create security gaps that attackers might exploit to execute arbitrary code. To prevent this, developers must carefully manage the state of each resource handle, ensuring release calls are paired one-to-one with successful acquisitions. A common best practice is to set pointers or handles to NULL (or another null-like state) immediately after release, as many safe implementations will check for this and ignore subsequent calls. Reusing the same variable identifier for a different resource before properly closing the first is a major risk, as it can lead to closing the wrong, active resource, compounding the problem.
Impacto en el mundo real

Real-world CVEs caused by CWE-1341

  • file descriptor double close can cause the wrong file to be associated with a file descriptor.

  • Chain: Signal handler contains too much functionality (CWE-828), introducing a race condition that leads to a double free (CWE-415).

  • Double free resultant from certain error conditions.

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    This example attempts to close a file twice. In some cases, the C library fclose() function will catch the error and return an error code. In other implementations, a double-free (CWE-415) occurs, causing the program to fault. Note that the examples presented here are simplistic, and double fclose() calls will frequently be spread around a program, making them more difficult to find during code reviews.

  2. 2

    There are multiple possible fixes. This fix only has one call to fclose(), which is typically the preferred handling of this problem - but this simplistic method is not always possible.

  3. 3

    This fix uses a flag to call fclose() only once. Note that this flag is explicit. The variable "f" could also have been used as it will be either NULL if the file is not able to be opened or a valid pointer if the file was successfully opened. If "f" is replacing "f_flg" then "f" would need to be set to NULL after the first fclose() call so the second fclose call would never be executed.

  4. 4

    The following code shows a simple example of a double free vulnerability.

  5. 5

    Double free vulnerabilities have two common (and sometimes overlapping) causes:

Ejemplo de código vulnerable

Vulnerable C

This example attempts to close a file twice. In some cases, the C library fclose() function will catch the error and return an error code. In other implementations, a double-free (CWE-415) occurs, causing the program to fault. Note that the examples presented here are simplistic, and double fclose() calls will frequently be spread around a program, making them more difficult to find during code reviews.

Vulnerable C
char b[2000];
 FILE *f = fopen("dbl_cls.c", "r");
 if (f)
 {

```
  b[0] = 0;
   fread(b, 1, sizeof(b) - 1, f);
   printf("%s\n'", b);
   int r1 = fclose(f);
   printf("\n-----------------\n1 close done '%d'\n", r1);
   int r2 = fclose(f); // Double close
   printf("2 close done '%d'\n", r2);
 }
Ejemplo de código seguro

Secure C

There are multiple possible fixes. This fix only has one call to fclose(), which is typically the preferred handling of this problem - but this simplistic method is not always possible.

Seguro C
char b[2000];
 FILE *f = fopen("dbl_cls.c", "r");
 if (f)
 {

```
  b[0] = 0;
   fread(b, 1, sizeof(b) - 1, f);
   printf("%s\n'", b);
   int r = fclose(f);
   printf("\n-----------------\n1 close done '%d'\n", r);
 }
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-1341

  • Implementation Change the code's logic so that the resource is only closed once. This might require simplifying or refactoring. This fix can be simple to do in small code blocks, but more difficult when multiple closes are buried within complex conditionals.
  • Implementation It can be effective to implement a flag that is (1) set when the resource is opened, (2) cleared when it is closed, and (3) checked before closing. This approach can be useful when there are disparate cases in which closes must be performed. However, flag-tracking can increase code complexity and requires diligent compliance by the programmer.
  • Implementation When closing a resource, set the resource's associated variable to NULL or equivalent value for the given language. Some APIs will ignore this null value without causing errors. For other APIs, this can lead to application crashes or exceptions, which may still be preferable to corrupting an unintended resource such as memory or data.
Señales de detección

How to detect CWE-1341

Automated Static Analysis

For commonly-used APIs and resource types, automated tools often have signatures that can spot this issue.

Automated Dynamic Analysis

Some compiler instrumentation tools such as AddressSanitizer (ASan) can indirectly detect some instances of this weakness.

Auto-corrección de Plexicus

Plexicus detecta automáticamente CWE-1341 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-1341?

This vulnerability occurs when a program incorrectly tries to close or release the same system resource—like memory, a file, or a network connection—more than once. This double-free or double-close violates the API's contract and leads to unpredictable and often dangerous behavior.

¿Qué gravedad tiene CWE-1341?

MITRE no ha publicado una calificación de probabilidad de explotación para esta debilidad. Trátala como de impacto medio hasta que tu modelo de amenazas demuestre lo contrario.

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

MITRE lists the following affected platforms: Java, Rust, C, C++, Not OS-Specific, Not Architecture-Specific, Not Technology-Specific.

¿Cómo puedo prevenir CWE-1341?

Change the code's logic so that the resource is only closed once. This might require simplifying or refactoring. This fix can be simple to do in small code blocks, but more difficult when multiple closes are buried within complex conditionals. It can be effective to implement a flag that is (1) set when the resource is opened, (2) cleared when it is closed, and (3) checked before closing. This approach can be useful when there are disparate cases in which closes must be performed. However,…

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

El motor SAST de Plexicus detecta la firma de flujo de datos para CWE-1341 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-1341?

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

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.