GuardAPI Logo
GuardAPI

Fix Command Injection in Flask

Command injection in Flask is a high-impact RCE vector where unsanitized user input flows directly into system shell evaluators. If you are using os.system, os.popen, or subprocess with shell=True, you are effectively providing a remote terminal to any attacker. Stop concatenating strings for system calls.

The Vulnerable Pattern

from flask import Flask, request
import subprocess

app = Flask(name)

@app.route(‘/check_host’) def check_host(): target = request.args.get(‘target’) # CRITICAL VULNERABILITY: shell=True and f-string allow command chaining # Payload example: ?target=127.0.0.1; cat /etc/passwd cmd = f’ping -c 1 {target}’ output = subprocess.check_output(cmd, shell=True) return output

The Secure Implementation

The vulnerability occurs because 'shell=True' invokes /bin/sh to parse the command string, interpreting metacharacters like ';', '&', and '|'. By switching to a list of arguments (e.g., ['ping', '-c', '1', target]) and setting 'shell=False', the OS treats the entire 'target' variable as a single literal argument to the ping binary, preventing execution of injected commands. Always combine this with strict regex whitelisting to ensure the input conforms to expected patterns before it ever touches a subprocess call.

from flask import Flask, request, abort
import subprocess
import re

app = Flask(name)

@app.route(‘/check_host’) def check_host(): target = request.args.get(‘target’)

# 1. Strict Input Validation (Whitelisting)
if not target or not re.match(r'^[a-zA-Z0-9.-]+$', target):
    abort(400, 'Invalid hostname format')

# 2. Use Argument Lists and shell=False (Default)
# This bypasses shell interpretation entirely
try:
    result = subprocess.run(['ping', '-c', '1', target], 
                            capture_output=True, 
                            text=True, 
                            timeout=5, 
                            check=True)
    return result.stdout
except subprocess.CalledProcessError as e:
    return f'Error: {e.output}', 500</code></pre>
System Alert • ID: 4704
Target: Flask API
Potential Vulnerability

Your Flask API might be exposed to Command Injection

74% of Flask 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.