Vulnerability class

Command injection in Python

Command injection is a flaw where data an attacker controls ends up in an operating-system command the program runs, so the attacker gets to run commands of their own with the program's privileges.

CWE
CWE-78, CWE-88
OWASP
A05:2025 Injection
Tag
command injection, critical impactargument injection, high impact
On this page

How it shows up in Python

The classic shape is a shell command assembled from a string. A Flask route that converts an uploaded image by name:

import subprocess
from flask import request

@app.post("/thumbnail")
def thumbnail():
    name = request.form["name"]
    subprocess.run(f"convert uploads/{name} -resize 200x200 thumbs/{name}", shell=True, check=True)
    return "ok"

A name that contains ; followed by a second command runs that command too, as the web server's user. os.system(), os.popen() and subprocess with shell=True all hand the whole string to /bin/sh, which treats ;, |, $( ) and backticks as syntax.

The fix is to skip the shell and pass a list. Each element reaches the program as exactly one argument, and nothing in it is interpreted:

import re
import subprocess
from flask import request, abort

SAFE_NAME = re.compile(r"[A-Za-z0-9_.]{1,64}")

@app.post("/thumbnail")
def thumbnail():
    name = request.form["name"]
    if not SAFE_NAME.fullmatch(name) or name.startswith("."):
        abort(400)
    subprocess.run(["convert", "--", f"uploads/{name}", "-resize", "200x200", f"thumbs/{name}"], check=True)
    return "ok"

A list is not the whole answer. If an element starts with -, many programs read it as an option, which is argument injection: a "filename" that is really an option flag changes what the command does without any shell. Validate the shape, reject a leading dash, and put -- before positional arguments when the program supports it. If you genuinely need a shell, shlex.quote() each value, and still prefer a list.

The same bug exists one hop away. paramiko's exec_command() sends a string to a remote shell, so client.exec_command(f"tar czf /backup/{tenant}.tgz /data/{tenant}") is command injection on the remote host.

Why it is hard to see

  • Aliases and dispatch tables. run = os.system then run(cmd), or ACTIONS = {"run": os.system} then ACTIONS[name](arg), or getattr(os, fn)(arg) with both parts from a request. Rules that match a literal os.system( call do not see these, and a static tool cannot prove which function a runtime key selects.
  • A custom parser in between. Data decoded by a hand-written binary or text parser before it reaches the command. Taint tracking that only follows data through libraries it knows loses it at the parser.
  • A successful injection does not crash. A coverage-guided fuzzer looks for crashes and new code paths. subprocess.run("convert " + arg, shell=True) with an injected ; echo exits 0, so the fuzzer has nothing to report.
  • Workers with no web request. A job pulled from a queue builds a command from the message. Tools scoped to the HTTP request lifecycle never look at it.
  • The sandbox dilemma. A system-call filter sees execve and a path, not the command string. It can block every command (and break the legitimate ones) or allow them all.

What the es-python event looks like

es-python reports when untrusted data reaches a command, at the call that would run it: os system for os.system(), subprocess exec and os spawn for subprocess (which os.popen() uses too), os execv and os execve for the exec family, and command injection for paramiko's exec_command(). These carry the command injection impact tag.

When the shape of the command says more, a sharper label is added beside the base event:

Label What it means
subprocess shell the program ran sh -c and the command string was untrusted: the shell=True shape
shell injection an untrusted argument contains a shell metacharacter
argument injection an untrusted argument starts with -, so the program may read it as an option
env injection an untrusted value reached the new process's environment
path hijack that environment value was a variable the loader consults, such as PATH

argument injection also fires on a value that legitimately starts with a dash, such as a negative number, so read it as "check this argument", not as a verdict.

The severity comes from where the data came from: network data reaching a command is Critical, and the same command fed from the program's own command line is Info, because whoever typed that line could run the command anyway. Under a Raise rule, the program gets a RuntimeError at the call; Report and Raise says exactly when it is raised.

The fixed version above still hands request data to a program, so es-python still records the base subprocess exec event for it. What changes is the shape: no subprocess shell, and with the validation in place no shell injection or argument injection. When EyalSec can prove the value could not break out of its argument, the event is suppressed rather than shown.

How to fix and prevent it

  1. Skip the shell: no shell=True, no os.system(), no os.popen(). Pass an argument list.
  2. Prefer a library call to a command. shutil, tarfile, Pillow and the zipfile module replace most cp, tar, convert and unzip invocations.
  3. Validate every untrusted argument against the shape you expect, reject a leading -, and use -- where the program supports it.
  4. Keep untrusted values out of the child's environment.
  5. Run es-python in Report mode with the socket source on, find every command that receives request data, then raise on subprocess shell first: it is the shape that is almost never intended.

Classification

Command injection is CWE-78, Improper Neutralization of Special Elements used in an OS Command; the option-injection variant is CWE-88, Argument Injection. OWASP maps both to A05:2025 Injection.

Questions people ask

The questions that come up on forums and in reviews about this class, each answered in a few sentences.

Is subprocess with a list always safe?

A list keeps the shell out, so metacharacters in an argument cannot start a second command, and that removes the common case. An argument that begins with a dash can still be read as an option by the program you call, and a program that runs its arguments through another shell, such as ssh, reintroduces the problem on the far side. es-python labels the first shape argument injection and the shell shape subprocess shell, so you see which one reached the call.

Is shlex.quote enough to make shell=True safe?

No: shlex.quote() is for POSIX shells only and protects a single word, so it does nothing on Windows, nothing for a value placed where the shell expects an option, and nothing once the string is parsed again by a second program. Passing a list without a shell removes the quoting problem instead of patching it. Keep shlex.quote() for the one case where a shell is unavoidable, and validate the value as well.

How do I detect command injection at runtime in Python?

Run the program with es-python and it reports every command built from untrusted data at the call that would run it, with the value, its source and the stack trace, labelled by shape: subprocess shell, shell injection or argument injection. The severity follows the source, so request data reaching a command is Critical and the program's own command line is Info. A Raise rule stops the call with a Python RuntimeError before the command runs.

Watch for Command injection in your own code

es-python runs your Python application unchanged and reports when untrusted data reaches the operation, with where the data came from and the line that used it. Ask to see it on your own application.

EyalSec Pricing Docs Security Research Vulnerabilities Play Security glossary About Contact עברית Login Get started Protect my Python app