# Time-of-check to time-of-use vulnerability in the std::fs::remove_dir_all() function of the Rust standard library

TOCTOU in Rust std::fs::remove_dir_all let an attacker swap a checked directory for a symlink, tricking privileged processes into deleting arbitrary sensitive files.

- Payout: $4,000
- Severity: high
- Program: Internet Bug Bounty
- Found by: hkratz
- Disclosed: 2022-03-24
- CVE: CVE-2022-21658
- Write-up quality: 8/10
- Original: https://hackerone.com/reports/1520931
- Library page: https://bugbountylibrary.com/r/h1%3A1520931
- Tags: area:oss domain:oss impact:integrity impact:privesc kind:bounty platform:hackerone sev:high tech:rust technique:chained technique:race-window technique:source-review vuln:path-traversal vuln:race-condition

**Target:** Rust standard library std::fs::remove_dir_all (Windows and sys_common implementations)
**Root cause:** The function checked whether an entry was a symlink then separately opened/deleted it by path, so a directory could be replaced with a symlink between check and use, and paths were re-resolved by the OS on each syscall.
**Steps:**
1. Attacker gains unprivileged write access to a directory `temp/` that a privileged process will delete via `remove_dir_all()`.
2. Create `temp/foo` as a real directory so the type check passes.
3. Race: replace `temp/foo` with a symlink to `sensitive/` between the is-directory check and the open/recursion.
4. Privileged process follows the symlink and recursively deletes `sensitive/` contents.
5. Repeat until the race window is hit (reliable within seconds per advisory).
**How found:** Researcher read the documented guarantee that remove_dir_all does not follow symlinks, then reviewed the recursive implementation and noticed the symlink check was separate from the deletion syscall, exposing a check/use gap and path re-resolution.
**Exploitation:** Precondition: attacker has write access to a directory being removed by a privileged/setuid process. Attacker races symlink replacement against the check-then-use window; the privileged process then deletes files/directories it can access but the attacker cannot, achieving arbitrary privileged deletion.
**Insight:** When a library documents a security property (e.g. 'does not follow symlinks'), audit whether it is enforced atomically by the syscall (O_NOFOLLOW/openat) or by a separate check — the latter is a TOCTOU. Also note path-based recursion re-resolves each component, enabling ancestor symlink swaps.

