Module lessons (2/3)
Encoding & Normalization Bugs
Security checks frequently break because the validator and the downstream interpreter read two different representations of the same string. When your guard rejects .. before HTTP/framework routing calls decodeURIComponent(input), encoded characters glide silently past the gate.
1. The Canonicalization Pipeline Trap
Look at what happens across three classic normalization bugs:
// Annotated Example 1: BUG — Checking BEFORE decoding lets `%2e%2e%2f` slip past!
function routeUnsafe(rawPath) {
if (rawPath.includes('..')) throw new Error('Blocked'); // sees "%2e%2e%2fsecrets.json" -> OK!
const decoded = decodeURIComponent(rawPath); // becomes "../secrets.json" downstream!
return readFileFromDisk('/srv/public/' + decoded);
}
// Annotated Example 2: BUG — Double-encoded `%252e` survives a single decode!
// Pass 1 (app middleware): decodeURIComponent("%252e%252e") -> "%2e%2e" (contains no "..")
// Pass 2 (downstream proxy): decodeURIComponent("%2e%2e") -> ".." (traversal!)Even case folding and ASCII control bytes (\x00 null bytes or \t) shift parser meaning after checks:
// Annotated Example 3: Case / whitespace tricks defeat naive prefix guards
const attackScheme = ' JaVaScRiPt:alert(1)';
attackScheme.startsWith('javascript:'); // false (guard thinks it's safe!)
attackScheme.trim().toLowerCase(); // "javascript:alert(1)" (browser executes!)
// Annotated Example 4: Correct Defense — Decode ONCE, verify stability, check strict allowlist
function normalizeSlug(raw) {
if (typeof raw !== 'string' || raw.length === 0 || raw.length > 64) return null;
if (raw.includes('\u0000') || raw.includes('\\')) return null;
const once = decodeURIComponent(raw);
if (once !== decodeURIComponent(once)) return null; // blocks double encoding (%252e)
return /^[a-z0-9-]+$/.test(once) ? once : null;
}2. Interactive Explorer: URL Parsing & Encoding Traps
Switch below between naive startsWith URL parsing and strict canonical new URL(...) normalization:
3. Progressive Labs: Warm-Up → Attack → Defend → Harden
Warm-Up: Normalize once and detect stability
Catch malformed % sequences with try/catch and return the decoded string safely.
Implement safeDecodeOnce(raw): if raw is not a string or decodeURIComponent(raw) throws a URIError (malformed %), return null; otherwise return the decoded lowercase trimmed string.
Show hint
Always wrap decodeURIComponent in try { ... } catch { return null; } because malformed sequences like '%E0%A4%A' throw URIError and crash unhandled route handlers.
Solution available after 3 attempts
Attack: Bypass the naive blocklist with percent encoding
Make isAllowedNaive(bypassPayload) return true while decoding to ../secrets.json.
Define bypassPayload so it passes isAllowedNaive(bypassPayload) (true) yet evaluates decodeURIComponent(bypassPayload) to '../secrets.json'.
Show hint
URL-encode . as %2e and / as %2f so the raw check sees neither .. nor /.
Solution available after 3 attempts
Defend: Canonicalize first, then enforce an allowlist
Decode safely, reject double encoding (once !== twice), and allow only lowercase alphanumeric slugs.
Implement isSafeNormalizedSlug(raw): decode once inside try/catch, reject if decoding twice changes the value (double encoding) or throws, and return true ONLY if the canonical value matches /^[a-z0-9-]+$/.
Show hint
Compare once === twice to catch %252e, wrap decodeURIComponent in try/catch for malformed %, then test /^[a-z0-9-]+$/.
Solution available after 3 attempts
Harden: Enforce max length, null-byte rejection & backslash guard
Build a production-grade canonicalizeRouteSegment(raw, maxLen) rejecting empty inputs, backslashes, null bytes, double encoding, and oversized payloads.
Implement canonicalizeRouteSegment(raw, maxLen): return null unless raw is a string within 1..maxLen, reject null bytes (\\u0000) or backslashes (\\\\), decode inside try/catch rejecting double-encoding (once !== twice), and return once ONLY if it matches /^[a-z0-9_-]+$/ (otherwise null).
Show hint
Check length bounds BOTH before and after decoding, verify !once.includes('\\u0000') && !once.includes('\\\\'), and return the canonical string rather than raw input.
Solution available after 3 attempts
4. Checkpoints & Code Review
Why is validating AFTER a single decodeURIComponent() pass still risky if you do not check for double encoding?
What is the primary bug in serveAsset(rawName)?
function serveAsset(rawName) {
if (rawName.includes('..') || rawName.includes('/')) {
throw new Error('Invalid filename');
}
const file = decodeURIComponent(rawName);
return loadFile('/var/www/static/' + file);
}