Filename Sanitizer
Easy About 20 min Free, no account needed
Reduce an uploaded filename to a safe, single path segment.
The brief
The bug in plain terms: This is a path traversal (also called directory traversal) bug, where a user-supplied filename is trusted as a place to write on disk. By smuggling characters like
/,\, or..into the name, an attacker can climb out of your uploads folder and read or overwrite files anywhere the app can reach (for example overwriting a config or planting a script in a web-served directory). The trap is that stripping one leading../is not enough: the dangerous parts can hide in the middle of the name, repeat, or appear as bare separators, so the only safe approach is to keep just the final path segment and allow-list the characters you permit rather than trying to blacklist the bad ones.
SafeName(name) turns a user-supplied upload filename into a single, safe path
segment to store on disk.
The starter only strips a leading ../, so it still lets through path
separators, the .. name, leading dots, and absurdly long names.
Fix SafeName to return a safe filename, or "file" when nothing safe
remains. Requirements:
- keep only the last path segment (split on both
/and\); - allow only letters, digits,
.,-,_; replace every other character with_; - collapse the names
.and..(any name that is only dots) to"file"; - trim leading dots so the result is never a hidden/empty name;
- cap the result at 64 characters;
- if the result is empty after all that, return
"file".
Starter code
using System;
public class Solution
{
// Sanitizes an upload filename - but only strips a leading "../".
public string SafeName(string name)
{
while (name.StartsWith("../"))
{
name = name.Substring(3);
}
return name;
}
}How it is graded
Functional tests and adversarial payloads both have to pass before the solution is accepted.
Related guides
What it practices
- Path traversal
- Canonicalize file paths and names so requests cannot escape their root.
- Allowlist validation
- Accept only known-good values, fields and types instead of chasing bad ones.
Related katas
- Mass Assignment Guard Easy Free Decide which submitted fields may be applied to a record using an allowlist, not a blocklist.
- Upload Content-Type Allowlist Easy Pro Accept only the exact content types you actually support, instead of any value that looks close enough.
- Link Scheme Allowlist Easy Pro Render a user-supplied link only when its scheme is one you trust, instead of blocklisting the dangerous ones.
- CORS Origin Reflection Medium Pro Decide the Access-Control-Allow-Origin value by exact allowlist, not a suffix match an attacker can satisfy.