cybersecurity · intermediate · ~15 min · safe pentest lab
Enforce strict allowlists on filenames to prevent directory traversal and command flag injection.
Path traversal attacks use ../ or separator injections to escape sandboxed storage directories and access sensitive files like /etc/passwd or overwrite configuration files.
Implement:
int sanitize_filename(const char *raw, char *clean, size_t clean_cap);
Validate and sanitize an untrusted relative filename.
raw == NULL, clean == NULL, or clean_cap == 0, return -1.-1 if raw:"") or equals "."'-' (prevents CLI flag injection)".." anywhere'/' or '\\'strlen(raw) >= clean_cap, return -1 (does not fit).raw into clean and return 0.char out[32];
sanitize_filename("report.pdf", out, sizeof out); // returns 0, out = "report.pdf"
sanitize_filename("../../etc/passwd", out, sizeof out); // returns -1 (traversal)
sanitize_filename("-rf", out, sizeof out); // returns -1 (flag injection)
raw: untrusted filename; clean: destination buffer; clean_cap: capacity of clean buffer.
Returns 0 on valid filename, -1 on any malicious or oversized path.
Freestanding C11. Only alphanumeric, spaces, and safe printable ASCII characters allowed.
#include <stddef.h>
/* Validate and sanitize raw filename into clean buffer (capacity clean_cap).
Reject path separators, '..', leading '-', and non-printable characters.
Return 0 on success, -1 on invalid or rejected filename. */
int sanitize_filename(const char *raw, char *clean, size_t clean_cap) {
(void)raw; (void)clean; (void)clean_cap;
return -1;
}
Checking only '/' and missing '\'; failing to reject leading '-' flags; permitting '..' sequences.
Dotfile like ".env"; path traversal like "..\foo"; raw starting with '-'; NULL pointers.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.