# Concurrent Execution Using Shared Resource with Improper Synchronization ('Race Condition') (CWE-362) The product contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently. **Stack:** Python - Prevalence: 中 3 言語をカバー - Impact: ハイ 4 件の重大度ハイのルール - Prevention: 文書化済み 6 件の修正例 **OWASP:** Insecure Design (A04:2021-Insecure Design) - #4 ## Description This can have security implications when the expected synchronization is in security-critical code, such as recording whether a user is authenticated or modifying important state information that should not be influenced by an outsider. ## Prevention 1 件の Shoulder 検出ルールに基づく Race Condition の予防策。 ### Python Use locks for shared data and atomic operations for file access ## Warning Signs - [MEDIUM] potential race conditions in concurrent Python code ## Consequences - アプリケーションデータの変更 - DoS - 未承認コードの実行 - 保護メカニズムの回避 ## Mitigations - ロック、ミューテックス、セマフォなど適切な同期プリミティブを使用する - クリティカルセクション内のコード量を最小限にする - 可能であればスレッドセーフなデータ構造を使用する ## Detection - Total rules: 6 - Languages: go, javascript, typescript, python ## Rules by Language ### Python (1 rules) - **Potential Race Condition** [MEDIUM]: Detects potential race conditions in concurrent Python code. Common race condition patterns: 1. Global variables accessed from threads without locking 2. TOCTOU (Time-of-check Time-of-use) file operations 3. Shared data structures modified in threads without synchronization 4. Check-then-act patterns without atomicity Python's GIL doesn't prevent all race conditions, especially with I/O operations and multi-process code. - Remediation: Use locks for shared data and atomic operations for file access. ```python import threading import os # Use locks for shared data lock = threading.Lock() with lock: counter += 1 # Atomic file creation (no TOCTOU) try: fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) os.close(fd) except FileExistsError: pass # Or use makedirs with exist_ok os.makedirs(path, exist_ok=True) ``` Learn more: https://shoulder.dev/learn/python/cwe-362/race-condition