Archive for July, 2015


This Article is designated for developers with C++ & Objective-C experience, A basic knowledge of iOS Operating System is assumed.


In this article I will describe an approach enabling code injection to an existing AppStore Application, In a nut-shell, this involves breaking FairPlay encryption, Injecting code, re-signing and re-packaging the App.

Once the process described in this article is complete, the App ( having the injected code on board ) can be freely installed on any type of device, whether Jail-broken OR NOT.

High-level Flow diagram


  • A developer account with Apple
    This is required so after Injecting the DynamicLib the application could get re-packaged and installed on the iOS device, use this link to create one.
  • X-code 6 ( supporting iOS Framework Compilation )
    With X-code 6 it is possible to create custom frameworks, which are, in essence, DynamicLibraries.
  • Two iOS device
    Two devices are required for the process, one, that will run the patched app, and another, JailBroken device with cydia installed where FairPlay is Removed.
  • Mach-O View
    An application used to parse Apple Executable files, use this link to download.

The Mach-O File format

Executable files on OS-X & iOS are stored using the Mach-O format, this executable format is specific for apple and is used to store multiple instances of the binary code, each using a different instruction set ( x86, ARM, … ) along with metadata telling the OS how the code is to be executed.

The Mach-O file format consists of a header followed by a set of commands and one or more segments, Of specific interest is the set of load commands, I will cover this later in details

Application Packaging

Applications are packaged in bundles, a bundle is a ZIP file with an ‘.IPA’ extension, these, contain the Program/Framework executable, and, all of the related resources such as Strings, Images, NIBs, and most importantly the developer certificates and application Entitlements.

A simple IPA is presented bellow, this IPA consists of the Mach-O Executable ( named Tester ), the program resources, located under the Base.lproj folder, the provisioning profile ( named mbedded.mobileprovision ) where the authorized devices are defined,

the Entitlements file ( named archived-expanded-entitlements.xcent ) where specific application capabilities and or security permissions are defined, and ‘Info.plist‘ where the bundle id and other application specific properties are set, later on, these are used to re-sign an re-pack the IPA with the Injected code.

FairPlay Workaround

FairPlay is apples DRM used to protect applications downloaded from the AppStore, it prevents execution of the application on unauthorized devices.

FairPlay removal requires a JailBroken device, Having Cydia and the Clutch tool installed, I have found this site to contain the most up-to-date iOS JailBreaks, high level instructions of the process are provided by this Tutorial, next, I will provide explanation regarding FairPlay Mach-O protection, How Clutch is removing encryption, and, why a Jailbroken device is needed.

Mach-O Executables are signed with the developer certificate, this certificate is used in conjunction with other OS information during FairPlay decryption, The code injection process mandate Mach-O modifications, and these, mandate re-signing with a different certificate ( eg. a custom developer certificate ), this is why it is needed to remove FairPlay before doing any change to the Mach-O Executable.

FairPlay encrypts part of the code segment of the Mach-O executable, the encrypted region is indicated using the LC_ENCRYPTION_INFO load command ( consisting of the ‘encryption_info_command’ structure ) as can be seen in the following Mach-O View snap:

Having ‘encryption_info_command::cryptid’ set to a value different than zero indicate that the Mach-O executable is FairPlay protected.
During the process of Mach-O loading, the operating system decrypt the protected region, and thus, the binary code reside un-encrypted in memory during execution, Clutch is taking advantage of that fact by starting the application, and, once loaded in memory, copies the decrypted section back to the physical Mach-O file replacing the encrypted segment, obviously, accessing another process memory mandate root privileges, and this, is why a Jailbroken device is needed.

Code Injection

Once we have FairPlay removed and the Mach-O is un-encrypted we can inject custom code to be executed on behalf of the application ( at the application sandbox ), this is done by having the code compiled as a framework ( consisting of a DynamicLib ), and, having a LC_LOAD_DYLIB command ( referring that DynamicLib ) added to the Mach-O executable.

As can be seen on the image to the right, With X-code 6, Creating an iOS DynamicLib was made much simpler, with older X-code versions, one would have to tinker through with the solution files to have X-code produce iOS compatible DynamicLib, X-code 6 has introduced a new type of project, the “Cocoa Touch Framework”, which in essence, is a DynamicLib packed together with it’s associated resources.

The compiler attribute “__attribute__((constructor))” is used to ensure the Framework code execute upon ‘module loading’/’application start-up’, this is illustrated bellow:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

void EntryPoint() {
    NSLog(@“Injected routine…\n”);
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@“Hello”
                                                        message:@“Code Injected”
        [alert show];

The framework code injected to the application executable might have references to common frameworks, for example, both, the Injected code and the Application code might use/refer UIKit.framework, this is a tricky situation since only a single framework version is loaded during execution, using different versions of the same type of framework might cause un-predictable behaviour, having that said, it is essential, either to have the injected code dependent on a minimal set of external frameworks, OR, to make sure to compile the Injected code with the same frameworks used by the application being injected too.

Once the framework to be injected was generated, the Application IPA ( Zip file ) must be extracted and the Injected framework must be copied to the Application executable folder so later on it could get loaded in to the application memory address space, this is demonstrated on the image to the right.
The Mach-O executable is then to be added a load command referring the Injected Framework, this, will make the OS load the framework when the Mach-O executable is lunched.

After the injection has taken place, the Application Executable looks as follows ( in red is the path to the Injected Framework ), Note the ‘@executable_path’ notation, this notation is used resemble a path relative to the current executing Mach-O.

The Injected framework is added as the last LC_LOAD_DYLIB Command to ensure that all the application dependent modules were already loaded.

Sample Code ( download )

This Article is accompanied a simple single file sample-code implementing the Injection logic, the following include an explanation of the major parts of the code.

As stated before, In-order to be able to inject the framework the Mach-O must be un-encrypted ( otherwise signature verification will fail, and, it’ll not get loaded by the OS ), the following code-snap iterate through all of the commands until it finds the ‘LC_ENCRYPTION_INFO‘ command, if found, it verify no encryption is applied by evaluating ‘cryptid‘, the file is concluded un-encrypted if either ‘cryptid‘ is evaluated to zero, OR, when the ‘LC_ENCRYPTION_INFO‘ command is not found.

m_pCmdFirst‘ in the code bellow is found immediately after the mach_header ( whether 64 bit or not )

template< typename T >// Supports both the 32bit and 64 bit versions of ‘mach_header’
bool MachOParser<T>::IsMachOEncrypted() {
    uint8_t*        pPtr = (uint8_t*)m_pCmdFirst;
    load_command*    pCmd = m_pCmdFirst;
    for (uint32_t i = 0;
        i < m_pMachO->ncmds;
        i++, pPtr += pCmd->cmdsize, pCmd = (load_command*)pPtr)
        if (LC_ENCRYPTION_INFO != pCmd->cmd)
        if (0 != ((encryption_info_command*)pCmd)->cryptid)
            return true;
        break;// We have found the encryption info section, no need to keep on searching
    return false;

The next code-snap is responsible for injecting the ‘dylib_command‘ as the last ‘dylib_command‘ of the Mach-O, this is done using ‘m_pCmdLastLoadLib ‘ which is pre-initialized to the last ‘dylib_command‘ upon Mach-O loading ( see the ‘ReloadCommands()‘ method of the accompanied code ).

cmdInjected‘ define the injected command, important variables are ‘dylib_command::cmd‘ that indicate the command type, and, ‘dylib_command::dylib::name::offset‘ that indicate an offset to where the name of the framework is located within the Mach-O, relative to the beginning of the ‘dylib_command‘ command, in our case, the name of the framework is directly located after the command, and thus, the relative offset is ‘sizeof(dylib_command)

One more thing to note, all commands must be aligned to 4 bytes length, and thus, the name of the framework is padded with zeros making sure it is appropriately aligned.

m_vecCommands‘ is pre-initialized with all commands upon Mach-O loading ( see the ‘ReloadCommands()‘ method of the accompanied code ).

template< typename T >// Supports both the 32bit and 64 bit versions of ‘mach_header’
int MachOParser<T>::InjectDyLib(const char* pDynLibPath) {
    union {
        dylib_command    cmdInjected;
        char            __pRaw__[512];
    cmdInjected.cmd = LC_LOAD_DYLIB;
    cmdInjected.dylib.compatibility_version = 0x00010000;
    cmdInjected.dylib.current_version = 0x00020000;
    cmdInjected.dylib.timestamp = 2; = (uint32_t)sizeof(dylib_command);

    char* pLibNameStart = (char*)(&cmdInjected + 1);
    strncpy(pLibNameStart, pDynLibPath, sizeof(__pRaw__);
    cmdInjected.cmdsize = + (uint32_t)strlen(pLibNameStart);
    const div_t d = div(cmdInjected.cmdsize, 4);
    if (0 != d.rem) {// Commands size must be aligned to 4
        memset((char*)&cmdInjected + cmdInjected.cmdsize, 0, 4 – d.rem);
        cmdInjected.cmdsize += (4 – d.rem);

    if (FALSE == IsThereEnoughSpaceForCmd((load_command*)&cmdInjected)) {
        // TBD: In case no space is available in the existing Mach-O, enlarge
        // the size of the file and update section offsets/RVAs
        return ENOBUFS;

    char* pInjectionOffset = (char*)m_pCmdLastLoadLib + m_pCmdLastLoadLib->cmdsize;
    const char* pLoadCmdsEnd = (char*)m_vecCommands[m_vecCommands.size() – 1] +
                                m_vecCommands[m_vecCommands.size() – 1]->cmdsize;
    // Make space for the new command
    memmove(pInjectionOffset + cmdInjected.cmdsize,
            (size_t)(pLoadCmdsEnd – pInjectionOffset));
    // Inject the dynlib command
    memcpy(pInjectionOffset, &cmdInjected, cmdInjected.cmdsize);
    m_pMachO->sizeofcmds += cmdInjected.cmdsize;
    return 0;

Sign & Re-package

This is the last step before the patched application can be used on a non Jail-broken device, In this section a method for signing/packaging using a provisioning profile is demonstrated although any other approach will work ( potentially, even AppStore distribution )

  1. Extract application IPA
    iOS applications are packed in IPA files, which, in essence, are zip files containing all of the application resources, the first thing to do is to extract the Application IPA to a known folder, this can be done using the unzip command-line utility in the following manner:

    unzip %Filename%.ipa -d %dest folder%
  2. Remove existing signature
    When applications are signed, a per file signature is generated, these are stored in a special file named ‘CodeResources‘ which is located under the ‘_CodeSignature‘ folder, to remove these signatures the ‘_CodeSignature‘ is to be removed:

    rm -fR %dest folder%/Payload/%App

  3. Update Provisioning Profile
    The provisioning profile defines the devices the application is allowed to execute on, An iOS developer account is required, click here to generate one, once the provisioning profile is ready it should be copied to the application @executable_path and named ‘embedded.mobileprovision‘:

    cp %profile file%.mobileprovision %dest folder%/Payload/%App

  4. Update Entitlements
    The Entitlements file is a simple ‘.plist‘ file that “confer specific capabilities or security permissions to your iOS” App, it should be copied to the application @executable_path and named ‘Entitlements.plist‘, it refers the developer via the ‘application-identifier‘ variable which must prefix with the developer id, this is illustrated bellow:

    <?xml version=“1.0” encoding=“UTF-8”?>
    <!DOCTYPE plist PUBLIC “-//Apple//DTD PLIST 1.0//EN”;>
    <plist version=“1.0”>
        <string>%Developer Id%.*</string>

    The %Developer Id% can be retrieved directly form the developer portal, OR, under the ‘User Id’/’Org Unit’ when inspecting the developer certificate using using the KeyChain tool.

    Copy the ‘Entitlements‘ file to the ‘@executable_folder‘:

    cp %entitlements file%.pinfo %dest folder%/Payload/%app

  5. Update Framework
    Once the framework is compiled ( into a folder named %Proj Name%.framework ) it should be copied into the the applications @executable_path, make sure to have any descendent _CodeSignature folder removed.

    cp -R %Name%.framework %dest folder%/Payload/%app

  6. Inject Framework to the App Executable
    This is where we use the above mentioned code, compile the accompanied code and run the following to Inject the framework into the application executable:

    Injector “%app path%/Payload/” “@executable_path/%Proj name%.framework/%Proj name%

  7. Sign
    It is needed to replace the signature embedded in the Mach-O executables, and, to re-generate the _CodeSignature folder using the developer identity, during the process of creating a developer account the development signing certificates were installed on the local machine ( this might have been done automatically by xcode ), these can be seen using the Key-Chain tool, OR, via the xcode project ‘Code Signing Identity’ of the project target ‘Build Settings’ ( located at ‘project properties->Target->Build settings->Code signing->Code signing Identity‘ ), the codesign tool is to be used to sign the Mach-O binaries with this identity as demonstrated bellow:

    codesign -s “%KeyChain cert name%” –force –deep “%dest folder%/Payload/%app”


    codesign -s “%KeyChain cert name%” –force –deep “%dest folder%/Payload/%app Name%.framework/%Proj Name%”

    Once the application executables signature is updated/replaced, the _CodeSignature folder is to be reconstructed using the development signing certificates and the Entitlements file:

    codesign -s “%KeyChain cert name%” –entitlements “%dest folder%/Payload/%app” –force –deep %dest folder%/Payload/%app

  8. Re-package
    The last step is to zip together all of the resulting files into an IPA, this is done using the zip command in the following manner:

    zip -r %dest folder%/%Name%.ipa “%dest folder%/Payload/

  9. Deploy
    That’s it, all is set, simply drag the resulting IPA on to iTunes and install the patched application on a provisioned device as described on the ‘Installing Your App on Test Devices’ of this link.
    If the app being packaged include 3rd party Frameworks and/or Extensions these are also to be signed, of specific importance is the order in which they are signed, for example, if the app is composed of the following dependent modules


    the order in which they are to be signed must be bottom to top, thus, %tool app% -> %Extension% -> %app name%, otherwise package verification will fail and the app will not get installed on the device.

    When signing a module ( App/Framework/Extension/… ) the generated _CodeSignature refer all of it’s decedents, if any of the decedents is changed AFTER the _CodeSignature was generated verification will fail due to signature inconsistency and the app will not be installed, To avoid that, module signing must be bottom to top.

    A handy way to verify validity is to use the following for each of the embedded modules

    codesign –verify –verbose %App/Extension/Framework Name%

End result

Background is intentionally blurred

Risks & Limitations

  • Usage of a provisioning profile ( ad-hoc distribution ) limits usage on up to 100 devices
  • Injected framework must consist of a minimal set of dependencies to avoid different version of the same framework being loaded by the Mach-O
  • The current injection code takes as granted that there is enough space available between the last command and the first section for the Injected ‘dylib_command‘, while I have seen no cases where there was not enough space, in theory such a case can exist, to deal with it, a page aligned block should be inserted, and, all sections RVA should get correspondingly modified.


The write of this article takes no liability for any direct of indirect damage that usage of the accompanied source code and the demonstrated approach might cause.


Register as a developer with Apple, Mach-O file format, Mach-O View, Appels FairPlay, Creating provisioning profiles,
Application Entitlements, Bundle Structure, Cydia, Clutch Open-Source project, Creating Your Team Provisioning Profile, Working with the System Key-Chain, codesign tool, Beta Testing iOS Apps


The intended audience of this article are Windows Driver C++ developers and architects, It is assumed that the reader of this article is familiar with object oriented programming and design and is intimately acquainted with the Windows Operating System.

For the purpose of brevity and clarity, thread synchronization and error checking aspects are omitted and not discussed in details in this the article.


For a while I have been searching for the means of simulating Bluetooth HID devices under windows desktop, this apparently, is not that trivial since the Bluetooth HID interface is reserved for operating system use.

This Article provide a brief review of windows 8 Bluetooth stack & Profile Drivers, Describes it’s limitation with HID, and, present a work-around enabling HID device simulation using windows standard Bluetooth stack.

High level overview

The above present the main modules related with our use-case, in green, are custom modules developed by a 3rd party, in blue, are protocols/APIs provided by the operating system, in red, are operating system modules we patch in-order to achieve the desired functionality, and, in orange are physical HW components.

Profile Driver is a mini port driver implementing a specific Bluetooth service, in contrast to RFCOMM services which can be implemented using winsock on the user-realm, services that directly use L2CAP ( such as HID ) mandate Kernel-mode profile driver (KDMF) implementation.

The HCI layer provides a unified API for communicating with Bluetooth controllers, of specific interest for us is the HCI CoD ( Class of device/service ) indicating the type of Bluetooth peripheral, unfortunately, with windows built-in bluetooth stack the CoD is limited to COD_MAJOR_COMPUTER, and this, limits connectivity with various Bluetooth devices such as iOS which mandate a ‘Peripheral’ major class and a minor class of eg. ‘Keyboard’ ( where the CoD is 0x540 ), I have found this tool to be quite useful in generating popper Bluetooth CoDs

SDP stands for Service Discovery Protocol, it is used to report the type of services provided by the Bluetooth device, this is, for example, where HID devices report their descriptors or where a Bluetooth headset report it’s audio interface.

L2CAP is a lower level transport layer over-which various other protocols are implemented ( eg. RFCOMM ), it is responsible, among other things, for maintaining sequential packet connection to remote devices and multiplexing data from various Bluetooth services, this is the transport used for HID devices, with L2CAP services are identified by a unique Protocol/Service Multiplexer (PSM) identifier, for HID, two specific and pre-defined PSMs are needed, Interrupt and Control ( 0x13 & 0x11 correspondingly ), the first is used for Device to Host communication and the latter is used for Host to Device. Windows built-in bluetooth stack reserve these PSMs for OS use preventing HID devices simulation, later on in the article I will explain how to go around this limitation.

bthport.sys is a kernel module encapsulating Bluetooth logic including, among others, HCI, SDP, L2CAP, …. It is not a driver, rather, it is a dynamic library directly used by Profile drivers and other system components to implement Bluetooth services. bthport.sys is responsible for reserving the HID PSMs ( 0x13 & 0x11 ) using the ‘bthprot!BthIsSystemPSM‘ internal method, I will show, later in this article how to patch this method to go around PSM reservation.

Bluetooth L2CAP HID Connection Flow

The above high-level level diagram present the main steps in establishing a HID Bluetooth connection, in red, is the initialization phase where we register the PSMs to be used, once these are registered we are able to receive incoming L2CAP connections, the initialization phase is elaborated the next chapter.

Once the L2CAP connection is established HID Reports are sent to the controlled device and back indicating Key-Strokes and feedback from the device.

Driver Initialization

The diagram to the left illustrate the main steps in setting-up an L2CAP HID Profile Driver, The first thing needed is to register a callback method to be invoked upon incoming L2CAP connections, this is done by querying for the Profile driver interface using WdfFdoQueryForInterface, Allocating a Bluetooth Request Block ( BRB ), Setting up the BRB and dispatching it to the IoTarget.

Once the L2CAP callbacks are installed the required PSMs are registered, this is done by dispatching a BRB_REGISTER_PSM with the desired PSMs, In our case: 0x1 for SDP, 0x13 for the Control channel, and, 0x11 for Interrupt.

Registering PSMs reserved for OS use will fail, that is, also if there is no existing connected/paired HID device, the next chapter discuss an approach to go around that limitation.

Once the PSMs are registered we need to use them in conjunction with the Keyboard HID Descriptor to set-up the SDP, bthport.sys expose “GUID_BTHDDI_SDP_PARSE_INTERFACE” obtained using WdfFdoQueryForInterface for that purpose.

Once the SDP is ready it is published to the IoTarget to be listed on the available Bluetooth services of the Desktop machine.

Reserved PSMs Workaround

As earlier mentioned, with Windows OS the HID PSMs are reserved and cannot be used by Profile Drivers, PSM registration logic is implemented by bthport.sys, to work around the PSM limitation a binary patch is applied.

bthport.sys implement an internal method called “BthIsSystemPSM”, this is where the magic happen and where the patch is applied, the process consists of the following steps:

  1. Upon driver startup, Find bthport.sys!BthIsSystemPSM on the loaded binary image
    for that, it is needed to get the address of a reference method in bthport.sys and have the offset to BthIsSystemPSM, this is used to get access to the binary code responsible for OS PSM reservation.
    The reference method we use is bthport.sys!BthAllocateBrb, this method is exposed using the BTH_PROFILE_DRIVER_INTERFACE we have previosly retrieved by calling WdfFdoQueryForInterface
    bthport.sys!BthIsSystemPSM is not accessible using WdfFdoQueryForInterface, getting it’s address is not straight forward and require some low-level PE analysis, Using IDA ( Interactive Disassembler ) we can resolve bthport.sys!BthIsSystemPSM and bthport.sys!BthAllocateBrb PE offsets, get the relative distance ( which is identical to the distance when the PE is loaded in memory ) and use it to find bthport.sys!BthIsSystemPSM address on the loaded binary ( on runtime )
  2. Binary-code modification
    The extracted binary code for bthport.sys!BthIsSystemPSM is the following:

    B8 ED FF 00 00 66 FF C9 66 85 C8 0F 94 C0 C3 CC

    Having this dis-assembled results the following, in green are the values of the relevant registers before executing the instruction on that line

    01> b8 ed ff 00 00
    02> 66 ff c9
    03> 66 85 c8
    04> 0f 94 c0
    05> c3
    06> cc
    mov eax,0FFEDh
    dec cx
    test ax,cx
    sete al
    int 3
    // ZF:1 AL:0x09 AX:0x109 CX:0x11
    // ZF:1 AL:0xed AX:0xffed CX:0x11
    // ZF:0 AL:0xed AX:0xffed CX:0x10
    // ZF:1 AL:0xed AX:0xffed CX:0x10
    // ZF:1 AL:0x01 AX:0xffed CX:0x10

    With the above assembly code, the PSM is set through register CX ( 0x11 in our case ), this value is deduced by one on line #02 and then, on line #03 applied a ‘bitwise and’ operator with the value at register AX ( 0xFFED ), this result a zero value, sets the Zero Flag ( register ZF ) to 1 and assign it’s value to register AL, the calling code evaluates AL to make sure if the PSM can be used by the calling code, in our case a value of AL=1 will cause BRB_REGISTER_PSM to fail.

    In order to workaround this PSM verification we should cause the code to return with AL set to Zero, this will prevent the calling code from rejecting our PSMs, and will, in turn, enable L2CAP HID connections

    Inspecting line #03 of the above it is clear that “0 == (0xFFED & (0x11 – 1))”, and also that “0 == (0xFFED & (0x13 – 1))”, and hence, we need to change the 0xFFED mask such that the bitwise and operation result will be different than Zero, this, is achieved by changing the 0xFFED mask to 0xFFFD, having that set, the code execute as follows:

    01> b8 fd ff 00 00
    02> 66 ff c9
    03> 66 85 c8
    04> 0f 94 c0
    05> c3
    06> cc
    mov eax,0FFFDh
    dec cx
    test ax,cx
    sete al
    int 3
    // ZF:1 AL:0x09 AX:0x109 CX:0x11
    // ZF:1 AL:0xfd AX:0xfffd CX:0x11
    // ZF:0 AL:0xfd AX:0xfffd CX:0x10
    // ZF:0 AL:0xfd AX:0xfffd CX:0x10
    // ZF:0 AL:0x00 AX:0xfffd CX:0x10

    The above returns AL=0 resulting acceptance of the HID PSMs, the raw binary code we need to update looks as follows:

    B8 FD FF 00 00 66 FF C9 66 85 C8 0F 94 C0 C3 CC

  3. Patch the binary code
    Once we have the offset between bthport.sys!BthIsSystemPSM and bthport.sys!BthAllocateBrb we need to updated the binary code with the above mentioned modification, we can’t however, directly update the binary code, before doing so we need to clear the Write Protectin ( WP ) bit of register cr0, Apply the update and then return the original value of cr0, this is done using the __writecr0 and __readcr0 kernel intrinsics, once we are done with the modification our code can freely Register the HID PSMs and intercept incoming HID L2CAP connections.

Sample Code

    // 000000000008B4D0 – BthIsSystemPSM PE Offset ( fixed )
    // 0000000000083698 – BthAllocateBrb PE Offset ( fixed )
    // bthprot!BthIsSystemPSM: B8 ED FF 00 00 66 FF C9 66 85 C8 0F 94 C0 C3 CC
    UCHAR    pMachineCode[] = { 0xb8, 0xed, 0xff, 0x00,
                                0x00, 0x66, 0xff, 0xc9,
                                0x66, 0x85, 0xc8, 0x0f,
                                0x94, 0xc0, 0xc3, 0xcc };
    // The approx distance between ‘itf.BthAllocateBrb’ and ‘bthprot!BthIsSystemPSM’
    INT64    qwOffset    = (INT64)(0x8B4D0 – 0x83698);
    PUCHAR    pAddr        = (PUCHAR)((UINT64)itf.BthAllocateBrb + qwOffset);
    // Make the start address page aligned
    PUCHAR    pAddrStart    = (PUCHAR)((UINT64)pAddr & 0xfffffffffffff000);
    UINT64    qwTrailer    = *(UINT64*)(pMachineCode + sizeof(pMachineCode)
                            - sizeof(qwTrailer));
    PUCHAR    pAddrEnd    = pAddrStart + PAGE_SIZE – sizeof(qwTrailer);

    pAddrStart += sizeof(pMachineCode) – sizeof(qwTrailer);
    while (pAddrStart <= pAddrEnd) {
        if (*(UINT64*)(pAddrStart) == qwTrailer) {
            if (0 == memcmp(pAddrStart + sizeof(qwTrailer) – sizeof(pMachineCode),
                            pMachineCode, sizeof(pMachineCode) – sizeof(qwTrailer)))
                NT_ASSERT(0xed == pAddrStart[-7]);
                const auto cr0 = __readcr0();
                const auto cr0noWP = cr0 & 0xFFFFFFFFFFFEFFFF;// Clear the WP bit
                pAddrStart[-7] = 0xfd;// Patch the code!!!
                return TRUE;
    return FALSE;

Risks & Limitations

  • All kernel modules are running under a shared address space, any change done to bthport.sys will affect any other module/driver referring/using it.
  • The HID PSMs are reserved by the OS for a reason, Usage of this patch should be done with care when other Bluetooth HID devices are connected.
  • This binary patch assumes a specific bthport.sys version with fixed bthport.sys!BthIsSystemPSM relative positing, while the above sample code demonstrate some flexibility regarding finding the right offset, updated bthport.sys versions might require re-calculating the new offsets.
  • As mentioned before, Some devices expect a specific HID CoD values, Windows OS doesn’t support the required HCI level API for changing the CoD, this way, using this kernel patch will enable HID device simulation for eg. Android Devices but not for iOS devices, the reader is encouraged to use the approach described in this article to patch this through.
  • Windows kernel implement a mechanism called Kernel Patch Protection (KPP), this mechanisms verify no binary changes were applied to core kernel modules on runtime, at the time this article was written bthport.sys wasn’t one of these modules, this, may ( and may not ) change in the future.


This Article discuss implementing an HID device using the Windows Desktop Bluetooth stack, this stack is limited and mandate a binary patch, When Windows OS is not a hard requirement the reader is encouraged to use solutions where the above mentioned is natively supported, such as the Linux BlueZ stack.

The patch was implemented on Windows 8 OS (x64) and should be verified if used on other/newer OS versions


KDMF Profile drivers, RFCOMM, Assigned CoD Numbers – Bluetooth Baseband, Bluetooth Class of Device/Service (CoD) Generator, PSMs reserved for OS use, HID: Human Interface Device Class, Bluetooth Request Block, L2CAP Bluetooth Echo Sample, Service Discovery Protocol, Keyboard HID Descriptor, Hex-Rays Interactive Disassembler (IDA), A Guide to Kernel Exploitation, Kernel Patch Protection (KPP), Linux BlueZ stack,


The intended audience of this article are MacOS C++/Obj-C developers and architects, It is assumed that the reader of this article is familiar with object oriented programming and design.

For the purpose of brevity and clarity, thread synchronization aspect is omitted and not discussed in details in this the article.


The Objective-C AVFoundation framework is encapsulating media processing ( capture, editing, … ), it is robust, well document and covers most of the A/V use-cases, however, some edge case use-cases are not supported by this framework, for example, being able to directly access the buffers sent out from the device, this, is specifically important when the payload sent out from the device is already muxed and/or compressed, in such cases, AVFoundation ( AVCaptureSession in-specific ) will de-mux and/or decode the payload before making it accessible to the user, to get direct access to the buffers sent out from the device w/o any intermediate intervention we will have to use a lower-level API, namely, the CoreMediaIO.

Apples CoreMediaIO is a low-level C++ framework for accessing and interacting with audio/video devices such as cameras, capture cards and even Mirroring sessions of iOS devices

The problem with CoreMediaIO is lack of documentation, and, the fact that the existing sample code is old and require quite some tinkering to have it compiling with latest SDKs

In this short article I will provide a simple sample code demonstrating capture and format resolution using CoreMediaIO and some AVFoundation


CoreMediaIO API are provided through the “CoreMediaIO.framework“, make sure to have it included by the project, and to have “CoreMediaIO/CMIOHardware.h” included/imported.

The first thing we have to do in-order to be able to start capture is to find the device of interest, if we are interested in screen capture ( for example capturing the screen of an attached iOS device ) we need to enable CoreMediaIO ‘DAL’ plug-ins, This, is demonstrated in the following code snap:

void EnableDALDevices()
    CMIOObjectPropertyAddress prop = {

    UInt32 allow = 1;
                            &prop, 0, NULL,
                            sizeof(allow), &allow );

Some devices are added or removed on runtime, to get runtime indications for device addition or removal, an A/V Capture device notification is set using the NSNotificationCenter class, the AVCaptureDevice added/removed is indicated by the ‘object‘ variable of the ‘note‘ ^block argument, This is demonstrated by the following code snap, Be aware that no notifications will be received unless a Run Loop is executed.

NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
id connObs =[notiCenter addObserverForName:AVCaptureDeviceWasConnectedNotification
                                     queue:[NSOperationQueue mainQueue]
                                usingBlock:^(NSNotification *note)
                                                // Device addition logic

id disconnObs =[notiCenter addObserverForName:AVCaptureDeviceWasDisconnectedNotification
                                        queue:[NSOperationQueue mainQueue]
                                 usingBlock:^(NSNotification *note)
                                                // Device removal logic

[[NSRunLoop mainRunLoop] run];
[notiCenter removeObserver:connObs];
[notiCenter removeObserver:disconnObs];

The next step is to enumerate the attached capture devices, this is either done using AVCaptureDevice class of AVFoundation or, directly using CoreMediaIO C++ APIs, each capture device provide an uniquely identifier, in the next code snap, that id will be used to find the device of interest

The Code Snap bellow demonstrate device enumeration using AVFoundation APIs, To filter a specific type of device use the ‘devicesWithMediaType’ method of the AVCaptureDevice class.

// Use the ‘devicesWithMediaType’ to filter devs by media type
// NSArray* devs = [AVCaptureDevice devicesWithMediaType:AVMediaTypeMuxed];
NSArray* devs = [AVCaptureDevice devices];
NSLog(@“devices: %d\n”, (int)[devs count]);

for(AVCaptureDevice* d in devs) {
    NSLog(@“uniqueID: %@\n”, [d uniqueID]);
    NSLog(@“modelID: %@\n”, [d modelID]);
    NSLog(@“description: %@\n”, [d localizedName]);

The next step is to find the device we want to use for capture, Capture devices in CoreMediaIO are identified by CMIODeviceID, the following code-snap demonstrate how to resolve the devices CMIODeviceID according to their unique ID which is a-priori known and externally provided.

OSStatus GetPropertyData(CMIOObjectID objID, int32_t sel, CMIOObjectPropertyScope scope,
                         UInt32 qualifierDataSize, const void* qualifierData, UInt32 dataSize,
                         UInt32& dataUsed, void* data) {
    CMIOObjectPropertyAddress addr={ (CMIOObjectPropertySelector)sel, scope,
                                     kCMIOObjectPropertyElementMaster };
    return CMIOObjectGetPropertyData(objID, &addr, qualifierDataSize, qualifierData,
                                     dataSize, &dataUsed, data);

OSStatus GetPropertyData(CMIOObjectID objID, int32_t selector, UInt32 qualifierDataSize,
                         const void* qualifierData, UInt32 dataSize, UInt32& dataUsed,
                         void* data) {
    return GetPropertyData(objID, selector, 0, qualifierDataSize,
                         qualifierData, dataSize, dataUsed, data);

OSStatus GetPropertyDataSize(CMIOObjectID objID, int32_t sel,
                             CMIOObjectPropertyScope scope, uint32_t& size) {
    CMIOObjectPropertyAddress addr={ (CMIOObjectPropertySelector)sel, scope,
                                     kCMIOObjectPropertyElementMaster };
    return CMIOObjectGetPropertyDataSize(objID, &addr, 0, 0, &size);

OSStatus GetPropertyDataSize(CMIOObjectID objID, int32_t selector, uint32_t& size) {
    return GetPropertyDataSize(objID, selector, 0, size);

OSStatus GetNumberDevices(uint32_t& cnt) {
    if(0 != GetPropertyDataSize(kCMIOObjectSystemObject, kCMIOHardwarePropertyDevices, cnt))
        return -1;
    cnt /= sizeof(CMIODeviceID);
    return 0;

OSStatus GetDevices(uint32_t& cnt, CMIODeviceID* pDevs) {
    OSStatus status;
    uint32_t numberDevices = 0, used = 0;
    if((status = GetNumberDevices(numberDevices)) < 0)
        return status;
    if(numberDevices > (cnt = numberDevices))
        return -1;
    uint32_t size = numberDevices * sizeof(CMIODeviceID);
    return GetPropertyData(kCMIOObjectSystemObject, kCMIOHardwarePropertyDevices,
                         0, NULL, size, used, pDevs);

template< const int C_Size >
OSStatus GetDeviceStrProp(CMIOObjectID objID, CMIOObjectPropertySelector sel,
                         char (&pValue)[C_Size]) {
    CFStringRef answer = NULL;
    UInt32     dataUsed= 0;
    OSStatus    status = GetPropertyData(objID, sel, 0, NULL, sizeof(answer),
                                         dataUsed, &answer);
    if(0 == status)// SUCCESS
        CFStringCopyUTF8String(answer, pValue);
    return status;

template< const int C_Size >
Boolean CFStringCopyUTF8String(CFStringRef aString, char (&pText)[C_Size]) {
    CFIndex length = CFStringGetLength(aString);
    if(sizeof(pText) < (length + 1))
        return false;
    CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
    return CFStringGetCString(aString, pText, maxSize, kCFStringEncodingUTF8);

Utility methods

OSStatus FindDeviceByUniqueId(const char* pUID, CMIODeviceID& devId) {
    OSStatus status = 0;
    uint32_t numDev = 0;
    if(((status = GetNumberDevices(numDev)) < 0) || (0 == numDev))
        return status;
    // Allocate memory on the stack
    CMIODeviceID* pDevs = (CMIODeviceID*)alloca(numDev * sizeof(*pDevs));
    if((status = GetDevices(numDev, pDevs)) < 0)
        return status;
    for(uint32_t i = 0; i < numDev; i++) {
        char pUniqueID[64];
        if((status = GetDeviceStrProp(pDevs[i], kCMIODevicePropertyDeviceUID, pUniqueID)) < 0)
        status = afpObjectNotFound;// Not Found…
        if(0 != strcmp(pUID, pUniqueID))
        devId = pDevs[i];
        return 0;
    return status;

Device resolution by UID

CoreMediaIO Capture devices expose streams, each such stream is a data source and is indicated using a CMIOStreamID type, one stream might provide Video payload, another can provide Audio payload and others might provide multiplexed payload, while capturing we have to select a stream and start pumping out data, the following code-snap demonstrate how to enumerate the available streams for a given device ( indicated by it’s CMIODeviceID ) and how to resolve the payload format.

uint32_t GetNumberInputStreams(CMIODeviceID devID)
    uint32 size = 0;
    GetPropertyDataSize(devID, kCMIODevicePropertyStreams,
                        kCMIODevicePropertyScopeInput, size);
    return size / sizeof(CMIOStreamID);

OSStatus GetInputStreams(CMIODeviceID devID, uint32_t&
                        ioNumberStreams, CMIOStreamID* streamList)
    ioNumberStreams = std::min(GetNumberInputStreams(devID), ioNumberStreams);
    uint32_t size     = ioNumberStreams * sizeof(CMIOStreamID);
    uint32_t dataUsed = 0;
    OSStatus err = GetPropertyData(devID, kCMIODevicePropertyStreams,
                                    kCMIODevicePropertyScopeInput, 0,
                                    NULL, size, dataUsed, streamList);
    if(0 != err)
        return err;
    ioNumberStreams = size / sizeof(CMIOStreamID);
    CMIOStreamID* firstItem = &(streamList[0]);
    CMIOStreamID* lastItem = firstItem + ioNumberStreams;
    std::sort(firstItem, lastItem);
    return 0;

Utility methods

CMIODeviceID devId;
FindDeviceByUniqueId(“4e58df701eb87”, devId);

uint32_t numStreams = GetNumberInputStreams(devId);
CMIOStreamID* pStreams = (CMIOStreamID*)alloca(numStreams * sizeof(CMIOStreamID));
GetInputStreams(devId, numStreams, pStreams);
for(uint32_t i = 0; i < numStreams; i++) {
    CMFormatDescriptionRef fmt = 0;
    uint32_t                used;
    GetPropertyData(pStreams[i], kCMIOStreamPropertyFormatDescription,
                    0, NULL, sizeof(fmt), used, &fmt);
    CMMediaType mt     = CMFormatDescriptionGetMediaType(fmt);
    uint8_t     null1 = 0;// ‘mt’ is a 4 char string, we use ‘null1’ so
                         // it could be printed.
    FourCharCode fourcc= CMFormatDescriptionGetMediaSubType(fmt);
    uint8_t     null2 = 0;// ‘fourcc’ is a 4 char string, we use ‘null1’
                         // so it could be printed.
    printf(“media type: %s\nmedia sub type: %s\n”, (char*)&mt, (char*)&fourcc);

Stream format resolution

The next and final stage is to start pumping data out of the stream, this is done by registering a callback to be called upon by CoreMediaIO with the sampled payload, the following code-snap demonstrate how this is done and how to get access to the raw payload bytes.

CMSimpleQueueRef    queueRef = 0;// The queue that will be used to
                                 // process the incoming data
CMIOStreamCopyBufferQueue(strmID, [](CMIOStreamID streamID, void*, void* refCon) {
    // The callback ( lambda in out case ) being called by CoreMediaIO
    CMSimpleQueueRef queueRef = *(CMSimpleQueueRef*)refCon;
    CMSampleBufferRef sb = 0;
    while(0 != (sb = (CMSampleBufferRef)CMSimpleQueueDequeue(queueRef))) {
        size_t            len     = 0;// The ‘len’ of our payload
        size_t            lenTotal = 0;
        char*             pPayload = 0;// This is where the RAW media
                                     // data will be stored
        const CMTime     ts         = CMSampleBufferGetOutputPresentationTimeStamp(sb);
        const double     dSecTime = (double)ts.value / (double)ts.timescale;
        CMBlockBufferRef bufRef     = CMSampleBufferGetDataBuffer(sb);
        CMBlockBufferGetDataPointer(bufRef, 0, &len, &lenTotal, &pPayload);
        assert(len == lenTotal);
        // TBD: Process ‘len’ bytes of ‘pPayload’
}, &queueRef, &queueRef);

One last thing to note, on more tan few cases the actual capture format is not available until the first sample is sent, in such cases it should be resolved upon first sample reception, the following code-snap demonstrate how to resolve Audio sample format using CMSampleBufferRef, the same can be done for video and other media types with a little more effort.

bool PrintAudioFormat(CMSampleBufferRef sb)
    CMFormatDescriptionRef    fmt    = CMSampleBufferGetFormatDescription(sb);
    CMMediaType                mt    = CMFormatDescriptionGetMediaType(fmt);

    if(kCMMediaType_Audio != mt) {
        printf(“Not an audio sample\n”);
        return false;
    CMAudioFormatDescriptionRef afmt = (CMAudioFormatDescriptionRef)fmt;
    const auto pAud = CMAudioFormatDescriptionGetStreamBasicDescription(afmt);
    if(0 == pAud)
        return false;
    // We are expecting PCM Audio
    if(‘lpcm’ != pAud->mFormatID)// ‘pAud->mFormatID’ == fourCC
        return false;// Not a supported format
    printf(“mChannelsPerFrame: %d\nmSampleRate: %.1f\n”\
            “mBytesPerFrame: %d\nmBitsPerChannel: %d\n”,
         pAud->mChannelsPerFrame, pAud->mSampleRate,
         pAud->mBytesPerFrame, pAud->mBitsPerChannel);
    return true;

Final words

What provided in this article is just a glimpse of what is doable with CoreMediaIO, further information of can be found in the reference links bellow.


CoreMediaIO, AVFoundation, AVCaptureSession, NSNotificationCenter, Run Loop, AVCaptureDevice