CWE-663 Base Rascunho

Use of a Non-reentrant Function in a Concurrent Context

This vulnerability occurs when a program uses a function that is not safe for reentrancy within a concurrent environment, such as multi-threaded code or signal handlers. If another thread or signal…

Definição

What is CWE-663?

This vulnerability occurs when a program uses a function that is not safe for reentrancy within a concurrent environment, such as multi-threaded code or signal handlers. If another thread or signal handler interrupts and calls the same function, it can corrupt shared data, cause crashes, or create unpredictable behavior.
Non-reentrant functions rely on or modify shared global or static data, making them unsafe when multiple execution flows can interrupt each other. In a concurrent context—like a multi-threaded application or a program using signal handlers—if one thread is inside such a function and another thread or signal handler calls the same function, the shared state can be corrupted. This leads to race conditions, memory corruption, or incorrect program outputs, often manifesting as intermittent, hard-to-debug failures. To prevent this, developers should identify functions not designed for concurrency (like many traditional C library functions) and protect their use with proper synchronization mechanisms, such as mutexes or semaphores. Alternatively, replace them with thread-safe, reentrant equivalents (often denoted with '_r' suffixes in C). Always audit code for global/static variable usage within functions that may be accessed by multiple threads or signal handlers, and design concurrent systems with clear ownership of shared resources.
Impacto no mundo real

Real-world CVEs caused by CWE-663

  • unsafe calls to library functions from signal handler

  • SIGCHLD signal to FTP server can cause crash under heavy load while executing non-reentrant functions like malloc/free.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    Identificar um caminho de código que trata input não confiável sem validação.

  2. 2

    Criar um payload que explora o comportamento inseguro — injeção, traversal, overflow ou abuso de lógica.

  3. 3

    Entregar o payload através de um pedido normal e observar a reação da aplicação.

  4. 4

    Iterar até que a resposta exponha dados, execute código do atacante ou escale privilégios.

Exemplo de código vulnerável

Vulnerable C

In this example, a signal handler uses syslog() to log a message:

Vulnerável C
char *message;
  void sh(int dummy) {
  	syslog(LOG_NOTICE,"%s\n",message);
  	sleep(10);
  	exit(0);
  }
  int main(int argc,char* argv[]) {
  	...
  	signal(SIGHUP,sh);
  	signal(SIGTERM,sh);
  	sleep(10);
  	exit(0);
  }
  	If the execution of the first call to the signal handler is suspended after invoking syslog(), and the signal handler is called a second time, the memory allocated by syslog() enters an undefined, and possibly, exploitable state.
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-663

  • Implementation Use reentrant functions if available.
  • Implementation Add synchronization to your non-reentrant function.
  • Implementation In Java, use the ReentrantLock Class.
Sinais de deteção

How to detect CWE-663

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

This vulnerability occurs when a program uses a function that is not safe for reentrancy within a concurrent environment, such as multi-threaded code or signal handlers. If another thread or signal handler interrupts and calls the same function, it can corrupt shared data, cause crashes, or create unpredictable behavior.

Qual a gravidade do CWE-663?

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

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

Use reentrant functions if available. Add synchronization to your non-reentrant function.

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

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

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

Fraquezas relacionadas

Weaknesses related to CWE-663

CWE-662 Pai

Improper Synchronization

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

CWE-1058 Irmão

Invokable Control Element in Multi-Thread Context with non-Final Static Storable or Member Element

This happens when a method or function, designed to run in a multi-threaded environment, accesses or modifies a non-final static variable…

CWE-1096 Irmão

Singleton Class Instance Creation without Proper Locking or Synchronization

This flaw occurs when a Singleton class is implemented without proper thread-safe controls, allowing multiple instances to be created in…

CWE-366 Irmão

Race Condition within a Thread

This vulnerability occurs when two or more threads within the same application access and manipulate a shared resource (like a variable,…

CWE-543 Irmão

Use of Singleton Pattern Without Synchronization in a Multithreaded Context

This vulnerability occurs when a singleton pattern is implemented in a multithreaded application without proper synchronization,…

CWE-567 Irmão

Unsynchronized Access to Shared Data in a Multithreaded Context

This vulnerability occurs when multiple threads in an application can read and modify shared data, like static variables, without proper…

CWE-667 Irmão

Improper Locking

This vulnerability occurs when a program fails to correctly acquire or release a lock on a shared resource, such as a file, database…

CWE-764 Irmão

Multiple Locks of a Critical Resource

This vulnerability occurs when a critical resource, such as a file, data structure, or connection, is locked more times than the software…

CWE-820 Irmão

Missing Synchronization

This vulnerability occurs when multiple parts of your application (like threads or processes) use the same resource—such as a variable,…

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.