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.
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…
What is CWE-362?
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].
Parcours de l'attaquant étape par étape
- 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
A race condition could occur between the calls to GetBalanceFromDatabase() and SendNewBalanceToDatabase().
- 3
Suppose the balance is initially 100.00. An attack could be constructed as follows:
- 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
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().
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.
$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"); Suppose the balance is initially 100.00. An attack could be constructed as follows:
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 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.
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);} 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.
How to detect CWE-362
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).
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.
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
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
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
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.
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.
Weaknesses related to CWE-362
Insufficient Control Flow Management
This vulnerability occurs when a program's execution flow isn't properly managed, allowing attackers to bypass critical checks, trigger…
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…
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…
Deployment of Wrong Handler
This vulnerability occurs when a system incorrectly assigns or routes an object to the wrong processing component.
Missing Handler
This vulnerability occurs when a software component lacks the necessary code to properly handle an error or unexpected event.
Improper Synchronization
This vulnerability occurs when a multi-threaded or multi-process application allows shared resources to be accessed by multiple threads or…
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.…
Incorrect Behavior Order
This weakness occurs when a system executes multiple dependent actions in the wrong sequence, leading to unexpected and potentially…
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…
Further reading
- MITRE — CWE-362 officiel https://cwe.mitre.org/data/definitions/362.html
- volatile - Multithreaded Programmer's Best Friend https://drdobbs.com/cpp/volatile-the-multithreaded-programmers-b/184403766
- Thread-safe webapps using Spring https://web.archive.org/web/20170609174845/http://www.javalobby.org/articles/thread-safe/index.jsp
- Prevent race conditions https://www.ida.liu.se/~TDDC90/literature/papers/SP-race-conditions.pdf
- Race Conditions, Files, and Security Flaws; or the Tortoise and the Hare Redux https://seclab.cs.ucdavis.edu/projects/vulnerabilities/scriv/ucd-ecs-95-08.pdf
- Secure Programming for Linux and Unix HOWTO https://dwheeler.com/secure-programs/Secure-Programs-HOWTO/avoid-race.html
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.