TExcelTAD

OS Command Injection

Some web features are thin wrappers around a command-line tool: a "ping this host" page on a router, a thumbnail generator calling ImageMagick, a "line count" for uploaded reports, a PDF export through a converter. If the application builds the command as one string and hands it to a shell, the shell interprets the user's input as shell syntax, and a ; or $( ) in a form field runs any command the web server's account may run. OS command injection (CWE-78) is usually critical: it gives the attacker the server, not just its data. Running Commands Safely showed the mechanism in a script; this lesson shows it in a web endpoint, with what the logs and the process tree reveal, and the fixed endpoint.

Definitions

  • Shell metacharacters: ; and &&/|| (command separators), | (pipe), `…` and $(…) (command substitution), > < (redirection), & (background), newline, and in Windows cmd.exe also & and ^.
  • Shell invocation: subprocess.run(cmd_string, shell=True) in Python, os.system, popen, PHP's system/exec/shell_exec/backticks, Node's child_process.exec, Java's Runtime.exec("sh -c …").
  • Argument vector: subprocess.run(["wc", "-l", name]), Node's execFile/spawn without shell: true: the program receives the list as-is; no shell parses it.
  • Argument injection: even without a shell, a value starting with - can be read as an option (--output=/etc/…, -o ProxyCommand=… for ssh). Fixed by -- (end of options) and validation.

A vulnerable endpoint and its fix

The app, started on 127.0.0.1 in your sandbox, serves /count?file=…: it counts lines of a report in its own reports/ directory. The vulnerable version builds a shell command. The payloads only run harmless commands (id, echo) that print who the server runs as and prove execution; everything stays inside the sandbox.

bash · try it yourself
mkdir -p reports && printf 'q1\nq2\nq3\n' > reports/sales.txt
cat > app.py <<'PY'
import re, subprocess, sys
from urllib.parse import parse_qs
from wsgiref.simple_server import make_server, WSGIRequestHandler

FIXED = sys.argv[1] == "fixed"
NAME = re.compile(r"^[A-Za-z0-9_-]{1,40}\.txt
quot;) class Quiet(WSGIRequestHandler): def log_message(self, *args): pass def app(environ, start_response): name = parse_qs(environ.get("QUERY_STRING", "")).get("file", [""])[0] if not FIXED: cmd = f"wc -l reports/{name}" out = subprocess.run(cmd, shell=True, capture_output=True, text=True) # BUG with open("commands.log", "a") as log: log.write(f"sh -c {cmd!r}\n") status, body = "200 OK", out.stdout + out.stderr elif not NAME.fullmatch(name): status, body = "400 Bad Request", "invalid file name\n" else: out = subprocess.run(["wc", "-l", "--", f"reports/{name}"], capture_output=True, text=True) status, body = ("200 OK", out.stdout) if out.returncode == 0 else ("404 Not Found", "no such report\n") start_response(status, [("Content-Type", "text/plain")]) return [body.encode()] make_server("127.0.0.1", 8000, app, handler_class=Quiet).serve_forever() PY req() { printf ' %-34s -> ' "$1"; curl -s -G -w '[%{http_code}]\n' --data-urlencode "file=$1" http://127.0.0.1:8000/count | tr '\n' ' '; echo; } for mode in vulnerable fixed; do python3 app.py $mode & for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8000/ && break; sleep 0.1; done echo "=== $mode" req 'sales.txt' req 'sales.txt; id -un' req 'x.txt || echo injected-$((6*7))' req '$(echo sales).txt' req '../app.py' kill %1; wait 2>/dev/null done echo "=== what the vulnerable app actually ran" cat commands.log
=== vulnerable
  sales.txt                          -> 3 reports/sales.txt [200]
  sales.txt; id -un                  -> 3 reports/sales.txt learner [200]
  x.txt || echo injected-$((6*7))    -> injected-42 wc: reports/x.txt: No such file or directory [200]
  $(echo sales).txt                  -> 3 reports/sales.txt [200]
  ../app.py                          -> 28 reports/../app.py [200]
=== fixed
  sales.txt                          -> 3 reports/sales.txt [200]
  sales.txt; id -un                  -> invalid file name [400]
  x.txt || echo injected-$((6*7))    -> invalid file name [400]
  $(echo sales).txt                  -> invalid file name [400]
  ../app.py                          -> invalid file name [400]
=== what the vulnerable app actually ran
sh -c 'wc -l reports/'
sh -c 'wc -l reports/sales.txt'
sh -c 'wc -l reports/sales.txt; id -un'
sh -c 'wc -l reports/x.txt || echo injected-$((6*7))'
sh -c 'wc -l reports/$(echo sales).txt'
sh -c 'wc -l reports/../app.py'

In the vulnerable mode each payload ran: id -un printed the account name, the arithmetic $((6*7)) came back as 42 (proof that the shell evaluated the input), command substitution rebuilt the file name, and ../app.py counted the lines of the application's own source, a path traversal for free. The log shows each whole shell command the application handed to sh -c (the first line, with an empty name, is the session's own readiness check). The fixed version passes an argument list (no shell), refuses any name that isn't a plain .txt file name, and puts -- before the path so a name can never become an option. Every payload became a 400.

How command injection is detected

  • Code review: shell=True, os.system, popen, exec( in PHP, child_process.exec, backticks; any command string built with +, %, f-strings or template literals. Bandit (B602, B605), Semgrep and CodeQL flag them.
  • Testing (in scope): inject separators and substitutions with a harmless, observable effect: ;echo t3st-$((7*6)) (look for t3st-42), |id, `id`, or a time delay (;sleep 5) when output isn't shown. For blind cases, testers use out-of-band callbacks to their own lab listener.
  • Logs: request parameters containing ;, |, `, $(, &&, %0a, /bin/sh, wget, curl.
  • Runtime (often the best signal): the web server process spawning a shell or unusual children (sh → id, sh → curl, python → bash). EDR tools and Linux auditd (execve events with the web server's uid as parent) catch this regardless of how the payload was encoded; Falco's default rules include one for a shell spawned by a web server process, and Sysmon for Linux records the process-creation events such a rule needs.

How it is fixed

  1. Don't call a program at all when a library does the job (count lines in Python, resize images with a library, resolve names with socket.getaddrinfo).
  2. If you must, pass an argument list without a shell, and put -- before user-supplied operands.
  3. Validate with an allow-list (file names from a fixed pattern, host names against a regex, or better, choose from a server-side list by id).
  4. Run the service as an unprivileged account in a container or sandbox (seccomp, no shell in the image, read-only filesystem), so a missed injection has little to work with.

Pitfalls

  • shlex.quote everywhere works for POSIX shells but is easy to forget once and doesn't protect against option injection; argument lists are simpler.
  • Blocklists of characters miss newline (%0a), $IFS tricks and Windows-specific syntax.
  • Windows cmd.exe parses arguments differently from POSIX shells: even argument lists can be re-parsed when the target is a .bat file (a class of bugs fixed in several language runtimes in 2024).

Practice

1. A PHP page runs system("ping -c 1 " . $_GET['host']). Write the fix in prose.

Validate host as an IP address or host name (filter_var($host, FILTER_VALIDATE_IP) or a strict regex), then run ping without a shell: proc_open(['ping', '-c', '1', '--', $host], …) (PHP 7.4+ accepts an array, which skips the shell). Better: does the feature need to exist?

2. The output of the command is never shown to the user. How would you test for injection, and how would a defender see it?

Time-based (;sleep 5 and compare with a baseline) or an out-of-band callback to a listener you control in the lab. Defenders see it in process telemetry: the web server spawning sh and sleep, or outbound connections from the server.

Test yourself

What makes subprocess.run(f"wc -l reports/{name}", shell=True) injectable?

  1. wc is unsafe
  2. A shell parses the whole string, so metacharacters in name become shell syntax
  3. The f-string is slow
  4. capture_output

Why did the fixed version add -- before the path?

  1. For readability
  2. So a value starting with - can't be read as an option (argument injection)
  3. It is required by wc
  4. To disable the shell

Which runtime signal catches command injection however the payload was encoded?

  1. A WAF regex
  2. The web server process spawning a shell or unexpected child processes
  3. HTTP 200 responses
  4. Long URLs

In the session, how did the payload x.txt || echo injected-$((6*7)) prove execution?

  1. It deleted a file
  2. The response contained injected-42: the shell evaluated the arithmetic
  3. It returned 500
  4. It printed the source