Course contentsShow
← Security
Lesson 971 of 3,05220. Web Security - File Upload and ProcessingFree lesson

Path Canonicalization and Validation

Master proper path normalization techniques and secure validation to prevent filename-based attacks.

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

  1. Canonicalize first: Convert the path to its absolute, simplified form (resolving all ., .., symlinks, and encodings)
  2. Validate second: Check if the canonical path starts with your allowed directory
  3. 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/passwd start 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.