DEV Community

Cover image for ๐Ÿš Command Injection: Stop Building Shell Strings (Python and Node)
Krishna Kumar
Krishna Kumar

Posted on

๐Ÿš Command Injection: Stop Building Shell Strings (Python and Node)

Most command injection bugs come from the same line of code: a string that mixes a program name, some flags, and a value from a user, handed to a shell. The shell reads the whole string, and anything in it that looks like syntax is syntax.

This article shows what that looks like in Python and Node, the two-layer fix (no shell, plus validation), the argument-injection gap that "no shell" alone leaves open, and how to prove the fix with a harmless marker instead of trusting a linter. I ran every snippet below locally, on stand-in data.

Only test applications you own or are authorized to test. The "target" here is a tiny script I wrote that pretends to be a legacy stock-report tool, and the only thing I inject is an echo.

What it is

OS command injection (also called shell injection) means user input ends up in a command your server runs, and it can change what that command does. It is CWE-78. The family also includes argument injection, CWE-88, where the input can't start a new command but can still add an option to the one you meant to run. OWASP's cheat sheet makes the point that every command injection is also an argument injection, which is why "we escaped the semicolon" isn't a fix.

PortSwigger's example is the classic one: a stock-check feature that calls a command-line tool with a product ID and a store ID. If the app builds the command as one string, an input like & echo something & becomes extra commands, because & is a command separator in the shell.

Where it shows up

You rarely find a field called "command". Look for features that wrap a command-line tool: image and PDF conversion, archive handling, ping or nslookup diagnostics, report generators, "run this script" admin pages, and anything that shells out to git or curl. In code review, grep for the calls that hand a string to a shell. In Python that is os.system, os.popen, and subprocess with shell=True. In Node it is exec and execSync.

A small script helps with the first pass. This one lists calls that need a human look, using only the standard library:

# find_shells.py - list calls that hand a string to a shell
import ast
import sys

SUBPROCESS = {"run", "call", "check_call", "check_output", "Popen"}


def findings(path):
    tree = ast.parse(open(path, encoding="utf-8").read(), path)
    for node in ast.walk(tree):
        if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
            continue
        owner = getattr(node.func.value, "id", "")
        name = node.func.attr
        if owner == "os" and name in {"system", "popen"}:
            yield node.lineno, f"os.{name}() always uses a shell"
        elif owner == "subprocess" and name in SUBPROCESS:
            for kw in node.keywords:
                if kw.arg == "shell" and not (
                    isinstance(kw.value, ast.Constant) and kw.value.value is False
                ):
                    yield node.lineno, f"subprocess.{name}(shell=...) - check the string"


if __name__ == "__main__":
    for path in sys.argv[1:]:
        for line, why in findings(path):
            print(f"{path}:{line}: {why}")
Enter fullscreen mode Exit fullscreen mode

Running it on the vulnerable code below prints one line, stock.py:14: subprocess.run(shell=...) - check the string. That line is a lead, not a finding. Bandit has checks in the same area (B602, B604 and B605 in its docs). No scanner tells you whether a user can reach that string. That part you prove.

The bug

Here is a stand-in tool. It takes a product ID and a store ID, and has a --debug flag, which I use later for the argument-injection case:

# stockreport.py - stand-in for a legacy command-line tool
import argparse

p = argparse.ArgumentParser()
p.add_argument("--debug", action="store_true")
p.add_argument("product")
p.add_argument("store")
a = p.parse_args()
if a.debug:
    print("DEBUG: internal paths and settings would print here")
print(f"stock for product={a.product} store={a.store}: 12 units")
Enter fullscreen mode Exit fullscreen mode

And the vulnerable wrapper, next to the fixed one, in one file:

# stock.py - the vulnerable version and the fixed one, side by side
import re
import subprocess
import sys
from pathlib import Path

TOOL = str(Path(__file__).with_name("stockreport.py"))
ID = re.compile(r"[0-9]{1,9}")


def check_stock_bad(product_id, store_id):
    # one string, parsed by a shell: & ; | $( ) and newlines are all syntax
    cmd = f"{sys.executable} {TOOL} {product_id} {store_id}"
    return subprocess.run(cmd, shell=True, capture_output=True, text=True).stdout


def check_stock(product_id, store_id):
    for value in (product_id, store_id):
        if not ID.fullmatch(value):
            raise ValueError("ids must be 1-9 digits")
    # a list, no shell: each item reaches the tool as exactly one argument,
    # and "--" ends option parsing so a value can never act as a flag
    argv = [sys.executable, TOOL, "--", product_id, store_id]
    done = subprocess.run(argv, capture_output=True, text=True, timeout=5, check=False)
    return done.stdout
Enter fullscreen mode Exit fullscreen mode

check_stock_bad is the bug: one f-string, shell=True. The Python docs are plain about the trade: subprocess doesn't choose a shell for you, so metacharacters can be passed safely as arguments, but if you invoke a shell yourself with shell=True, quoting all whitespace and metacharacters is your responsibility.

Prove it, safely

Send a control first, then one harmless marker. The control tells you what normal looks like. The marker is an echo of a made-up word: if the word comes back from a command you didn't write, input reached the shell. Here is the demo, and its output from my run:

# demo.py - control first, then one stand-in injection marker
import subprocess
import sys

from stock import TOOL, check_stock, check_stock_bad

print("control:      ", check_stock_bad("381", "29").strip())
print("marker:       ", check_stock_bad("381 & echo canary", "29").strip().replace("\n", " | "))
print("flag smuggled:", check_stock_bad("--debug 381", "29").strip().replace("\n", " | "))
print("fixed control:", check_stock("381", "29").strip())
for bad in ("381 & echo canary", "--debug 381"):
    try:
        check_stock(bad, "29")
    except ValueError as e:
        print(f"fixed {bad!r}: ValueError: {e}")

# the "--" layer on its own, with validation switched off: still just data
raw = subprocess.run([sys.executable, TOOL, "--", "--debug", "29"], capture_output=True, text=True)
print("'--' alone:   ", raw.stdout.strip())
Enter fullscreen mode Exit fullscreen mode
control:       stock for product=381 store=29: 12 units
marker:        canary 29
flag smuggled: DEBUG: internal paths and settings would print here | stock for product=381 store=29: 12 units
fixed control: stock for product=381 store=29: 12 units
fixed '381 & echo canary': ValueError: ids must be 1-9 digits
fixed '--debug 381': ValueError: ids must be 1-9 digits
'--' alone:    stock for product=--debug store=29: 12 units
Enter fullscreen mode Exit fullscreen mode

Read it line by line:

  • control: the normal answer.
  • marker: the output is canary 29. My injected echo canary ran, and the real tool received no product ID (its error went to stderr, which I don't capture). PortSwigger's page shows the same shape of result: the injected command runs and the original arguments get mangled.
  • flag smuggled: no shell metacharacter at all, just a space. The value --debug 381 was split by the shell into a flag plus the ID, and the tool printed its debug line. That's argument injection, and it works without any special character.
  • fixed control / fixed: the fix answers the control, and refuses both bad values before anything runs.
  • -- alone: with validation switched off but -- in place, --debug arrives as a plain product ID.

Left: a shell parses one string, so the marker runs and the tool never gets its ID. Right: a list, validation and the double dash keep every value as plain data.

I ran all of this on Windows (Python 3.14, Node 24), where shell=True and exec mean cmd.exe. & is a command separator there and in POSIX shells, which is why PortSwigger's example uses it, but I didn't run the vulnerable half on Linux, so treat the exact output as Windows output.

The fix: two layers

Layer 1: no shell, a list. Pass the program and each argument as separate list items. Nothing parses them, so each value reaches the tool as exactly one argument. That kills command injection. In check_stock above: [sys.executable, TOOL, "--", product_id, store_id].

Layer 2: validate the values, and end option parsing. A list doesn't stop --debug from being read as a flag by the tool. OWASP's guidance for this is to validate arguments against an allowlist (for example a regular expression that allows only digits, with a length cap) and to use -- to end option parsing where the command supports it. Mine does both. PortSwigger's list of strong validation includes allowlisting, checking for a number, and alphanumerics only, with no other syntax or whitespace.

What about escaping? PortSwigger says never to try to sanitize by escaping shell metacharacters, calling it error-prone and bypassable. OWASP lists escaping as a second-tier option, and itself notes the catch: even with escaping, an attacker can still pass a single argument, so you still need to control which one. shlex.quote exists, and the Python docs say it can be used for this on some platforms. I'd treat it as a last resort for the rare case where a shell is truly needed.

And if you can avoid the command, do. OWASP and PortSwigger both put "don't call OS commands from application code" first. If a library does the job (a PDF library instead of a CLI converter), use it.

The Node version

Node has the same split between a shell function and a no-shell function. The docs say exec spawns a shell and processes the command string directly, so special characters need handling. execFile doesn't spawn a shell by default and starts the file directly.

// stock.mjs
import { exec, execFile } from "node:child_process";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";

const TOOL = fileURLToPath(new URL("./stockreport.mjs", import.meta.url));
const run = promisify(execFile);
const sh = promisify(exec);

export async function checkStockBad(id) {
  // a template string handed to a shell
  const { stdout } = await sh(`"${process.execPath}" "${TOOL}" ${id}`);
  return stdout;
}

export async function checkStock(id) {
  if (!/^[0-9]{1,9}$/.test(id)) throw new RangeError("id must be 1-9 digits");
  // no shell by default: the id is one argv entry, whatever it contains
  const { stdout } = await run(process.execPath, [TOOL, id], { timeout: 5000 });
  return stdout;
}
Enter fullscreen mode Exit fullscreen mode

And the demo, with its output:

// demo.mjs
import { checkStock, checkStockBad } from "./stock.mjs";

console.log("control:      ", (await checkStockBad("381")).trim());
console.log("marker:       ", (await checkStockBad("381 & echo canary")).trim().replace(/\r?\n/g, " | "));
console.log("fixed control:", (await checkStock("381")).trim());
try { await checkStock("381 & echo canary"); } catch (e) { console.log("fixed marker: ", `${e.name}: ${e.message}`); }

// execFile alone, validation skipped: the hostile text stays one argument
import { execFile } from "node:child_process";
import { promisify } from "node:util";
const { stdout } = await promisify(execFile)(process.execPath, ["stockreport.mjs", "381 & echo canary"]);
console.log("execFile only:", stdout.trim());
Enter fullscreen mode Exit fullscreen mode
control:       argv received: ["381"]
marker:        argv received: ["381"] | canary
fixed control: argv received: ["381"]
fixed marker:  RangeError: id must be 1-9 digits
execFile only: argv received: ["381 & echo canary"]
Enter fullscreen mode Exit fullscreen mode

One trap: execFile and spawn with { shell: true } and an args array. Node's deprecation notice DEP0190 says the values aren't escaped, only joined with spaces, which can lead to shell injection. It's a documentation-only deprecation since v23.11.0 and v22.15.0 and a runtime deprecation since v24.0.0. The array looks safe and isn't.

Windows adds a wrinkle for both languages. The Python docs warn that .bat and .cmd files may be launched through a system shell regardless of what you pass, so arguments can be parsed by shell rules. Node's docs describe the same area for batch files. If you must launch one with untrusted input, validate harder, or avoid it.

Lock it in with a test

Make the hostile inputs permanent. This test sends eight of them through both parameters:

# test_stock.py - the regression test that keeps the fix honest
import unittest
from stock import check_stock

HOSTILE = [
    "381 & echo canary",
    "381; echo canary",
    "381 | echo canary",
    "$(echo canary)",
    "`echo canary`",
    "381\necho canary",
    "--debug",
    "381 --debug",
]


class StockTests(unittest.TestCase):
    def test_control_works(self):
        self.assertIn("stock for product=381 store=29", check_stock("381", "29"))

    def test_hostile_ids_are_rejected(self):
        for bad in HOSTILE:
            for args in ((bad, "29"), ("381", bad)):
                with self.subTest(args=args):
                    with self.assertRaises(ValueError):
                        check_stock(*args)


if __name__ == "__main__":
    unittest.main()
Enter fullscreen mode Exit fullscreen mode
test_control_works (test_stock.StockTests.test_control_works) ... ok
test_hostile_ids_are_rejected (test_stock.StockTests.test_hostile_ids_are_rejected) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.221s

OK
Enter fullscreen mode Exit fullscreen mode

I also pointed the same test at check_stock_bad. It failed with 16 failures, so the test goes red on the bug and green on the fix, which is the only reason to trust it.

Try it yourself

Practice on legal targets. PortSwigger's Web Security Academy has labs for this: OS command injection, simple case, Blind OS command injection with time delays and Blind OS command injection with output redirection. Then take any shell=True or exec( in your own code, write the control plus the marker, and see which answer comes back.

Conclusion

A shell is a parser, and every user value you put in its input is a vote on what the command means. Pass a list, validate each value, end option parsing with --, and then prove it: a control, a marker, and a test that fails on the old code. A linter hit on shell=True is where the work starts, and a marker that never comes back is the evidence you were looking for.

Further reading

I'm Krishna, a pentester and the founder of Xalgorix, an open-source AI pentester that only reports vulnerabilities it has actually exploited.


๐Ÿ” If this was useful, follow me for more hands-on web & API security write-ups.

๐Ÿ”— Connect with me on LinkedIn: https://www.linkedin.com/in/xalgord/

Top comments (0)