cybersecurity · intermediate · ~20 min
Allow-list filtering, leading-dot rule, and length capping in one pass.
Scrub an attacker-controlled filename down to a safe set of characters, in place — the standard defense against path traversal, hidden-file tricks, and shell-special bytes.
Implement void sanitize_filename(char *s) that mutates s in place so that:
_),. is replaced with _ (no hidden files), and'\0' at index 64).Allowlist: ASCII letters A-Z / a-z, digits 0-9, and _ - ..
s: a mutable, NUL-terminated filename the grader provides. May be empty or longer than 64 chars.No return value. s is modified in place to the sanitized filename.
"hello.txt" -> "hello.txt"
"hello world.txt" -> "hello_world.txt"
"../etc/passwd" -> "_._etc_passwd"
".htaccess" -> "_htaccess"
"normal_name-1.tar.gz" -> "normal_name-1.tar.gz"
(100 'a' chars) -> first 64 'a's, then NUL
"" -> ""
When a user uploads a file or names an export, the filename is attacker-controlled. Allowing arbitrary bytes invites path traversal, NUL injection, hidden-file creation (.htaccess), and shell-special bytes. A short allowlist scrub is the standard defensive answer.
A mutable, NUL-terminated filename (may be empty or over 64 chars).
No return; s is mutated in place to the sanitized, allowlisted, <=64-char name.
Allowlist letters/digits/_-.; replace leading dot; cap at 64; single pass, no allocations.
void sanitize_filename(char *s) { /* TODO */ }
Using a deny-list (if (c == '/' || c == '\\') ...) — endlessly incomplete. Forgetting the leading-dot rule.
Empty; leading dot; all special chars; longer than 64.
O(strlen(s)).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.