Your subprocess call is a shell injection waiting to happen
A few weeks ago a build script of mine died with a bash syntax error. The command looked harmless: prompt = "compute (17*23) and print it" subprocess.run(f"echo {prompt}", shell=True) Bash saw (17*23) and tried
A few weeks ago a build script of mine died with a bash syntax error. The command looked harmless:
prompt = "compute (17*23) and print it"
subprocess.run(f"echo {prompt}", shell=True)
Bash saw (17*23) and tried to parse a subshell. The script aborted. Worse: if that string had come from a user, `rm -rf ~` would have executed.
This is the single most common way Python code accidentally becomes an attack surface. shell=True plus an f-string is a remote code execution primitive dressed up as convenience.
The usual advice, and why it is not enough
"Use a list, never shell=True." Correct, and still incomplete:
subprocess.run(["echo", "(17*23)"]) # safe
subprocess.run(["sh", "-c", user_input]) # back to square one
The moment you legitimately need a shell — pipes, globs, a tool that only speaks shell — you are back to building a string. And building a shell string by hand is where people get it wrong.
What actually goes wrong
MSYS/git-bash on Windows expands * and ~ in argv before your program sees them. shlex.quote protects against the shell, but not against a layer that rewrites arguments before the shell runs. Quoting rules differ between cmd.exe, PowerShell, and POSIX sh. A single ! can trigger history expansion in an interactive shell.
I wrote shellguard to make this boring:
import shellguard as sg
sg.run(["echo", "(17*23)"]) # -> '(17*23)\n'
sg.run(["echo", "`echo INJECTED`"]) # -> literal text, nothing executed
Zero dependencies. It builds the command line correctly for the shell you are actually targeting, and it refuses to silently interpolate untrusted data into a shell string.
The part I care about most
The test suite is 26 real attack cases. Not mocked. Each test spawns an actual subprocess and asserts on the real exit code and real stdout:
- command substitution with backticks and
$() - chained commands with
;,&&,|| - glob and tilde expansion under MSYS
- newline and carriage-return injection
- quote-breaking with mixed
'and"
If a payload executes, the test fails. That is the only assertion that matters for a security library.
Try it
- Library: https://github.com/derbaroser-eng/shellguard-lib
- Docs and examples: https://derbaroser-eng.github.io/shellguard/
If you have ever written f"grep {user_input} file.txt", this is for you.
What is the worst shell-quoting bug you have shipped? I would genuinely like to know — the test suite grows from real incidents.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.