5 rules for running subprocesses in Python without the injection risk
Tags: python · cybersecurity · development · shell
My teammate shut down a pipeline with a single prompt containing a parenthesis. Another stayed up all
night because a generated command contained backticks. Both were caused by the same one-line mistake:
handing untrusted text to a shell.
This is the classic shell=True mistake. It is also the reason I built shellguard .
If you run subprocesses in Python, read the five rules below. They are short and they will keep you
safe.
Rule 1 — Never pass a shell string built from text you do not trust
The moment you build a command as a string and ask the shell to interpret it, you have handed the shell
a program you did not write.
# DANGEROUS cmd = f "cd {dir} && run --model {model} {prompt}" subprocess . run ( cmd , shell = True )
Enter fullscreen mode
Exit fullscreen mode
A prompt containing ( makes bash abort with syntax error near unexpected token .…