Sub topic 10
Avoiding shell injection
This chapter assumes you can use subprocess.run with an argument list, you know what shell=True does, and you have read the earlier chapter on argument lists and shlex. You should also be comfortable reading a short shell command. The examples that use echo, grep and ; assume Linux or macOS. The ideas carry over to Windows, with the differences covered near the end.
What shell injection is
Shell injection happens when text you did not write ends up being parsed by a shell as syntax. The shell has no way to tell your command from the attacker's text. It reads one string and splits it on spaces, semicolons, pipes, $(...) and other metacharacters.
Here is the pattern in its simplest form:
import subprocess
user_value = "report.txt; echo injected"
# Dangerous: the shell sees two commands separated by a semicolon.
subprocess.run(f"echo {user_value}", shell=True)This prints report.txt and then injected. The echo command is harmless, so you can run this safely. If the injected part were rm -rf ~ or a command that uploads your SSH keys, it would run with your program's privileges. The attacker only needs control over part of the string. That part might be a filename, a form field, a branch name from a git repository, or a value read from a database.
The injected text does not have to look suspicious. The shell also expands $HOME, backticks, * and ~ before the program starts. Even a well-meaning value like my file.txt breaks a command because the space splits it into two arguments.
The fix: do not involve a shell
The most reliable defense is to remove the shell. With an argument list and the default shell=False, Python starts the program directly. Each list item becomes exactly one argument.
import subprocess
import sys
user_value = "report.txt; echo injected"
subprocess.run(
[sys.executable, "-c", "import sys; print(sys.argv[1:])", user_value],
)The child prints ['report.txt; echo injected']. The semicolon is an ordinary character inside one argument. No parsing step exists where it could take on special meaning.
Why shlex.split does not make input safe
shlex.split turns a string into a list using POSIX shell quoting rules. It is the right tool when you hold a trusted command line, such as one from your own configuration file, and need a list. It does not make an untrusted string safe. If the user controls the whole string, they still choose the program and every option:
import shlex
print(shlex.split("ls -l 'my folder'"))
print(shlex.split("rm -rf /tmp/data"))The second call produces ['rm', '-rf', '/tmp/data']. Nothing was blocked. The shell is gone, but the user still picks the program. Use shlex.split on text you trust, and keep untrusted values as individual list items.
Option injection: the attack that survives lists
Removing the shell stops metacharacters, but a value can still be dangerous to the program itself. If a user-supplied filename starts with -, many programs read it as an option. A file called --help or -rf changes what the command does.
Two defenses work together:
- Put
--before positional arguments. Most POSIX tools treat everything after it as plain operands. - When a tool has a flag that takes a value, use that flag (such as
-efor agreppattern) so the value cannot be read as an option.
import os
import subprocess
import tempfile
def count_matches(pattern: str, path: str) -> int:
result = subprocess.run(
["grep", "-c", "-e", pattern, "--", path],
capture_output=True,
text=True,
)
# grep exits 0 for matches, 1 for no matches, 2 or more for errors.
if result.returncode > 1:
raise RuntimeError(result.stderr.strip())
return int(result.stdout)
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "data.txt")
with open(path, "w") as handle:
handle.write("a\n-v\nb\n")
print(count_matches("-v", path))This prints 1. Without -e, the pattern -v would be read as the "invert match" option and the count would change. Note that this function uses the exit status to separate "no matches" from "failed", which is why it does not use check=True.
-- is a convention and not a guarantee. Some programs do not support it, and a few treat it differently. Read the tool's manual. For file arguments, another option is to make the path unambiguous, for example by passing os.path.abspath(name) or "./" + name, so it can never begin with a dash.
Validate against an allowlist
When user input selects an action, do not build a command from it. Map the input to a fixed set of commands. Anything not in the table is rejected:
import subprocess
import sys
ACTIONS = {
"version": [sys.executable, "--version"],
"paths": [sys.executable, "-c", "import sys; print(sys.path[0])"],
}
def run_action(name: str) -> str:
try:
command = ACTIONS[name]
except KeyError:
raise ValueError(f"unknown action: {name!r}") from None
result = subprocess.run(command, capture_output=True, text=True, check=True)
return result.stdout.strip()
print(run_action("version"))The user's text is only ever used as a dictionary key. It never reaches the command line. This works well for admin tools, chat bots and web endpoints.
When you truly need a shell
Sometimes a command string is unavoidable: a legacy script, a user-written cmd field that is meant to be a shell command, or a feature that exists only in the shell. In that case:
- Quote every untrusted value with
shlex.quote. It wraps the value so the shell sees it as one literal word. - Quote each value separately and only values, never a fragment of syntax.
- Avoid quoting a value twice, and avoid placing it inside your own quotes.
import shlex
import subprocess
user_value = "report.txt; echo injected"
command = f"echo {shlex.quote(user_value)}"
print(command)
subprocess.run(command, shell=True)The printed command is echo 'report.txt; echo injected', and running it prints the text on one line. Compare that with the first example in this chapter.
For pipelines, you rarely need the shell. Two Popen objects connected with a pipe (covered later in this tutorial) replace a | b without any parsing step. Replace shell globs such as *.txt with pathlib.Path.glob in Python.
Other places where trust leaks
- Program lookup.
["git", ...]searchesPATH. If an attacker can changePATHor drop a program earlier in it, they get their program run. Use absolute paths for sensitive tools, orshutil.whichat startup and cache the result. Usesys.executablefor Python children. - Environment.
env={**os.environ, ...}passes everything, including secrets, to the child. For untrusted children, build a small environment instead. - Secrets on the command line. Arguments are visible to other users through
ps. Pass secrets through stdin or an environment variable. - Child programs that run commands.
ssh host cmd,docker exec sh -c,githooks andfind -execrun their arguments through another shell on the other side. A list protects only your local call. You must still quote for the remote shell.
Windows differences
shlex.quote follows POSIX rules and is wrong for cmd.exe, which treats &, |, ^ and % as special. With a list on Windows, Python builds a single command line with subprocess.list2cmdline, and the program parses it. Executables usually parse it the standard way, but .bat and .cmd files are run through cmd.exe, so metacharacters in arguments can still be interpreted. Avoid passing untrusted values to batch files. Validate them strictly against a narrow pattern such as letters, digits and a few safe symbols.
Summary of the rules
| Situation | Safe approach |
|---|---|
| Fixed command with variable values | List of arguments, `shell=False` |
| Value could start with `-` | Add `--` or use a value-taking flag |
| User picks an action | Allowlist dictionary |
| Trusted command string | `shlex.split`, then pass the list |
| Shell syntax is required | `shlex.quote` on every untrusted value |
| Windows batch files | Strict validation of values |
Exercise
A function runs subprocess.run(["rm", filename]) where filename comes from a web form. A user submits -rf. Does using a list with no shell prevent harm? What two changes make the call safer?
Show answer
A list prevents shell injection, but it does not prevent option injection. The value -rf is passed as one argument and rm reads it as options. Add -- before the filename (["rm", "--", filename]) so it is always treated as an operand, and validate the name against an allowlist or a strict pattern, or resolve it to an absolute path inside an expected directory. An absolute path cannot begin with a dash.
Exercise
You have the command string f"grep {term} data.txt | wc -l" and must keep the pipe behavior. Show two ways to make it safe for an untrusted term.
Show answer
Option one keeps the shell: f"grep -e {shlex.quote(term)} data.txt | wc -l" with shell=True. The quoting makes term a single literal word, and -e stops it being read as an option. Option two removes the shell: start Popen(["grep", "-e", term, "data.txt"], stdout=PIPE), then start Popen(["wc", "-l"], stdin=first.stdout, stdout=PIPE), close first.stdout in the parent, and read the result with communicate(). Option two is preferred because no parser sees the value.