path_jail
A zero-dependency filesystem sandbox for Rust. Restricts paths to a root directory, preventing traversal attacks while supporting files that don't exist yet.
Python bindings: path-jail on PyPI
Installation
The Problem
The standard approach fails for new files:
// This breaks if the file doesn't exist yet!
let path = root.join.canonicalize?;
if !path.starts_with
The Solution
// One-liner for simple cases
let path = join?;
write?;
// Blocked: returns Err(EscapedRoot)
join?;
For multiple paths, create a Jail and reuse it:
use Jail;
let jail = new?;
let path1 = jail.join?;
let path2 = jail.join?;
Features
- Zero dependencies - only stdlib (optional
secure-openfeature for TOCTOU protection) - Symlink-safe - resolves and validates symlinks
- Works for new files - validates paths that don't exist yet
- Type-safe paths - optional
JailedPathnewtype prevents confused deputy bugs - Segment joining - safely build paths from user IDs, filenames, etc.
- Helpful errors - tells you what went wrong and why
Security
| Attack | Example | Blocked |
|---|---|---|
| Path traversal | ../../etc/passwd |
Yes |
| Symlink escape | link -> /etc |
Yes |
| Symlink chains | a -> b -> /etc |
Yes |
| Broken symlinks | link -> /nonexistent |
Yes |
| Absolute injection | /etc/passwd |
Yes |
| Parent escape | foo/../../secret |
Yes |
| Null byte injection | file\x00.txt |
Yes |
Limitations
This library validates paths. It does not hold file descriptors.
Rejected at construction:
- Filesystem roots (
/,C:\,\\server\share) are rejected because they defeat the purpose of jailing.
Defends against:
- Logic errors in path construction
- Confused deputy attacks from untrusted input
Does not defend against:
- Malicious local processes racing your I/O
For kernel-enforced sandboxing, use cap-std.
Platform-Specific Edge Cases
Hard Links
Hard links cannot be detected by path inspection. If an attacker has shell access and creates a hard link to a sensitive file inside your jail, path_jail will allow access.
Mitigations:
- Use a separate partition for the jail (hard links cannot cross partitions)
- Use container isolation
Mount Points
If an attacker can mount a filesystem inside the jail, they can escape:
let jail = new?;
// Attacker (with root): mount /dev/sda1 /var/uploads/mnt
jail.join?; // Passes check, but accesses root filesystem!
Detecting mount points would require stat() on every path component (expensive) or parsing /proc/mounts (Linux-only).
Mitigations:
- Mounting requires root privileges. If attacker has root, path validation is moot.
- Use container isolation (separate mount namespace)
TOCTOU Race Conditions
path_jail validates paths at call time. A symlink could be created between validation and use:
let path = jail.join?; // Validated
// Attacker creates symlink here
write?; // Escapes!
Mitigations:
- Enable the
secure-openfeature forO_NOFOLLOW-protected file operations (see below) - Use container/chroot isolation
Windows Reserved Device Names
On Windows, filenames like CON, PRN, AUX, NUL, COM1-COM9, LPT1-LPT9 are special device names.
let path = jail.join?; // Returns C:\uploads\CON.txt
open?; // Opens console device, not file!
Impact: Denial of Service (not a filesystem escape).
Mitigation: Validate filenames against a blocklist before calling path_jail, or use UUIDs for stored filenames.
Unicode Normalization (macOS)
macOS automatically converts filenames to NFD (decomposed) form. A file saved as café.txt (NFC) may be stored as café.txt (NFD).
path_jail handles this correctly (all paths are canonicalized). The issue arises when storing paths externally:
let user_input = "café"; // NFC from web form
let jail = new?;
// Wrong: storing original input
db.insert; // NFC bytes
// Later: comparison fails
db.get == jail.root.to_str; // NFC != NFD
Mitigation: Always store jail.root() or jail.relative(), never the original input. These are already canonicalized.
Case Sensitivity (Windows/macOS)
Windows and macOS (by default) have case-insensitive filesystems.
path_jail handles this correctly for existing paths because canonicalize() normalizes case to what's on disk:
let jail = new?; // Canonicalized
jail.contains?; // Also canonicalized - works!
The issue is for blocklist checks on user input before calling path_jail:
let blocklist = ;
let input = "SECRET.TXT";
// Wrong: case-sensitive comparison
if blocklist.contains
// Right: normalize first
if blocklist.contains
Mitigation: Normalize case before blocklist checks.
Trailing Dots and Spaces (Windows)
Windows silently strips trailing dots and spaces:
jail.join?; // Becomes "file.txt"
jail.join?; // Becomes "file.txt"
Mitigation: Strip trailing dots/spaces before validation.
Alternate Data Streams (Windows NTFS)
NTFS supports alternate data streams: file.txt:hidden. Consider rejecting filenames containing :.
Unicode Display Attacks
Filenames can contain Unicode control characters that manipulate display:
jail.join?; // Right-to-left override: displays as "exe.txt"
path_jail passes these through (they're valid filenames). This is a UI attack, not a path attack. Sanitize filenames before displaying to users.
Special Filesystems (Linux)
/proc and /dev contain symlinks that can escape any jail:
let jail = new?;
jail.join?; // /proc/self/root → /
path_jail catches this via symlink resolution (the above returns EscapedRoot). However, these filesystems have many such escape vectors. Avoid using them as jail roots.
Path Canonicalization
All returned paths are canonicalized (symlinks resolved, .. eliminated):
// macOS: /var is a symlink to /private/var
let jail = new?;
assert!;
// Windows: Long paths (>260 chars) use \\?\ prefix
let long_name = "a".repeat;
let path = jail.join?;
assert!;
When comparing paths, always canonicalize your expected values.
API
One-shot validation
// Validate and join in one call
let safe: PathBuf = join?;
Reusable jail
use Jail;
// Create a jail (root must exist, be a directory, and not be filesystem root)
let jail = new?;
// Get the canonicalized root
let root: &Path = jail.root;
// Safely join a relative path
let path: PathBuf = jail.join?;
// Check if an absolute path is inside the jail
let verified: PathBuf = jail.contains?;
// Get relative path for database storage
let rel: PathBuf = jail.relative?; // "subdir/file.txt"
Type-safe paths
Use JailedPath for compile-time guarantees:
use ;
let jail = new?;
let path: JailedPath = jail.join_typed?;
save_upload?;
Segment joining
Safely build paths from multiple user inputs:
use Jail;
let jail = new?;
let user_id = "alice";
let filename = "photo.jpg";
// Safe: each segment is validated (no /, \, or .. allowed in segments)
let path = jail.join_segments?;
// These would fail:
// jail.join_segments(["../etc", "passwd"])?; // ".." rejected
// jail.join_segments(["users/files"])?; // "/" in segment rejected
// Type-safe version:
let path: JailedPath = jail.segments?;
Error Handling
Construction errors
use ;
match new
Path validation errors
use ;
let jail = new?;
match jail.join
Example: File Uploads
use Jail;
use PathBuf;
Framework Integration
Axum
use ;
use Bytes;
use Jail;
use LazyLock;
static UPLOADS: = new;
async
Actix-web
use ;
use Jail;
use LazyLock;
static UPLOADS: = new;
async
TOCTOU-Safe File Operations (Unix)
Enable the secure-open feature for O_NOFOLLOW-protected file operations:
[]
= { = "0.3", = ["secure-open"] }
use Jail;
use ;
let jail = new?;
// Open with O_NOFOLLOW - fails if path is a symlink
let mut file = jail.open?;
let mut contents = Stringnew;
file.read_to_string?;
// Create with O_CREAT | O_EXCL | O_NOFOLLOW - fails if file exists or is symlink
let mut file = jail.create?;
file.write_all?;
// Other options
let file = jail.create_or_truncate?; // Truncate if exists
let file = jail.open_append?; // Append mode
This protects against symlink swap attacks between validation and file open. Zero additional dependencies.
Limitation: Protects the final path component only. For full TOCTOU protection against intermediate directory attacks, use cap-std.
Alternatives
| path_jail | strict-path | cap-std | |
|---|---|---|---|
| Approach | Path validation | Type-safe path system | File descriptors |
| Returns | PathBuf / JailedPath |
Custom StrictPath<T> |
Custom Dir/File |
| Dependencies | 0 | ~5 | ~10 |
| TOCTOU-safe | With secure-open* |
No | Yes |
| Best for | Simple file sandboxing | Complex type-safe paths | Kernel-enforced security |
strict-path- More comprehensive, uses marker types for compile-time guaranteescap-std- Capability-based, TOCTOU-safe, but different API thanstd::fs
*With secure-open: Safe against remote attackers and symlink attacks on the final path component. Not safe against local attackers who can swap intermediate directories. See TOCTOU Race Conditions.
Thread Safety
Jail implements Clone, Send, and Sync. It can be safely shared across threads:
use Arc;
use Jail;
let jail = new;
let jail_clone = clone;
spawn;
MSRV
Minimum Supported Rust Version: 1.80
This crate tracks recent stable Rust. We use LazyLock for ergonomic static initialization in examples.
Development
License
MIT OR Apache-2.0