SlideShare a Scribd company logo
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
The Python Bites your Apple
Fuzzing and exploiting OSX Kernel bugs
Flanker
KeenLab Tencent
XKungfoo Shanghai, April 2016
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Table of Contents
1 Introduction
About
2 IOKit Security Background
Core of the Apple
3 Introducing Kitlib
Introducing Kitlib
4 Introducing KextHelper
Introducing KextHelper
5 Case Studies
Case Studies
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
About
About me
Senior Security Researcher at KeenLab, Tencent
Pwn2Own 2016 OSX Category Winner
BlackHat, CanSecWest, HITCON, QCon Speaker
*nix platform sandbox bypass and kernel exploitation
Google Android Security Top Researchers Hall of Fame
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
About
About KeenLab
Former KeenTeam with all researchers move to Tencent and
form KeenLab
8 Pwn2Own Champions
Universal Rooting
We’re hiring!
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
About
Objective of this talk
Basic description of IOKit
Kernel Zone Allocator and Fengshui Technique
Introducing KitLib and distributed Fuzzer
Introducing Kexthelper, a IDA plugin for OSX KEXT
Case Studies
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Core of the Apple
IOKit Security Background
What’s IOKit
I/O Kit is a collection of system frameworks, libraries, tools, and
other resources for creating device drivers in OS X
Security researchers tend to refer it as Kernel drivers and
frameworks written with IOKit and accessible via IOKit
method calls
Why attacking IOKit
IOKit drivers runs in Kernel space, some of them even
reachable from browser sandbox for efficiency (Graphics).
Huge number of drivers implemented
Few access restrictions (compared to Android)
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Core of the Apple
IOKit Security Background
IOService
Different services are exposed via IOKit. We can consult most of
them in Hardware IO tools and ioreg.
IOAccelerator
IOHIDDevice
IOPMrootDomain
...
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Core of the Apple
IOKit Security Background
IOUserClient
External method calls are first routed via IOUserClient, triggered
by mach msg IPC
kern_return_t IOServiceOpen( io_service_t service, task_port_t owningTask, uint32_t type,
io_connect_t *connect );
When userspace openService is called, corresponding
newUserClient at Kernel space is invoked
Different types may map to different userClient
IOAccelerator
May check caller’s identity: is root? (OSX and iOS differ)
IOServiceClose maps to clientClose in is io service close (race
condition here?)
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Core of the Apple
IOKit Security Background
externalMethod
Method calls are dispatched through getTargetMethodForIndex
and/or externalMethod
virtual IOExternalMethod * getTargetAndMethodForIndex(IOService ** targetP, UInt32 index );
virtual IOReturn externalMethod(uint32_t selector, IOExternalMethodArguments *
args,IOExternalMethodDispatch * dispatch, OSObject * target, void * reference)
IOExternalMethodArguments is constructed in
is io connect method containing incoming parameter
IOExternalMethod/IOExternalMethodDispatch specifies
parameters constraint
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Core of the Apple
IOKit Security Background
Calling conventions
structureInput will be converted to descriptor if size >0x4000
in IOConnectCallMethod
if size <0x4000 passes through inband buffer
io connect method generate and send mach msg
of course we can directly call io connect method, bypass this
constraint
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Core of the Apple
libkern C++ Runtime
Reduced set of C++
No Exception
No Multiple Inherience
No template
Custom implementation of RTTI
OSMetaClass
OSMetaClass is defined by macros
Contains Name, size and father class for each corresponding
class
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Core of the Apple
IOKit Security Background
IOConnectCallMethod
kern_return_t
IOConnectCallMethod(
mach_port_t connection, // In
uint32_t selector, // In
const uint64_t *input, // In
uint32_t inputCnt, // In
const void *inputStruct, // In
size_t inputStructCnt, // In
uint64_t *output, // Out
uint32_t *outputCnt, // In/Out
void *outputStruct, // Out
size_t *outputStructCntP) // In/Out
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Core of the Apple
IOKit historical vulnerabilities
Race condition (hottest) (CVE-2015-7084)
Heap overflow
UAF
TOCTOU
OOB write (Our P2O bug!)
NULL dereference (not exploitable with SMAP and in
sandbox)
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Core of the Apple
Cons of traditional fuzzer
written in C/C++, more time consuming
error-prone, easy to make mistakes
less supporting library
socket
logging
not dynamically expandable due to language nature
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing Kitlib
Introducing Kitlib
io_connect_t t;
io_service_t svc =
IOServiceGetMatchingService(kIOMasterPortDefault,
IOServiceMatching("fuckliangchen"));
IOServiceOpen(svc, mach_task_self(), 0, &t);
uint32_t outputCnt = 0x100;
size_t outputStructCnt = 0x2000;
uint64_t* output = new uint64_t[outputCnt];
char* outputStruct = new
char[outputStructCnt];
const uint32_t inputCnt = 0x100;
uint64_t input[inputCnt];
const size_t inputStructCnt = 0x2000;
char inputStruct[inputStructCnt];
IOConnectCallMethod(t, 0, input, inputCnt,
inputStruct, inputStructCnt, output,
&outputCnt, outputStruct,
&outputStructCnt);
import kitlib
h = kitlib.openSvc(’fuckliangchen’, 0)
kitlib.callConnectMethod(h, [0L]*0x100,
’a’*0x2000, 0x100, 0x2000)
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing Kitlib
What’s Kitlib
Kitlib is a Python wrapper for IOKit calls
Internally written in C++ and Python, provides convenient
functions for writing fuzzers, using SWIG and ctypes
Performance cost is low
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing Kitlib
SWIG usage
Define interfaces in header file (kitlib.h)
C++ wrapper layer in cpp file (if needed) (kitlib.cpp)
Writing wrapping code for argument convention from Python
to C++ in glue file (kitlib.i)
Questions
Memory management?
Type conventions?
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing Kitlib
Header file
Defining basic types
mach port t
mach vm address t
io object t
io service t
io iterator t
Define interfaces
mach_port_t openSvc(const char* svc_name, uint32_t type);
mach_port_t* openMultiSvc(const char* svc_name, uint32_t* typearr);
size_t getSvcCntForName(const char* svc_name);
bool svcAva(const char* svc_name,uint32_t type);
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing Kitlib
Glue file
Wraps functions
size_t getSvcCntForName(const char* svc_name)
{
io_iterator_t iter;
kern_return_t kr;
io_service_t device;
size_t ret = 0;
kr = IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching(svc_name), &iter);
while ((device = IOIteratorNext(iter)))
{
++ret;
IOObjectRelease(device);
}
IOObjectRelease(iter);
return ret;
}
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing Kitlib
Glue file
Wraps functions
unsigned int callConnectMethod(
mach_port_t connection, // In
uint32_t selector, // In
const uint64_t *input, // In
uint32_t inputCnt, // In
const void *inputStruct, // In
size_t inputStructCnt, // In
uint64_t *output, // Out
uint32_t *outputCnt, // In/Out
void *outputStruct, // Out
size_t *outputStructCnt)
{ kern_return_t kt = IOConnectCallMethod((mach_port_t) connection, /* Connection */
selector, /* Selector */
input, inputCnt, /* input, inputCnt */
inputStruct, /* inputStruct */
inputStructCnt, /* inputStructCnt */
output, outputCnt, outputStruct, outputStructCnt); /*
Output stuff */
return kt;
}
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing Kitlib
Argument Wrapping
/*
This function handles scalar input, translate the incoming python value, which is list,
to native representation. Memory cleanup is needed afterwards
*/
%typemap(in) (const uint64_t *input, uint32_t inputCnt) {
/* Check if is a list */
if (PyList_Check($input)) {
uint32_t size = PyList_Size($input);
uint32_t i = 0;
$2 = size;
$1 = (uint64_t*) malloc(size * sizeof(uint64_t));
for (i = 0; i < size; i++) {
PyObject *o = PyList_GetItem($input,i);
if (PyLong_Check(o)) {
$1[i] = PyLong_AsUnsignedLongLong(o);
}
else {
PyErr_SetString(PyExc_TypeError,"list must contain L numbers");
free($1);
return NULL;
}
}
} else if ($input == Py_None) {
$1 = NULL;
$2 = 0;
} else {
PyErr_SetString(PyExc_TypeError,"not a list");
return NULL;
}
}
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing Kitlib
Argument wrapping
freeing memory
%typemap(freearg) (const uint64_t *input, uint32_t inputCnt) {
free($1);
}
Call flow
user Python code calls in SWIG auto-generated function
SWIG auto-generated function calls user convention typemap
code, mapping python types to C++ arguments $1 $2, etc
SWIG auto-generated function passes $1 $2, etc into C++
glue code
SWIG auto-generated function calls freearg code to free
memory
NO GIL TROUBLE LOLFlanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing Kitlib
Kitlib Implementation
Example source code
import kitlib
h = kitlib.openSvc(’fuckliangchen’, 0)
kitlib.callConnectMethod(h, [0L]*0x100, ’a’*0x2000, 0x100, 0x2000)
inputScalar to list
inputStruct to string/bytearray
outputScalar/outputStruct maps to len
output maps to tuple (retcode, outscalar, outstruct)
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing Kitlib
Problems for Kitlib1
I’m lazy and I don’t want to write wrapper for each interface
Argument passing is immutable, cannot do TOCTOU fuzzing
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing Kitlib
Calling directly into library functions
ctypes
For functions without need for wrapping we directly call ctypes
Build-in mutable support (TOCTOU and race condition
fuzzing)
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing Kitlib
Basic ctypes primitives
ctypes
c int, c ulonglong, c char p
create string buffer
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing KextHelper
Parsing KEXT for arguments
static const IOExternalMethodDispath/IOExternalMethod
array (parseable)
dynamic routed via code (oops)
for former we can automatically retrieve arguments via
pattern matching
Scan const-data section for matching
Map class to arguments array
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing KextHelper
Example IOExternalMethodDispatch
__const:0000000000064BC0 ; IGAccelCLContext::attach(IOService *)::methodDescs
__const:0000000000064BC0 __ZZN16IGAccelCLContext6attachEP9IOServiceE11methodDescs db 0
__const:0000000000064BC0 ; DATA XREF:
IGAccelCLContext::attach(IOService *)+16
__const:0000000000064BC1 db 0
__const:0000000000064BC2 db 0
__const:0000000000064BC3 db 0
__const:0000000000064BC4 db 0
__const:0000000000064BC5 db 0
__const:0000000000064BC6 db 0
__const:0000000000064BC7 db 0
__const:0000000000064BC8 dq offset
__ZN16IGAccelCLContext15map_user_memoryEP22IntelCLMapUserMemoryInP23IntelCLMapUserMemoryOutyPy
; IGAccelCLContext::map_user_memory(IntelCLMapUserMemoryIn *,IntelCLMapUserMemoryOut
*,ulong long,ulong long *)
__const:0000000000064BD0 db 0
__const:0000000000064BD1 db 0
__const:0000000000064BD2 db 0
__const:0000000000064BD3 db 0
__const:0000000000064BD4 db 0
__const:0000000000064BD5 db 0
__const:0000000000064BD6 db 0
__const:0000000000064BD7 db 0
__const:0000000000064BD8 db 3
__const:0000000000064BD9 db 0
__const:0000000000064BDA db 0
__const:0000000000064BDB db 0
__const:0000000000064BDC db 0
__const:0000000000064BDD db 0
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing KextHelper
After parsing
_const:0000000000064BC0 ; IGAccelCLContext::attach(IOService *)::methodDescs
__const:0000000000064BC0 __ZZN16IGAccelCLContext6attachEP9IOServiceE11methodDescs
IOExternalMethod <0, 
__const:0000000000064BC0 ; DATA XREF:
IGAccelCLContext::attach(IOService *)+16
__const:0000000000064BC0 offset
__ZN16IGAccelCLContext15map_user_memoryEP22IntelCLMapUserMemoryInP23IntelCLMapUserMemoryOutyPy,
; IGAccelCLContext::map_user_memory(IntelCLMapUserMemoryIn *,IntelCLMapUserMemoryOut
*,ulong long,ulong long *)
__const:0000000000064BC0 0, 3, 0FFFFFFFFh, 0FFFFFFFFh>
__const:0000000000064BF0 IOExternalMethod <0,  ;
IGAccelCLContext::unmap_user_memory(IntelCLUnmapUserMemoryIn *,ulong long)
__const:0000000000064BF0 offset
__ZN16IGAccelCLContext17unmap_user_memoryEP24IntelCLUnmapUserMemoryIny,
__const:0000000000064BF0 0, 4, 0, 0FFFFFFFFh>
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing KextHelper
Example: IOExternalMethodDispatch
matching
+0 points to TEXT or zero
+8, +16, +24 reasonable integers (NO TEXT pointing)
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing KextHelper
Example: Vtable matching
Reference from constructor
+8, +16, ... all points to TEXT section or EXTERN(UNDEF)
section
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing KextHelper
Pseudo Algo
matchers = [IOExternalMethodDispatchMatcher, VtableMatcher, IOExternalMethodMatcher]
for matcher in matchers:
if matcher.isSectionBegin(const_data_section):
matcher.deflateToList(section, offset)
break
map userclient with arguments
scan newUserClient for service-userclient mappings
add father’s userclient to children service
scan constructor for service size
scan for offset access to determine field offset
Construct vtable as a structure S, set vt(offset 0, size 8) type to S*
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing KextHelper
Restoring object structure
Scanning MetaClass function for object’s size
Create the object’s whole vtable area as a struct
Setting +0(8) field as vt and type to previous struct pointer
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing KextHelper
Restoring object structure(cont.)
//...
__text:0000000000048079 mov r14, rdi
__text:000000000004807C movzx eax, word ptr [rbx+22h]
__text:0000000000048080 cmp eax, 3
__text:0000000000048083 jnz loc_48122
__text:0000000000048089 cmp qword ptr [rbx], 0
__text:000000000004808D jz loc_48129
//...
__text:00000000000480A6 cmp rax, rcx
__text:00000000000480A9 jnb short loc_48129
__text:00000000000480AB mov rax, [r14]
__text:00000000000480AE mov rdi, r14
__text:00000000000480B1 mov rsi, rbx
__text:00000000000480B4 call qword ptr [rax+9E8h]
__text:00000000000480BA mov rdi, [r14+1030h]
__text:00000000000480C1 mov rax, [rdi]
__text:00000000000480C4 mov esi, [r15+8]
__text:00000000000480C8 shl rsi, 6
__text:00000000000480CC add rsi, [r14+610h]
__text:00000000000480D3 call qword ptr [rax+140h]
__text:00000000000480D9 inc dword ptr [rbx+2Ch]
__text:00000000000480DC cmp byte ptr [rbx+30h], 0
__text:00000000000480E0 jz short loc_480F8
__text:00000000000480E2 mov eax, [r15+8]
__text:00000000000480E6 mov rcx, [r14+608h]
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing KextHelper
Restoring object structure(cont.)
Scanning functions and perform forward-flow analysis on
registers starting RDI
Retriving MOV/LEA offset and do addStructMember
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing KextHelper
__int64 __fastcall IGAccelCLContext::process_token_SetFence(__int64 this, __int64 a2)
{
__int64 v2; // r15@3
__int64 result; // rax@6
unsigned int v4; // esi@7
if ( *(_WORD *)(a2 + 34) != 3 )
{
v4 = -5;
return IOAccelContext2::setContextError((IOAccelContext2 *)this, v4);
}
if ( !*(_QWORD *)a2
|| (v2 = *(_QWORD *)(a2 + 24), (unsigned __int64)*(unsigned int *)(v2 + 8) << 6 >=
*(unsigned int *)(this + 1600)) )
{
v4 = -2;
return IOAccelContext2::setContextError((IOAccelContext2 *)this, v4);
}
(*(void (__cdecl **)(__int64))(*(_QWORD *)this + 2536LL))(this);
(*(void (__fastcall **)(_QWORD, unsigned __int64))(**(_QWORD **)(this + 4144) + 320LL))(
*(_QWORD *)(this + 4144),
*(_QWORD *)(this + 1552) + ((unsigned __int64)*(unsigned int *)(v2 + 8) << 6));
++*(_DWORD *)(a2 + 44);
if ( *(_BYTE *)(a2 + 48) )
*(_DWORD *)(*(_QWORD *)(this + 1544) + 16LL * *(unsigned int *)(v2 + 8)) = 0;
*(_BYTE *)(this + 4154) = 1;
result = (*(__int64 (__fastcall **)(__int64, __int64))(*(_QWORD *)this + 2528LL))(this, a2);
*(_BYTE *)(this + 4154) = 0;
return result;
}
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Introducing KextHelper
__int64 __fastcall IGAccelCLContext::process_token_SetFence(IGAccelCLContext *this, __int64 a2)
{
__int64 v2; // r15@3
__int64 result; // rax@6
unsigned int v4; // esi@7
if ( *(_WORD *)(a2 + 34) != 3 )
{
v4 = -5;
return IOAccelContext2::setContextError((IOAccelContext2 *)this, v4);
}
if ( !*(_QWORD *)a2
|| (v2 = *(_QWORD *)(a2 + 24), (unsigned __int64)*(unsigned int *)(v2 + 8) << 6 >=
LODWORD(this->field_640)) )
{
v4 = -2;
return IOAccelContext2::setContextError((IOAccelContext2 *)this, v4);
}
((void (__cdecl *)(IGAccelCLContext
*))this->vt->__ZN16IGAccelCLContext16endCommandStreamER24IOAccelCommandStreamInfo)(this);
(*(void (__fastcall **)(__int64, unsigned __int64))(*(_QWORD *)this->field_1030 + 320LL))(
this->field_1030,
*(_QWORD *)&this->gap610[0] + ((unsigned __int64)*(unsigned int *)(v2 + 8) << 6));
++*(_DWORD *)(a2 + 44);
if ( *(_BYTE *)(a2 + 48) )
*(_DWORD *)(this->field_608 + 16LL * *(unsigned int *)(v2 + 8)) = 0;
this->field_103a = 1;
result = ((__int64 (__fastcall *)(IGAccelCLContext *,
__int64))this->vt->__ZN16IGAccelCLContext18beginCommandStreamER24IOAccelCommandStreamInfo)(
this,
a2);
this->field_103a = 0;
return result;
}
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
Running fuzzer
retriving metadata for all kexts and store using pickle
idc.Batch
Set up multiple VM on fuzzing server
add fuzzer as start-up item, load pickle and record progress
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
Fuzzing outcome
Heap overflow in AppleXXX (CVE-2016-?)
Race condition in IOXXX (CVE-2016-?)
Double free in AppleXXX (CVE-2016-?)
Integer overflow in IOXXX (CVE-2016-?)
NULL pointer dereferences in IOXXX (CVE-2016-?)
.....(more waiting disclosure)
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
A hidden ignored attack surface in IOKit
oops, Apple hasn’t fixed it yet, will disclose later.
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
Infoleak in AppleBDWGraphics/IntelHD5000
via racecondition
IGAccelCLContext/IGAccelGLContext provides interface via
externalMethod for mapping/unmapping user memory, passed
in mach vm address t
Ian Beer and us both discovered a race condition in
unmapping user memory, which lead to code execution
Apple fixes this issue by adding a lock in un map usermemory
(the delete operation), but its incomplete.
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
Operation Procedure
map user memory
contains
index slot using hash function
iterate the list for matching
add
Append item to corresponding slot list
unmap user memory
contains
get
remove (get a object ptr and call virtual function)
Update head and tail when appropriate
Update prev-¿next and next-¿prev
Call stored object’s release virtual functionFlanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
The IGHashTable structure
IGHashTable::Slot
IGHashTable::Slot
IGHashTable::Slot
IGHashTable::Slot
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
The LinkedList connecting elements with
same hash values
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
The normal idea that failes (Ian Beer one)
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
The ideal situation is both threads passes hash table::contains, and when one is
retrieving IOAccelMemoryMap* after get returns valid pointer, the other frees it and
we control the pointer
However in reality more frequently they do passes contains
but thread 1 will remove it before thread 2 do get
and thread 2 hit a null pointer dereference
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
The advanced racing by us
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
After 2 is removed
After 3 is removed
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
The new vulnerability
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
next
prev
mach_vm_addr_t
IOAccelMemoryMap*
IGElement
heap address leaked!
tail element
tail element
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
Unmap frees the element while map is still
traversing
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
Overwriting free’d element’s next pointer
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
Questions?
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
Credits
Liang Chen
Marco Grassi
Wushi
Flanker KeenLab Tencent
The Python Bites your Apple
Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies
Case Studies
Thanks!
Flanker KeenLab Tencent
The Python Bites your Apple

More Related Content

What's hot (20)

PDF
Chromium Sandbox on Linux (NDC Security 2019)
Patricia Aas
 
PDF
Find your own iOS kernel bug
Gustavo Martinez
 
PPTX
Using the android ndk - DroidCon Paris 2014
Paris Android User Group
 
PPTX
Hdl simulators
Haribabu Kannuri
 
PPT
Python intro01classes in_navi_mumbai
vibrantuser
 
PDF
Advanced Evasion Techniques by Win32/Gapz
Alex Matrosov
 
PPTX
SWIG Hello World
e8xu
 
PDF
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
Maksim Shudrak
 
PDF
Zero bugs found? Hold my beer AFL! how to improve coverage-guided fuzzing and...
Maksim Shudrak
 
PDF
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
Christopher Frohoff
 
PDF
Can We Prevent Use-after-free Attacks?
inaz2
 
PDF
SnakeGX (full version)
Flavio Toffalini
 
PDF
SnakeGX (short version)
Flavio Toffalini
 
PPTX
How to design Programs using VHDL
Eutectics
 
PDF
[Blackhat EU'14] Attacking the Linux PRNG on Android and Embedded Devices
srkedmi
 
PDF
Verification of Security for Untrusted Third Party IP Cores
IRJET Journal
 
PPTX
Fixing the Java Serialization Mess
Salesforce Engineering
 
PDF
Tools and Techniques for Understanding Threading Behavior in Android
Intel® Software
 
PPTX
Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...
PyData
 
PDF
Recon2016 shooting the_osx_el_capitan_kernel_like_a_sniper_chen_he
Liang Chen
 
Chromium Sandbox on Linux (NDC Security 2019)
Patricia Aas
 
Find your own iOS kernel bug
Gustavo Martinez
 
Using the android ndk - DroidCon Paris 2014
Paris Android User Group
 
Hdl simulators
Haribabu Kannuri
 
Python intro01classes in_navi_mumbai
vibrantuser
 
Advanced Evasion Techniques by Win32/Gapz
Alex Matrosov
 
SWIG Hello World
e8xu
 
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
Maksim Shudrak
 
Zero bugs found? Hold my beer AFL! how to improve coverage-guided fuzzing and...
Maksim Shudrak
 
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
Christopher Frohoff
 
Can We Prevent Use-after-free Attacks?
inaz2
 
SnakeGX (full version)
Flavio Toffalini
 
SnakeGX (short version)
Flavio Toffalini
 
How to design Programs using VHDL
Eutectics
 
[Blackhat EU'14] Attacking the Linux PRNG on Android and Embedded Devices
srkedmi
 
Verification of Security for Untrusted Third Party IP Cores
IRJET Journal
 
Fixing the Java Serialization Mess
Salesforce Engineering
 
Tools and Techniques for Understanding Threading Behavior in Android
Intel® Software
 
Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...
PyData
 
Recon2016 shooting the_osx_el_capitan_kernel_like_a_sniper_chen_he
Liang Chen
 

Viewers also liked (20)

PDF
D1T3-Anto-Joseph-Droid-FF
Anthony Jose
 
PPTX
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...
Alexandre Moneger
 
PPTX
What the fuzz
Christopher Frenz
 
PDF
50 Shades of Fuzzing by Peter Hlavaty & Marco Grassi
Shakacon
 
PDF
Henrique Dantas - API fuzzing using Swagger
DevSecCon
 
PDF
[CB16] About the cyber grand challenge: the world’s first all-machine hacking...
CODE BLUE
 
PDF
SmartphoneHacking_Android_Exploitation
Malachi Jones
 
PDF
Bug Hunting with Media Formats
Russell Sanford
 
PPTX
American Fuzzy Lop
Michael Overmeyer
 
PPTX
Discovering Vulnerabilities For Fun and Profit
Abhisek Datta
 
ODP
The Nightmare Fuzzing Suite and Blind Code Coverage Fuzzer
Joxean Koret
 
PPTX
You didnt see it’s coming? "Dawn of hardened Windows Kernel"
Peter Hlavaty
 
PDF
Hacking Web Apps by Brent White
EC-Council
 
PDF
High Definition Fuzzing; Exploring HDMI vulnerabilities
E Hacking
 
PPT
Beyond Automated Testing - RVAsec 2016
Andrew McNicol
 
PDF
Rainbow Over the Windows: More Colors Than You Could Expect
Peter Hlavaty
 
PDF
Fuzzing underestimated method of finding hidden bugs
Pawel Rzepa
 
PDF
Moony li pacsec-1.8
PacSecJP
 
PPTX
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Peter Hlavaty
 
PPTX
Fuzzing | Null OWASP Mumbai | 2016 June
nullowaspmumbai
 
D1T3-Anto-Joseph-Droid-FF
Anthony Jose
 
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...
Alexandre Moneger
 
What the fuzz
Christopher Frenz
 
50 Shades of Fuzzing by Peter Hlavaty & Marco Grassi
Shakacon
 
Henrique Dantas - API fuzzing using Swagger
DevSecCon
 
[CB16] About the cyber grand challenge: the world’s first all-machine hacking...
CODE BLUE
 
SmartphoneHacking_Android_Exploitation
Malachi Jones
 
Bug Hunting with Media Formats
Russell Sanford
 
American Fuzzy Lop
Michael Overmeyer
 
Discovering Vulnerabilities For Fun and Profit
Abhisek Datta
 
The Nightmare Fuzzing Suite and Blind Code Coverage Fuzzer
Joxean Koret
 
You didnt see it’s coming? "Dawn of hardened Windows Kernel"
Peter Hlavaty
 
Hacking Web Apps by Brent White
EC-Council
 
High Definition Fuzzing; Exploring HDMI vulnerabilities
E Hacking
 
Beyond Automated Testing - RVAsec 2016
Andrew McNicol
 
Rainbow Over the Windows: More Colors Than You Could Expect
Peter Hlavaty
 
Fuzzing underestimated method of finding hidden bugs
Pawel Rzepa
 
Moony li pacsec-1.8
PacSecJP
 
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Peter Hlavaty
 
Fuzzing | Null OWASP Mumbai | 2016 June
nullowaspmumbai
 
Ad

Similar to The Python bites your apple (20)

PDF
[DefCon 2016] I got 99 Problems, but 
Little Snitch ain’t one!
Synack
 
PDF
DEF CON 24 - Patrick Wardle - 99 problems little snitch
Felipe Prado
 
PDF
NYU Hacknight: iOS and OSX ABI
Mikhail Sosonkin
 
PDF
Poc2015 os x_kernel_is_as_strong_as_its_weakest_part_liang_shuaitian
Liang Chen
 
PDF
CODE BLUE 2014 : BadXNU, A rotten apple! by PEDRO VILAÇA
CODE BLUE
 
PDF
Introduction to iOS Penetration Testing
OWASP
 
PDF
The Python in the Apple
zeroSteiner
 
PDF
Attacking the macOS Kernel Graphics Driver
Priyanka Aash
 
PDF
[CONFidence 2016] Sławomir Kosowski - Introduction to iOS Application Securit...
PROIDEA
 
PPTX
Linux binary analysis and exploitation
Dharmalingam Ganesan
 
PDF
Pentesting iOS Apps
Herman Duarte
 
PDF
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Lyon Yang
 
PPTX
Beyond the 'cript practical i os reverse engineering lascon
Nino Ho
 
PPTX
iOS Application Exploitation
Positive Hack Days
 
PDF
SyScan Singapore 2011 - Stefan Esser - Targeting the iOS Kernel
Stefan Esser
 
PDF
Targeting the iOS kernel
Seguridad Apple
 
PDF
Presentation mac os x security
reza jalaluddin
 
PDF
Building an EmPyre with Python
Will Schroeder
 
PDF
DEF CON 23 - COLIN O'FLYNN - dont whisper my chips
Felipe Prado
 
PDF
Synack Shakacon OSX Malware Persistence
Ivan Einstein
 
[DefCon 2016] I got 99 Problems, but 
Little Snitch ain’t one!
Synack
 
DEF CON 24 - Patrick Wardle - 99 problems little snitch
Felipe Prado
 
NYU Hacknight: iOS and OSX ABI
Mikhail Sosonkin
 
Poc2015 os x_kernel_is_as_strong_as_its_weakest_part_liang_shuaitian
Liang Chen
 
CODE BLUE 2014 : BadXNU, A rotten apple! by PEDRO VILAÇA
CODE BLUE
 
Introduction to iOS Penetration Testing
OWASP
 
The Python in the Apple
zeroSteiner
 
Attacking the macOS Kernel Graphics Driver
Priyanka Aash
 
[CONFidence 2016] Sławomir Kosowski - Introduction to iOS Application Securit...
PROIDEA
 
Linux binary analysis and exploitation
Dharmalingam Ganesan
 
Pentesting iOS Apps
Herman Duarte
 
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Lyon Yang
 
Beyond the 'cript practical i os reverse engineering lascon
Nino Ho
 
iOS Application Exploitation
Positive Hack Days
 
SyScan Singapore 2011 - Stefan Esser - Targeting the iOS Kernel
Stefan Esser
 
Targeting the iOS kernel
Seguridad Apple
 
Presentation mac os x security
reza jalaluddin
 
Building an EmPyre with Python
Will Schroeder
 
DEF CON 23 - COLIN O'FLYNN - dont whisper my chips
Felipe Prado
 
Synack Shakacon OSX Malware Persistence
Ivan Einstein
 
Ad

Recently uploaded (20)

PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 

The Python bites your apple

  • 1. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies The Python Bites your Apple Fuzzing and exploiting OSX Kernel bugs Flanker KeenLab Tencent XKungfoo Shanghai, April 2016 Flanker KeenLab Tencent The Python Bites your Apple
  • 2. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Table of Contents 1 Introduction About 2 IOKit Security Background Core of the Apple 3 Introducing Kitlib Introducing Kitlib 4 Introducing KextHelper Introducing KextHelper 5 Case Studies Case Studies Flanker KeenLab Tencent The Python Bites your Apple
  • 3. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies About About me Senior Security Researcher at KeenLab, Tencent Pwn2Own 2016 OSX Category Winner BlackHat, CanSecWest, HITCON, QCon Speaker *nix platform sandbox bypass and kernel exploitation Google Android Security Top Researchers Hall of Fame Flanker KeenLab Tencent The Python Bites your Apple
  • 4. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies About About KeenLab Former KeenTeam with all researchers move to Tencent and form KeenLab 8 Pwn2Own Champions Universal Rooting We’re hiring! Flanker KeenLab Tencent The Python Bites your Apple
  • 5. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies About Objective of this talk Basic description of IOKit Kernel Zone Allocator and Fengshui Technique Introducing KitLib and distributed Fuzzer Introducing Kexthelper, a IDA plugin for OSX KEXT Case Studies Flanker KeenLab Tencent The Python Bites your Apple
  • 6. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Core of the Apple IOKit Security Background What’s IOKit I/O Kit is a collection of system frameworks, libraries, tools, and other resources for creating device drivers in OS X Security researchers tend to refer it as Kernel drivers and frameworks written with IOKit and accessible via IOKit method calls Why attacking IOKit IOKit drivers runs in Kernel space, some of them even reachable from browser sandbox for efficiency (Graphics). Huge number of drivers implemented Few access restrictions (compared to Android) Flanker KeenLab Tencent The Python Bites your Apple
  • 7. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Core of the Apple IOKit Security Background IOService Different services are exposed via IOKit. We can consult most of them in Hardware IO tools and ioreg. IOAccelerator IOHIDDevice IOPMrootDomain ... Flanker KeenLab Tencent The Python Bites your Apple
  • 8. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Core of the Apple IOKit Security Background IOUserClient External method calls are first routed via IOUserClient, triggered by mach msg IPC kern_return_t IOServiceOpen( io_service_t service, task_port_t owningTask, uint32_t type, io_connect_t *connect ); When userspace openService is called, corresponding newUserClient at Kernel space is invoked Different types may map to different userClient IOAccelerator May check caller’s identity: is root? (OSX and iOS differ) IOServiceClose maps to clientClose in is io service close (race condition here?) Flanker KeenLab Tencent The Python Bites your Apple
  • 9. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Core of the Apple IOKit Security Background externalMethod Method calls are dispatched through getTargetMethodForIndex and/or externalMethod virtual IOExternalMethod * getTargetAndMethodForIndex(IOService ** targetP, UInt32 index ); virtual IOReturn externalMethod(uint32_t selector, IOExternalMethodArguments * args,IOExternalMethodDispatch * dispatch, OSObject * target, void * reference) IOExternalMethodArguments is constructed in is io connect method containing incoming parameter IOExternalMethod/IOExternalMethodDispatch specifies parameters constraint Flanker KeenLab Tencent The Python Bites your Apple
  • 10. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Core of the Apple IOKit Security Background Calling conventions structureInput will be converted to descriptor if size >0x4000 in IOConnectCallMethod if size <0x4000 passes through inband buffer io connect method generate and send mach msg of course we can directly call io connect method, bypass this constraint Flanker KeenLab Tencent The Python Bites your Apple
  • 11. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Core of the Apple libkern C++ Runtime Reduced set of C++ No Exception No Multiple Inherience No template Custom implementation of RTTI OSMetaClass OSMetaClass is defined by macros Contains Name, size and father class for each corresponding class Flanker KeenLab Tencent The Python Bites your Apple
  • 12. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Core of the Apple IOKit Security Background IOConnectCallMethod kern_return_t IOConnectCallMethod( mach_port_t connection, // In uint32_t selector, // In const uint64_t *input, // In uint32_t inputCnt, // In const void *inputStruct, // In size_t inputStructCnt, // In uint64_t *output, // Out uint32_t *outputCnt, // In/Out void *outputStruct, // Out size_t *outputStructCntP) // In/Out Flanker KeenLab Tencent The Python Bites your Apple
  • 13. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Core of the Apple IOKit historical vulnerabilities Race condition (hottest) (CVE-2015-7084) Heap overflow UAF TOCTOU OOB write (Our P2O bug!) NULL dereference (not exploitable with SMAP and in sandbox) Flanker KeenLab Tencent The Python Bites your Apple
  • 14. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Core of the Apple Cons of traditional fuzzer written in C/C++, more time consuming error-prone, easy to make mistakes less supporting library socket logging not dynamically expandable due to language nature Flanker KeenLab Tencent The Python Bites your Apple
  • 15. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing Kitlib Introducing Kitlib io_connect_t t; io_service_t svc = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("fuckliangchen")); IOServiceOpen(svc, mach_task_self(), 0, &t); uint32_t outputCnt = 0x100; size_t outputStructCnt = 0x2000; uint64_t* output = new uint64_t[outputCnt]; char* outputStruct = new char[outputStructCnt]; const uint32_t inputCnt = 0x100; uint64_t input[inputCnt]; const size_t inputStructCnt = 0x2000; char inputStruct[inputStructCnt]; IOConnectCallMethod(t, 0, input, inputCnt, inputStruct, inputStructCnt, output, &outputCnt, outputStruct, &outputStructCnt); import kitlib h = kitlib.openSvc(’fuckliangchen’, 0) kitlib.callConnectMethod(h, [0L]*0x100, ’a’*0x2000, 0x100, 0x2000) Flanker KeenLab Tencent The Python Bites your Apple
  • 16. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing Kitlib What’s Kitlib Kitlib is a Python wrapper for IOKit calls Internally written in C++ and Python, provides convenient functions for writing fuzzers, using SWIG and ctypes Performance cost is low Flanker KeenLab Tencent The Python Bites your Apple
  • 17. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing Kitlib SWIG usage Define interfaces in header file (kitlib.h) C++ wrapper layer in cpp file (if needed) (kitlib.cpp) Writing wrapping code for argument convention from Python to C++ in glue file (kitlib.i) Questions Memory management? Type conventions? Flanker KeenLab Tencent The Python Bites your Apple
  • 18. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing Kitlib Header file Defining basic types mach port t mach vm address t io object t io service t io iterator t Define interfaces mach_port_t openSvc(const char* svc_name, uint32_t type); mach_port_t* openMultiSvc(const char* svc_name, uint32_t* typearr); size_t getSvcCntForName(const char* svc_name); bool svcAva(const char* svc_name,uint32_t type); Flanker KeenLab Tencent The Python Bites your Apple
  • 19. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing Kitlib Glue file Wraps functions size_t getSvcCntForName(const char* svc_name) { io_iterator_t iter; kern_return_t kr; io_service_t device; size_t ret = 0; kr = IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching(svc_name), &iter); while ((device = IOIteratorNext(iter))) { ++ret; IOObjectRelease(device); } IOObjectRelease(iter); return ret; } Flanker KeenLab Tencent The Python Bites your Apple
  • 20. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing Kitlib Glue file Wraps functions unsigned int callConnectMethod( mach_port_t connection, // In uint32_t selector, // In const uint64_t *input, // In uint32_t inputCnt, // In const void *inputStruct, // In size_t inputStructCnt, // In uint64_t *output, // Out uint32_t *outputCnt, // In/Out void *outputStruct, // Out size_t *outputStructCnt) { kern_return_t kt = IOConnectCallMethod((mach_port_t) connection, /* Connection */ selector, /* Selector */ input, inputCnt, /* input, inputCnt */ inputStruct, /* inputStruct */ inputStructCnt, /* inputStructCnt */ output, outputCnt, outputStruct, outputStructCnt); /* Output stuff */ return kt; } Flanker KeenLab Tencent The Python Bites your Apple
  • 21. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing Kitlib Argument Wrapping /* This function handles scalar input, translate the incoming python value, which is list, to native representation. Memory cleanup is needed afterwards */ %typemap(in) (const uint64_t *input, uint32_t inputCnt) { /* Check if is a list */ if (PyList_Check($input)) { uint32_t size = PyList_Size($input); uint32_t i = 0; $2 = size; $1 = (uint64_t*) malloc(size * sizeof(uint64_t)); for (i = 0; i < size; i++) { PyObject *o = PyList_GetItem($input,i); if (PyLong_Check(o)) { $1[i] = PyLong_AsUnsignedLongLong(o); } else { PyErr_SetString(PyExc_TypeError,"list must contain L numbers"); free($1); return NULL; } } } else if ($input == Py_None) { $1 = NULL; $2 = 0; } else { PyErr_SetString(PyExc_TypeError,"not a list"); return NULL; } } Flanker KeenLab Tencent The Python Bites your Apple
  • 22. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing Kitlib Argument wrapping freeing memory %typemap(freearg) (const uint64_t *input, uint32_t inputCnt) { free($1); } Call flow user Python code calls in SWIG auto-generated function SWIG auto-generated function calls user convention typemap code, mapping python types to C++ arguments $1 $2, etc SWIG auto-generated function passes $1 $2, etc into C++ glue code SWIG auto-generated function calls freearg code to free memory NO GIL TROUBLE LOLFlanker KeenLab Tencent The Python Bites your Apple
  • 23. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing Kitlib Kitlib Implementation Example source code import kitlib h = kitlib.openSvc(’fuckliangchen’, 0) kitlib.callConnectMethod(h, [0L]*0x100, ’a’*0x2000, 0x100, 0x2000) inputScalar to list inputStruct to string/bytearray outputScalar/outputStruct maps to len output maps to tuple (retcode, outscalar, outstruct) Flanker KeenLab Tencent The Python Bites your Apple
  • 24. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing Kitlib Problems for Kitlib1 I’m lazy and I don’t want to write wrapper for each interface Argument passing is immutable, cannot do TOCTOU fuzzing Flanker KeenLab Tencent The Python Bites your Apple
  • 25. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing Kitlib Calling directly into library functions ctypes For functions without need for wrapping we directly call ctypes Build-in mutable support (TOCTOU and race condition fuzzing) Flanker KeenLab Tencent The Python Bites your Apple
  • 26. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing Kitlib Basic ctypes primitives ctypes c int, c ulonglong, c char p create string buffer Flanker KeenLab Tencent The Python Bites your Apple
  • 27. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing KextHelper Parsing KEXT for arguments static const IOExternalMethodDispath/IOExternalMethod array (parseable) dynamic routed via code (oops) for former we can automatically retrieve arguments via pattern matching Scan const-data section for matching Map class to arguments array Flanker KeenLab Tencent The Python Bites your Apple
  • 28. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing KextHelper Example IOExternalMethodDispatch __const:0000000000064BC0 ; IGAccelCLContext::attach(IOService *)::methodDescs __const:0000000000064BC0 __ZZN16IGAccelCLContext6attachEP9IOServiceE11methodDescs db 0 __const:0000000000064BC0 ; DATA XREF: IGAccelCLContext::attach(IOService *)+16 __const:0000000000064BC1 db 0 __const:0000000000064BC2 db 0 __const:0000000000064BC3 db 0 __const:0000000000064BC4 db 0 __const:0000000000064BC5 db 0 __const:0000000000064BC6 db 0 __const:0000000000064BC7 db 0 __const:0000000000064BC8 dq offset __ZN16IGAccelCLContext15map_user_memoryEP22IntelCLMapUserMemoryInP23IntelCLMapUserMemoryOutyPy ; IGAccelCLContext::map_user_memory(IntelCLMapUserMemoryIn *,IntelCLMapUserMemoryOut *,ulong long,ulong long *) __const:0000000000064BD0 db 0 __const:0000000000064BD1 db 0 __const:0000000000064BD2 db 0 __const:0000000000064BD3 db 0 __const:0000000000064BD4 db 0 __const:0000000000064BD5 db 0 __const:0000000000064BD6 db 0 __const:0000000000064BD7 db 0 __const:0000000000064BD8 db 3 __const:0000000000064BD9 db 0 __const:0000000000064BDA db 0 __const:0000000000064BDB db 0 __const:0000000000064BDC db 0 __const:0000000000064BDD db 0 Flanker KeenLab Tencent The Python Bites your Apple
  • 29. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing KextHelper After parsing _const:0000000000064BC0 ; IGAccelCLContext::attach(IOService *)::methodDescs __const:0000000000064BC0 __ZZN16IGAccelCLContext6attachEP9IOServiceE11methodDescs IOExternalMethod <0, __const:0000000000064BC0 ; DATA XREF: IGAccelCLContext::attach(IOService *)+16 __const:0000000000064BC0 offset __ZN16IGAccelCLContext15map_user_memoryEP22IntelCLMapUserMemoryInP23IntelCLMapUserMemoryOutyPy, ; IGAccelCLContext::map_user_memory(IntelCLMapUserMemoryIn *,IntelCLMapUserMemoryOut *,ulong long,ulong long *) __const:0000000000064BC0 0, 3, 0FFFFFFFFh, 0FFFFFFFFh> __const:0000000000064BF0 IOExternalMethod <0, ; IGAccelCLContext::unmap_user_memory(IntelCLUnmapUserMemoryIn *,ulong long) __const:0000000000064BF0 offset __ZN16IGAccelCLContext17unmap_user_memoryEP24IntelCLUnmapUserMemoryIny, __const:0000000000064BF0 0, 4, 0, 0FFFFFFFFh> Flanker KeenLab Tencent The Python Bites your Apple
  • 30. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing KextHelper Example: IOExternalMethodDispatch matching +0 points to TEXT or zero +8, +16, +24 reasonable integers (NO TEXT pointing) Flanker KeenLab Tencent The Python Bites your Apple
  • 31. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing KextHelper Example: Vtable matching Reference from constructor +8, +16, ... all points to TEXT section or EXTERN(UNDEF) section Flanker KeenLab Tencent The Python Bites your Apple
  • 32. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing KextHelper Pseudo Algo matchers = [IOExternalMethodDispatchMatcher, VtableMatcher, IOExternalMethodMatcher] for matcher in matchers: if matcher.isSectionBegin(const_data_section): matcher.deflateToList(section, offset) break map userclient with arguments scan newUserClient for service-userclient mappings add father’s userclient to children service scan constructor for service size scan for offset access to determine field offset Construct vtable as a structure S, set vt(offset 0, size 8) type to S* Flanker KeenLab Tencent The Python Bites your Apple
  • 33. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing KextHelper Restoring object structure Scanning MetaClass function for object’s size Create the object’s whole vtable area as a struct Setting +0(8) field as vt and type to previous struct pointer Flanker KeenLab Tencent The Python Bites your Apple
  • 34. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing KextHelper Restoring object structure(cont.) //... __text:0000000000048079 mov r14, rdi __text:000000000004807C movzx eax, word ptr [rbx+22h] __text:0000000000048080 cmp eax, 3 __text:0000000000048083 jnz loc_48122 __text:0000000000048089 cmp qword ptr [rbx], 0 __text:000000000004808D jz loc_48129 //... __text:00000000000480A6 cmp rax, rcx __text:00000000000480A9 jnb short loc_48129 __text:00000000000480AB mov rax, [r14] __text:00000000000480AE mov rdi, r14 __text:00000000000480B1 mov rsi, rbx __text:00000000000480B4 call qword ptr [rax+9E8h] __text:00000000000480BA mov rdi, [r14+1030h] __text:00000000000480C1 mov rax, [rdi] __text:00000000000480C4 mov esi, [r15+8] __text:00000000000480C8 shl rsi, 6 __text:00000000000480CC add rsi, [r14+610h] __text:00000000000480D3 call qword ptr [rax+140h] __text:00000000000480D9 inc dword ptr [rbx+2Ch] __text:00000000000480DC cmp byte ptr [rbx+30h], 0 __text:00000000000480E0 jz short loc_480F8 __text:00000000000480E2 mov eax, [r15+8] __text:00000000000480E6 mov rcx, [r14+608h] Flanker KeenLab Tencent The Python Bites your Apple
  • 35. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing KextHelper Restoring object structure(cont.) Scanning functions and perform forward-flow analysis on registers starting RDI Retriving MOV/LEA offset and do addStructMember Flanker KeenLab Tencent The Python Bites your Apple
  • 36. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing KextHelper __int64 __fastcall IGAccelCLContext::process_token_SetFence(__int64 this, __int64 a2) { __int64 v2; // r15@3 __int64 result; // rax@6 unsigned int v4; // esi@7 if ( *(_WORD *)(a2 + 34) != 3 ) { v4 = -5; return IOAccelContext2::setContextError((IOAccelContext2 *)this, v4); } if ( !*(_QWORD *)a2 || (v2 = *(_QWORD *)(a2 + 24), (unsigned __int64)*(unsigned int *)(v2 + 8) << 6 >= *(unsigned int *)(this + 1600)) ) { v4 = -2; return IOAccelContext2::setContextError((IOAccelContext2 *)this, v4); } (*(void (__cdecl **)(__int64))(*(_QWORD *)this + 2536LL))(this); (*(void (__fastcall **)(_QWORD, unsigned __int64))(**(_QWORD **)(this + 4144) + 320LL))( *(_QWORD *)(this + 4144), *(_QWORD *)(this + 1552) + ((unsigned __int64)*(unsigned int *)(v2 + 8) << 6)); ++*(_DWORD *)(a2 + 44); if ( *(_BYTE *)(a2 + 48) ) *(_DWORD *)(*(_QWORD *)(this + 1544) + 16LL * *(unsigned int *)(v2 + 8)) = 0; *(_BYTE *)(this + 4154) = 1; result = (*(__int64 (__fastcall **)(__int64, __int64))(*(_QWORD *)this + 2528LL))(this, a2); *(_BYTE *)(this + 4154) = 0; return result; } Flanker KeenLab Tencent The Python Bites your Apple
  • 37. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Introducing KextHelper __int64 __fastcall IGAccelCLContext::process_token_SetFence(IGAccelCLContext *this, __int64 a2) { __int64 v2; // r15@3 __int64 result; // rax@6 unsigned int v4; // esi@7 if ( *(_WORD *)(a2 + 34) != 3 ) { v4 = -5; return IOAccelContext2::setContextError((IOAccelContext2 *)this, v4); } if ( !*(_QWORD *)a2 || (v2 = *(_QWORD *)(a2 + 24), (unsigned __int64)*(unsigned int *)(v2 + 8) << 6 >= LODWORD(this->field_640)) ) { v4 = -2; return IOAccelContext2::setContextError((IOAccelContext2 *)this, v4); } ((void (__cdecl *)(IGAccelCLContext *))this->vt->__ZN16IGAccelCLContext16endCommandStreamER24IOAccelCommandStreamInfo)(this); (*(void (__fastcall **)(__int64, unsigned __int64))(*(_QWORD *)this->field_1030 + 320LL))( this->field_1030, *(_QWORD *)&this->gap610[0] + ((unsigned __int64)*(unsigned int *)(v2 + 8) << 6)); ++*(_DWORD *)(a2 + 44); if ( *(_BYTE *)(a2 + 48) ) *(_DWORD *)(this->field_608 + 16LL * *(unsigned int *)(v2 + 8)) = 0; this->field_103a = 1; result = ((__int64 (__fastcall *)(IGAccelCLContext *, __int64))this->vt->__ZN16IGAccelCLContext18beginCommandStreamER24IOAccelCommandStreamInfo)( this, a2); this->field_103a = 0; return result; } Flanker KeenLab Tencent The Python Bites your Apple
  • 38. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies Running fuzzer retriving metadata for all kexts and store using pickle idc.Batch Set up multiple VM on fuzzing server add fuzzer as start-up item, load pickle and record progress Flanker KeenLab Tencent The Python Bites your Apple
  • 39. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies Fuzzing outcome Heap overflow in AppleXXX (CVE-2016-?) Race condition in IOXXX (CVE-2016-?) Double free in AppleXXX (CVE-2016-?) Integer overflow in IOXXX (CVE-2016-?) NULL pointer dereferences in IOXXX (CVE-2016-?) .....(more waiting disclosure) Flanker KeenLab Tencent The Python Bites your Apple
  • 40. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies A hidden ignored attack surface in IOKit oops, Apple hasn’t fixed it yet, will disclose later. Flanker KeenLab Tencent The Python Bites your Apple
  • 41. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies Infoleak in AppleBDWGraphics/IntelHD5000 via racecondition IGAccelCLContext/IGAccelGLContext provides interface via externalMethod for mapping/unmapping user memory, passed in mach vm address t Ian Beer and us both discovered a race condition in unmapping user memory, which lead to code execution Apple fixes this issue by adding a lock in un map usermemory (the delete operation), but its incomplete. Flanker KeenLab Tencent The Python Bites your Apple
  • 42. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies Operation Procedure map user memory contains index slot using hash function iterate the list for matching add Append item to corresponding slot list unmap user memory contains get remove (get a object ptr and call virtual function) Update head and tail when appropriate Update prev-¿next and next-¿prev Call stored object’s release virtual functionFlanker KeenLab Tencent The Python Bites your Apple
  • 43. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies The IGHashTable structure IGHashTable::Slot IGHashTable::Slot IGHashTable::Slot IGHashTable::Slot next prev mach_vm_addr_t IOAccelMemoryMap* IGElement next prev mach_vm_addr_t IOAccelMemoryMap* IGElement next prev mach_vm_addr_t IOAccelMemoryMap* IGElement Flanker KeenLab Tencent The Python Bites your Apple
  • 44. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies The LinkedList connecting elements with same hash values next prev mach_vm_addr_t IOAccelMemoryMap* IGElement next prev mach_vm_addr_t IOAccelMemoryMap* IGElement next prev mach_vm_addr_t IOAccelMemoryMap* IGElement next prev mach_vm_addr_t IOAccelMemoryMap* IGElement Flanker KeenLab Tencent The Python Bites your Apple
  • 45. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies The normal idea that failes (Ian Beer one) next prev mach_vm_addr_t IOAccelMemoryMap* IGElement next prev mach_vm_addr_t IOAccelMemoryMap* IGElement next prev mach_vm_addr_t IOAccelMemoryMap* IGElement The ideal situation is both threads passes hash table::contains, and when one is retrieving IOAccelMemoryMap* after get returns valid pointer, the other frees it and we control the pointer However in reality more frequently they do passes contains but thread 1 will remove it before thread 2 do get and thread 2 hit a null pointer dereference Flanker KeenLab Tencent The Python Bites your Apple
  • 46. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies The advanced racing by us next prev mach_vm_addr_t IOAccelMemoryMap* IGElement next prev mach_vm_addr_t IOAccelMemoryMap* IGElement next prev mach_vm_addr_t IOAccelMemoryMap* IGElement next prev mach_vm_addr_t IOAccelMemoryMap* IGElement After 2 is removed After 3 is removed Flanker KeenLab Tencent The Python Bites your Apple
  • 47. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies The new vulnerability next prev mach_vm_addr_t IOAccelMemoryMap* IGElement next prev mach_vm_addr_t IOAccelMemoryMap* IGElement next prev mach_vm_addr_t IOAccelMemoryMap* IGElement next prev mach_vm_addr_t IOAccelMemoryMap* IGElement heap address leaked! tail element tail element Flanker KeenLab Tencent The Python Bites your Apple
  • 48. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies Unmap frees the element while map is still traversing Flanker KeenLab Tencent The Python Bites your Apple
  • 49. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies Overwriting free’d element’s next pointer Flanker KeenLab Tencent The Python Bites your Apple
  • 50. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies Questions? Flanker KeenLab Tencent The Python Bites your Apple
  • 51. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies Credits Liang Chen Marco Grassi Wushi Flanker KeenLab Tencent The Python Bites your Apple
  • 52. Introduction IOKit Security Background Introducing Kitlib Introducing KextHelper Case Studies Case Studies Thanks! Flanker KeenLab Tencent The Python Bites your Apple