HIGH command injectionflaskbearer tokens

Command Injection in Flask with Bearer Tokens

Command Injection in Flask with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Command Injection occurs when an attacker can inject and execute arbitrary system commands on the host. In Flask APIs that use Bearer Tokens for authentication, the combination of dynamic input from HTTP headers and unsafe subprocess invocation can expose these vulnerabilities. A common pattern is reading the Authorization header (e.g., request.headers.get("Authorization")), validating or extracting a token, and then using data from the request — such as a filename or user-controlled parameter — in a shell command constructed via string interpolation. Because the API may treat the Bearer Token as trusted metadata, developers sometimes mistakenly believe that authentication alone prevents command injection, but authentication and input validation are separate concerns.

Consider a Flask endpoint that accepts a filename via query or body and passes it to a shell utility like tar or grep. If the developer builds the command using Python string formatting, an attacker-supplied filename such as ; cat /etc/passwd or $(id) can lead to arbitrary command execution. The presence of a Bearer Token does not sanitize this input. In some designs, the token is forwarded to downstream services or used in logging; if those logs or downstream calls incorporate unchecked data into shell commands, the token’s context may inadvertently aid privilege escalation or data exfiltration. Moreover, an unauthenticated LLM endpoint or SSRF-related misconfiguration can complement weak input validation, increasing the attack surface when tokens are handled inconsistently across services.

middleBrick’s security checks include Input Validation and Unsafe Consumption scans that can detect command construction patterns and unsafe subprocess usage even when Bearer Tokens are present. These scans run in parallel across 12 checks, including Authentication and BOLA/IDOR, to highlight where trust boundaries are misaligned. For example, a scan might flag a route that uses subprocess.run with user data despite requiring a Bearer Token, indicating that authentication is not a substitute for strict input validation and output encoding.

Bearer Tokens-Specific Remediation in Flask — concrete code fixes

Remediation focuses on never passing untrusted data to a shell, regardless of authentication state. Use parameterized APIs such as subprocess.run with a list of arguments and shell=False (the default). Avoid constructing shell commands via string interpolation. Additionally, treat Bearer Tokens as opaque values; do not embed them into commands or logs that include user-controlled content.

Example: Unsafe pattern with Bearer Token handling

import subprocess
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route("/archive")
def unsafe_archive():
    token = request.headers.get("Authorization", "").replace("Bearer ", "")
    filename = request.args.get("file", "")
    # Unsafe: filename used in shell command string
    cmd = f"tar -xzf {filename} -C /tmp"
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    return jsonify({"stdout": result.stdout, "stderr": result.stderr, "token_present": bool(token)})

Example: Safe remediation in Flask

import subprocess
from flask import Flask, request, jsonify
import shlex

app = Flask(__name__)

@app.route("/archive")
def safe_archive():
    token = request.headers.get("Authorization", "")
    # Bearer Tokens are validated separately (e.g., via library), but not used in commands
    filename = request.args.get("file", "")
    # Validate and sanitize input
    if not filename:
        return jsonify({"error": "missing file parameter"}), 400
    # Use a whitelist or strict allowlist for filenames
    if not filename.replace("-", "").replace(".", "").isalnum():
        return jsonify({"error": "invalid filename"}), 400
    # Safe: shell=False, arguments as a list
    result = subprocess.run(
        ["tar", "-xzf", filename, "-C", "/tmp"],
        shell=False,
        capture_output=True,
        text=True,
    )
    return jsonify({"stdout": result.stdout, "stderr": result.stderr, "token_present": bool(token)})

Additional defenses include using a web framework’s built-in validation (e.g., Marshmallow or Pydantic) to enforce type and format constraints, and ensuring that any logging that includes the Bearer Token redacts or omits the token value to prevent accidental leakage. middleBrick’s LLM/AI Security checks can surface system prompt leakage or improper handling of tokens in model interactions, complementing traditional input validation by identifying logic flaws in how tokens and data are processed across services.

When integrating with downstream services, prefer HTTPS client libraries with strict certificate verification rather than shelling out to tools like curl or wget. If you must use subprocess, enforce strict environment controls and avoid inheriting a broad shell context. The Pro plan’s continuous monitoring can help detect regressions in API behavior, including patterns where authentication headers are mishandled alongside dynamic inputs.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Does using Bearer Tokens prevent command injection in Flask APIs?
No. Authentication and input validation are independent; Bearer Tokens do not sanitize user-controlled data. Always validate and avoid passing untrusted input to shell commands.
How can I safely handle filenames in Flask while using Bearer Tokens?
Use allowlists for filenames, avoid shell=True, pass arguments as a list to subprocess.run, and keep tokens out of logs and commands. Consider using structured libraries for archive operations instead of invoking shell utilities.