Defense: Canonical Form Validation Strategies
What you'll learn: How to safely validate input by converting it to a standard, simplified form first—closing the door on encoding tricks and path manipulation attacks.
The Core Problem
Attackers exploit the gap between how input looks and what it actually means. They use double encoding, Unicode tricks, mixed case, null bytes, and path traversal sequences to sneak past validation. If you check the raw input without standardizing it first, you're checking the disguise, not the real data.
The Canonical Form Solution
Canonicalization means converting input to its simplest, standard representation before applying security checks. Think of it like removing all disguises before checking someone's ID at a secure facility.
For example:
../../../etc/passwdand.%2F..%2F..%2Fetc%2Fpasswdboth canonicalize to the same dangerous path<script>and%3Cscript%3Eboth represent the same XSS vectoradminandADMINmight be the same username
Implementation Strategy
- Decode all encoding layers (URL encoding, HTML entities, Unicode normalization)
- Resolve path shortcuts (collapse
..,., redundant slashes) - Normalize case according to your context (case-insensitive filesystems, usernames)
- Remove null bytes and other terminator tricks
- THEN validate against your allowlist or security rules
Use Safe APIs
Modern frameworks provide canonicalization functions:
- File path resolution APIs that automatically collapse traversals
- URL parsers that decode and normalize
- Unicode normalization libraries
Don't write your own parser—use battle-tested libraries that handle edge cases.
Key Takeaway:
Always convert input to canonical form before validation—validate the reality, not the disguise. Use trusted canonicalization APIs rather than building your own.