## https://sploitus.com/exploit?id=DA81215A-F52F-5329-BA43-F9DE58268E88
# ๐ Race Condition Exploit & Mitigation (TOCTOU)
This project demonstrates a race condition vulnerability in a privileged program
that writes to /tmp/XYZ. An attacker exploits a time-of-check to time-of-use
flaw using symbolic links to overwrite sensitive files such as /etc/passwd.
A secure version of the program is implemented and tested to prevent the exploit.
## Vulnerability Explanation
The vulnerable program contains a **Time-of-Check to Time-of-Use (TOCTOU) race condition** when accessing the file `/tmp/XYZ`.
### Root Cause
The program performs a security check on the file (such as verifying permissions or ownership), and then later opens and writes to the same file. However, these operations are **not atomic**, meaning an attacker can modify the file between the check and the use.
### Why This Is Dangerous
The `/tmp` directory is globally writable, allowing any user to create or manipulate files within it. An attacker can exploit this by replacing `/tmp/XYZ` with a **symbolic link** pointing to a sensitive file such as `/etc/passwd`.
### Exploit Method
The attacker program continuously deletes `/tmp/XYZ`, recreates it as a normal file, and then replaces it with a symbolic link to `/tmp/race_target` by using:
1. unlink("/tmp/XYZ");
2. symlink("/tmp/race_target", "/tmp/XYZ");
Then when race is won, the vulnerable program write into `/tmp/race_target`.
### Attack Window
Between the check and the file access:
1. The program checks `/tmp/XYZ`
2. The attacker swaps it with a malicious symbolic link
3. The program unknowingly writes to the attacker-controlled target
This allows **privilege escalation**, as the program runs with elevated privileges.
### Key Issue
- Lack of atomic file operations
- Unsafe use of shared directory (`/tmp`)
- No protection against symbolic link manipulation
### Security Impact
An attacker can:
- Overwrite sensitive system files
- Escalate privileges to root
- Compromise system integrity
### Way to mitigate
The fixed program removes the race condition by eliminating the unsafe check:
1. Avoids access() before open()
2. Uses safer file handling practices.
This ensures that the file cannot be swapped between check and use.
### HOW to demo
- make scripts executable
- chmod +x scripts/run_attack.sh
- chmod +x scripts/run_fixed.sh
- chmod +x tests/test_race_condition.sh
- if `tmp/XYZ` or `/tmp/race_target` already exists:
- make clean
- to begin demo:
- make
- make test