返回 Skill 列表
extension
分类: 开发与工程无需 API Key

cwe-367-race-condition-toctou

当需要修复Java代码中的CWE-367(竞争条件(TOCTOU))漏洞时使用此技能。在SAST发现、安全审查或修复竞争条件(toctou)问题时触发。

person作者: jakexiaohubgithub

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

// VULNERABLE: TOCTOU - check and use are separate operations
File file = new File(path);
if (file.exists()) {
    // Attacker can replace file between check and read!
    FileInputStream fis = new FileInputStream(file);
    // ... process file
}

// VULNERABLE: Balance check race condition
if (account.getBalance() >= amount) {
    // Another thread could withdraw between check and update!
    account.withdraw(amount);
}

Why it's vulnerable: This pattern is vulnerable to Race Condition (TOCTOU)


Deterministic Fix

✅ Secure Implementation: Secure Implementation

// SECURE: Atomic file operations
Path path = Paths.get(filePath);
try {
    // Atomic open - fails if file doesn't exist
    byte[] content = Files.readAllBytes(path);
} catch (NoSuchFileException e) {
    // Handle missing file
}

// SECURE: Use file locks for exclusive access
try (FileChannel channel = FileChannel.open(path,
        StandardOpenOption.READ, StandardOpenOption.WRITE)) {
    FileLock lock = channel.lock();  // Exclusive lock
    try {
        // Safe to read/write with lock held
        ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
        channel.read(buffer);
    } finally {
        lock.release();
    }
}

// SECURE: Atomic balance operations with synchronization
public synchronized void withdraw(BigDecimal amount) {
    if (balance.compareTo(amount) >= 0) {
        balance = balance.subtract(amount);
    } else {
        throw new InsufficientFundsException();
    }
}

// Or use database-level locking
@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:

# Find file exists checks
grep -rn "file.exists()\\|Files.exists" --include="*.java" -A3

Remediation Steps

  1. Combine check and action into single atomic operation

  2. Use file locks for concurrent file access

  3. Use synchronized blocks or Lock objects for shared state

  4. 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

| Layer | Files | Patterns | |-------|-------|----------|

| 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