CWE-1265 Base Rascunho

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…

Definição

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 no 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]

Como os atacantes a exploram

Trajeto do atacante passo a passo

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

Exemplo de código vulnerável

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.

Vulnerável 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 */
  		}
  }
Exemplo 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 verificação de prevenção

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

How to detect CWE-1265

SAST High

Executar análise estática (SAST) na base de código à procura do padrão inseguro no fluxo de dados.

DAST Moderate

Executar testes dinâmicos de segurança de aplicações (DAST) contra o endpoint em execução.

Runtime Moderate

Monitorizar os registos em tempo de execução para traços de exceção invulgares, input malformado ou tentativas de contornar a autorização.

Code review Moderate

Revisão de código: sinalizar qualquer novo código que trate input desta superfície sem usar os ajudantes validados do framework.

Correção automática do Plexicus

O Plexicus deteta automaticamente o CWE-1265 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-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.

Qual a gravidade do CWE-1265?

A MITRE não publicou uma classificação de probabilidade de exploração para esta fraqueza. Trate-a como impacto médio até o seu modelo de ameaças provar o contrário.

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

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-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…

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

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-1265 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-1265?

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

Fraquezas relacionadas

Weaknesses related to CWE-1265

CWE-691 Pai

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

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

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

Deployment of Wrong Handler

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

CWE-431 Irmão

Missing Handler

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

CWE-662 Irmão

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

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

Incorrect Behavior Order

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

CWE-705 Irmão

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…

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.