SlideShare a Scribd company logo
1 of 37
Download to read offline
Tracing Objective-C
(Hacking in context)
Mikhail Sosonkin
Security Researcher at SYNACK
Working on low level emulation with QEMU and iPhone automation.
Graduate of Polytechnic University
a.k.a Polytechnic Institute of New York University
a.k.a New York University Polytechnic School of Engineering
a.k.a New York University Tandon School of Engineering
Getting started with iOS
- Get iPhone 5s
- Swappa
- Apply Jailbreak
- Install OpenSSH via Cydia
- Use tcprelay to SSH over USB
- Start exploring
- Debugserver
- Objective-c: Phrack 0x42
- http://phrack.org/issues/66/4.html
- https://github.com/iosre/iOSAppReverseEngineering
- https://nabla-c0d3.github.io/blog/2014/12/30/tcprelay-multiple-devices/
Pangu TaiG
Where are the vulns?!
Jailbreaks are basically chains of memory corruptions going all the way down to the
kernel.
Memory corruption - just won’t go away!
That’s what a lot of CTFs seem to be focusing on.
History thereof
Memory Errors
Beg, borrow and steal
Finding vulnerabilities
Fuzzing (AFL, Many frameworks)
Code reading (SourceInsight, Understand)
Dynamic/Static analysis (Qira, Panda)
Code coverage is important for this type
Before we begin...
Let’s cover some basics.
ARM64 Registers
31 General purpose registers
X0 … X30 or W0 … W30
X31 - (zr) The Zero register
X30 - (lr) Procedure Link Register (RIP)
X29 - (fp) Frame pointer (RBP)
X18 - Reserved on iOS
ARM64 Instructions
Conditional Branches
B.EQ, B.NE, TBNZ (Test bit and Branch if Nonzero), etc.
Unconditional Branches
B, RET, SVC
Conditional Select
CSEL W9, W9, W10, EQ
“W9 = EQ?W9:W10”
Calling Convention
On ARM64:
X0 … X8 Contain function parameters
X16 has the system call number
Positive for Posix
Negative for Mach Ports
0x80000000 for thread_set_self
SVC 0x80; jumps to kernel
Syscall numbers
OSX:
0x01000000 - mach ports
0x02000000 - Posix
0x03000003 - pthread_set_self
IOS
0x00000000 and below - mach ports
0x00000000 and above - Posix
0x80000000 - pthread_set_self
More details
See the iOS ABI Function Call Guide
Let’s explorer how Objective-C
calls methods
@interface TestObject : NSObject { }
-(void)print;
@end
@implementation TestObject
-(void)print { NSLog(@"Test Object"); }
@end
…
TestObject* obj = [TestObject alloc];
[obj print];
__text:0000000100000DB0 mov rsi, cs:classRef_TestObject
__text:0000000100000DB7 mov rdi, cs:selRef_alloc
__text:0000000100000DBE mov [rbp+var_38], rdi
__text:0000000100000DC2 mov rdi, rsi
__text:0000000100000DC5 mov rsi, [rbp+var_38]
__text:0000000100000DC9 call _objc_msgSend
__text:0000000100000DCE mov [rbp+var_18], rax
__text:0000000100000DD2 mov rax, [rbp+var_18]
__text:0000000100000DD6 mov rsi, cs:selRef_print
__text:0000000100000DDD mov rdi, rax
__text:0000000100000DE0 call _objc_msgSend
[obj print];
objc_msgSend(obj, “print”);
-[TestObject print](obj, “print”);
id objc_msgSend(id self, SEL op, ...)
void __cdecl -[TestObject print]
(struct TestObject *self, SEL)
The Plan
Steps
1. Allocate a page - a jump page
2. Set objc_msgSend readable and writable
3. Copy bytes from objc_msgSend
4. Check for branch instructions in preamble
5. Modify objc_msgSend preamble
6. Set jump page to readable and executable
7. Set objc_msgSend readable and executable
Repository: https://github.com/nologic/objc_trace
Step 1 - allocate a page
mmap(NULL,
4096,
PROT_READ | PROT_WRITE,
MAP_ANON | MAP_PRIVATE,
-1,
0);
Step 2 - Set objc_msgSend readable and writable
mach_port_t self_task = mach_task_self();
vm_protect(self_task, (vm_address_t)o_func, 4096, true,
VM_PROT_READ | VM_PROT_WRITE) != KERN_SUCCESS
vm_protect(self_task, (vm_address_t)o_func, 4096, false,
VM_PROT_READ | VM_PROT_WRITE) != KERN_SUCCESS
set_maximum
Step 3 - Copy bytes from objc_msgSend
*t_func = *(jump_page());
// save first 4 32bit instructions
// original -> trampoline
instruction_t* orig_preamble = (instruction_t*)o_func;
for(int i = 0; i < 4; i++) {
t_func->inst [i] = orig_preamble[i];
t_func->backup[i] = orig_preamble[i]; }
Step 3 - Types
typedef uint32_t instruction_t;
__attribute__((naked)) void d_jump_patch() {
__asm__ __volatile__(
"ldr x16, #8;n"
"br x16;n"
".long 0;n" // place for jump address
".long 0;n" ); }
Step 3 - Jump page
__attribute__((naked)) void d_jump_page() {
__asm__ __volatile__(
"B INST1;n" // placeholder for original instructions
"B INST2;n"
"B INST3;n"
"B INST4;n"
Step 3 - Copy bytes from objc_msgSend
__text:18DBB41C0 EXPORT _objc_msgSend
__text:18DBB41C0 _objc_msgSend
__text:18DBB41C0 CMP X0, #0
__text:18DBB41C4 B.LE loc_18DBB4230
__text:18DBB41C8 loc_18DBB41C8
__text:18DBB41C8 LDR X13, [X0]
__text:18DBB41CC AND X9, X13, #0x1FFFFFFF8
Step 4 - Check for branch instructions in preamble
CMP B.LE LDR AND LDR BR #Addr64 LDR BR #Addr64 LDR BR #Addr64
PC
Jump page:
objc_msgSend+16
objc_msgSend+##
Step 4 - Check for branch instructions in preamble
(lldb) x/10i 0x0000000104ef4000 ; Jump page
0x104ef4000: 0xf100001f cmp x0, #0
0x104ef4004: 0x540000ed b.le 0x104ef4020
0x104ef4008: 0xf940000d ldr x13, [x0]
0x104ef400c: 0x927d75a9 and x9, x13, #0x1fffffff8
; Jump patch 1
0x104ef4010: 0x58000050 ldr x16, #8
0x104ef4014: 0xd61f0200 br x16
0x104ef4018: 0x964efbd0 bl 0xfe2b2f58
0x104ef401c: 0x00000001 .long 0x00000001 ; unknown opcode
; Jump patch 2
0x104ef4020: 0x58000050 ldr x16, #8
0x104ef4024: 0xd61f0200 br x16
Step 4 - Working with instructions
typedef struct {
uint32_t offset : 26;
uint32_t inst_num : 6;
} inst_b;
…
instruction_t inst = t_func->inst[i];
inst_b* i_b = (inst_b*)&inst;
inst_b_cond* i_b_cond = (inst_b_cond*)&inst;
if(i_b->inst_num == 0x5) {
// unconditional branch
Step 5 - Modify objc_msgSend preamble
Think back to d_jump_patch
(lldb) x/10i 0x1964efbc0 ; objc_msgSend
-> 0x1964efbc0: 0x58000050 ldr x16, #8 ; <+8>
0x1964efbc4: 0xd61f0200 br x16
0x1964efbc8: 0x04eeb730 .long 0x04eeb730 ; unknown opcode
0x1964efbcc: 0x00000001 .long 0x00000001 ; unknown opcode
0x1964efbd0: 0xa9412d2a ldp x10, x11, [x9, #16]
0x1964efbd4: 0x0a0b002c and w12, w1, w11
0x1964efbd8: 0x8b0c114c add x12, x10, x12, lsl #4
Step 5 - Jump patch destination
__attribute__((naked)) id objc_msgSend_trace(id self, SEL op) { __asm__ __volatile__ (
"stp fp, lr, [sp, #-16]!;n"
"mov fp, sp;n"
"sub sp, sp, #(10*8 + 8*16);n"
"stp q0, q1, [sp, #(0*16)];n"
...
"stp x0, x1, [sp, #(8*16+0*8)];n"
..
"BL _hook_callback64_pre;n"
"mov x9, x0;n"
// Restore all the parameter registers to the initial state.
"ldp q0, q1, [sp, #(0*16)];n"
...
"ldp x0, x1, [sp, #(8*16+0*8)];n"
// Restore the stack pointer, frame pointer and link register
"mov sp, fp;n"
"ldp fp, lr, [sp], #16;n"
"BR x9;n" // call the original ); }
Step 6 - Set jump page to readable and executable
// set permissions to exec
if(mprotect((void*)t_func, 4096, PROT_READ | PROT_EXEC) != 0) {
perror("Unable to change trampoline permissions to exec");
return NULL;
}
Step 7 - Set objc_msgSend readable and executable
mach_port_t self_task = mach_task_self();
vm_protect(self_task, (vm_address_t)o_func, 4096, true,
VM_PROT_READ | VM_PROT_EXECUTE) != KERN_SUCCESS
vm_protect(self_task, (vm_address_t)o_func, 4096, false,
VM_PROT_READ | VM_PROT_EXECUTE) != KERN_SUCCESS
The end game!
void* hook_callback64_pre(id self, SEL op, void* a1, … ) {
// get the important bits: class, method
char* classname = (char*) object_getClassName( self );
char* opname = (char*) op;
// print some useful info.
fprintf(output, "%016x: [%s %s (", pthread_self(), classname, (char*)opname);
int printParam = 0;
for(int i = 0; i < namelen; i++) {
if(opname[i] == ':') {
fprintf(output, "%p ", getParam(printParam, a1, a2, a3, a4, a5));
}
}
return original_msgSend;
}
Done! Let’s execute.
On the command line:
iPhone:~ root# DYLD_INSERT_LIBRARIES=libobjc_trace.dylib /Applications/Maps.app/Maps
objc_msgSend function substrated from 0x197967bc0 to 0x10065b730, trampoline
0x100718000
000000009c158310: [NSStringROMKeySet_Embedded alloc ()]
000000009c158310: [NSSharedKeySet initialize ()]
000000009c158310: [NSStringROMKeySet_Embedded initialize ()]
000000009c158310: [NSStringROMKeySet_Embedded init ()]
000000009c158310: [NSStringROMKeySet_Embedded initWithKeys:count: (0x0 0x0 )]
000000009c158310: [NSStringROMKeySet_Embedded setSelect: (0x1 )]
000000009c158310: [NSStringROMKeySet_Embedded setC: (0x1 )]
000000009c158310: [NSStringROMKeySet_Embedded setM: (0xf6a )]
000000009c158310: [NSStringROMKeySet_Embedded setFactor: (0x7b5 )]
Attaching to a process
iPhone:~ root# ./debugserver *:1234 --attach=DamnVulnerableIOSApp
MacBook-Pro-2:~ nl$ lldb
(lldb) process connect connect://127.0.0.1:3234
Process 2826 stopped
* thread #1: tid = 0x463b0, 0x0000000196c9f0c0 libsystem_kernel.
dylib`__psynch_mutexwait + 8, queue = 'com.apple.main-thread', stop reason = signal
SIGSTOP
frame #0: 0x0000000196c9f0c0 libsystem_kernel.dylib`__psynch_mutexwait + 8
libsystem_kernel.dylib`__psynch_mutexwait:
-> 0x196c9f0c0 <+8>: b.lo 0x196c9f0d8
The Challenge
1. Make function tracing work for another architecture:
a. ARMv7, x86_64, PPC, etc.
2. Make function tracing work from shell code.
a. ShellCC might be of help
Where to learn about security?
- iOS Reverse Engineering Book
- https://seccasts.com/
- http://www.opensecuritytraining.info/
- https://www.corelan.be
- youtube for conference
- Security meetups
- Just practice
- Read/follow walkthroughs
- follow the reddits:
- netsec
- reverseengineering
- malware
- lowlevel
- blackhat
- securityCTF
- rootkit
- vrd
Thank you!
Mikhail Sosonkin
mikhail@synack.com

More Related Content

What's hot

Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereSergey Platonov
 
Linux kernel debugging
Linux kernel debuggingLinux kernel debugging
Linux kernel debuggingJungMinSEO5
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCanSecWest
 
Exploit ie using scriptable active x controls version English
Exploit ie using scriptable active x controls version EnglishExploit ie using scriptable active x controls version English
Exploit ie using scriptable active x controls version Englishchen yuki
 
Catch a spider monkey
Catch a spider monkeyCatch a spider monkey
Catch a spider monkeyChengHui Weng
 
Endless fun with Arduino and Eventmachine
Endless fun with Arduino and EventmachineEndless fun with Arduino and Eventmachine
Endless fun with Arduino and EventmachineBodo Tasche
 
Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012
Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012
Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012DefCamp
 
[2007 CodeEngn Conference 01] seaofglass - Linux Virus Analysis
[2007 CodeEngn Conference 01] seaofglass - Linux Virus Analysis[2007 CodeEngn Conference 01] seaofglass - Linux Virus Analysis
[2007 CodeEngn Conference 01] seaofglass - Linux Virus AnalysisGangSeok Lee
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
The Php Life Cycle
The Php Life CycleThe Php Life Cycle
The Php Life CycleXinchen Hui
 
An introduction to PHP 5.4
An introduction to PHP 5.4An introduction to PHP 5.4
An introduction to PHP 5.4Giovanni Derks
 
Работа с реляционными базами данных в C++
Работа с реляционными базами данных в C++Работа с реляционными базами данных в C++
Работа с реляционными базами данных в C++corehard_by
 
Rop and it's friends
Rop and it's friendsRop and it's friends
Rop and it's friendsnuc13us
 
Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations DVClub
 
Bug fix sharing : where does bug come from
Bug fix sharing : where does bug come fromBug fix sharing : where does bug come from
Bug fix sharing : where does bug come from宇 申
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopyayaria
 
Дмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортДмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортSergey Platonov
 
Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧Orange Tsai
 

What's hot (20)

Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhere
 
Linux kernel debugging
Linux kernel debuggingLinux kernel debugging
Linux kernel debugging
 
Book
BookBook
Book
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemes
 
Exploit ie using scriptable active x controls version English
Exploit ie using scriptable active x controls version EnglishExploit ie using scriptable active x controls version English
Exploit ie using scriptable active x controls version English
 
Catch a spider monkey
Catch a spider monkeyCatch a spider monkey
Catch a spider monkey
 
Endless fun with Arduino and Eventmachine
Endless fun with Arduino and EventmachineEndless fun with Arduino and Eventmachine
Endless fun with Arduino and Eventmachine
 
3
33
3
 
Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012
Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012
Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012
 
[2007 CodeEngn Conference 01] seaofglass - Linux Virus Analysis
[2007 CodeEngn Conference 01] seaofglass - Linux Virus Analysis[2007 CodeEngn Conference 01] seaofglass - Linux Virus Analysis
[2007 CodeEngn Conference 01] seaofglass - Linux Virus Analysis
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
The Php Life Cycle
The Php Life CycleThe Php Life Cycle
The Php Life Cycle
 
An introduction to PHP 5.4
An introduction to PHP 5.4An introduction to PHP 5.4
An introduction to PHP 5.4
 
Работа с реляционными базами данных в C++
Работа с реляционными базами данных в C++Работа с реляционными базами данных в C++
Работа с реляционными базами данных в C++
 
Rop and it's friends
Rop and it's friendsRop and it's friends
Rop and it's friends
 
Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations
 
Bug fix sharing : where does bug come from
Bug fix sharing : where does bug come fromBug fix sharing : where does bug come from
Bug fix sharing : where does bug come from
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptop
 
Дмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортДмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репорт
 
Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧
 

Viewers also liked

After pcl-reconstruction - POSTSURGICAL PCL REHABILITATION PROTOCOL
After pcl-reconstruction - POSTSURGICAL PCL REHABILITATION PROTOCOLAfter pcl-reconstruction - POSTSURGICAL PCL REHABILITATION PROTOCOL
After pcl-reconstruction - POSTSURGICAL PCL REHABILITATION PROTOCOLpriyaakumarr
 
Blue Hacathon-Γ. Ρεμούνδος
Blue Hacathon-Γ. ΡεμούνδοςBlue Hacathon-Γ. Ρεμούνδος
Blue Hacathon-Γ. ΡεμούνδοςConnected Islands
 
до свята мами,6 кл
до свята мами,6 клдо свята мами,6 кл
до свята мами,6 клgalynazdzhanska
 
Historia natural de la infección por vih
Historia natural de la infección por vihHistoria natural de la infección por vih
Historia natural de la infección por vihdiana estacio
 
CV OF RAJESH.DOC
CV OF RAJESH.DOCCV OF RAJESH.DOC
CV OF RAJESH.DOCRajesh Mav
 
HT16 - DA156A - Användbarhet 2
HT16 - DA156A - Användbarhet 2HT16 - DA156A - Användbarhet 2
HT16 - DA156A - Användbarhet 2Anton Tibblin
 
Interesting Facts about Instagram that You Should Know [Infographic]
Interesting Facts about Instagram that You Should Know [Infographic]Interesting Facts about Instagram that You Should Know [Infographic]
Interesting Facts about Instagram that You Should Know [Infographic]88 Digital Cloud Marketing
 
Digital text book
Digital text bookDigital text book
Digital text bookarcha1989
 
Application of extreme learning machine for estimating solar radiation from s...
Application of extreme learning machine for estimating solar radiation from s...Application of extreme learning machine for estimating solar radiation from s...
Application of extreme learning machine for estimating solar radiation from s...mehmet şahin
 
Презентация об игральных заведениях
Презентация об игральных заведенияхПрезентация об игральных заведениях
Презентация об игральных заведенияхViktor Alexeev
 
09 mario unibertsoa
09 mario unibertsoa 09 mario unibertsoa
09 mario unibertsoa 3ZIKLO
 
Mandatory Insurance_DUBAI_EB_2015
Mandatory Insurance_DUBAI_EB_2015Mandatory Insurance_DUBAI_EB_2015
Mandatory Insurance_DUBAI_EB_2015Saeed Khan
 

Viewers also liked (17)

After pcl-reconstruction - POSTSURGICAL PCL REHABILITATION PROTOCOL
After pcl-reconstruction - POSTSURGICAL PCL REHABILITATION PROTOCOLAfter pcl-reconstruction - POSTSURGICAL PCL REHABILITATION PROTOCOL
After pcl-reconstruction - POSTSURGICAL PCL REHABILITATION PROTOCOL
 
Blue Hacathon-Γ. Ρεμούνδος
Blue Hacathon-Γ. ΡεμούνδοςBlue Hacathon-Γ. Ρεμούνδος
Blue Hacathon-Γ. Ρεμούνδος
 
WabiSabiFinalOct29th
WabiSabiFinalOct29thWabiSabiFinalOct29th
WabiSabiFinalOct29th
 
до свята мами,6 кл
до свята мами,6 клдо свята мами,6 кл
до свята мами,6 кл
 
Historia natural de la infección por vih
Historia natural de la infección por vihHistoria natural de la infección por vih
Historia natural de la infección por vih
 
Island Hopping
Island HoppingIsland Hopping
Island Hopping
 
CV OF RAJESH.DOC
CV OF RAJESH.DOCCV OF RAJESH.DOC
CV OF RAJESH.DOC
 
HT16 - DA156A - Användbarhet 2
HT16 - DA156A - Användbarhet 2HT16 - DA156A - Användbarhet 2
HT16 - DA156A - Användbarhet 2
 
7. Журнали.
7. Журнали.7. Журнали.
7. Журнали.
 
Interesting Facts about Instagram that You Should Know [Infographic]
Interesting Facts about Instagram that You Should Know [Infographic]Interesting Facts about Instagram that You Should Know [Infographic]
Interesting Facts about Instagram that You Should Know [Infographic]
 
Digital text book
Digital text bookDigital text book
Digital text book
 
Application of extreme learning machine for estimating solar radiation from s...
Application of extreme learning machine for estimating solar radiation from s...Application of extreme learning machine for estimating solar radiation from s...
Application of extreme learning machine for estimating solar radiation from s...
 
Презентация об игральных заведениях
Презентация об игральных заведенияхПрезентация об игральных заведениях
Презентация об игральных заведениях
 
09 mario unibertsoa
09 mario unibertsoa 09 mario unibertsoa
09 mario unibertsoa
 
Mandatory Insurance_DUBAI_EB_2015
Mandatory Insurance_DUBAI_EB_2015Mandatory Insurance_DUBAI_EB_2015
Mandatory Insurance_DUBAI_EB_2015
 
EBONY_0215_Selma-2-2
EBONY_0215_Selma-2-2EBONY_0215_Selma-2-2
EBONY_0215_Selma-2-2
 
Double
Double Double
Double
 

Similar to NYU hacknight, april 6, 2016

Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Vincenzo Iozzo
 
Return Oriented Programming, an introduction
Return Oriented Programming, an introductionReturn Oriented Programming, an introduction
Return Oriented Programming, an introductionPatricia Aas
 
NDC TechTown 2023_ Return Oriented Programming an introduction.pdf
NDC TechTown 2023_ Return Oriented Programming an introduction.pdfNDC TechTown 2023_ Return Oriented Programming an introduction.pdf
NDC TechTown 2023_ Return Oriented Programming an introduction.pdfPatricia Aas
 
Writing Metasploit Plugins
Writing Metasploit PluginsWriting Metasploit Plugins
Writing Metasploit Pluginsamiable_indian
 
SFO15-500: VIXL
SFO15-500: VIXLSFO15-500: VIXL
SFO15-500: VIXLLinaro
 
04 - I love my OS, he protects me (sometimes, in specific circumstances)
04 - I love my OS, he protects me (sometimes, in specific circumstances)04 - I love my OS, he protects me (sometimes, in specific circumstances)
04 - I love my OS, he protects me (sometimes, in specific circumstances)Alexandre Moneger
 
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)Gavin Guo
 
Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016PVS-Studio
 
08 - Return Oriented Programming, the chosen one
08 - Return Oriented Programming, the chosen one08 - Return Oriented Programming, the chosen one
08 - Return Oriented Programming, the chosen oneAlexandre Moneger
 
02 - Introduction to the cdecl ABI and the x86 stack
02 - Introduction to the cdecl ABI and the x86 stack02 - Introduction to the cdecl ABI and the x86 stack
02 - Introduction to the cdecl ABI and the x86 stackAlexandre Moneger
 
200 Open Source Projects Later: Source Code Static Analysis Experience
200 Open Source Projects Later: Source Code Static Analysis Experience200 Open Source Projects Later: Source Code Static Analysis Experience
200 Open Source Projects Later: Source Code Static Analysis ExperienceAndrey Karpov
 
Offensive cyber security: Smashing the stack with Python
Offensive cyber security: Smashing the stack with PythonOffensive cyber security: Smashing the stack with Python
Offensive cyber security: Smashing the stack with PythonMalachi Jones
 
The true story_of_hello_world
The true story_of_hello_worldThe true story_of_hello_world
The true story_of_hello_worldfantasy zheng
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2PVS-Studio
 
Troubleshooting Linux Kernel Modules And Device Drivers
Troubleshooting Linux Kernel Modules And Device DriversTroubleshooting Linux Kernel Modules And Device Drivers
Troubleshooting Linux Kernel Modules And Device DriversSatpal Parmar
 
Troubleshooting linux-kernel-modules-and-device-drivers-1233050713693744-1
Troubleshooting linux-kernel-modules-and-device-drivers-1233050713693744-1Troubleshooting linux-kernel-modules-and-device-drivers-1233050713693744-1
Troubleshooting linux-kernel-modules-and-device-drivers-1233050713693744-1Jagadisha Maiya
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationWei-Ren Chen
 
Kernelvm 201312-dlmopen
Kernelvm 201312-dlmopenKernelvm 201312-dlmopen
Kernelvm 201312-dlmopenHajime Tazaki
 

Similar to NYU hacknight, april 6, 2016 (20)

Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
 
Return Oriented Programming, an introduction
Return Oriented Programming, an introductionReturn Oriented Programming, an introduction
Return Oriented Programming, an introduction
 
Virtual machine re building
Virtual machine re buildingVirtual machine re building
Virtual machine re building
 
NDC TechTown 2023_ Return Oriented Programming an introduction.pdf
NDC TechTown 2023_ Return Oriented Programming an introduction.pdfNDC TechTown 2023_ Return Oriented Programming an introduction.pdf
NDC TechTown 2023_ Return Oriented Programming an introduction.pdf
 
Writing Metasploit Plugins
Writing Metasploit PluginsWriting Metasploit Plugins
Writing Metasploit Plugins
 
SFO15-500: VIXL
SFO15-500: VIXLSFO15-500: VIXL
SFO15-500: VIXL
 
04 - I love my OS, he protects me (sometimes, in specific circumstances)
04 - I love my OS, he protects me (sometimes, in specific circumstances)04 - I love my OS, he protects me (sometimes, in specific circumstances)
04 - I love my OS, he protects me (sometimes, in specific circumstances)
 
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
 
Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016
 
08 - Return Oriented Programming, the chosen one
08 - Return Oriented Programming, the chosen one08 - Return Oriented Programming, the chosen one
08 - Return Oriented Programming, the chosen one
 
02 - Introduction to the cdecl ABI and the x86 stack
02 - Introduction to the cdecl ABI and the x86 stack02 - Introduction to the cdecl ABI and the x86 stack
02 - Introduction to the cdecl ABI and the x86 stack
 
200 Open Source Projects Later: Source Code Static Analysis Experience
200 Open Source Projects Later: Source Code Static Analysis Experience200 Open Source Projects Later: Source Code Static Analysis Experience
200 Open Source Projects Later: Source Code Static Analysis Experience
 
Offensive cyber security: Smashing the stack with Python
Offensive cyber security: Smashing the stack with PythonOffensive cyber security: Smashing the stack with Python
Offensive cyber security: Smashing the stack with Python
 
The true story_of_hello_world
The true story_of_hello_worldThe true story_of_hello_world
The true story_of_hello_world
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
 
Troubleshooting Linux Kernel Modules And Device Drivers
Troubleshooting Linux Kernel Modules And Device DriversTroubleshooting Linux Kernel Modules And Device Drivers
Troubleshooting Linux Kernel Modules And Device Drivers
 
Troubleshooting linux-kernel-modules-and-device-drivers-1233050713693744-1
Troubleshooting linux-kernel-modules-and-device-drivers-1233050713693744-1Troubleshooting linux-kernel-modules-and-device-drivers-1233050713693744-1
Troubleshooting linux-kernel-modules-and-device-drivers-1233050713693744-1
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate Representation
 
Marat-Slides
Marat-SlidesMarat-Slides
Marat-Slides
 
Kernelvm 201312-dlmopen
Kernelvm 201312-dlmopenKernelvm 201312-dlmopen
Kernelvm 201312-dlmopen
 

Recently uploaded

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 

Recently uploaded (20)

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 

NYU hacknight, april 6, 2016

  • 1. Tracing Objective-C (Hacking in context) Mikhail Sosonkin
  • 2. Security Researcher at SYNACK Working on low level emulation with QEMU and iPhone automation. Graduate of Polytechnic University a.k.a Polytechnic Institute of New York University a.k.a New York University Polytechnic School of Engineering a.k.a New York University Tandon School of Engineering
  • 3. Getting started with iOS - Get iPhone 5s - Swappa - Apply Jailbreak - Install OpenSSH via Cydia - Use tcprelay to SSH over USB - Start exploring - Debugserver - Objective-c: Phrack 0x42 - http://phrack.org/issues/66/4.html - https://github.com/iosre/iOSAppReverseEngineering - https://nabla-c0d3.github.io/blog/2014/12/30/tcprelay-multiple-devices/
  • 5. Where are the vulns?! Jailbreaks are basically chains of memory corruptions going all the way down to the kernel. Memory corruption - just won’t go away! That’s what a lot of CTFs seem to be focusing on. History thereof Memory Errors
  • 6. Beg, borrow and steal Finding vulnerabilities Fuzzing (AFL, Many frameworks) Code reading (SourceInsight, Understand) Dynamic/Static analysis (Qira, Panda) Code coverage is important for this type
  • 7. Before we begin... Let’s cover some basics.
  • 8. ARM64 Registers 31 General purpose registers X0 … X30 or W0 … W30 X31 - (zr) The Zero register X30 - (lr) Procedure Link Register (RIP) X29 - (fp) Frame pointer (RBP) X18 - Reserved on iOS
  • 9. ARM64 Instructions Conditional Branches B.EQ, B.NE, TBNZ (Test bit and Branch if Nonzero), etc. Unconditional Branches B, RET, SVC Conditional Select CSEL W9, W9, W10, EQ “W9 = EQ?W9:W10”
  • 10. Calling Convention On ARM64: X0 … X8 Contain function parameters X16 has the system call number Positive for Posix Negative for Mach Ports 0x80000000 for thread_set_self SVC 0x80; jumps to kernel
  • 11. Syscall numbers OSX: 0x01000000 - mach ports 0x02000000 - Posix 0x03000003 - pthread_set_self IOS 0x00000000 and below - mach ports 0x00000000 and above - Posix 0x80000000 - pthread_set_self
  • 12. More details See the iOS ABI Function Call Guide
  • 13. Let’s explorer how Objective-C calls methods
  • 14. @interface TestObject : NSObject { } -(void)print; @end @implementation TestObject -(void)print { NSLog(@"Test Object"); } @end … TestObject* obj = [TestObject alloc]; [obj print];
  • 15. __text:0000000100000DB0 mov rsi, cs:classRef_TestObject __text:0000000100000DB7 mov rdi, cs:selRef_alloc __text:0000000100000DBE mov [rbp+var_38], rdi __text:0000000100000DC2 mov rdi, rsi __text:0000000100000DC5 mov rsi, [rbp+var_38] __text:0000000100000DC9 call _objc_msgSend __text:0000000100000DCE mov [rbp+var_18], rax __text:0000000100000DD2 mov rax, [rbp+var_18] __text:0000000100000DD6 mov rsi, cs:selRef_print __text:0000000100000DDD mov rdi, rax __text:0000000100000DE0 call _objc_msgSend
  • 16. [obj print]; objc_msgSend(obj, “print”); -[TestObject print](obj, “print”); id objc_msgSend(id self, SEL op, ...) void __cdecl -[TestObject print] (struct TestObject *self, SEL)
  • 18. Steps 1. Allocate a page - a jump page 2. Set objc_msgSend readable and writable 3. Copy bytes from objc_msgSend 4. Check for branch instructions in preamble 5. Modify objc_msgSend preamble 6. Set jump page to readable and executable 7. Set objc_msgSend readable and executable Repository: https://github.com/nologic/objc_trace
  • 19. Step 1 - allocate a page mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
  • 20. Step 2 - Set objc_msgSend readable and writable mach_port_t self_task = mach_task_self(); vm_protect(self_task, (vm_address_t)o_func, 4096, true, VM_PROT_READ | VM_PROT_WRITE) != KERN_SUCCESS vm_protect(self_task, (vm_address_t)o_func, 4096, false, VM_PROT_READ | VM_PROT_WRITE) != KERN_SUCCESS set_maximum
  • 21. Step 3 - Copy bytes from objc_msgSend *t_func = *(jump_page()); // save first 4 32bit instructions // original -> trampoline instruction_t* orig_preamble = (instruction_t*)o_func; for(int i = 0; i < 4; i++) { t_func->inst [i] = orig_preamble[i]; t_func->backup[i] = orig_preamble[i]; }
  • 22. Step 3 - Types typedef uint32_t instruction_t; __attribute__((naked)) void d_jump_patch() { __asm__ __volatile__( "ldr x16, #8;n" "br x16;n" ".long 0;n" // place for jump address ".long 0;n" ); }
  • 23. Step 3 - Jump page __attribute__((naked)) void d_jump_page() { __asm__ __volatile__( "B INST1;n" // placeholder for original instructions "B INST2;n" "B INST3;n" "B INST4;n"
  • 24. Step 3 - Copy bytes from objc_msgSend __text:18DBB41C0 EXPORT _objc_msgSend __text:18DBB41C0 _objc_msgSend __text:18DBB41C0 CMP X0, #0 __text:18DBB41C4 B.LE loc_18DBB4230 __text:18DBB41C8 loc_18DBB41C8 __text:18DBB41C8 LDR X13, [X0] __text:18DBB41CC AND X9, X13, #0x1FFFFFFF8
  • 25. Step 4 - Check for branch instructions in preamble CMP B.LE LDR AND LDR BR #Addr64 LDR BR #Addr64 LDR BR #Addr64 PC Jump page: objc_msgSend+16 objc_msgSend+##
  • 26. Step 4 - Check for branch instructions in preamble (lldb) x/10i 0x0000000104ef4000 ; Jump page 0x104ef4000: 0xf100001f cmp x0, #0 0x104ef4004: 0x540000ed b.le 0x104ef4020 0x104ef4008: 0xf940000d ldr x13, [x0] 0x104ef400c: 0x927d75a9 and x9, x13, #0x1fffffff8 ; Jump patch 1 0x104ef4010: 0x58000050 ldr x16, #8 0x104ef4014: 0xd61f0200 br x16 0x104ef4018: 0x964efbd0 bl 0xfe2b2f58 0x104ef401c: 0x00000001 .long 0x00000001 ; unknown opcode ; Jump patch 2 0x104ef4020: 0x58000050 ldr x16, #8 0x104ef4024: 0xd61f0200 br x16
  • 27. Step 4 - Working with instructions typedef struct { uint32_t offset : 26; uint32_t inst_num : 6; } inst_b; … instruction_t inst = t_func->inst[i]; inst_b* i_b = (inst_b*)&inst; inst_b_cond* i_b_cond = (inst_b_cond*)&inst; if(i_b->inst_num == 0x5) { // unconditional branch
  • 28. Step 5 - Modify objc_msgSend preamble Think back to d_jump_patch (lldb) x/10i 0x1964efbc0 ; objc_msgSend -> 0x1964efbc0: 0x58000050 ldr x16, #8 ; <+8> 0x1964efbc4: 0xd61f0200 br x16 0x1964efbc8: 0x04eeb730 .long 0x04eeb730 ; unknown opcode 0x1964efbcc: 0x00000001 .long 0x00000001 ; unknown opcode 0x1964efbd0: 0xa9412d2a ldp x10, x11, [x9, #16] 0x1964efbd4: 0x0a0b002c and w12, w1, w11 0x1964efbd8: 0x8b0c114c add x12, x10, x12, lsl #4
  • 29. Step 5 - Jump patch destination __attribute__((naked)) id objc_msgSend_trace(id self, SEL op) { __asm__ __volatile__ ( "stp fp, lr, [sp, #-16]!;n" "mov fp, sp;n" "sub sp, sp, #(10*8 + 8*16);n" "stp q0, q1, [sp, #(0*16)];n" ... "stp x0, x1, [sp, #(8*16+0*8)];n" .. "BL _hook_callback64_pre;n" "mov x9, x0;n" // Restore all the parameter registers to the initial state. "ldp q0, q1, [sp, #(0*16)];n" ... "ldp x0, x1, [sp, #(8*16+0*8)];n" // Restore the stack pointer, frame pointer and link register "mov sp, fp;n" "ldp fp, lr, [sp], #16;n" "BR x9;n" // call the original ); }
  • 30. Step 6 - Set jump page to readable and executable // set permissions to exec if(mprotect((void*)t_func, 4096, PROT_READ | PROT_EXEC) != 0) { perror("Unable to change trampoline permissions to exec"); return NULL; }
  • 31. Step 7 - Set objc_msgSend readable and executable mach_port_t self_task = mach_task_self(); vm_protect(self_task, (vm_address_t)o_func, 4096, true, VM_PROT_READ | VM_PROT_EXECUTE) != KERN_SUCCESS vm_protect(self_task, (vm_address_t)o_func, 4096, false, VM_PROT_READ | VM_PROT_EXECUTE) != KERN_SUCCESS
  • 32. The end game! void* hook_callback64_pre(id self, SEL op, void* a1, … ) { // get the important bits: class, method char* classname = (char*) object_getClassName( self ); char* opname = (char*) op; // print some useful info. fprintf(output, "%016x: [%s %s (", pthread_self(), classname, (char*)opname); int printParam = 0; for(int i = 0; i < namelen; i++) { if(opname[i] == ':') { fprintf(output, "%p ", getParam(printParam, a1, a2, a3, a4, a5)); } } return original_msgSend; }
  • 33. Done! Let’s execute. On the command line: iPhone:~ root# DYLD_INSERT_LIBRARIES=libobjc_trace.dylib /Applications/Maps.app/Maps objc_msgSend function substrated from 0x197967bc0 to 0x10065b730, trampoline 0x100718000 000000009c158310: [NSStringROMKeySet_Embedded alloc ()] 000000009c158310: [NSSharedKeySet initialize ()] 000000009c158310: [NSStringROMKeySet_Embedded initialize ()] 000000009c158310: [NSStringROMKeySet_Embedded init ()] 000000009c158310: [NSStringROMKeySet_Embedded initWithKeys:count: (0x0 0x0 )] 000000009c158310: [NSStringROMKeySet_Embedded setSelect: (0x1 )] 000000009c158310: [NSStringROMKeySet_Embedded setC: (0x1 )] 000000009c158310: [NSStringROMKeySet_Embedded setM: (0xf6a )] 000000009c158310: [NSStringROMKeySet_Embedded setFactor: (0x7b5 )]
  • 34. Attaching to a process iPhone:~ root# ./debugserver *:1234 --attach=DamnVulnerableIOSApp MacBook-Pro-2:~ nl$ lldb (lldb) process connect connect://127.0.0.1:3234 Process 2826 stopped * thread #1: tid = 0x463b0, 0x0000000196c9f0c0 libsystem_kernel. dylib`__psynch_mutexwait + 8, queue = 'com.apple.main-thread', stop reason = signal SIGSTOP frame #0: 0x0000000196c9f0c0 libsystem_kernel.dylib`__psynch_mutexwait + 8 libsystem_kernel.dylib`__psynch_mutexwait: -> 0x196c9f0c0 <+8>: b.lo 0x196c9f0d8
  • 35. The Challenge 1. Make function tracing work for another architecture: a. ARMv7, x86_64, PPC, etc. 2. Make function tracing work from shell code. a. ShellCC might be of help
  • 36. Where to learn about security? - iOS Reverse Engineering Book - https://seccasts.com/ - http://www.opensecuritytraining.info/ - https://www.corelan.be - youtube for conference - Security meetups - Just practice - Read/follow walkthroughs - follow the reddits: - netsec - reverseengineering - malware - lowlevel - blackhat - securityCTF - rootkit - vrd