TExcelTAD
Home › Programming for Security: Python, Bash, PowerShell & C Tools › Running Commands Safely: subprocess and shell=True

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).

bash · try it yourself
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'
ls
unsafe    '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:

  1. The normal name works in every version.
  2. With shell=True, the shell split the string at ; and ran touch INJECTED and echo ran: the file appeared in the directory listing.
  3. Without a shell, the ; is harmless, but a name starting with - is still read as an option: wc printed 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.
  4. The safe version passes a list and puts -- before the untrusted argument. The whole string is one file name that does not exist, and --version is treated as a file name too. No INJECTED2 was 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.exec in Node. Bandit reports subprocess with shell=True as B602 and os.system as B605. Then trace whether any part of the string can come from a user.
  • At run time: process-creation logs (Linux auditd execve records, Sysmon event ID 1 and Windows event 4688 with command lines) showing a web or service account starting sh -c or cmd.exe /c with ;, &&, | 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

  1. Don't call a program when a library does the job. hashlib instead of sha256sum, ssl/cryptography instead of openssl x509, shutil instead of cp. No process, no injection.
  2. Pass a list, never a string, and never shell=True with outside data. Each untrusted value is one list element.
  3. 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 inside base stops ../.
  4. 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.
  5. 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 with stdin/stdout.
  6. Run with least privilege and a timeout (timeout= in subprocess.run), so that a bug that slips through does less harm.

Pitfalls

  • shlex.quote is for POSIX shells only. It does not protect cmd.exe, whose quoting rules differ; on Windows pass a list and avoid shell=True entirely.
  • A list with shell=True still 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_PRELOAD or GIT_SSH_COMMAND inherited from a request context can also change what runs. Pass env= explicitly for privileged wrappers and call programs by absolute path.
  • Error messages leak. Returning stderr to 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?

  1. The program named in cmd, directly
  2. /bin/sh -c with the string, so the shell interprets ;, |, $() and quotes
  3. A sandboxed copy of the command
  4. Python code

In the session, the list version without -- printed wc's version for the name --version. What is this called?

  1. Command injection
  2. Argument (option) injection
  3. Path traversal
  4. Buffer overflow

Which is the best fix for computing a file's SHA-256 inside a Python tool?

  1. subprocess.run(f"sha256sum {path}", shell=True)
  2. os.system("sha256sum " + path)
  3. hashlib.sha256 on the file's bytes
  4. subprocess.run("sha256sum " + shlex.quote(path)) without a list

Which log record most strongly suggests command injection on a web server?

  1. A 404 for /favicon.ico
  2. The web server account starting sh -c with ; and curl in its arguments
  3. A TLS handshake
  4. A successful login by an admin