Path Traversal Prevention Cheat Sheet¶
Introduction¶
Path traversal happens when an application builds a file system path from user input and the input can make that path point outside the directory the application meant to use. Sequences such as ../, absolute paths, or symbolic links let an attacker read, write or include files such as configuration, credentials or source code (CWE-22).
This cheat sheet covers how to build file paths from untrusted input safely. For storing uploaded files, see the File Upload Cheat Sheet. For testing, see WSTG-ATHZ-01 Testing Directory Traversal File Include.
Avoid User Input in File Paths¶
The most reliable defense is to never put user input into a path:
- Refer to files by an identifier, such as a database ID or a random name generated by the server, and map it to the real path on the server side.
- If the user picks from a fixed set of files or templates, look the name up in an allowlist and use the stored path, not the input.
- Store user content where paths don't matter, such as a database or object storage keyed by an ID.
When the application has to accept a name from the user, also restrict it to a simple allowlist of characters, for example letters, digits, - and _, with no path separators. This is an extra layer, not a replacement for the containment check below, because a character filter can't account for every way an operating system interprets a path (CWE-22).
Validate the Resolved Path¶
If the input has to become part of a path, resolve the full path first and then check that the result is still inside the intended base directory:
- Decode the input completely (URL decoding, Unicode normalization) before using it, and don't decode it again afterwards.
- Join it to a fixed base directory and resolve it to an absolute, normalized path. Resolve symbolic links as well where the platform allows it.
- Check that the resolved path is inside the base directory. Compare path components, or compare strings only after making sure the base ends with a path separator, so
/srv/uploads-olddoesn't pass a check for/srv/uploads. - Use the path you checked. Don't rebuild it from the original input.
Don't try to remove ../ from the input instead. A filter misses \ on systems that also accept it as a separator, can leave a ../ behind when it only removes one occurrence, is bypassed by input that gets decoded after the check (such as %2e%2e%2f), and does nothing about absolute paths (CWE-22).
Many join functions drop the base directory when the second argument is absolute. Python's os.path.join('/srv/uploads', '/etc/passwd') returns /etc/passwd (Python os.path.join), .NET's Path.Combine returns the second path if it's absolute (.NET Path.Combine), and Node's path.resolve starts over at the last absolute segment (Node.js path.resolve). The containment check after resolving catches this.
The examples below are minimal and assume userPath is untrusted. Adapt the error handling to your application.
Go 1.24 and later: open files through os.Root, which refuses any name that refers to a location outside the directory, including through .. or symbolic links. It does not stop access to mount points, /proc files or devices inside the directory. For a purely lexical check of a relative path, use filepath.IsLocal.
root, err := os.OpenRoot("/srv/uploads")
if err != nil {
return err
}
defer root.Close()
f, err := root.Open(userPath) // fails if userPath escapes /srv/uploads
Java: Path.startsWith compares name elements, not characters (Java Path.startsWith).
Path base = Path.of("/srv/uploads").toRealPath();
Path target = base.resolve(userPath).normalize();
if (!target.startsWith(base)) {
throw new SecurityException("Invalid path");
}
Python: os.path.realpath resolves symbolic links and os.path.commonpath compares whole path components. On Windows, commonpath raises ValueError when the paths are on different drives, which an input like D:foo causes, so treat that as a rejection too.
base = os.path.realpath("/srv/uploads")
target = os.path.realpath(os.path.join(base, user_path))
try:
contained = os.path.commonpath([base, target]) == base
except ValueError:
contained = False
if not contained:
raise ValueError("Invalid path")
.NET: Path.GetFullPath(path, basePath) resolves the input against a fixed base. Keep the trailing separator on the base for the prefix check, and use a case-insensitive comparison on Windows.
string baseDir = Path.GetFullPath("/srv/uploads/");
string target = Path.GetFullPath(userPath, baseDir);
StringComparison comparison = OperatingSystem.IsWindows()
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
if (!target.StartsWith(baseDir, comparison))
{
throw new UnauthorizedAccessException("Invalid path");
}
Node.js: check the result of path.relative instead of comparing string prefixes.
const base = path.resolve('/srv/uploads');
const target = path.resolve(base, userPath);
const rel = path.relative(base, target);
if (rel === '..' || rel.startsWith('..' + path.sep) || path.isAbsolute(rel)) {
throw new Error('Invalid path');
}
The Java, Python, .NET and Node.js examples all accept the base directory itself. The Java, .NET and Node.js examples check the path lexically, so a symbolic link inside the base directory can still point outside it. The Python example resolves existing links with realpath first, but a link created after the check still can. See the next section.
Symbolic Links and Race Conditions¶
A check on the path string doesn't account for symbolic links that exist, or are created, inside the base directory. Resolving links before the check helps, but leaves a time-of-check to time-of-use (TOCTOU) race: an attacker who can write to the directory can replace a component with a link after the check and before the file is opened (Go blog: Traversal-resistant file APIs).
- Don't let untrusted users create files or links in directories the application reads from or writes to by path.
- Prefer APIs that enforce the restriction while opening the file, such as Go's
os.Rootor Linuxopenat2withRESOLVE_BENEATH(Linux 5.6 and later), which fails if any part of the resolution leaves the directory. - Run the application with the least file system permissions it needs, so a traversal reaches as little as possible.
Archive Extraction¶
Archive entries are filenames chosen by whoever built the archive. Extracting an entry named ../../app/config.yml, or an absolute path, writes outside the destination directory, a problem known as Zip Slip. Archives can also contain symbolic links or hard links that point outside the destination, which later entries are then written through.
- Validate every entry name with the containment check above before writing it, and reject the archive if any entry fails.
- Reject or skip symbolic link and hard link entries unless the application needs them.
- Use the library's safe extraction mode where one exists. Python's
tarfileextraction filters do this, and thedatafilter is the default from Python 3.14. Passfilter='data'explicitly on older versions, and use a Python release that includes the June 2025tarfilesecurity fixes, since earlier releases let crafted archives bypass the filters (Python tarfile extraction filters, CPython issue 135034).
Windows Paths¶
Windows accepts path forms that checks written for Unix often miss (Microsoft: Naming Files, Paths, and Namespaces):
- Both
\and/are separators, and paths starting with a drive letter (C:\) or a UNC prefix (\\server\share\) are absolute. - Reserved device names such as
CON,NUL,COM1andLPT1refer to devices, even with an extension likeNUL.txt. - Filenames that end with a space or a period aren't supported by Windows tools, so reject them.
- On NTFS,
file.txt::$DATAis another name forfile.txtandfile.txt:namerefers to a named stream of it, so a check on the name or extension can see a different string than the file that gets opened. Reject:in filenames (Microsoft: File Streams). - Names are case-insensitive by default, so compare them case-insensitively.
- Paths starting with
\\?\skip the normalization that removes trailing spaces and periods, and paths starting with\\.\address devices directly. Reject both.
Use the platform's path functions for these cases instead of parsing paths yourself.
File Inclusion¶
Passing user input to include, require, template loaders or similar functions lets an attacker load an unintended file and, depending on the language, run it as code. Map the input to a fixed allowlist of templates or modules instead of using it as a path. In PHP, open_basedir limits which directory trees include and fopen() can access, which is a useful extra layer but not a replacement for not using the input as a path.