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.

Definición

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 en el mundo real

Real-world CVEs caused by CWE-543

Todavía no hay CVEs públicos enlazados a esta CWE en el catálogo de MITRE.

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  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.

Ejemplo de código vulnerable

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.

Vulnerable Java
private static NumberConverter singleton;
  public static NumberConverter get_singleton() {
  	if (singleton == null) {
  		singleton = new NumberConverter();
  	}
  	return singleton;
  }
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-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).
Señales de detección

How to detect CWE-543

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

¿Qué gravedad tiene CWE-543?

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

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

¿Cómo puedo prevenir 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.

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

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

MITRE publica la definición canónica en https://cwe.mitre.org/data/definitions/543.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.