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.
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(())
}docs/a.txt -> allowed
../secret.txt -> refused
docs/../../secret.txt -> refused
/etc/passwd -> refused
C:\Windows\win.ini -> refused
missing.txt -> refusedThe 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#
- Keep user-controlled data out of paths when you can: store files under generated IDs and look the real name up in a table.
- When a name must be used, check components first, then canonicalize and compare against the canonical base.
- Open the file right after the check, and do not accept the original string again afterwards.
- Run the service with a user that has access only to the intended folder, so a missed check does less damage.
- On Windows also think about reserved device names (such as
CONorNUL) 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_withon the un-canonicalized path.base/../xstarts withbase. - Canonicalizing only the user part, or forgetting that
canonicalizefails 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