CWE-662 Clase Borrador

Improper Synchronization

This vulnerability occurs when a multi-threaded or multi-process application allows shared resources to be accessed by multiple threads or processes simultaneously, without proper safeguards to…

Definición

What is CWE-662?

This vulnerability occurs when a multi-threaded or multi-process application allows shared resources to be accessed by multiple threads or processes simultaneously, without proper safeguards to enforce exclusive access.
Synchronization is the set of techniques that prevent multiple threads or processes from interfering with each other when they need to use the same resource, like a variable, file, or memory location. Since many operations on these resources cannot be performed in a single, atomic step, you need mechanisms like locks, mutexes, or semaphores to guarantee that one thread completes its entire sequence of operations before another can begin. Without this coordination, the application's behavior becomes unpredictable and unstable. Improper synchronization directly leads to race conditions, where the final state of the resource depends on the unpredictable timing of thread execution. This can corrupt data, crash the program, create security bypasses, or cause a denial of service. As a developer, you must identify all shared resources in your concurrent code and explicitly protect them with appropriate synchronization primitives to ensure only one thread can access them at a time.
Impacto en el mundo real

Real-world CVEs caused by CWE-662

  • Chain: improper locking (CWE-667) leads to race condition (CWE-362), as exploited in the wild per CISA KEV.

  • Attacker provides invalid address to a memory-reading function, causing a mutex to be unlocked twice

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    The following function attempts to acquire a lock in order to perform operations on a shared resource.

  2. 2

    However, the code does not check the value returned by pthread_mutex_lock() for errors. If pthread_mutex_lock() cannot acquire the mutex for any reason, the function may introduce a race condition into the program and result in undefined behavior.

  3. 3

    In order to avoid data races, correctly written programs must check the result of thread synchronization functions and appropriately handle all errors, either by attempting to recover from them or reporting them to higher levels.

  4. 4

    The following code intends to fork a process, then have both the parent and child processes print a single line.

  5. 5

    One might expect the code to print out something like:

Ejemplo de código vulnerable

Vulnerable C

The following function attempts to acquire a lock in order to perform operations on a shared resource.

Vulnerable C
void f(pthread_mutex_t *mutex) {
  		pthread_mutex_lock(mutex);
```
/* access shared resource */* 
  		
  		
  		pthread_mutex_unlock(mutex);}
Ejemplo de código seguro

Secure C

In order to avoid data races, correctly written programs must check the result of thread synchronization functions and appropriately handle all errors, either by attempting to recover from them or reporting them to higher levels.

Seguro C
int f(pthread_mutex_t *mutex) {
  		int result;
  		result = pthread_mutex_lock(mutex);
  		if (0 != result)
  			return result;
```
/* access shared resource */* 
  		
  		
  		return pthread_mutex_unlock(mutex);}
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-662

  • Implementation Use industry standard APIs to synchronize your code.
Señales de detección

How to detect CWE-662

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

This vulnerability occurs when a multi-threaded or multi-process application allows shared resources to be accessed by multiple threads or processes simultaneously, without proper safeguards to enforce exclusive access.

¿Qué gravedad tiene CWE-662?

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

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

Use industry standard APIs to synchronize your code.

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

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

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

Debilidades relacionadas

Weaknesses related to CWE-662

CWE-664 Padre

Improper Control of a Resource Through its Lifetime

This vulnerability occurs when software fails to properly manage a resource throughout its entire lifecycle—from creation and active use…

CWE-118 Hermano

Incorrect Access of Indexable Resource ('Range Error')

This vulnerability occurs when software fails to properly check the boundaries of an indexed resource, like an array, buffer, or file,…

CWE-1229 Hermano

Creation of Emergent Resource

This vulnerability occurs when a system's normal operations unintentionally create new, exploitable resources that attackers can use to…

CWE-1250 Hermano

Improper Preservation of Consistency Between Independent Representations of Shared State

This vulnerability occurs when a system with multiple independent components (like distributed services or separate hardware units) each…

CWE-1329 Hermano

Reliance on Component That is Not Updateable

This vulnerability occurs when a product depends on a component that cannot be updated or patched to fix security flaws or critical bugs.

CWE-221 Hermano

Information Loss or Omission

This weakness occurs when an application fails to log critical security events or records them inaccurately, which can misguide security…

CWE-372 Hermano

Incomplete Internal State Distinction

This vulnerability occurs when an application fails to accurately track its own operational state. The system incorrectly assumes it's in…

CWE-400 Hermano

Uncontrolled Resource Consumption

This vulnerability occurs when an application fails to properly manage a finite resource, allowing an attacker to exhaust it and cause a…

CWE-404 Hermano

Improper Resource Shutdown or Release

This vulnerability occurs when a program fails to properly close or release a system resource—like a file handle, database connection, or…

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.