Recipe 10.1 · C#
Safe Path Handling
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.
public ActionResult Download(string file)
{
string path = Server.MapPath("~/App_Data/reports/") + file;
return File(path, "application/octet-stream");
}
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.
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.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
namespace ImproveCode.Files;
public static class SafePath
{
private static readonly StringComparison Comparison =
OperatingSystem.IsWindows()
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
private static readonly char[] InvalidChars = Path
.GetInvalidFileNameChars()
.Concat(['<', '>', ':', '"', '|', '?', '*', '\\', '/'])
.Distinct()
.ToArray();
private static readonly HashSet<string> ReservedNames = new(
["CON", "PRN", "AUX", "NUL",
"COM1", "COM2", "COM3", "COM4", "COM5",
"COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5",
"LPT6", "LPT7", "LPT8", "LPT9"],
StringComparer.OrdinalIgnoreCase);
public static string Combine(string root, string relativePath)
{
if (!TryCombine(root, relativePath, out string? full))
{
throw new UnauthorizedAccessException(
"The path is outside the allowed folder or invalid.");
}
return full;
}
public static bool TryCombine(
string root,
string relativePath,
[NotNullWhen(true)] out string? fullPath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(root);
fullPath = null;
if (string.IsNullOrWhiteSpace(relativePath)
|| Path.IsPathRooted(relativePath))
{
return false;
}
string[] segments = relativePath.Split(
['/', '\\'], StringSplitOptions.RemoveEmptyEntries);
if (segments.Length == 0
|| !segments.All(s => s == "." || IsValidSegment(s)))
{
return false;
}
string rootFull = Path.GetFullPath(root);
if (!Path.EndsInDirectorySeparator(rootFull))
{
rootFull += Path.DirectorySeparatorChar;
}
string candidate = Path.GetFullPath(
Path.Join(rootFull, Path.Join(segments)));
if (!candidate.StartsWith(rootFull, Comparison))
{
return false;
}
fullPath = candidate;
return true;
}
public static string ToSafeFileName(
string? name, string fallback = "file", int maxLength = 120)
{
string candidate = Path.GetFileName(
(name ?? "").Replace('\\', '/'));
var chars = candidate
.Select(c => InvalidChars.Contains(c) || char.IsControl(c)
? '_' : c)
.ToArray();
string cleaned = new string(chars).Trim().TrimEnd('.', ' ');
if (cleaned.Length == 0 || cleaned.All(c => c == '.'))
{
cleaned = fallback;
}
if (ReservedNames.Contains(BaseName(cleaned)))
{
cleaned = "_" + cleaned;
}
if (cleaned.Length > maxLength)
{
string ext = Path.GetExtension(cleaned);
ext = ext.Length > 10 ? "" : ext;
cleaned = cleaned[..(maxLength - ext.Length)] + ext;
}
return cleaned;
}
private static bool IsValidSegment(string segment) =>
segment != ".."
&& segment.IndexOfAny(InvalidChars) < 0
&& !segment.Any(char.IsControl)
&& !segment.EndsWith('.')
&& !segment.EndsWith(' ')
&& !ReservedNames.Contains(BaseName(segment));
private static string BaseName(string segment)
{
int dot = segment.IndexOf('.');
return dot < 0 ? segment : 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.