# [CRUCIBLE-SEED]
# category: command_injection
# severity: high
# language: python
# expected: command injection via paramiko exec_command with user-controlled command string

import paramiko
from flask import Flask, request, jsonify

app = Flask(__name__)


def get_ssh_client(host: str) -> paramiko.SSHClient:
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(host, username="deploy", key_filename="/home/deploy/.ssh/id_rsa")
    return client


@app.route("/ssh/run", methods=["POST"])
def run_remote_command():
    data = request.get_json()
    host = data.get("host", "")
    # command from user — attacker appends malicious commands
    command = data.get("command", "")
    allowed_hosts = ["web-01.internal", "web-02.internal"]
    if host not in allowed_hosts:
        return jsonify({"error": "Host not allowed"}), 403

    client = get_ssh_client(host)
    # command not validated — attacker sends "ls; cat /etc/shadow"
    stdin, stdout, stderr = client.exec_command(command)
    output = stdout.read().decode()
    client.close()
    return jsonify({"output": output})
