CWE-543 Variante Incompleto

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, potentially leading to multiple instances or corrupted state.

Definição

What is CWE-543?

This vulnerability occurs when a singleton pattern is implemented in a multithreaded application without proper synchronization, potentially leading to multiple instances or corrupted state.
The singleton pattern is designed to ensure only one instance of a class exists. However, in a multithreaded environment, if the creation of that instance is not properly synchronized, multiple threads can simultaneously pass the instance check and create their own copies. This breaks the fundamental guarantee of the pattern and leads to unpredictable application behavior. To prevent this, developers must implement thread-safe initialization. Common solutions include using synchronized blocks during creation, employing eager initialization at class-load time, or leveraging language-specific constructs like atomic references or initialization-on-demand holder idioms. The correct approach depends on your performance requirements and programming language, but ignoring synchronization is not an option in concurrent code.
Impacto no mundo real

Real-world CVEs caused by CWE-543

Ainda não há referências CVE públicas associadas a este CWE no catálogo da MITRE.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    This method is part of a singleton pattern, yet the following singleton() pattern is not thread-safe. It is possible that the method will create two objects instead of only one.

  2. 2

    Consider the following course of events:

  3. 3

    - Thread A enters the method, finds singleton to be null, begins the NumberConverter constructor, and then is swapped out of execution. - Thread B enters the method and finds that singleton remains null. This will happen if A was swapped out during the middle of the constructor, because the object reference is not set to point at the new object on the heap until the object is fully initialized. - Thread B continues and constructs another NumberConverter object and returns it while exiting the method. - Thread A continues, finishes constructing its NumberConverter object, and returns its version.

  4. 4

    At this point, the threads have created and returned two different objects.

Exemplo de código vulnerável

Vulnerable Java

This method is part of a singleton pattern, yet the following singleton() pattern is not thread-safe. It is possible that the method will create two objects instead of only one.

Vulnerável Java
private static NumberConverter singleton;
  public static NumberConverter get_singleton() {
  	if (singleton == null) {
  		singleton = new NumberConverter();
  	}
  	return singleton;
  }
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-543

  • Architecture and Design Use the Thread-Specific Storage Pattern. See References.
  • Implementation Do not use member fields to store information in the Servlet. In multithreading environments, storing user data in Servlet member fields introduces a data access race condition.
  • Implementation Avoid using the double-checked locking pattern in language versions that cannot guarantee thread safety. This pattern may be used to avoid the overhead of a synchronized call, but in certain versions of Java (for example), this has been shown to be unsafe because it still introduces a race condition (CWE-209).
Sinais de deteção

How to detect CWE-543

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

This vulnerability occurs when a singleton pattern is implemented in a multithreaded application without proper synchronization, potentially leading to multiple instances or corrupted state.

Qual a gravidade do CWE-543?

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

MITRE lists the following affected platforms: Java, C++.

Como posso prevenir o CWE-543?

Use the Thread-Specific Storage Pattern. See References. Do not use member fields to store information in the Servlet. In multithreading environments, storing user data in Servlet member fields introduces a data access race condition.

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

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

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

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.