# 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