Projects STRLCPY CVE-2022-42864 Commits 5896a3b9
🤬
  • HIDDriverPoC.xcodeproj/project.xcworkspace/xcuserdata/tommy.xcuserdatad/UserInterfaceState.xcuserstate
    Binary file.
  • ■ ■ ■ ■ ■ ■
    README.md
     1 +# CVE-2022-42864
     2 + 
     3 +## What is this repo?
     4 +This is my (incomplete) proof-of-concept exploit for CVE-2022-42864, a time-of-check-time-of-use vulnerability in IOHIDFamily that was fixed in iOS 16.2 / macOS Ventura 13.1.
     5 + 
     6 +## What is the status of the proof-of-concept?
     7 +The exploit currently achieves the same "arbitrary kfree" primitive used in the multicast_bytecopy exploit. However, the subsequent exploit flow of multicast_bytecopy has been heavily mitigated against, so this is not a complete exploit, it merely demonstrates the severity of the issue.
     8 + 
     9 +## Should I run this?
     10 +If you have to ask, no. This does not do anything useful, it just causes a kernel panic.
     11 + 
     12 +## The bug
     13 +[Apple's comment](https://github.com/apple-oss-distributions/IOHIDFamily/blob/19666c840a6d896468416ff0007040a10b7b46b8/IOHIDFamily/IOHIDDevice.cpp#L1601) from the source code when this issue was fixed sums this up nicely:
     14 + 
     15 + // Find the number of cookies in the data. The data from elementData is shared with user space and may change at any time.
     16 + 
     17 +Let us have a look at the function before the patch (I have tried to label relevant lines):
     18 + 
     19 + IOReturn IOHIDDevice::postElementTransaction(const void* elementData, UInt32 dataSize, UInt32 completionTimeout, IOHIDCompletion * completion)
     20 + {
     21 + IOReturn ret = kIOReturnError;
     22 + uint32_t cookies_[kMaxLocalCookieArrayLength];
     23 + uint32_t *cookies = cookies_;
     24 + uint32_t cookieCount = 0;
     25 + uint32_t cookieSize = 0;
     26 + uint32_t dataOffset = 0;
     27 + uint8_t *data = (uint8_t*)elementData;
     28 + IOMemoryDescriptor *elementDesc = getMemoryWithCurrentElementValues();
     29 + require(_elementArray && elementDesc, fail);
     30 + 
     31 + WORKLOOP_LOCK;
     32 + 
     33 + // Find the number of cookies in the data. Check that all cookies are valid elements. [1]
     34 + while (dataOffset < dataSize) {
     35 + const IOHIDElementValueHeader *headerPtr = (const IOHIDElementValueHeader *)(data + dataOffset);
     36 + IOHIDElementPrivate *element = GetElement(headerPtr->cookie);
     37 + if (!element) {
     38 + HIDDeviceLogError("Could not find element for cookie: %d", headerPtr->cookie);
     39 + ret = kIOReturnAborted;
     40 + goto fail;
     41 + }
     42 + cookieCount++;
     43 + 
     44 + require_noerr_action(os_add3_overflow(dataOffset, headerPtr->length, sizeof(IOHIDElementValueHeader), &dataOffset), fail, HIDDeviceLogError("Overflow iterating cookie data buffer %u %u", dataOffset, headerPtr->length));
     45 + }
     46 + // Data isn't as large as expected, don't overrun, just abort
     47 + if (dataOffset != dataSize) { // [2]
     48 + HIDDeviceLogError("Cookie data buffer is smaller than expected. %u vs. %u",
     49 + (unsigned int)dataSize, (unsigned int)dataOffset);
     50 + ret = kIOReturnAborted;
     51 + goto fail;
     52 + }
     53 + dataOffset = 0;
     54 + 
     55 + require_noerr_action(os_mul_overflow(cookieCount, sizeof(uint32_t), &cookieSize),
     56 + fail,
     57 + HIDDeviceLogError("Overflow calculating cookieSize"));
     58 + 
     59 + cookies = (cookieCount <= kMaxLocalCookieArrayLength) ? cookies : (uint32_t*)IOMallocData(cookieSize); // [3]
     60 + 
     61 + if (cookies == NULL) {
     62 + ret = kIOReturnNoMemory;
     63 + goto fail;
     64 + }
     65 + 
     66 + // Update the elements, this replaced the shared kernel-user shared memory.
     67 + for (size_t index = 0; dataOffset < dataSize; ++index) { // [4]
     68 + const IOHIDElementValueHeader *headerPtr;
     69 + IOHIDElementPrivate *element;
     70 + OSData *elementVal;
     71 + 
     72 + headerPtr = (const IOHIDElementValueHeader *)(data + dataOffset);
     73 + element = GetElement(headerPtr->cookie);
     74 + dataOffset += headerPtr->length + sizeof(IOHIDElementValueHeader);
     75 + 
     76 + elementVal = OSData::withBytesNoCopy((void*)headerPtr->value,
     77 + headerPtr->length); // [5]
     78 + require_action(elementVal, fail, ret = kIOReturnNoMemory);
     79 + element->setDataBits(elementVal);
     80 + elementVal->release();
     81 + 
     82 + cookies[index] = headerPtr->cookie; // [6]
     83 + }
     84 + 
     85 + // Actually post elements
     86 + ret = postElementValues((IOHIDElementCookie *)cookies, (UInt32)cookieCount, 0, completionTimeout, completion);
     87 + 
     88 + fail:
     89 + WORKLOOP_UNLOCK;
     90 + if (cookies != &cookies_[0]) {
     91 + IOFreeData(cookies, cookieSize);
     92 + }
     93 + 
     94 + return ret;
     95 + }
     96 + 
     97 +- The loop at `[1]` counts the number of `IOHIDElementValue`s in the buffer, and stores this count in `cookieCount`.
     98 +- The check at `[2]` (combined with the condition of the while loop) will make sure that the `length` field of each header does not extend out of the bounds of the `elementData` buffer (nor can it fall short of the end of the buffer, although this is less relevant).
     99 +- Once all the elements have been counted and sanity-checked by this loop, a `cookies` buffer is allocated to the heap at `[3]` with a size of `cookieCount * 4` (or a stack buffer is used if `cookieCount` is sufficiently small).
     100 +- A second loop at `[4]` then makes a second pass through the buffer, parsing the `IOHIDElementValue`s again.
     101 +- `OSData` objects are created to hold each element's value at `[5]`, using the `length` field that was validated in the first loop.
     102 +- At `[6]`, each element's `cookie` is written into the `cookies` array allocated at `[3]`.
     103 + 
     104 +So what's the issue? This function behaves entirely correctly when `elementData` is non-volatile, the issue comes when the method is called with shared memory. Enter the `IOHIDInterface::SetElementValues_Impl` DriverKit method:
     105 + 
     106 + kern_return_t
     107 + IMPL(IOHIDInterface, SetElementValues)
     108 + {
     109 + IOReturn ret = kIOReturnError;
     110 + UInt8 *values = NULL;
     111 + IOBufferMemoryDescriptor *md = NULL;
     112 +
     113 + md = OSDynamicCast(IOBufferMemoryDescriptor, elementValues);
     114 + require_action(md && count, exit, ret = kIOReturnBadArgument);
     115 + 
     116 + values = (UInt8 *)md->getBytesNoCopy();
     117 +
     118 + // Post the data to the device
     119 + ret = _owner->postElementTransaction(values, (UInt32)md->getLength());
     120 + require_noerr_action(ret, exit, HIDServiceLogError("postElementValues failed: 0x%x", ret));
     121 + 
     122 + exit:
     123 + return ret;
     124 + }
     125 + 
     126 +Here, `postElementTransaction` is called with `md->getBytesNoCopy()`, memory shared with userspace, violating the assumption that `elementData` is non-volatile. The content of the `elementData` buffer can change after the loop at `[1]`, but before the loop at `[4]`, so what does this mean for an attacker?
     127 + 
     128 +There are two ways an attacker can abuse this:
     129 +- The first is to swap the `length` of a small `IOHIDElementValueHeader` at the end of the buffer to a much larger value. This means that when the `OSData` at `[5]` is created, it will extend far outside the bounds of the `elementData` buffer, allowing an attacker to read out-of-bounds data using `IOHIDInterface::GetElementValues_Impl`.
     130 +- The second is to swap the `length` of a large `IOHIDElementValueHeader` at the beginning of the buffer to a much smaller value. This will make the loop at `[4]` parse many more headers than were originally counted in the loop at `[1]`, so when cookies are written to the `cookies` array at `[6]`, they will overflow out of the array as `index` is never validated against `cookieCount`.
     131 + 
     132 +In practice, this allows an attacker to read out-of-bounds kernel heap data of an arbitrary size, and to write arbitrary data (again of an arbitrary size) out-of-bounds to the kernel heap. These are two powerful primitives.
     133 + 
     134 +## Winning the race
     135 +With race conditions, we always look for ways to determine whether the race was won successfully, that way we can keep trying until we succeed, making our trigger deterministic. Luckily in the case of this race condition, we can do exactly that.
     136 + 
     137 +For the OOB read variant, I place one more `IOHIDElementValueHeader` after the header that I'm switching the `length` of, with its `value` set to the recognisable constant of `0xD1AB011CAC1DF00D`. Then, when reading the value of the element back, I know I have won the race if I see the familiar `0xD1AB011CAC1DF00D` header at the start of the returned data.
     138 + 
     139 +For the OOB write variant, I place one `IOHIDElementValueHeader` after the header that I'm switching the `length` of, but before the headers whose `cookie`s will be overflowed, this time with the recognisable `value` of `0xD15EA5ED`. This header will be encapsulated inside the `value` of the larger element in the case where we do not win the race, so the header will only be parsed and the element's value be set to `0xD15EA5ED` if we win the race. By reading back the element's value, I know whether I was successful.
     140 + 
     141 +## Apple's fix
     142 +To fix the issue, Apple chose to add a third loop in between loop `[1]` and loop `[4]`, validating each `length` field, and then caching it in a new `dataLengths` array, while ensuring the number of elements had not changed. The final loop then uses the cached lengths for its calculations, avoiding reading from the buffer another time.
     143 + 
     144 +## Issues with exploitation
     145 +The main obstacle to overcome when exploiting this issue is that the buffer we are overflowing out of belongs to `KHEAP_DATA_BUFFERS`, so exploitation targets are limited. In this proof-of-concept I chose to target kmsg headers, as these are one of very few structures in `KHEAP_DATA_BUFFERS` that contain kernel pointers. The "arbitrary kfree" primitive I obtained using this approach is the same primitive used in the multicast_bytecopy exploit, however the `IOSurfaceClient` array is now PAC'd and forged clients need to have a valid pointer back to the `IOSurfaceRootUserClient` that created them, rendering this no longer a desirable kernel r/w target.
     146 + 
     147 +## Building and installing
     148 +Apple have not made building and installing custom DriverKit extensions very easy, especially without a paid Apple Developer account, but it is possible.
     149 + 
     150 +Before you start, I recommend:
     151 +- Disabling SIP
     152 +- Setting the boot-args `amfi_get_out_of_my_way=1 cs_enforcement_disable=1`
     153 +- Running `systemextensionsctl developer on`
     154 +- Restarting your computer
     155 + 
     156 +After that, you should be able to select your developer team in the Xcode project settings and the project will build successfully. You can the run HIDDriverLoader, use "Install Dext" to install the DriverKit extension and "Trigger Exploit" to, you guessed it, trigger the exploit.
     157 + 
     158 +If this fails, you can also try building without signing using:
     159 + 
     160 + xcodebuild build CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO
     161 + 
     162 +And then manually signing using:
     163 + 
     164 + codesign -fs self-sign-cert --entitlements HIDDriverLoader/HIDDriverLoader.entitlements build/Release/HIDDriverLoader.app/Contents/MacOS/HIDDriverLoader
     165 + codesign -fs self-sign-cert --entitlements HIDDriver/HIDDriver.entitlements build/Release/HIDDriverLoader.app/Contents/Library/SystemExtensions/*.dext/*.driver
     166 + 
     167 +### Thank you for reading :)
     168 + 
Please wait...
Page is in error, reload to recover