Command Injection and Path Traversal, Explained
If you are reading this, you have met SQL injection and cross-site scripting and noticed that the OWASP list keeps returning to the same pattern: untrusted input ends up somewhere it is treated as more than data. Two more members of that family show up constantly in bug reports and in code review: command injection and path traversal.
By the end you will be able to explain what each flaw is, read vulnerable code and see why it fails, run a tested demo of each, name the wrong fixes that look safe but are not, and describe the defences that work. All demos run on your own computer, on files you create.
You should know what SQL injection is (SQL Injection) and the basics of the shell (Linux Fundamentals). The demos use Python (Python Basics for Security) and Unix commands, so they run on macOS and Linux. On Windows use WSL.
1. The same idea again
Every injection flaw has the same shape: a program builds an instruction out of fixed text it wrote and variable text from outside, then hands the result to something that interprets it. If the outside text can change the meaning of the instruction, the attacker is now giving instructions.
| Flaw | Input is put into... | The interpreter is... |
|---|---|---|
| SQL injection | A database query | The database |
| Cross-site scripting | A web page | The browser |
| Command injection | An operating-system command | The shell |
| Path traversal | A file path | The file system |
MITRE's weakness catalogue (CWE) defines the two flaws of this post:
- CWE-78, "Improper Neutralization of Special Elements used in an OS Command": the product "constructs all or part of an OS command using externally-influenced input from an upstream component", but "does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command" (CWE-78).
- CWE-22, "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')": the product "does not properly neutralize special elements within the pathname" (CWE-22).
(Path traversal is also one of the weakness types OWASP maps to its number-one category, Broken Access Control, as noted in Web-Based Attacks and the OWASP Top 10.)
2. Command injection
How it happens
A programmer needs the size of a file the user names, so they run an existing command. The easy way is to build one string and let a shell run it. A shell treats some characters specially: a semicolon, for example, ends one command and starts another. If the user's text can contain a semicolon, the user can add commands of their own.
Set up a tiny lab. Use a new empty folder:
mkdir cmdlab && cd cmdlab
printf 'hello\n' > a.txt
Save this as cmd.py:
import subprocess
def size_unsafe(name):
subprocess.run("wc -c " + name, shell=True) # one string, run by a shell
def size_list(name):
subprocess.run(["wc", "-c", name]) # no shell, separate arguments
print("--- shell=True, normal input", flush=True)
size_unsafe("a.txt")
print("--- shell=True, hostile input", flush=True)
size_unsafe("a.txt; echo INJECTED")
print("--- list of arguments, same hostile input", flush=True)
size_list("a.txt; echo INJECTED")
Run python3 cmd.py. Output on macOS (column spacing from wc differs slightly on Linux):
--- shell=True, normal input
6 a.txt
--- shell=True, hostile input
6 a.txt
INJECTED
--- list of arguments, same hostile input
wc: a.txt; echo INJECTED: open: No such file or directory
Read it line by line:
- With normal input the program works: 6 bytes in
a.txt. - With hostile input, the shell saw
wc -c a.txt; echo INJECTED. The semicolon ended the first command and started a second.INJECTEDis printed by a command the programmer never wrote. Here it is a harmlessecho; a real attacker would use a real command. - In the list form, there is no shell. The whole text
a.txt; echo INJECTEDis passed as one argument, andwcsimply reports that no file has that name.
The Python documentation says why: subprocess "will not implicitly choose to call a system shell", but if you call the shell with shell=True, "it is the application's responsibility to ensure that all whitespace and metacharacters are quoted appropriately to avoid shell injection vulnerabilities" (subprocess, Security Considerations).
Defences, in order of preference
The OWASP OS Command Injection Defense Cheat Sheet lists these in order (OWASP):
| Order | Defence | Meaning |
|---|---|---|
| 1 | Avoid calling OS commands | Best of all: do not run a command at all |
| 2 | Use built-in library APIs | MITRE gives the same advice: "If at all possible, use library calls rather than external processes to recreate the desired functionality." For the example above, Python can get a file's size without running wc (os.path.getsize) |
| 3 | Parameterization | If you must run a command, use "structured mechanisms that automatically enforce the separation between data and command". In practice: pass a list of arguments and do not use a shell. CWE-78 says to find any function that "invokes a command shell using a single string" and replace it with one that "requires individual arguments" |
| 4 | Input validation | Check input against an allowlist (OWASP calls it "positive or allowlist input validation"). OWASP lists it fourth, after the structural defences above |
Escaping or filtering dangerous characters is the weakest option. MITRE's conservative version is to "escape or filter all characters that do not pass an extremely strict allowlist". A blocklist of bad characters is easy to get wrong.
A second problem: argument injection
Even without a shell, input can cause trouble if it starts with a dash, because many commands read -something as an option, not as a filename. Add this to cmd.py (or a new file in the same folder):
def list_dir_unsafe(name):
subprocess.run(["ls", name])
def list_dir_safe(name):
subprocess.run(["ls", "--", name])
print("--- list form, input that looks like an option", flush=True)
list_dir_unsafe("-1")
print("--- list form with --", flush=True)
list_dir_safe("-1")
With only a.txt and cmd.py in the folder, the output is:
--- list form, input that looks like an option
a.txt
cmd.py
--- list form with --
ls: -1: No such file or directory
The user asked for a "file" named -1. The first call treated it as the option -1 (list one entry per line) and listed the whole folder. The second call put -- before the user's value. The POSIX utility conventions define this: "The first -- argument that is not an option-argument should be accepted as a delimiter indicating the end of options. Any following arguments should be treated as operands, even if they begin with the - character" (POSIX utility syntax guidelines, guideline 10). Now -1 is treated as a file name, and no such file exists.
Whether a given command honors -- depends on the command, so check its manual.
3. Path traversal
How it happens
Many applications serve or read files named by the user: "download report.pdf", "show image avatar.png", "include template.html". The program joins a trusted base folder and the user's text. Special parts of a path can step out of that folder:
| Input | Meaning |
|---|---|
../ |
Go up one folder. ../secret.txt is a file one level above the base |
An absolute path (/etc/...) |
Start from the top of the file system, ignoring the base |
| A symbolic link inside the folder | A file that points somewhere else |
The Python documentation spells out the absolute-path surprise for os.path.join: "If a segment is an absolute path ..., then all previous segments are ignored and joining continues from the absolute path segment" (os.path). So os.path.join("/home/foo", "/home/bar") gives /home/bar.
Demo
Create the lab in a new folder:
mkdir travlab && cd travlab
mkdir -p webroot/files webroot/files_backup
echo "Q3 report: public" > webroot/files/report.txt
echo "SECRET: db password is hunter2" > webroot/secret.txt
echo "old backup" > webroot/files_backup/old.txt
ln -s "$(pwd)/webroot/secret.txt" webroot/files/link.txt
(The "password" is fake. Never put real secrets in a lab.) The only folder visitors may read is webroot/files. Outside it sit secret.txt and a sibling folder, files_backup. Inside it, link.txt is a symbolic link to the secret.
Save this as trav.py in the travlab folder:
import os
from pathlib import Path
BASE = os.path.realpath("webroot/files") # the only folder visitors may read
SECRET = os.path.realpath("webroot/secret.txt") # a file outside it
def naive(name):
return open(os.path.join(BASE, name)).read()
def prefix_check(name): # a common but wrong "fix"
target = os.path.realpath(os.path.join(BASE, name))
if not target.startswith(BASE):
raise PermissionError("blocked")
return open(target).read()
def safe(name):
base = Path(BASE)
target = (base / name).resolve()
if not target.is_relative_to(base):
raise PermissionError("blocked")
return target.read_text()
tests = ["report.txt", "../secret.txt", SECRET, "../files_backup/old.txt", "link.txt"]
for fn in (naive, prefix_check, safe):
print("==", fn.__name__)
for name in tests:
shown = "<absolute path to secret.txt>" if name == SECRET else name
try:
print(f" {shown:<30} -> {fn(name).strip()}")
except Exception as e:
print(f" {shown:<30} -> {type(e).__name__}: {e}")
Run python3 trav.py (Python 3.9 or newer; the output below is from Python 3.12 and also matched on 3.9):
== naive
report.txt -> Q3 report: public
../secret.txt -> SECRET: db password is hunter2
<absolute path to secret.txt> -> SECRET: db password is hunter2
../files_backup/old.txt -> old backup
link.txt -> SECRET: db password is hunter2
== prefix_check
report.txt -> Q3 report: public
../secret.txt -> PermissionError: blocked
<absolute path to secret.txt> -> PermissionError: blocked
../files_backup/old.txt -> old backup
link.txt -> PermissionError: blocked
== safe
report.txt -> Q3 report: public
../secret.txt -> PermissionError: blocked
<absolute path to secret.txt> -> PermissionError: blocked
../files_backup/old.txt -> PermissionError: blocked
link.txt -> PermissionError: blocked
What each version teaches:
naivejoins and reads. Onlyreport.txtis meant to work, yet four other inputs read files outside the allowed area or through a symbolic link:../stepped up, the absolute path replaced the base, a sibling folder was reached, and the symbolic link led to the secret.prefix_checklooks right. It resolves the final path and checks that it starts with the base folder's name. It blocks the obvious attacks but still leaksfiles_backup/old.txt. Why? The base is.../webroot/filesand the sibling is.../webroot/files_backup. The sibling's path begins with the base's text, so a string-prefix test passes. Comparing strings is not the same as comparing folders.saferesolves the path (removing..parts and following symbolic links) and then checks that the result is inside the base folder, using path logic and not text. The Python documentation says to callPath.resolve()"so as to resolve symlinks and eliminate '..' components", and warns thatis_relative_tois "string-based; it neither accesses the filesystem nor treats '..' segments specially" (pathlib). That is whyresolve()must come first.
MITRE's mitigations for CWE-22 match this: use "an 'accept known good' input validation strategy"; "when validating filenames, use stringent allowlists that limit the character set to be used"; and use "a built-in path canonicalization function (such as realpath() in C)" which "effectively removes '..' sequences and symbolic links" (CWE-22).
The strongest fix: do not use user text as a path
The best defence is often to avoid the problem. Instead of accepting a file name, accept an ID that your program maps to a file it chose:
FILES = {"q3": "report.txt"} # allowlist: the only names that exist
def download(file_id):
return Path(BASE, FILES[file_id]).read_text() # unknown IDs raise KeyError
Then the visitor cannot name anything outside your list. Combine this with least privilege: run the web application as an account that cannot read the secrets at all (see Security Design Principles), so that a mistake in the code does not become a leak.
4. Finding these flaws (legally)
Testers look for every feature that takes a file name, a path or a host name from the user, such as downloads, image loaders, import and export features, and anything that calls an external tool. They try odd values and watch for different behavior or errors. Do this only on your own lab or on systems where you have written permission. Deliberately vulnerable applications such as OWASP Juice Shop, WebGoat and DVWA, and the PortSwigger Web Security Academy labs, are built for it (see Build a Safe Practice Lab and Security Testing).
Developers can catch these in review with a simple search: find every call that runs a shell (shell=True, os.system, backticks and similar in other languages) and every place a user-controlled value is joined into a path.
5. Common mistakes
| Mistake | The facts |
|---|---|
| "I'll escape the semicolon" | A blocklist of bad characters misses others. Avoid the shell and pass arguments separately |
"shell=True is shorter, and I validate input" |
The Python documentation puts the burden of correct quoting on you. Prefer a list of arguments |
| "No shell, so no injection" | A value that starts with - can still be read as an option (argument injection). Use -- where the command supports it, and validate |
| "Calling a command is easier than a library" | MITRE and OWASP both recommend library calls rather than external processes |
"I strip ../ from the input" |
The demo shows other routes: absolute paths and symbolic links. Resolve and check the final path instead |
| "I check that the path starts with the base folder" | A sibling named files_backup starts with files. Compare paths as paths, with is_relative_to after resolve() |
| "The file is in a public folder, so it is fine" | Symbolic links and permissions can point anywhere. Resolve first |
| "Allowlist file names? Too much work" | An ID-to-file map is a few lines, and removes the problem |
| "The app runs as an administrator for convenience" | Least privilege limits what a traversal or injection can reach |
Closing
Command injection and path traversal are the same lesson in new places: if untrusted text reaches an interpreter, the attacker may be the one giving instructions. The fixes are also the same lesson: keep data and instructions apart, prefer designs where user text never becomes a command or a path, and check the final, resolved value rather than the text that went in.
Keep these points:
- Command injection: user text reaches a shell. Avoid shells and commands; use libraries; pass argument lists; allowlist input.
- Argument injection: a leading
-can become an option. Use--where supported. - Path traversal: user text escapes a folder through
.., absolute paths or symbolic links. - Resolve, then compare as paths. Not string prefixes, and not stripping
../. - Prefer IDs to file names, and run applications with least privilege.
- Test only in labs or with written permission.
If you can read a function that runs a command or opens a file from user input, name the character or path form that breaks it, and fix it two ways, you have the foundation.
Related: SQL Injection and Cross-Site Scripting are the same pattern in a database and a browser, Broken Access Control and IDOR covers the access checks that should stop a visitor from reaching other users' files, and Python Basics for Security explains the safe habits used here.