CWE-366 Base Borrador Medium likelihood

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, data structure, or file) without proper synchronization.…

Definición

What is CWE-366?

This vulnerability occurs when two or more threads within the same application access and manipulate a shared resource (like a variable, data structure, or file) without proper synchronization. Because the threads can execute in an unpredictable order, they can corrupt the resource's state, leading to crashes, incorrect calculations, or data loss.
Unlike race conditions between separate processes, this issue happens entirely within a single program's threads. It's a flaw in the program's internal logic where the developer assumed certain operations would complete in a specific sequence, but the operating system's thread scheduler can interleave them arbitrarily. Common triggers include checking a flag or counter in one thread while another is modifying it, or performing non-atomic 'read-modify-write' operations on shared data. To prevent this, developers must use proper synchronization primitives like mutexes, semaphores, or atomic operations. These tools create critical sections that ensure only one thread can access the shared resource at a time, guaranteeing predictable and valid states. Failing to implement synchronization correctly—or incorrectly assuming certain operations are thread-safe—leaves the application's behavior undefined and unreliable.
Impacto en el mundo real

Real-world CVEs caused by CWE-366

  • Chain: two threads in a web browser use the same resource (CWE-366), but one of those threads can destroy the resource before the other has completed (CWE-416).

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    Identifica una ruta de código que maneje entrada no confiable sin validación.

  2. 2

    Crea un payload que ejercite el comportamiento inseguro — inyección, traversal, overflow o abuso de lógica.

  3. 3

    Envía el payload a través de una solicitud normal y observa la reacción de la aplicación.

  4. 4

    Itera hasta que la respuesta filtre datos, ejecute código del atacante o escale privilegios.

Ejemplo de código vulnerable

Vulnerable C

The following example demonstrates the weakness.

Vulnerable C
int foo = 0;
  int storenum(int num) {
  	static int counter = 0;
  	counter++;
  	if (num > foo) foo = num;
  	return foo;
  }
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-366

  • Architecture and Design Use locking functionality. This is the recommended solution. Implement some form of locking mechanism around code which alters or reads persistent data in a multithreaded environment.
  • Architecture and Design Create resource-locking validation checks. If no inherent locking mechanisms exist, use flags and signals to enforce your own blocking scheme when resources are being used by other threads of execution.
Señales de detección

How to detect CWE-366

Automated Static Analysis High

Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without having to execute it. Typically, this is done by building a model of data flow and control flow, then searching for potentially-vulnerable patterns that connect "sources" (origins of input) with "sinks" (destinations where the data interacts with external components, a lower layer such as the OS, etc.)

CWE-366

Don't catalog this weakness. Prove it's reachable.

Plexicus turns CWE catalogs into evidence: every CWE-pattern is matched against your real code graph, reach is proven on a sandbox clone, and verified findings ship as reviewed PRs.

Preguntas frecuentes

Frequently asked questions

¿Qué es CWE-366?

This vulnerability occurs when two or more threads within the same application access and manipulate a shared resource (like a variable, data structure, or file) without proper synchronization. Because the threads can execute in an unpredictable order, they can corrupt the resource's state, leading to crashes, incorrect calculations, or data loss.

¿Qué gravedad tiene CWE-366?

MITRE califica la probabilidad de explotación como Media — la explotación es realista pero suele requerir condiciones específicas.

¿Qué lenguajes o plataformas se ven afectados por CWE-366?

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

¿Cómo puedo prevenir CWE-366?

Use locking functionality. This is the recommended solution. Implement some form of locking mechanism around code which alters or reads persistent data in a multithreaded environment. Create resource-locking validation checks. If no inherent locking mechanisms exist, use flags and signals to enforce your own blocking scheme when resources are being used by other threads of execution.

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

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

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

Debilidades relacionadas

Weaknesses related to CWE-366

CWE-362 Padre

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-1223 Hermano

Race Condition for Write-Once Attributes

This vulnerability occurs when an untrusted software component wins a race condition and writes to a hardware register before the trusted…

CWE-1298 Hermano

Hardware Logic Contains Race Conditions

A hardware race condition occurs when security-critical logic circuits receive signals at slightly different times, creating temporary…

CWE-364 Hermano

Signal Handler Race Condition

A signal handler race condition occurs when a program's signal handling routine is vulnerable to timing issues, allowing its state to be…

CWE-367 Hermano

Time-of-check Time-of-use (TOCTOU) Race Condition

This vulnerability occurs when a program verifies a resource's state (like a file's permissions or existence) but then uses it after that…

CWE-368 Hermano

Context Switching Race Condition

This vulnerability occurs when an application switches between different security contexts (like privilege levels or domains) using a…

CWE-421 Hermano

Race Condition During Access to Alternate Channel

A race condition occurs when an application opens a secondary communication channel intended for an authorized user, but fails to secure…

CWE-689 Hermano

Permission Race Condition During Resource Copy

This vulnerability occurs when a system copies a file or resource but delays setting its final permissions until the entire copy operation…

¿Listo para validar lo que importa?

Listo para validar lo que importa.

Plexicus es Proof-Driven AppSec: hallazgos validados, comprensión contextual y remediación revisada — anclada en evidencia, acotada contigo.

Calificación

Comprueba si el AI Swarm Pentest encaja en tu entorno.

Déjanos el contexto mínimo. Revisaremos el alcance y te indicaremos el siguiente paso comercial.

Antes de enviar — verifica que encajas

0 / 280

Sin compromiso. Si no encajas, te lo decimos.

SAMPLE HANDOVER · ILLUSTRATIVE

Sample evidence handover

A trimmed view of what your team receives at the end of an AI Swarm Pentest engagement. Real engagements include full technical evidence, executive narrative, and a remediation plan.

VALIDATED FINDING Evidence attached

Server-Side Request Forgery in webhooks/receiver

demo-project/sample-app · src/webhooks/receiver.py:42

SeverityHigh CVSS 3.18.6 Priority79 Confirmedvia replay

Untrusted caller-supplied URLs reach an internal egress without an allowlist. Replayed in a sandbox against a fresh authorized target — the same control was validated to fail twice.

REVIEWER-READY REMEDIATION Merge-ready PR

Validate the target URL against an allowlist of permitted hostnames. Reject private/internal IP ranges. Enforce HTTPS only.

plexicus/remediation/webhooks-ssrf 3 changed · 0 new files
42resp = requests.get(target_url)
42+if not is_allowed_host(target_url):
43+  raise WebhookRejected(target_url)
44+resp = requests.get(target_url, timeout=5)
Every engagement hands over:
  • Executive briefing
  • Validated findings list
  • Merge-ready PRs
  • Compliance mapping (NIS2 · DORA · CRA)
Ronda privada Para inversores