# How do I stop path traversal when I open files named by users?
Source: https://ruststudio.org/community/t/86/how-do-i-stop-path-traversal-when-i-open-files-named-by-users
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, tempfile 3.27.0, Windows 11
Category: Help and questions | Kind: FAQ | Tags: security, files, path-traversal | Views: 0

## Short answer
Accept only plain file-name components, reject anything with .., a root or a drive prefix, then join to your base folder, canonicalize the result and confirm it still starts with the canonical base. The canonical check also catches symbolic links that point outside the folder.

## Answer
## Answer
If a program builds a path as `base + user_input`, then `../../secret.txt` walks out of the base folder. On Windows, absolute paths such as `C:\...` and drive-relative forms also replace or escape the base. This is path traversal.

A defence has two layers. First, look at the **components** of the path with `Path::components` and allow only `Component::Normal` (plain names). That rejects `..`, a leading `/` or `\`, and drive prefixes. Second, canonicalize the joined path (this resolves symbolic links and `.`/`..`) and check `starts_with` against the canonical base folder.

```rust title=src/main.rs
use std::fs;
use std::path::{Component, Path, PathBuf};

/// Turn a user-supplied relative path into a path inside `base`, or None.
fn resolve(base: &Path, user: &str) -> Option<PathBuf> {
    let rel = Path::new(user);
    // Only plain names: no "..", no root, no drive prefix like C:
    if !rel.components().all(|c| matches!(c, Component::Normal(_))) {
        return None;
    }
    let full = base.join(rel).canonicalize().ok()?; // also resolves symbolic links; fails if missing
    full.starts_with(base.canonicalize().ok()?).then_some(full)
}

fn main() -> std::io::Result<()> {
    let tmp = tempfile::tempdir()?;
    let public = tmp.path().join("public");
    fs::create_dir_all(public.join("docs"))?;
    fs::write(public.join("docs").join("a.txt"), "a")?;
    fs::write(tmp.path().join("secret.txt"), "s")?;

    for user in ["docs/a.txt", "../secret.txt", "docs/../../secret.txt", "/etc/passwd", "C:\\Windows\\win.ini", "missing.txt"] {
        println!("{user:24} -> {}", if resolve(&public, user).is_some() { "allowed" } else { "refused" });
    }
    Ok(())
}
```

```text
docs/a.txt               -> allowed
../secret.txt            -> refused
docs/../../secret.txt    -> refused
/etc/passwd              -> refused
C:\Windows\win.ini       -> refused
missing.txt              -> refused
```

The demonstration builds a throw-away folder with a "public" directory and a secret file next to it, and runs on Windows 11.

## How to do it
1. Keep user-controlled data out of paths when you can: store files under generated IDs and look the real name up in a table.
2. When a name must be used, check components first, then canonicalize and compare against the canonical base.
3. Open the file right after the check, and do not accept the original string again afterwards.
4. Run the service with a user that has access only to the intended folder, so a missed check does less damage.
5. On Windows also think about reserved device names (such as `CON` or `NUL`) and alternate data stream syntax (`name:stream`); an allow-list of characters for file names avoids these, see the thread on checked types.

## Common mistakes
- Removing `../` from the string. Variations (`....//`, encoded forms) defeat that. Check the parsed path, not the text.
- Checking `starts_with` on the un-canonicalized path. `base/../x` starts with `base`.
- Canonicalizing only the user part, or forgetting that `canonicalize` fails for files that do not exist yet: for new files, canonicalize the parent folder and append a validated file name.
- A time-of-check to time-of-use gap: someone replaces a folder with a symbolic link between your check and the open.

## Related questions
### Does `Path::join` with an absolute path keep the base?
No. Joining an absolute path replaces the base entirely, which is why the component check comes first.

### Is it safe to serve a folder with a static file handler from a library?
Use a maintained one and read how it treats `..`, symbolic links and Windows names. Do not assume; test with such names in a scratch folder.

## Sources
- OWASP Path Traversal: https://owasp.org/www-community/attacks/Path_Traversal
- Standard library, `std::path::Component`: https://doc.rust-lang.org/std/path/enum.Component.html
- Standard library, `std::fs::canonicalize`: https://doc.rust-lang.org/std/fs/fn.canonicalize.html
