CWE-1265 Base Borrador

Unintended Reentrant Invocation of Non-reentrant Code Via Nested Calls

This vulnerability occurs when a non-reentrant function is called, and during its execution, another call is triggered that unexpectedly re-enters the same non-reentrant code path, corrupting its…

Definición

What is CWE-1265?

This vulnerability occurs when a non-reentrant function is called, and during its execution, another call is triggered that unexpectedly re-enters the same non-reentrant code path, corrupting its internal state.
In complex software, a single function call can branch into many unexpected execution paths, especially when processing external inputs. Attackers can often manipulate these inputs—like scripts in a web browser or embedded code in a PDF—to force the program into a state where a nested call re-enters code that wasn't designed to handle re-invocation. This is dangerous because the non-reentrant code typically relies on global or static data that gets corrupted when called again before the first invocation finishes. For developers, the core issue is that a function assumes its own internal state or global resources remain stable for the duration of its execution. When a nested call—perhaps via a callback, event handler, or virtual method—breaks that assumption, it leads to race conditions, data corruption, or crashes. To prevent this, you must audit code paths triggered during non-reentrant operations and isolate or protect any state that shouldn't be accessed concurrently, even from within the same thread.
Impacto en el mundo real

Real-world CVEs caused by CWE-1265

  • In this vulnerability, by registering a malicious onerror handler, an adversary can produce unexpected re-entrance of a CDOMRange object. [REF-1098]

  • This CVE covers several vulnerable scenarios enabled by abuse of the Class_Terminate feature in Microsoft VBScript. In one scenario, Class_Terminate is used to produce an undesirable re-entrance of ScriptingDictionary during execution of that object's destructor. In another scenario, a vulnerable condition results from a recursive entrance of a property setter method. This recursive invocation produces a second, spurious call to the Release method of a reference-counted object, causing a UAF when that object is freed prematurely. This vulnerability pattern has been popularized as "Double Kill". [REF-1099]

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    The implementation of the Widget class in the following C++ code is an example of code that is not designed to be reentrant. If an invocation of a method of Widget inadvertently produces a second nested invocation of a method of Widget, then data member backgroundImage may unexpectedly change during execution of the outer call.

  2. 2

    Looking closer at this example, Widget::click() calls backgroundImage->click(), which in turn calls scriptEngine->fireOnImageClick(). The code within fireOnImageClick() invokes the appropriate script handler routine as defined by the document being rendered. In this scenario this script routine is supplied by an adversary and this malicious script makes a call to Widget::changeBackgroundImage(), deleting the Image object pointed to by backgroundImage. When control returns to Image::click, the function's backgroundImage "this" pointer (which is the former value of backgroundImage) is a dangling pointer. The root of this weakness is that while one operation on Widget (click) is in the midst of executing, a second operation on the Widget object may be invoked (in this case, the second invocation is a call to different method, namely changeBackgroundImage) that modifies the non-local variable.

  3. 3

    This is another example of C++ code that is not designed to be reentrant.

  4. 4

    The expected order of operations is a call to Request::setup(), followed by a call to Request::send(). Request::send() calls scriptEngine->coerceToString(_data) to coerce a script-provided parameter into a string. This operation may produce script execution. For example, if the script language is ECMAScript, arbitrary script execution may result if _data is an adversary-supplied ECMAScript object having a custom toString method. If the adversary's script makes a new call to Request::setup, then when control returns to Request::send, the field uri and the local variable credentials will no longer be consistent with one another. As a result, credentials for one resource will be shared improperly with a different resource. The root of this weakness is that while one operation on Request (send) is in the midst of executing, a second operation may be invoked (setup).

Ejemplo de código vulnerable

Vulnerable C++

The implementation of the Widget class in the following C++ code is an example of code that is not designed to be reentrant. If an invocation of a method of Widget inadvertently produces a second nested invocation of a method of Widget, then data member backgroundImage may unexpectedly change during execution of the outer call.

Vulnerable C++
class Widget
  {
  	private:
  		Image* backgroundImage;
  	public:
  		void click()
  		{
  			if (backgroundImage)
  			{
  				backgroundImage->click();
  			}
  		}
  		void changeBackgroundImage(Image* newImage)
  		{
  			if (backgroundImage)
  			{
  				delete backgroundImage;
  			}
  			backgroundImage = newImage;
  		}
  }
  class Image
  {
  	public:
  		void click()
  		{
  			scriptEngine->fireOnImageClick();
  			/* perform some operations using "this" pointer */
  		}
  }
Ejemplo de código seguro

Secure pseudo

Seguro pseudo
// Validate, sanitize, or use a safe API before reaching the sink.
function handleRequest(input) {
  const safe = validateAndEscape(input);
  return executeWithGuards(safe);
}
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-1265

  • Architecture and Design When architecting a system that will execute untrusted code in response to events, consider executing the untrusted event handlers asynchronously (asynchronous message passing) as opposed to executing them synchronously at the time each event fires. The untrusted code should execute at the start of the next iteration of the thread's message loop. In this way, calls into non-reentrant code are strictly serialized, so that each operation completes fully before the next operation begins. Special attention must be paid to all places where type coercion may result in script execution. Performing all needed coercions at the very beginning of an operation can help reduce the chance of operations executing at unexpected junctures.
  • Implementation Make sure the code (e.g., function or class) in question is reentrant by not leveraging non-local data, not modifying its own code, and not calling other non-reentrant code.
Señales de detección

How to detect CWE-1265

SAST High

Ejecuta análisis estático (SAST) sobre el código buscando el patrón inseguro en el flujo de datos.

DAST Moderate

Ejecuta pruebas dinámicas de seguridad de aplicaciones (DAST) contra el endpoint en vivo.

Runtime Moderate

Vigila los logs en tiempo de ejecución para detectar trazas de excepción inusuales, entradas malformadas o intentos de bypass de autorización.

Code review Moderate

Revisión de código: marca cualquier código nuevo que maneje entrada desde esta superficie sin usar los helpers validados del framework.

Auto-corrección de Plexicus

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

This vulnerability occurs when a non-reentrant function is called, and during its execution, another call is triggered that unexpectedly re-enters the same non-reentrant code path, corrupting its internal state.

¿Qué gravedad tiene CWE-1265?

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-1265?

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-1265?

When architecting a system that will execute untrusted code in response to events, consider executing the untrusted event handlers asynchronously (asynchronous message passing) as opposed to executing them synchronously at the time each event fires. The untrusted code should execute at the start of the next iteration of the thread's message loop. In this way, calls into non-reentrant code are strictly serialized, so that each operation completes fully before the next operation begins. Special…

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

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

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

Debilidades relacionadas

Weaknesses related to CWE-1265

CWE-691 Padre

Insufficient Control Flow Management

This vulnerability occurs when a program's execution flow isn't properly managed, allowing attackers to bypass critical checks, trigger…

CWE-1281 Hermano

Sequence of Processor Instructions Leads to Unexpected Behavior

Certain sequences of valid and invalid processor instructions can cause the CPU to lock up or behave unpredictably, often requiring a hard…

CWE-362 Hermano

Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')

A race condition occurs when multiple processes or threads access a shared resource simultaneously without proper coordination, creating a…

CWE-430 Hermano

Deployment of Wrong Handler

This vulnerability occurs when a system incorrectly assigns or routes an object to the wrong processing component.

CWE-431 Hermano

Missing Handler

This vulnerability occurs when a software component lacks the necessary code to properly handle an error or unexpected event.

CWE-662 Hermano

Improper Synchronization

This vulnerability occurs when a multi-threaded or multi-process application allows shared resources to be accessed by multiple threads or…

CWE-670 Hermano

Always-Incorrect Control Flow Implementation

This weakness occurs when a section of code is structured in a way that always executes incorrectly, regardless of input or conditions.…

CWE-696 Hermano

Incorrect Behavior Order

This weakness occurs when a system executes multiple dependent actions in the wrong sequence, leading to unexpected and potentially…

CWE-705 Hermano

Incorrect Control Flow Scoping

This vulnerability occurs when a program fails to return execution to the correct point in the code after finishing a specific operation…

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.