Path Canonicalization and Validation
What you'll learn: How to properly normalize and validate file paths to prevent attackers from bypassing security checks with specially crafted filenames.
The Core Problem
After an attacker crafts a malicious filename (using tricks like ../../, encoding, null bytes, or symbolic links), your application must validate it's safe. But here's the catch: you can't just check the raw input — attackers count on that. You need to canonicalize the path first, which means converting it to its simplest, standardized form before checking if it's allowed.
Think of canonicalization like reducing a fraction: 4/8 and 1/2 look different, but they're the same value. Similarly, uploads/../../etc/passwd and /etc/passwd can point to the same place, but look different to simple string checks.
Why Simple Validation Fails
If you just check whether a filename contains .. before allowing it, an attacker can bypass this with:
- URL encoding:
%2e%2e%2f - Double encoding:
%252e%252e%252f - Mixed separators:
..\../ - Trailing characters:
..;/
The Right Approach
- Canonicalize first: Convert the path to its absolute, simplified form (resolving all
.,.., symlinks, and encodings) - Validate second: Check if the canonical path starts with your allowed directory
- Never trust again: Don't manipulate the path after validation
Example validation logic (conceptual):
- User uploads:
profile_../../etc/passwd - Canonicalize to:
/var/www/uploads/../etc/passwd→/var/www/etc/passwd - Check: Does
/var/www/etc/passwdstart with/var/www/uploads/? No → reject
Key Takeaway: Always canonicalize paths to their simplest absolute form before validation — checking raw filenames is like locking your front door but leaving windows open.