Skip to content
Katabench
Try free

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

C#
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.

C# secure coding exercises →

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