#include "ServiceProbe.h"
#include <IOKit/IOKitLib.h>
#include <CoreFoundation/CoreFoundation.h>
#include <mach/mach.h>
#include <string.h>

// ============================================================================
// Read-only IOKit service probe (NO memory corruption).
// ============================================================================

static const char *g_all_candidates[] = {
    // mDNS offload kext (com.apple.driver.mDNSOffloadUserClient-Embedded)
    "mDNSOffloadUserClient",
    "mDNSOffload",
    "mDNSHandoff",
    // Wi-Fi / Skywalk (CVE-2026-28819, CVE-2026-39877)
    "AppleBCMWLANBusInterfacePCIe",
    "AppleBCMWLANCore",
    "AppleBCMWLANPCIe",
    "IOSkywalkNetworkInterface",
    "IO80211Interface",
    "IO80211Controller",
    // IOHID (CVE-2026-28992)
    "IOHIDEventService",
    "IOHIDInterface",
    "IOHIDDevice",
    "AppleMultitouchDevice",
    // Common app-reachable kernel user clients
    "IOSurfaceRoot",
    "IOSurfaceRootUserClient",
    "IOAccelerator",
    "AGXAcceleratorG13",
    "AGXDeviceUserClient",
    "AppleCredentialManager",
    "AppleKeyStore",
    "AppleJPEGDriver",
    "AppleAVE2Driver",
    "AppleH11ANEInterface",
    "AppleSMC",
    "AppleSEPManager",
    NULL
};

bool service_probe_one(const char *class_name, service_probe_result_t *out) {
    if (!class_name || !out) return false;
    memset(out, 0, sizeof(*out));
    out->class_name = class_name;
    out->connect = MACH_PORT_NULL;
    out->open_kr = (kern_return_t)-1;

    CFMutableDictionaryRef matching = IOServiceMatching(class_name);
    if (!matching) return false;

    io_iterator_t iter = IO_OBJECT_NULL;
    kern_return_t kr = IOServiceGetMatchingServices(kIOMainPortDefault, matching, &iter);
    if (kr != KERN_SUCCESS) return false;

    io_service_t service = IO_OBJECT_NULL;
    while ((service = IOIteratorNext(iter)) != IO_OBJECT_NULL) {
        out->found = true;
        out->obj_count++;

        if (out->obj_count == 1) {
            io_name_t name = {0};
            IORegistryEntryGetName(service, name);

            io_connect_t conn = MACH_PORT_NULL;
            kern_return_t okr = IOServiceOpen(service, mach_task_self(), 0, &conn);
            out->open_kr = okr;

            if (okr == KERN_SUCCESS) {
                out->connect = conn;
                exploit_log(LOG_WARN, "  [%s] FOUND name='%s' -> USER CLIENT OPENABLE",
                            class_name, name);
            } else {
                exploit_log(LOG_INFO, "  [%s] FOUND name='%s' -> open denied 0x%x",
                            class_name, name, okr);
            }
        }
        IOObjectRelease(service);
    }
    IOObjectRelease(iter);

    if (out->connect != MACH_PORT_NULL) {
        IOServiceClose(out->connect);
        out->connect = MACH_PORT_NULL;
    }
    return out->found;
}

// Only attempt to open classes/names that look like real app-reachable user
// clients. This avoids poking random kernel objects we don't care about.
static const char *g_interest_tokens[] = {
    "Surface", "KeyStore", "KeyBag", "AES", "JPEG", "AVE", "Video", "Cam",
    "ISP", "ANE", "GPU", "Accel", "Touch", "HID", "WLAN", "Skywalk", "BCM",
    "Multitouch", "SEP", "SMC", "Baseband", "PCIe", "Smart", "Crypto",
    "AppleV", "AppleH", "AppleS", "IOGPU", "IOSurface", NULL
};

static bool service_name_is_interesting(const char *cls, const char *name) {
    for (int i = 0; g_interest_tokens[i]; i++) {
        const char *tok = g_interest_tokens[i];
        if ((cls && strcasestr(cls, tok)) || (name && strcasestr(name, tok)))
            return true;
    }
    return false;
}

void service_probe_enumerate(void) {
    exploit_log(LOG_INFO, "----- full IOService enumeration -----");

    CFMutableDictionaryRef matching = IOServiceMatching("IOService");
    if (!matching) {
        exploit_log(LOG_WARN, "  IOServiceMatching failed");
        return;
    }

    io_iterator_t iter = IO_OBJECT_NULL;
    kern_return_t kr = IOServiceGetMatchingServices(kIOMainPortDefault, matching, &iter);
    if (kr != KERN_SUCCESS) {
        exploit_log(LOG_WARN, "  IOServiceGetMatchingServices failed 0x%x", kr);
        return;
    }

    int total = 0;
    int interesting = 0;
    int openable = 0;

    io_service_t service = IO_OBJECT_NULL;
    while ((service = IOIteratorNext(iter)) != IO_OBJECT_NULL) {
        total++;

        io_name_t name = {0};
        io_name_t cls = {0};
        IORegistryEntryGetName(service, name);
        IOObjectGetClass(service, cls);

        if (service_name_is_interesting(cls, name)) {
            interesting++;
            io_connect_t conn = MACH_PORT_NULL;
            kern_return_t okr = IOServiceOpen(service, mach_task_self(), 0, &conn);
            if (okr == KERN_SUCCESS) {
                openable++;
                exploit_log(LOG_WARN, "  OPEN  %s (%s)", cls, name);
                IOServiceClose(conn);
            } else {
                exploit_log(LOG_DEBUG, "  deny  %s (%s) 0x%x", cls, name, okr);
            }
        }

        IOObjectRelease(service);
    }
    IOObjectRelease(iter);

    exploit_log(LOG_INFO, "  total=%d interesting=%d openable=%d",
                total, interesting, openable);
}

void service_probe_run(void) {
    exploit_log(LOG_INFO, "===== IOKit service probe (read-only) =====");

    int found = 0;
    int openable = 0;

    for (int i = 0; g_all_candidates[i]; i++) {
        service_probe_result_t r;
        if (service_probe_one(g_all_candidates[i], &r)) {
            found++;
            if (r.open_kr == KERN_SUCCESS) openable++;
        } else {
            exploit_log(LOG_DEBUG, "  [%s] not present", g_all_candidates[i]);
        }
    }

    exploit_log(LOG_INFO, "===== candidate probe: %d present, %d openable =====",
                found, openable);

    service_probe_enumerate();

    exploit_log(LOG_INFO, "===== probe done =====");
}
