Recipe 10.1 · Python
Safe Path Handling
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
Code combines a base folder with a name that came from outside: a query string, an uploaded file name, a zip entry, a column in an import file. If that name contains ..\, a drive letter or a UNC path, the result points somewhere else on the server. This is path traversal, and it is still one of the most common findings in security reviews of line-of-business applications.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
A request for ?file=..\..\web.config returns the configuration file, connection strings included. Path.Combine does not help on its own: Path.Combine(@"D:\reports", @"C:\Windows\win.ini") returns the second path, because a rooted second argument replaces the first.
Requirements: Python 3.12+. Install: pip install fastapi
"""Download endpoint that concatenates a user-supplied file name onto a folder
Source: ImproveCode, Chapter 10, Recipe 10.1 "Safe Path Handling"
Section: The way it's often written
Book page: 204 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
ASP.NET MVC action -> FastAPI route; Server.MapPath -> a fixed base folder string;
File(...) -> FileResponse. "../" in `file` escapes the reports folder.
"""
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
APP_DATA_REPORTS = "./App_Data/reports/" # stands in for Server.MapPath("~/App_Data/reports/")
@app.get("/download")
def download(file: str) -> FileResponse:
path = APP_DATA_REPORTS + file
return FileResponse(path, media_type="application/octet-stream")
The improved recipe
SafePath.Combine resolves the combined path to its full form and checks that it is still inside the root. It also rejects rooted input, characters that are invalid on Windows, alternate data streams and reserved device names. A companion method turns any client-supplied name into a safe single file name.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Combine paths safely under a root folder and sanitize file names
Source: ImproveCode, Chapter 10, Recipe 10.1 "Safe Path Handling"
Section: The improved recipe
Book page: 205-207 -- original C# listing
Converted from C# to Python.
System.IO.Path -> os.path; UnauthorizedAccessException -> PermissionError;
the C# `out` parameter of TryCombine becomes a `str | None` return value.
"""
from __future__ import annotations
import os
import sys
import unicodedata
_IS_WINDOWS = sys.platform == "win32"
# Path.GetInvalidFileNameChars() plus the Windows-reserved punctuation.
_INVALID_CHARS: frozenset[str] = frozenset(
{chr(c) for c in range(32)} | set('<>:"|?*\\/')
)
_RESERVED_NAMES: frozenset[str] = frozenset(
["CON", "PRN", "AUX", "NUL",
"COM1", "COM2", "COM3", "COM4", "COM5",
"COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5",
"LPT6", "LPT7", "LPT8", "LPT9"]
)
def _is_control(ch: str) -> bool:
return unicodedata.category(ch) == "Cc"
def _starts_with(value: str, prefix: str) -> bool:
if _IS_WINDOWS:
return value.casefold().startswith(prefix.casefold())
return value.startswith(prefix)
def _is_reserved(segment: str) -> bool:
return _base_name(segment).upper() in _RESERVED_NAMES
def combine(root: str, relative_path: str) -> str:
full = try_combine(root, relative_path)
if full is None:
raise PermissionError(
"The path is outside the allowed folder or invalid.")
return full
def try_combine(root: str, relative_path: str) -> str | None:
"""Return the full path under `root`, or None if it is unsafe."""
if root is None or not root.strip():
raise ValueError("root must not be null or whitespace")
if (not relative_path or not relative_path.strip()
or os.path.isabs(relative_path)
or relative_path.startswith(("/", "\\"))
or os.path.splitdrive(relative_path)[0]):
return None
segments = [s for s in relative_path.replace("\\", "/").split("/") if s]
if not segments or not all(s == "." or _is_valid_segment(s) for s in segments):
return None
root_full = os.path.abspath(root)
if not root_full.endswith(os.sep):
root_full += os.sep
candidate = os.path.abspath(os.path.join(root_full, *segments))
if not _starts_with(candidate, root_full):
return None
return candidate
def to_safe_file_name(
name: str | None, fallback: str = "file", max_length: int = 120
) -> str:
candidate = os.path.basename((name or "").replace("\\", "/"))
chars = ["_" if (c in _INVALID_CHARS or _is_control(c)) else c
for c in candidate]
cleaned = "".join(chars).strip().rstrip(". ")
if len(cleaned) == 0 or all(c == "." for c in cleaned):
cleaned = fallback
if _is_reserved(cleaned):
cleaned = "_" + cleaned
if len(cleaned) > max_length:
ext = os.path.splitext(cleaned)[1]
ext = "" if len(ext) > 10 else ext
cleaned = cleaned[: max_length - len(ext)] + ext
return cleaned
def _is_valid_segment(segment: str) -> bool:
return (
segment != ".."
and not any(c in _INVALID_CHARS for c in segment)
and not any(_is_control(c) for c in segment)
and not segment.endswith(".")
and not segment.endswith(" ")
and not _is_reserved(segment)
)
def _base_name(segment: str) -> str:
dot = segment.find(".")
return segment if dot < 0 else segment[:dot]
How it works
The check that matters is the last one in TryCombine: resolve the full path with Path.GetFullPath, which collapses . and .., and confirm it still starts with the root plus a trailing separator. The separator is important. Without it, a root of D:\data\reports would accept D:\data\reports-archive\secret.txt, because the string starts with the same characters.
The segment checks reject input before it is resolved. .. is refused outright instead of being allowed when it happens to stay inside the root; no legitimate client needs to send it. A colon is refused because on NTFS report.txt:hidden addresses an alternate data stream. Names such as CON, NUL and COM1, with or without an extension, are device names on Windows and do strange things when opened. Trailing dots and spaces are refused because Windows silently strips them, so report.txt. and report.txt are the same file.
ToSafeFileName is for the opposite situation: you want to keep a user's file name for display or download, not use it as a path. It takes only the last segment, replaces anything unsafe with _, guards against reserved names and limits the length while keeping the extension. For storage, prefer a generated name, as in Recipe 8.4, and keep the original name in the database.
Variations and pitfalls
- Links can escape. A symbolic link or junction inside the root can point outside it, and string checks cannot see that. If users can create links in the folder, resolve them with
FileSystemInfo.ResolveLinkTarget(returnFinalTarget: true)and check the target too. - Use an ID instead of a path. The safest download endpoint takes a database key, looks up the stored file name, and never accepts a path at all.
- Return 404, not 403. When
TryCombinefails in a web endpoint, return "not found." There is no need to confirm to a scanner that it found something interesting. - Chapter 7 covers injection and traversal as security topics. This recipe is the reusable code for the file side of that discussion.