# Time-of-check Time-of-use (TOCTOU) Race Condition (CWE-367) The product checks the state of a resource before using that resource, but the resource's state can change between the check and the use in a way that invalidates the results of the check. - Prevalence: Medium 1 language covered - Impact: Medium Review recommended - Prevention: Documented 1 fix examples **OWASP:** Insecure Design (A04:2021-Insecure Design) - #4 ## Description This race condition occurs when a resource is checked for a condition, and the resource is later used under the assumption that the condition still holds. An attacker can exploit the window between check and use. ## Prevention ### Key Practices - Use atomic operations or proper locking instead ### Python Use atomic operations (EAFP pattern) instead of check-then-use (TOCTOU) ## Warning Signs - [MEDIUM] potential race conditions where a resource is checked (exists, permissions) and then used later ## Consequences - Gain Privileges - Modify Files or Directories - Bypass Protection Mechanism ## Mitigations - Use atomic operations that combine check and use - Use file locking mechanisms - Use secure temporary file creation functions ## Detection - Total rules: 1 - Languages: python ## Rules by Language ### Python (1 rules) - **Time-of-Check Time-of-Use (TOCTOU) Race Condition** [MEDIUM]: Detects potential race conditions where a resource is checked (exists, permissions) and then used later. Between check and use, the resource state can change, leading to security issues. Use atomic operations or proper locking instead. - Remediation: Use atomic operations instead of check-then-use patterns. ```python def read_file_safely(filename): try: with open(filename, 'r') as f: return f.read() except FileNotFoundError: return None def create_file_safely(filename, content): with open(filename, 'x') as f: # 'x' mode is atomic f.write(content) ``` Learn more: https://shoulder.dev/learn/python/cwe-367/race-condition