GuardAPI Logo
GuardAPI

Fix Command Injection in CherryPy

Command injection in CherryPy occurs when untrusted user input is passed directly to system shells (e.g., via os.system, os.popen, or subprocess.run with shell=True). This allows an attacker to append arbitrary OS commands, leading to full Remote Code Execution (RCE) on the server. To fix this, you must avoid shell invocation and treat user input as data, not executable code.

The Vulnerable Pattern

import cherrypy
import os

class VulnerableApp: @cherrypy.expose def index(self, hostname): # CRITICAL: hostname is concatenated directly into a shell command # Attack: hostname=; cat /etc/passwd stream = os.popen(f’nslookup {hostname}’) return stream.read()

if name == ‘main’: cherrypy.quickstart(VulnerableApp())

The Secure Implementation

The fix involves two layers of defense. First, replace dangerous functions like os.popen() with the subprocess module. By passing command arguments as a list (e.g., ['nslookup', hostname]) and ensuring shell=False, the OS treats the user input as a literal string argument rather than a command to be parsed by /bin/sh or cmd.exe. This effectively neutralizes shell metacharacters like ';', '&', and '|'. Second, implement strict input validation using regex or type-checking to ensure the input conforms to expected formats before it ever reaches the execution layer.

import cherrypy
import subprocess
import ipaddress

class SecureApp: @cherrypy.expose def index(self, hostname): # 1. Strict Input Validation (Whitelisting) # Forcing input to be a valid IP or simple hostname if not hostname.isalnum() and ’.’ not in hostname: raise cherrypy.HTTPError(400, ‘Invalid Input’)

    # 2. Use subprocess.run with a list and shell=False (Default)
    # This treats 'hostname' as a literal argument, not a shell command
    try:
        result = subprocess.run(
            ['nslookup', hostname],
            capture_output=True,
            text=True,
            check=True,
            timeout=5
        )
        return result.stdout
    except subprocess.CalledProcessError as e:
        return f'Error: {e.stderr}'

if name == ‘main’: cherrypy.quickstart(SecureApp())

System Alert • ID: 1146
Target: CherryPy API
Potential Vulnerability

Your CherryPy API might be exposed to Command Injection

74% of CherryPy apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.