CWE-362 Classe Brouillon Medium likelihood

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 timing window where the resource's state can be…

Définition

What is CWE-362?

A race condition occurs when multiple processes or threads access a shared resource simultaneously without proper coordination, creating a timing window where the resource's state can be unexpectedly altered, leading to unpredictable behavior or security vulnerabilities.
At its core, a race condition is a flaw in how a program manages concurrent access. It happens when a section of code that temporarily needs exclusive control over a shared resource—like a variable, file, or memory location—fails to properly block other code sequences from accessing it during that critical window. This breaks the required guarantees of exclusivity (no other process can modify the resource) and atomicity (the operation executes as a single, indivisible unit). The risk arises from an 'interfering code sequence' that can slip into this window. This interfering code can be internal and trusted (another part of the program you control) or external and untrusted (directly invoked by an attacker). The security impact is most severe when an attacker can reliably influence or trigger the interfering sequence, potentially corrupting data, bypassing checks, or escalating privileges.
Vulnerability Diagram CWE-362
Race Condition Thread A read balance=100 Thread B read balance=100 shared balance no lock / atomic op A writes 100-50 balance=50 B writes 100-50 balance=50 (lost!) Concurrent read-modify-write loses one update — money created out of thin air.
Impact réel

Real-world CVEs caused by CWE-362

  • Go application for cloud management creates a world-writable sudoers file that allows local attackers to inject sudo rules and escalate privileges to root by winning a race condition.

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

  • Chain: mobile platform race condition (CWE-362) leading to use-after-free (CWE-416), as exploited in the wild per CISA KEV.

  • Chain: race condition (CWE-362) leads to use-after-free (CWE-416), as exploited in the wild per CISA KEV.

  • chain: JTAG interface is not disabled (CWE-1191) during ROM code execution, introducing a race condition (CWE-362) to extract encryption keys

  • Chain: race condition (CWE-362) in anti-malware product allows deletion of files by creating a junction (CWE-1386) and using hard links during the time window in which a temporary file is created and deleted.

  • TOCTOU in sandbox process allows installation of untrusted browser add-ons by replacing a file after it has been verified, but before it is executed

  • Chain: chipset has a race condition (CWE-362) between when an interrupt handler detects an attempt to write-enable the BIOS (in violation of the lock bit), and when the handler resets the write-enable bit back to 0, allowing attackers to issue BIOS writes during the timing window [REF-1237].

Comment les attaquants l'exploitent

Parcours de l'attaquant étape par étape

  1. 1

    This code could be used in an e-commerce application that supports transfers between accounts. It takes the total amount of the transfer, sends it to the new account, and deducts the amount from the original account.

  2. 2

    A race condition could occur between the calls to GetBalanceFromDatabase() and SendNewBalanceToDatabase().

  3. 3

    Suppose the balance is initially 100.00. An attack could be constructed as follows:

  4. 4

    At this stage, the attacker should have a balance of 19.00 (due to 81.00 worth of transfers), but the balance is 99.00, as recorded in the database.

  5. 5

    To prevent this weakness, the programmer has several options, including using a lock to prevent multiple simultaneous requests to the web application, or using a synchronization mechanism that includes all the code between GetBalanceFromDatabase() and SendNewBalanceToDatabase().

Exemple de code vulnérable

Vulnerable Perl

This code could be used in an e-commerce application that supports transfers between accounts. It takes the total amount of the transfer, sends it to the new account, and deducts the amount from the original account.

Vulnérable Perl
$transfer_amount = GetTransferAmount();
  $balance = GetBalanceFromDatabase();
  if ($transfer_amount < 0) {
  	FatalError("Bad Transfer Amount");
  }
  $newbalance = $balance - $transfer_amount;
  if (($balance - $transfer_amount) < 0) {
  	FatalError("Insufficient Funds");
  }
  SendNewBalanceToDatabase($newbalance);
  NotifyUser("Transfer of $transfer_amount succeeded.");
  NotifyUser("New balance: $newbalance");
Charge utile de l'attaquant

Suppose the balance is initially 100.00. An attack could be constructed as follows:

Charge utile de l'attaquant Other
In the following pseudocode, the attacker makes two simultaneous calls of the program, CALLER-1 and CALLER-2. Both callers are for the same user account.
  CALLER-1 (the attacker) is associated with PROGRAM-1 (the instance that handles CALLER-1). CALLER-2 is associated with PROGRAM-2.
  CALLER-1 makes a transfer request of 80.00.
  PROGRAM-1 calls GetBalanceFromDatabase and sets $balance to 100.00
  PROGRAM-1 calculates $newbalance as 20.00, then calls SendNewBalanceToDatabase().
  Due to high server load, the PROGRAM-1 call to SendNewBalanceToDatabase() encounters a delay.
  CALLER-2 makes a transfer request of 1.00.
  PROGRAM-2 calls GetBalanceFromDatabase() and sets $balance to 100.00. This happens because the previous PROGRAM-1 request was not processed yet.
  PROGRAM-2 determines the new balance as 99.00.
  After the initial delay, PROGRAM-1 commits its balance to the database, setting it to 20.00.
  PROGRAM-2 sends a request to update the database, setting the balance to 99.00
Exemple de code sécurisé

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.

Sécurisé 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.
Liste de contrôle de prévention

How to prevent CWE-362

  • Architecture and Design In languages that support it, use synchronization primitives. Only wrap these around critical code to minimize the impact on performance.
  • Architecture and Design Use thread-safe capabilities such as the data access abstraction in Spring.
  • Architecture and Design Minimize the usage of shared resources in order to remove as much complexity as possible from the control flow and to reduce the likelihood of unexpected conditions occurring. Additionally, this will minimize the amount of synchronization necessary and may even help to reduce the likelihood of a denial of service where an attacker may be able to repeatedly trigger a critical section (CWE-400).
  • Implementation When using multithreading and operating on shared variables, only use thread-safe functions.
  • Implementation Use atomic operations on shared variables. Be wary of innocent-looking constructs such as "x++". This may appear atomic at the code layer, but it is actually non-atomic at the instruction layer, since it involves a read, followed by a computation, followed by a write.
  • Implementation Use a mutex if available, but be sure to avoid related weaknesses such as CWE-412.
  • Implementation Avoid double-checked locking (CWE-609) and other implementation errors that arise when trying to avoid the overhead of synchronization.
  • Implementation Disable interrupts or signals over critical parts of the code, but also make sure that the code does not go into a large or infinite loop.
Signaux de détection

How to detect CWE-362

Black Box

Black box methods may be able to identify evidence of race conditions via methods such as multiple simultaneous connections, which may cause the software to become instable or crash. However, race conditions with very narrow timing windows would not be detectable.

White Box

Common idioms are detectable in white box analysis, such as time-of-check-time-of-use (TOCTOU) file operations (CWE-367), or double-checked locking (CWE-609).

Automated Dynamic Analysis Moderate

This weakness can be detected using dynamic tools and techniques that interact with the software using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results. Race conditions may be detected with a stress-test by calling the software simultaneously from a large number of threads or processes, and look for evidence of any unexpected behavior. Insert breakpoints or delays in between relevant code statements to artificially expand the race window so that it will be easier to detect.

Automated Static Analysis - Binary or Bytecode High

According to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Bytecode Weakness Analysis - including disassembler + source code weakness analysis ``` Cost effective for partial coverage: ``` Binary Weakness Analysis - including disassembler + source code weakness analysis

Dynamic Analysis with Automated Results Interpretation SOAR Partial

According to SOAR [REF-1479], the following detection techniques may be useful: ``` Cost effective for partial coverage: ``` Web Application Scanner Web Services Scanner Database Scanners

Dynamic Analysis with Manual Results Interpretation High

According to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Framework-based Fuzzer ``` Cost effective for partial coverage: ``` Fuzz Tester Monitored Virtual Environment - run potentially malicious code in sandbox / wrapper / virtual machine, see if it does anything suspicious

Correction automatique Plexicus

Plexicus détecte automatiquement CWE-362 et ouvre une PR de correction en moins de 60 secondes.

Codex Remedium analyse chaque commit, identifie cette faiblesse précise et livre une pull request prête à être relue avec le correctif. Pas de tickets. Pas de transferts.

Questions fréquentes

Frequently asked questions

Qu'est-ce que CWE-362 ?

A race condition occurs when multiple processes or threads access a shared resource simultaneously without proper coordination, creating a timing window where the resource's state can be unexpectedly altered, leading to unpredictable behavior or security vulnerabilities.

Quelle est la gravité de CWE-362 ?

MITRE évalue la probabilité d'exploitation comme Moyenne — l'exploitation est réaliste mais nécessite généralement des conditions spécifiques.

Quels langages ou plateformes sont affectés par CWE-362 ?

MITRE lists the following affected platforms: C, C++, Java, Mobile, ICS/OT.

Comment puis-je prévenir CWE-362 ?

In languages that support it, use synchronization primitives. Only wrap these around critical code to minimize the impact on performance. Use thread-safe capabilities such as the data access abstraction in Spring.

Comment Plexicus détecte et corrige CWE-362 ?

Le moteur SAST de Plexicus reconnaît la signature de flux de données de CWE-362 à chaque commit. Lorsqu'une correspondance est trouvée, notre agent Codex Remedium ouvre une PR de correction avec le code corrigé, les tests et un résumé d'une ligne pour le relecteur.

Où puis-je en savoir plus sur CWE-362 ?

MITRE publie la définition canonique à https://cwe.mitre.org/data/definitions/362.html. Vous pouvez également consulter la documentation OWASP et NIST pour des conseils adjacents.

Faiblesses associées

Weaknesses related to CWE-362

CWE-691 Parent

Insufficient Control Flow Management

This vulnerability occurs when a program's execution flow isn't properly managed, allowing attackers to bypass critical checks, trigger…

CWE-1265 Frère

Unintended Reentrant Invocation of Non-reentrant Code Via Nested Calls

This vulnerability occurs when a non-reentrant function is called, and during its execution, another call is triggered that unexpectedly…

CWE-1281 Frère

Sequence of Processor Instructions Leads to Unexpected Behavior

Certain sequences of valid and invalid processor instructions can cause the CPU to lock up or behave unpredictably, often requiring a hard…

CWE-430 Frère

Deployment of Wrong Handler

This vulnerability occurs when a system incorrectly assigns or routes an object to the wrong processing component.

CWE-431 Frère

Missing Handler

This vulnerability occurs when a software component lacks the necessary code to properly handle an error or unexpected event.

CWE-662 Frère

Improper Synchronization

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

CWE-670 Frère

Always-Incorrect Control Flow Implementation

This weakness occurs when a section of code is structured in a way that always executes incorrectly, regardless of input or conditions.…

CWE-696 Frère

Incorrect Behavior Order

This weakness occurs when a system executes multiple dependent actions in the wrong sequence, leading to unexpected and potentially…

CWE-705 Frère

Incorrect Control Flow Scoping

This vulnerability occurs when a program fails to return execution to the correct point in the code after finishing a specific operation…

Prêt quand vous l'êtes

Arrêtez de payer par développeur.
Commencez à fermer la boucle.

Plexicus est l'ASPM natif IA qui scanne, filtre, corrige, penteste et explique — de façon autonome. Développeurs illimités, dépôts illimités, actions IA à usage équitable. Vrai niveau gratuit, €269/mo annuel quand vous êtes prêt.