# 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: 中 1 言語をカバー - Impact: ミディアム レビュー推奨 - Prevention: 文書化済み 1 件の修正例 **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 - 権限の取得 - ファイルまたはディレクトリの変更 - 保護メカニズムの回避 ## Mitigations - 検査と利用を一体化したアトミック操作を使用する - ファイルロック機構を使用する - 安全な一時ファイル作成関数を使用する ## 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