# 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: Mittel 1 Sprachen abgedeckt - Impact: Mittel Review empfohlen - Prevention: Dokumentiert 1 Fix-Beispiele **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 - Privilegien erlangen - Dateien oder Verzeichnisse ändern - Schutzmechanismus umgehen ## Mitigations - Atomare Operationen verwenden, die Prüfung und Nutzung verbinden - Datei-Sperrmechanismen einsetzen - Sichere Funktionen zur Erstellung temporärer Dateien verwenden ## 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