Tar Extract Path Guard

Validate archive entry names before extraction, blocking absolute paths, parent traversal, and anything outside the destination.

RustSecurity Boundaries

Code

rustsnippet
50 lines
use std::path::{Component, Path, PathBuf};

fn safe_entry_path(destination: &Path, entry_name: &str) -> Result<PathBuf, String> {
    let entry = Path::new(entry_name);
    if entry.is_absolute() {
        return Err(format!("absolute entry rejected: {entry_name}"));
    }

    let mut output = destination.to_path_buf();
    let mut depth = 0usize;
    for component in entry.components() {
        match component {
            Component::Normal(part) => {
                output.push(part);
                depth += 1;
            }
            Component::CurDir => {}
            Component::ParentDir => {
                if depth == 0 {
                    return Err(format!("entry escapes destination: {entry_name}"));
                }
                output.pop();
                depth -= 1;
            }
            _ => return Err(format!("unsupported component in {entry_name}")),
        }
    }

    if !output.starts_with(destination) {
        return Err(format!("resolved entry escapes destination: {entry_name}"));
    }
    Ok(output)
}

fn main() {
    let destination = Path::new("/var/lib/app/uploads");
    let entries = [
        "reports/2026.csv",
        "docs/../notes.txt",
        "../etc/cron.d/job",
        "/etc/passwd",
        "a/../../b",
    ];
    for entry in entries {
        match safe_entry_path(destination, entry) {
            Ok(path) => println!("ok   {entry:<22} => {}", path.display()),
            Err(error) => println!("skip {entry:<22} => {error}"),
        }
    }
}

How the snippet works

One way to read it: the functions safe_entry_path and main, doing all the work.

Repetition is confined to for component in entry.components() — the rest of the file is straight-line. Errors ride back inside Result, forcing an explicit decision at every call site. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Points of care

  • Error handling is typed — each Result must be matched or forwarded with ?.

Applying it

The primary signature is fn safe_entry_path(destination: &Path, entry_name: &str) -> Result<PathBuf, String>

Running the file prints labeled results such as ok, skip — each operation’s effect is visible in the output.

main sequences safe_entry_path; executing the file runs that flow once.

Statements that matter

return Err(format!("resolved entry escapes destination: {entry_name}"));
return Err(format!("entry escapes destination: {entry_name}"));
return Err(format!("absolute entry rejected: {entry_name}"));

Interactive Tools for This Topic

FAQ

How do errors reach the caller?
Each fallible operation returns `Result`; nothing is silently discarded.
What does Tar Extract Path Guard print when run?
Run it as a complete program — the output lines carry labels such as `ok`, `skip`.