logo

Database

Python Command Injection In Shell Call

Description

Detects potential command injection vulnerabilities in Python code where shell commands are executed using os.popen or subprocess.Popen. When user-controlled input reaches these functions without proper sanitization, attackers could execute arbitrary system commands on the host.

Weakness:

004 - Remote command execution

Category: Unexpected Injection

Detection Strategy

    • Identifies calls to os.popen and subprocess.Popen functions in Python code

    • Checks if the command string parameter passed to these functions contains or is influenced by external input

    • Reports a vulnerability if unsanitized external data can reach the command execution functions

    • Common patterns include: command = user_input; os.popen(command) or subprocess.Popen(user_controlled_string, shell=True)

Vulnerable code example

from flask import request
import os
import subprocess

def process_address():
    address = request.args.get('address')
    cmd = f"ping -c 1 {address}"
    ...

✅ Secure code example

from flask import request
import subprocess
import shlex

def process_address():
    address = request.args.get('address')
    if not address:
        return...