diff --git a/src/exploit/checkm8.c b/src/exploit/checkm8.c index 47354c8..aefd5ec 100644 --- a/src/exploit/checkm8.c +++ b/src/exploit/checkm8.c @@ -59,6 +59,62 @@ int exploit_init(exploit_ctx_t *ctx, device_info_t *dev) /* exploit_deliver */ /* ------------------------------------------------------------------ */ +/* + * exploit_reacquire -- drop the handle and look the device up again. + * + * The reference implementation re-acquires the device before every stage + * (wait_usb_handle() sits in the condition of its stage loop). A device + * that re-enumerates during a stage leaves us holding a descriptor for a + * node that no longer exists, and every later transfer fails with + * NO_DEVICE (-4) even though the device is still on the bus. Re-opening + * does not reset the device, so the state built by the previous stage + * stays where it is. + */ +static int exploit_reacquire(exploit_ctx_t *ctx) +{ + device_info_t *dev = ctx->dev; + uint8_t iserial = 0; + unsigned old_addr = 0; + int i; + + if (dev->usb) { + libusb_device *old = libusb_get_device(dev->usb); + + if (old) + old_addr = (unsigned)libusb_get_device_address(old); + + usb_dfu_close(dev->usb); + dev->usb = NULL; + } + + for (i = 0; i < 100; i++) { /* up to ~10 s at 100 ms */ + if (usb_dfu_find(&dev->usb, &iserial) == 0) { + libusb_device *now = libusb_get_device(dev->usb); + unsigned new_addr = 0; + + if (now) + new_addr = (unsigned)libusb_get_device_address(now); + + /* + * The descriptor index of the serial string is not stable + * across enumerations; the retry paths in checkm8_exploit + * carry it forward for that reason, and the PWND check + * reads it back through dev->iserial_index. + */ + dev->iserial_index = iserial; + + log_info("exploit_deliver: device re-acquired " + "(iserial %u, address %u -> %u)", + (unsigned)iserial, old_addr, new_addr); + return 0; + } + usleep(100000); + } + + log_error("exploit_deliver: device did not come back after re-acquiring"); + return -1; +} + int exploit_deliver(exploit_ctx_t *ctx) { if (!ctx || !ctx->dev || !ctx->chip) @@ -70,12 +126,21 @@ int exploit_deliver(exploit_ctx_t *ctx) if (checkm8_stage_reset(ctx) != 0) return -1; + if (exploit_reacquire(ctx) != 0) + return -1; + if (checkm8_stage_setup(ctx) != 0) return -1; + if (exploit_reacquire(ctx) != 0) + return -1; + if (checkm8_stage_spray(ctx) != 0) return -1; + if (exploit_reacquire(ctx) != 0) + return -1; + if (checkm8_stage_patch(ctx) != 0) return -1;