| name | cwe-367-race-condition-toctou |
| description | Use this skill when you need to remediate CWE-367 (Race Condition (TOCTOU)) vulnerabilities in Java code. Triggers on SAST findings, security reviews, or when fixing race condition (toctou) issues. |
| version | 1.0.0 |
| license | MIT |
| tags | ["security","java","cwe-367","remediation","sast"] |
CWE-367 Race Condition (TOCTOU)
Description
Race Condition (TOCTOU)
Reference:
https://cwe.mitre.org/data/definitions/367.html
OWASP Category: A04:2021 – Insecure Design
Vulnerable Pattern
❌ Example 1: Vulnerable Pattern
File file = new File(path);
if (file.exists()) {
FileInputStream fis = new FileInputStream(file);
}
if (account.getBalance() >= amount) {
account.withdraw(amount);
}
Why it's vulnerable: This pattern is vulnerable to Race Condition (TOCTOU)
Deterministic Fix
✅ Secure Implementation: Secure Implementation
Path path = Paths.get(filePath);
try {
byte[] content = Files.readAllBytes(path);
} catch (NoSuchFileException e) {
}
try (FileChannel channel = FileChannel.open(path,
StandardOpenOption.READ, StandardOpenOption.WRITE)) {
FileLock lock = channel.lock();
try {
ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
channel.read(buffer);
} finally {
lock.release();
}
}
public synchronized void withdraw(BigDecimal amount) {
if (balance.compareTo(amount) >= 0) {
balance = balance.subtract(amount);
} else {
throw new InsufficientFundsException();
}
}
@Transactional
@Lock(LockModeType.PESSIMISTIC_WRITE)
public void withdrawWithLock(Long accountId, BigDecimal amount) {
Account account = accountRepository.findById(accountId).orElseThrow();
account.withdraw(amount);
}
Why it's secure: Implements proper protection against Race Condition (TOCTOU)
Detection Pattern
Look for these patterns in your codebase:
grep -rn "file.exists()\\|Files.exists" --include="*.java" -A3
Remediation Steps
-
Combine check and action into single atomic operation
-
Use file locks for concurrent file access
-
Use synchronized blocks or Lock objects for shared state
-
Use database transactions with pessimistic locking
Key Imports
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import javax.persistence.LockModeType;
Verification
After remediation:
-
Run SAST scanner to confirm vulnerability is resolved
-
Review all instances of the vulnerable pattern
-
Add unit tests that verify the secure implementation
-
Check for similar patterns in related code
Trigger Examples
Fix CWE-367 vulnerability
Resolve Race Condition (TOCTOU) issue
Secure this Java code against race condition (toctou)
SAST reports CWE-367
Common Vulnerable Locations
| Controller | *Controller.java | User input handling |
| Service | *Service.java | Business logic |
| Repository | *Repository.java | Data access |
References
Source: Generated by Java CWE Security Skills Generator
Last Updated: 2026-03-07