Running Commands Safely: subprocess and shell=True
Security tools often wrap other tools: a Python script calls openssl, nmap, tshark or sha256sum and parses what they print. The moment any part of that command line comes from outside (a file name from an upload, a host name from a ticket, a field from a log), the wrapper can become a command-injection vulnerability: the attacker's text is run as a command, with the tool's privileges. OWASP Top 10 2025 files this under A05 Injection, and MITRE's 2025 CWE Top 25 ranks OS command injection (CWE-78) ninth; internal tools and admin panels are a typical place to find it. This lesson shows the mechanism inside a sandbox, then the fix.
The session runs in your sandbox, as an unprivileged user with no network; the only "victim" is a file in its own working directory.
Definitions
subprocess.run(args): start a program and wait for it. With a list of arguments, Python calls the program directly (execve): every list item is one argument, and no shell interprets anything.shell=True: Python runs/bin/sh -c "<your string>". The shell then interprets;,|,&&,$(...), backticks,>, globs and quotes in the string.- Command injection: attacker-controlled text reaches a shell and adds commands.
- Argument injection: no shell, but attacker text that starts with
-is taken by the program as an option. The fix is--, which most tools read as "end of options". shlex.quote(s): wraps a string in single quotes so the shell treats it as one literal word; only for the rare case where a shell is unavoidable.
The mechanism
A small "line counter" service takes a file name and runs wc -l on it. The first version builds a shell string. The attacker's "file name" contains a ; and a second command, which creates a marker file to prove it ran (in a real attack it would be anything the account may do).
mkdir -p uploads && printf 'a\nb\nc\n' > uploads/notes.txt
cat > count.py <<'PY'
import subprocess, sys
def count_unsafe(name):
r = subprocess.run(f"wc -l uploads/{name}", shell=True, capture_output=True, text=True)
return (r.stdout + r.stderr).strip()
def count_list_no_dashes(name):
r = subprocess.run(["wc", "-l", name], capture_output=True, text=True, cwd="uploads")
return (r.stdout + r.stderr).strip().splitlines()[0]
def count_safe(name):
r = subprocess.run(["wc", "-l", "--", name], capture_output=True, text=True, cwd="uploads")
return (r.stdout + r.stderr).strip()
mode, name = sys.argv[1], sys.argv[2]
print(f"{mode:<9} {name!r:<34} -> {globals()['count_' + mode](name)}")
PY
python3 count.py unsafe 'notes.txt'
python3 count.py unsafe 'notes.txt; touch INJECTED; echo ran'
ls
python3 count.py list_no_dashes '--version'
python3 count.py safe 'notes.txt; touch INJECTED2'
python3 count.py safe '--version'
lsunsafe 'notes.txt' -> 3 uploads/notes.txt
unsafe 'notes.txt; touch INJECTED; echo ran' -> 3 uploads/notes.txt
ran
INJECTED
count.py
uploads
list_no_dashes '--version' -> wc (GNU coreutils) 9.4
safe 'notes.txt; touch INJECTED2' -> wc: 'notes.txt; touch INJECTED2': No such file or directory
safe '--version' -> wc: --version: No such file or directory
INJECTED
count.py
uploads
Read the four cases in order:
- The normal name works in every version.
- With
shell=True, the shell split the string at;and rantouch INJECTEDandecho ran: the file appeared in the directory listing. - Without a shell, the
;is harmless, but a name starting with-is still read as an option:wcprinted its version instead of counting. For other programs an option can mean "read this other file" or "run this program" (--files0-from=,-o ProxyCommand=,--use-compress-program=), so argument injection can be as bad as command injection. - The safe version passes a list and puts
--before the untrusted argument. The whole string is one file name that does not exist, and--versionis treated as a file name too. NoINJECTED2was created.
How it is detected
- In code review and static analysis:
shell=True,os.system(,os.popen(,subprocess.getoutput(,commands., backticks in Perl/Ruby,Runtime.exec(String)in Java,child_process.execin Node. Bandit reportssubprocesswithshell=Trueas B602 andos.systemas B605. Then trace whether any part of the string can come from a user. - At run time: process-creation logs (Linux
auditdexecverecords, Sysmon event ID 1 and Windows event 4688 with command lines) showing a web or service account startingsh -corcmd.exe /cwith;,&&,|or$(in the arguments, or unusual children (curl,bash,nc) under a web server process. - In tests: put
;,|,$(id), a leading-, spaces and quotes into every argument the tool accepts, as the session does.
How it is fixed
- Don't call a program when a library does the job.
hashlibinstead ofsha256sum,ssl/cryptographyinstead ofopenssl x509,shutilinstead ofcp. No process, no injection. - Pass a list, never a string, and never
shell=Truewith outside data. Each untrusted value is one list element. - Put
--before untrusted arguments (and check that the program honours it), or validate that they do not start with-. For paths,os.path.join(base, name)plus a check that the resolved path stays insidebasestops../. - Validate against an allowlist where the format is known: a host name matches
^[a-z0-9.-]{1,253}$, a port is an integer 1–65535. - If a shell is truly required (a pipeline), build it from constants and insert data only through
shlex.quote(). Prefer running the pipeline steps as separate list commands connected withstdin/stdout. - Run with least privilege and a timeout (
timeout=insubprocess.run), so that a bug that slips through does less harm.
Pitfalls
shlex.quoteis for POSIX shells only. It does not protectcmd.exe, whose quoting rules differ; on Windows pass a list and avoidshell=Trueentirely.- A list with
shell=Truestill uses a shell: on POSIX the first item becomes the script and the rest become$0 $1 …. Don't combine them. - Environment variables such as
PATH,LD_PRELOADorGIT_SSH_COMMANDinherited from a request context can also change what runs. Passenv=explicitly for privileged wrappers and call programs by absolute path. - Error messages leak. Returning
stderrto the user, as the example does for teaching, reveals paths and versions; log it instead.
Practice
1. Rewrite subprocess.run(f"openssl x509 -in {path} -noout -enddate", shell=True) safely.
subprocess.run(["openssl", "x509", "-noout", "-enddate", "-in", path], capture_output=True, text=True, timeout=10). Because path follows -in as that option's value, a leading - is not taken as an option here, but checking that the resolved path is inside the expected directory is still wise. Better still: load the certificate with cryptography.x509 and read not_valid_after_utc (cryptography 42 and later; older releases call it not_valid_after).
2. Which of these inputs injects a command into sh -c "ping -c 1 " + host: 10.10.0.1, 10.10.0.1;id, $(id), `id`, 10.10.0.1 -c 999?
10.10.0.1;id, $(id) and `id` run id. 10.10.0.1 -c 999 is argument injection (it changes ping's behaviour without a second command). Only the first is clean. A list plus a strict IP-address check (ipaddress.ip_address(host)) fixes all of them.
3. Why is shlex.quote enough for '; touch X' but validation is still recommended?
Quoting makes the shell pass the string as one argument, so no command runs. But the program receiving it may still treat a leading - as an option or the value as a path outside the intended directory. Quoting solves the shell layer only.
Test yourself
What does subprocess.run(cmd, shell=True) actually execute?
- The program named in cmd, directly
- /bin/sh -c with the string, so the shell interprets ;, |, $() and quotes
- A sandboxed copy of the command
- Python code
In the session, the list version without -- printed wc's version for the name --version. What is this called?
- Command injection
- Argument (option) injection
- Path traversal
- Buffer overflow
Which is the best fix for computing a file's SHA-256 inside a Python tool?
subprocess.run(f"sha256sum {path}", shell=True)os.system("sha256sum " + path)hashlib.sha256on the file's bytessubprocess.run("sha256sum " + shlex.quote(path))without a list
Which log record most strongly suggests command injection on a web server?
- A 404 for /favicon.ico
- The web server account starting
sh -cwith;andcurlin its arguments - A TLS handshake
- A successful login by an admin