How do you identify and prevent directory traversal attacks in file uploads?
home / developersection / forums / how do you identify and prevent directory traversal attacks in file uploads?
How do you identify and prevent directory traversal attacks in file uploads?
Anubhav Kumar
23-May-2025Directory traversal attacks (also known as path traversal) aim to access files and directories outside the intended file system structure by manipulating file paths (e.g., using
../
to escape the intended directory). Preventing such attacks in file uploads is critical.Here’s how to identify and prevent directory traversal in file uploads:
1. Understanding the Attack
Example
If the server directly uses this
filename
, it may write to a sensitive path or overwrite system files.Prevention Techniques
1. Never Trust User Input for File Paths
Always treat uploaded filenames as untrusted input.
2. Sanitize the Filename
Strip or reject any path-related characters like
../
,\
,/
, null bytes, etc.Example in C#:
Example in Python:
3. Use a Safe Upload Directory
Ensure uploaded files are stored in a dedicated directory:
Do not store uploads in root, config, or executable directories.
4. Enforce File Name Policies
5. Validate File Type and Size
.jpg
,.pdf
, etc.)magic numbers
)6. Prevent Null Byte Injection
Some languages (e.g., older PHP versions) are vulnerable to null byte injections (
%00
) which can terminate strings early.%00
or\0
Additional Hardening
.php
or.exe
from running).Detection (Logging and Monitoring)
../
,..%2F
,\..\
,%5C
, or Unicode variants.Summary Checklist