guides · 2026-11-14
Command Injection: shell=True, os.system and child_process.exec in Generated Code
Published 2026-11-14 · Reviewed 2026-11-14 · By the Ingenious AI team
The short answer
If user input is formatted into a shell command — os.system(f'convert {name}'), subprocess with shell=True, child_process.exec with a template string — the input stops being data and becomes commands, starting with ; cat .env. Never build shell strings from input: call the program with an argument array and shell=False, and validate any value that selects options against an allow-list.
Check your own app free: paste your code or enter your site URL on the Vibe-Code Audit homepage — the free scan checks for exposed secrets, injection flaws, XSS patterns, missing headers and exposed .env/.git paths, with a copy-paste fix for every finding. No credit card.
What is Command injection?
a flaw where attacker-controlled text is interpreted by a system shell as commands. Because the shell happily chains operators (; && | $() and backticks), one crafted filename or parameter can run arbitrary commands with the server process's privileges.
The feature shapes that hide it
Shell calls in generated apps cluster around media and file work: convert this image, render this PDF, zip these files, run this exporter, ping this host, process this video. The model reaches for the shell because tutorials do — os.system and exec one-liners are how quick scripts glue tools together. The input that reaches the command is usually a filename, a URL, a format option or a user ID — all 'not really user input' in the developer's mind and all fully attacker-controlled in fact. Vibe-Code Audit detects child_process.exec/execSync, os.system called with formatted or concatenated strings, and any shell=True — the three shapes that account for nearly every instance in AI-generated codebases.
Why quoting and escaping lose
Developers try to keep the shell and sanitise the input: wrap it in quotes, blacklist semicolons. This loses reliably — shells have too many metacharacters, quoting contexts nest, and one missed $() inside double quotes executes anyway. The structural fix removes the shell from the equation: subprocess.run(['convert', name, out], shell=False) passes name as one argument; even if it contains '; rm -rf /', it is a (weird) filename, not a command. The same holds for Node's execFile/spawn with argument arrays. If a value chooses flags or subcommands, it comes from a fixed allow-list mapping — user picks 'png', your code supplies '--format=png' — so user bytes never become syntax.
Also audit the second order: values stored earlier (a display name, a project title) that later flow into a backup or export command. Taint does not expire because it visited a database.
Finding every call site
Grep for exec, execSync, spawn with shell options, os.system, popen, subprocess with shell=True, backticks in shell-out contexts, and Runtime.exec in Java. For each, trace whether any fragment of the command string derives from request data, stored user data, filenames or environment values an attacker can set. Vibe-Code Audit's taint tracking accelerates exactly this: it follows untrusted input toward sinks and names the path, which matters because the dangerous call is often three functions away from the request handler that collected the input.
Where a shell pipeline is genuinely needed (rare), redesign into sequential argument-array calls with the data passed between your own processes — you keep the tools and lose the interpreter.
If it shipped
Command injection is full server compromise: assume credentials reachable from the process are burned (environment, .env, cloud metadata), rotate them, and review the host for persistence — new cron entries, SSH keys, modified binaries. The app-level fix prevents recurrence; it does not evict an intruder who already ran commands. For small apps on managed hosts, the honest remediation is often rebuild-the-environment, restore-the-app, rotate-everything — in that order.
Argument injection: the echo of the bug after the shell is gone
Removing the shell closes command injection but leaves its quieter sibling: argument injection. When user input becomes an argument to a powerful tool, a value that starts with a dash can be parsed as the tool's own flag — an 'image filename' of --write=/etc/cron.d/x handed to a converter, or an email field interpreted as a sendmail option. Generated code that dutifully switched to argument arrays often still interpolates user values into the flag positions. The defences are mechanical: place a '--' end-of-options marker before user-supplied file arguments where the tool supports it, validate values against the shape they should have (an ID is digits; a filename extension is from a list), and prefer passing sensitive content via stdin or a config file your code writes, rather than as command-line text at all. Then keep the taint question alive in review: not just 'does input reach a shell?' but 'does input reach a position where a program will interpret it?'
Worked example: ClipForge, a video-thumbnail service
ClipForge (fictional), processing about 11,000 thumbnails a month, built its converter on child_process.exec with the uploaded filename interpolated into the command. A scan reported command injection as HIGH with a taint path from the upload handler to the exec call. The team reproduced it in staging with a filename containing '; touch /tmp/pwned #' — the marker file appeared. The converter moved to execFile with an argument array, filenames became server-generated UUIDs (original names kept as metadata only), and format choices moved to an allow-list. The marker-payload test now runs in CI against every media endpoint.
Your five-action checklist
- Grep for os.system, shell=True, child_process.exec/execSync, popen and backtick shell-outs; list every call site.
- Trace each command for fragments derived from requests, filenames, stored user data or headers — including second-order flows.
- Convert every call to an argument-array form with shell=False / execFile, so input is data, never syntax.
- Route any user-selected options through a fixed allow-list mapping; never interpolate choices into command text.
- Add a marker-file injection probe ('; touch /tmp/probe #') to your tests for every media/file feature, and re-scan.
Sources
- CWE-89: Improper Neutralization of Special Elements used in an SQL Command, MITRE's weakness entry for SQL injection and its mitigations: cwe.mitre.org, 2026
- PortSwigger Web Security Academy — SQL injection, the reference tutorial on how SQL injection works and how parameterized queries prevent it: portswigger.net, 2026
- OWASP Top 10, the OWASP Foundation's standard awareness list of the most critical web application security risks: owasp.org, 2021
Frequently asked questions
If I escape the input carefully, can I keep the shell string?
History says no: shell quoting has too many contexts and metacharacters, and each future edit must preserve your escaping perfectly. Argument arrays make the safe thing the easy thing — switch.
Is spawn/execFile with user arguments fully safe?
It removes shell interpretation. You must still watch argument injection: a value beginning with '-' can be parsed as a flag by the target program. Use '--' separators where supported and allow-list option-like inputs.
Our command runs a fixed string with no input. Still a finding?
A truly constant command is low risk, but scanners flag the shape because the next edit adds a variable. Moving to argument arrays anyway keeps the pattern clean for future code — including AI-generated code that copies your style.
Why are filenames treated as attacker input?
Because uploaders choose them. Filenames carry spaces, quotes and shell metacharacters by design of the attack, and generated code interpolates them constantly. Generate storage names server-side; keep original names as display metadata.
Related guides
- Mass Assignment: How Passing req.body to Your Model Lets Users Promote Themselves
- Open Redirects: How Your Real Domain Becomes Someone Else's Phishing Link
- Prompt-Injection Sinks: The Exact Code Shapes That Let Text Become Instructions
- When LLM Output Is Rendered as HTML: The Stored XSS Nobody Escaped
- RAG Poisoning: How One Planted Document Rewrites Your Chatbot's Answers
- Production Source Maps: You Are Probably Shipping Your Original Source Code
- 7 Security Mistakes AI Coders Keep Making
- Supply-Chain Attacks in the AI-Coding Era
- Secret Hygiene: Stop API Key Leaks
- What Code Scanners Can't Find
- Bolt.new Pre-Deploy Security Checklist
- Cursor-Generated Code Review Checklist
Browse the full library on the guides index, run the checks in the launch audit, or compare plans on pricing.
Informational explainer, not a security guarantee. Scan your code free before every deploy.