Guide //
Command injection in Python: os.system, subprocess and shell=True
Why os.system and subprocess with shell=True let attackers run commands, how to fix them with argument lists, and how to test the fix.
The bug in one line
When a Python program builds a shell command from user input, a user can add their own commands. A filename like report; rm -rf ~ turns one command into two. The shell runs both.
import os
def archive(name):
# Vulnerable: name goes straight into a shell command
return os.system("tar -czf /backups/" + name + ".tar.gz /srv/data/" + name)Why it happens
os.system, os.popen, and subprocess calls with shell=True hand a single string to /bin/sh. The shell interprets ;, &&, |, $(...), backticks and more. Any of those characters in user input become instructions.
The fix: pass a list, skip the shell
Call the program directly with a list of arguments. Without a shell, there's nothing to interpret ; or $(...): each list item reaches the program as exactly one argument.
import subprocess
def archive(name):
result = subprocess.run(
["tar", "-czf", f"/backups/{name}.tar.gz", f"/srv/data/{name}"],
check=False,
)
return result.returncodeThree details worth knowing
- Leading dashes. A list stops shell injection, but a value starting with
-can still look like an option to the program. Validate names, or put--before them where the program supports it. - Return values change.
os.systemreturns an encoded wait status on Unix.subprocess.run(...).returncodereturns the plain exit code. Check whether callers rely on the exact number, and update them if they do. - `shlex.quote` is the fallback when you truly need a shell (pipes, globbing). Prefer removing the shell.
Test it
A good regression test intercepts the process call and checks that the attack text arrives as one argument, never as shell syntax. It should fail on the os.system version and pass on the list version.
import unittest
from unittest import mock
from app import backup
class ArchiveTest(unittest.TestCase):
def test_name_cannot_add_shell_commands(self):
with mock.patch("subprocess.run") as run, mock.patch("os.system") as system:
run.return_value.returncode = 0
backup.archive("nightly; rm -rf ~")
system.assert_not_called()
args = run.call_args.args[0]
self.assertIsInstance(args, list)
self.assertFalse(run.call_args.kwargs.get("shell", False))Let Mallace do it
Mallace finds command injection in Python (and in Node's child_process) by following user input to the shell. It writes a test like this one, proves it fails on your code, writes the argument-list fix, and opens a pull request with both. Scan your repository free.