Fix Command Injection in Pyramid
Pyramid applications are susceptible to Command Injection when request parameters are passed unsanitized to system-level execution functions. This typically happens when developers use `os.system`, `os.popen`, or `subprocess.run` with `shell=True`. An attacker can inject shell metacharacters (e.g., `;`, `&&`, `|`) to execute arbitrary code with the privileges of the web server process.
The Vulnerable Pattern
from pyramid.view import view_config
import subprocess
@view_config(route_name=‘check_host’, renderer=‘json’)
def check_host(request):
# VULNERABLE: User input is concatenated directly into a shell command
host = request.params.get(‘host’)
command = f”ping -c 1 {host}”
# shell=True triggers the system shell, allowing command chaining
result = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
return {"output": result.decode()}</code></pre>
The Secure Implementation
The vulnerability occurs because `shell=True` tells Python to spawn a subshell and interpret the string as a full command. By passing a list (e.g., ['ping', 'host']) and setting `shell=False`, the `subprocess` module passes the arguments directly to the `execvp` system call. This prevents the shell from interpreting characters like `;` or `>` as control operators. Additionally, implementing strict regex validation on the `host` parameter ensures that even if a logic flaw exists in the subprocess call, the input is restricted to safe characters.
from pyramid.view import view_config
import subprocess
import shlex
import re
@view_config(route_name=‘check_host’, renderer=‘json’)
def check_host_secure(request):
host = request.params.get(‘host’, ”)
# 1. Strict Validation: Only allow alphanumeric and dots
if not re.match(r"^[a-zA-Z0-9.-]+$", host):
return {"error": "Invalid hostname format"}
# 2. Secure Execution: Use a list of arguments and shell=False (default)
# This bypasses the shell interpreter entirely
cmd = ["ping", "-c", "1", host]
try:
result = subprocess.check_output(cmd, shell=False, stderr=subprocess.STDOUT, timeout=5)
return {"output": result.decode()}
except subprocess.CalledProcessError as e:
return {"error": "Host unreachable", "details": e.output.decode()}
except subprocess.TimeoutExpired:
return {"error": "Command timed out"}</code></pre>
Your Pyramid API
might be exposed to Command Injection
74% of Pyramid apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.