Sub topic 10
Avoiding shell injection
This chapter assumes you can use subprocess.run, know what an exit code is, and understand the difference between a list of arguments and a command string. It covers how shell injection happens and the habits that prevent it.
What shell injection is
Shell injection happens when text from an untrusted source ends up inside a command string that a shell parses. The shell treats characters such as ;, &&, |, $() and backticks as syntax. An attacker who controls part of the string can add commands of their own.
Suppose a program lets a user name a file to print:
import subprocess
filename = input("File to show: ")
subprocess.run(f"cat {filename}", shell=True)If the user types report.txt; rm -rf ~, the shell sees two commands and runs both. The code is wrong because it builds a program in the shell's language out of user data.
The fix: pass a list
When you pass a list and leave shell at its default of False, Python starts the program directly. No shell parses the arguments. Each list item reaches the program as exactly one argument, whatever characters it contains.
import subprocess
user_value = "report.txt; echo injected"
# Safe: cat gets one argument. It will look for a file with that odd name.
result = subprocess.run(["cat", user_value], capture_output=True, text=True)
print(result.returncode)
print(result.stderr)On Linux and macOS, cat reports that no such file exists and exits with a non-zero code. Nothing is injected, because the semicolon is just a character in a file name.
Using shlex correctly
shlex.split turns a command string into a list using shell-like quoting rules. Use it when you have a trusted string, such as one from your own configuration file, and need a list.
import shlex
print(shlex.split("ls -l 'my folder'"))This prints ['ls', '-l', 'my folder']. The quoted folder name stays one item.
Do not build a string from untrusted input and then split it. The attacker can include quotes and spaces to create extra arguments. Build the list directly instead:
import subprocess
folder = "my folder"
subprocess.run(["ls", "-l", folder])If you must put a value into a string that a shell will parse, shlex.quote(value) escapes it. Treat this as a last resort. A list is simpler and harder to get wrong.
Argument injection
Avoiding the shell does not remove every risk. A value that starts with - can be read by the program as an option. A user value of --output=/etc/passwd handed to some tools changes what they do.
Two defenses help:
- Put
--before user values when the program supports it. This marks the end of options. - Validate input against what you expect, such as a fixed set of names or a strict pattern, before you pass it on.
import subprocess
user_value = "-n"
subprocess.run(["cat", "--", user_value])Here cat treats -n as a file name, not an option.
Summary of rules
| Situation | What to do |
|---|---|
| Command and arguments are known | Pass a list |
| Part of the command comes from a user | Pass a list, validate the value, add `--` if supported |
| You have a trusted command string | Use `shlex.split` to get a list |
| You need shell features | Use `shell=True` with a fixed string only |
Exercise
A script runs subprocess.run(f"grep {term} log.txt", shell=True), where term comes from a web form. Rewrite the call so that term cannot inject commands, and say what extra step protects against a term such as -r.
Show answer
Use subprocess.run(["grep", "--", term, "log.txt"]). Passing a list with no shell means characters like ; are not interpreted, and term arrives at grep as a single argument. The -- marks the end of options, so a value such as -r is treated as the search pattern and not as an option. You can also validate term against an allowed pattern before the call.