"""
Vulnerable Lab: CVE-2026-105134-style OS Command Injection
------------------------------------------------------------
Simulates the Ahsay AhsayCBS "Replication Receiver" flaw:
an endpoint accepts a 'random' parameter and unsafely feeds it
into a shell command.

FOR ISOLATED, LOCAL LAB / TRAINING USE ONLY.
Do not expose this to any network you don't fully control.
There is also a PATCHED version below (see patched_app.py) to
compare secure vs. insecure handling.
"""

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

app = Flask(__name__)

# Simulates the Replication Receiver config store
RECEIVERS_DB = {}


@app.route("/rps/api/json/UpdateReceivers.do", methods=["POST"])
def update_receivers():
    """
    VULNERABLE endpoint.
    Expects JSON: {"receiver_id": "...", "random": "<token>"}
    The 'random' value is meant to be an opaque nonce/token used
    to name a temp file for the replication handshake - but it's
    passed straight into a shell command, unsanitized.
    """
    data = request.get_json(force=True, silent=True) or {}
    receiver_id = data.get("receiver_id", "default")
    random_token = data.get("random", "")

    # --- THE BUG ---
    # Builds a shell command string using untrusted input directly,
    # with no quoting around the injected value at all.
    # shell=True + unquoted string interpolation = direct command injection.
    cmd = f"echo sync-token-{random_token} > /tmp/receiver_{receiver_id}.sync"
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=5)
        RECEIVERS_DB[receiver_id] = random_token
        return jsonify({
            "status": "ok",
            "receiver_id": receiver_id,
            "stdout": result.stdout,
            "stderr": result.stderr
        })
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500


@app.route("/", methods=["GET"])
def index():
    return jsonify({
        "lab": "CVE-2026-105134-style OS Command Injection",
        "endpoint": "/rps/api/json/UpdateReceivers.do (POST)",
        "expected_body": {"receiver_id": "string", "random": "string"},
        "note": "The 'random' field is injected unsanitized into a shell command."
    })


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5000, debug=True)
