Why unsafe path handling matters

A path bug often becomes a security bug when an attacker can influence a filename, directory name, or relative path. Common failure modes include:

  • Writing outside an upload directory with ../ segments
  • Following symlinks into sensitive locations
  • Resolving paths differently on Windows vs. Unix
  • Treating a path as safe because it “looks relative”
  • Checking a path once, then using it later after it has been swapped

These issues show up in:

  • file upload handlers
  • backup and export tools
  • plugin or template loaders
  • log rotation and archival code
  • CLI tools that accept output paths

Rust’s Path and PathBuf types are excellent for representing paths, but they do not validate trust boundaries. You still need a policy.


The core rule: anchor paths to a trusted base directory

The safest pattern is to define a trusted root directory and ensure every user-supplied path stays inside it. Instead of accepting arbitrary paths, accept a relative path fragment and resolve it against a base directory you control.

Bad idea: trusting raw input

use std::fs;
use std::path::Path;

fn save_report(user_path: &str, contents: &[u8]) -> std::io::Result<()> {
    fs::write(Path::new(user_path), contents)
}

This code lets the caller write anywhere the process has permission. A malicious input like ../../etc/cron.d/job is enough to escape the intended location.

Better: resolve against a fixed root

use std::fs;
use std::path::{Path, PathBuf};

fn safe_join(base: &Path, user_relative: &Path) -> std::io::Result<PathBuf> {
    let candidate = base.join(user_relative);

    // Canonicalize the base directory once, ideally at startup.
    let base_canon = fs::canonicalize(base)?;

    // Canonicalize the parent if it exists; this resolves symlinks in the path.
    let parent = candidate.parent().ok_or_else(|| {
        std::io::Error::new(std::io::ErrorKind::InvalidInput, "missing parent")
    })?;

    let parent_canon = fs::canonicalize(parent)?;

    if !parent_canon.starts_with(&base_canon) {
        return Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "path escapes base directory",
        ));
    }

    Ok(candidate)
}

This is a useful start, but it is not enough by itself. Canonicalization can fail for non-existent files, and it does not eliminate race conditions between validation and use.


Canonicalization is helpful, but not a complete defense

std::fs::canonicalize resolves symlinks and normalizes a path to an absolute form. That makes it useful for comparing locations, but there are important caveats:

  • It only works if the path exists.
  • It can change meaning across time if the filesystem changes.
  • It does not prevent a race after the check.
  • It may resolve to a path outside your intended directory if the input already contains a symlink.

A secure design uses canonicalization for policy decisions, but avoids relying on it as the only guard.

Practical guidance

Use canonicalization to:

  • validate a base directory once at startup
  • compare resolved locations before opening sensitive files
  • reject paths that resolve outside the allowed tree

Do not use it to:

  • prove a path will remain safe after validation
  • “clean” a path and then assume the result is trustworthy forever

Symlinks are a common way to bypass directory restrictions. An attacker may place a symlink inside an allowed directory that points to a sensitive file elsewhere. If your code follows that link, the base-directory check may be defeated.

There are two strong defenses:

  1. Refuse symlinks when opening files
  2. Open files relative to a directory handle, not a string path

On Unix-like systems, the openat family of APIs is designed for this. In Rust, you can reach for platform-specific crates or carefully use OS-specific options.

use std::fs::OpenOptions;
use std::os::unix::fs::OpenOptionsExt;
use std::path::Path;

fn create_new_regular_file(path: &Path) -> std::io::Result<std::fs::File> {
    OpenOptions::new()
        .write(true)
        .create_new(true)
        .custom_flags(libc::O_NOFOLLOW)
        .open(path)
}

O_NOFOLLOW prevents the final path component from being a symlink. This is not a universal solution, but it is a strong building block on Unix.

Important note

Even with O_NOFOLLOW, you still need to validate the parent directory and consider races on intermediate components. For high-risk code, prefer directory-relative operations with a trusted directory handle.


Use directory handles for stronger containment

A robust pattern is to open the trusted base directory first, then resolve child paths relative to that directory. This reduces the chance of escaping through path manipulation or directory replacement.

Rust’s standard library does not yet provide a fully portable, high-level API for this pattern, but the design principle is still valuable:

  • open the base directory once
  • keep the handle private
  • resolve children relative to that handle
  • avoid re-parsing absolute paths from user input

This is especially relevant for services that repeatedly create or read files in a workspace, cache directory, or tenant-specific storage root.


Validate path shape before filesystem access

Before touching the filesystem, validate the shape of the user input:

  • reject absolute paths
  • reject empty paths
  • reject .. segments
  • reject embedded NUL bytes
  • define a maximum length
  • allow only a narrow character set if your use case permits it

This is not a substitute for filesystem checks, but it reduces attack surface and makes your policy easier to reason about.

Example: accept only simple relative names

use std::path::{Component, Path};

fn is_safe_relative_path(path: &Path) -> bool {
    if path.is_absolute() {
        return false;
    }

    path.components().all(|c| matches!(c, Component::Normal(_)))
}

This function rejects . and .. components, along with platform-specific prefixes and root markers. It is appropriate when your application only needs simple relative names, such as per-user document IDs or upload filenames.


A practical secure write workflow

The following example combines several defenses for a file-write endpoint:

  • accept only a relative path
  • anchor it to a trusted base directory
  • reject unsafe path shapes
  • create new files atomically
  • avoid overwriting existing files
  • avoid following symlinks where supported
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Component, Path, PathBuf};

fn is_safe_relative_path(path: &Path) -> bool {
    !path.is_absolute()
        && path.components().all(|c| matches!(c, Component::Normal(_)))
}

fn save_user_file(base_dir: &Path, relative: &Path, data: &[u8]) -> std::io::Result<PathBuf> {
    if !is_safe_relative_path(relative) {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "invalid relative path",
        ));
    }

    let base_canon = fs::canonicalize(base_dir)?;
    let target = base_dir.join(relative);

    let parent = target.parent().ok_or_else(|| {
        std::io::Error::new(std::io::ErrorKind::InvalidInput, "missing parent")
    })?;

    let parent_canon = fs::canonicalize(parent)?;
    if !parent_canon.starts_with(&base_canon) {
        return Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "path escapes base directory",
        ));
    }

    let mut file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&target)?;

    file.write_all(data)?;
    Ok(target)
}

This code is not perfect for every environment, but it demonstrates the right shape: policy first, filesystem checks second, atomic creation third.


Common mistakes and safer alternatives

MistakeWhy it is riskySafer alternative
Accepting raw absolute pathsCaller can target arbitrary locationsAccept only relative paths under a trusted base
Using string replacement to remove ..Easy to bypass with encoding or separatorsParse with Path and inspect components
Checking a path, then opening it laterRace conditions can swap the targetUse atomic open flags and directory-relative APIs
Following symlinks blindlyCan escape the intended directoryReject symlinks or use O_NOFOLLOW where available
Assuming canonicalization is enoughIt does not prevent TOCTOU racesCombine canonicalization with atomic operations
Reusing user input as a filenameMay create collisions or invalid namesMap input to a controlled filename scheme

Handling reads safely

Reading files has similar risks. A malicious path can expose secrets, configuration files, or private keys. The same principles apply:

  • restrict reads to a known directory
  • validate that the path is relative and simple
  • reject symlinks if the file should be regular and local
  • avoid reading files whose location can be replaced after validation

For sensitive reads, consider a whitelist approach: map a small set of logical names to fixed filenames instead of accepting arbitrary user input.

Example: whitelist logical names

use std::path::{Path, PathBuf};

fn config_path(base: &Path, name: &str) -> Option<PathBuf> {
    let file = match name {
        "public" => "public.toml",
        "tenant" => "tenant.toml",
        _ => return None,
    };

    Some(base.join(file))
}

This pattern is often safer than trying to “sanitize” a free-form path.


When to use a stricter policy

Not every application needs arbitrary nested paths. If your feature only needs a filename, do not accept directories. If it only needs a small set of known resources, do not accept filenames at all.

Choose the narrowest policy that satisfies the product requirement:

  • Single file name: accept only one path segment
  • Relative subpath: accept normal components only
  • Known resource key: use a lookup table
  • High-risk storage: use directory handles and OS-level no-follow protections

The less freedom you give the caller, the less validation logic you need to maintain.


Testing your path policy

Security bugs often survive because tests only cover the happy path. Add tests for:

  • ../escape.txt
  • /absolute/path
  • empty input
  • a/../../b
  • symlinked parent directories
  • filenames with unusual Unicode or separators
  • Windows-style prefixes if your code is cross-platform

A good test suite should verify both acceptance and rejection. If your policy changes later, the tests should make that visible immediately.


Summary

Safe file path handling in Rust is about controlling trust boundaries, not just manipulating strings. The most reliable approach is to:

  • anchor all user-controlled paths to a trusted base directory
  • reject absolute paths and traversal segments
  • use canonicalization as a check, not as a guarantee
  • avoid symlink following where possible
  • prefer atomic creation and directory-relative operations
  • narrow the input format whenever the feature allows it

Rust gives you the tools to express these rules clearly. The security comes from using them with a strict policy and a filesystem-aware mindset.

Learn more with useful resources