forked from P5-2005/opainject
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrop_inject.m
474 lines (402 loc) · 15.9 KB
/
rop_inject.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
#import <stdio.h>
#import <unistd.h>
#import <stdlib.h>
#import <dlfcn.h>
#import <errno.h>
#import <string.h>
#import <limits.h>
#import <pthread.h>
#import <pthread_spis.h>
#import <mach/mach.h>
#import <mach/error.h>
#import <mach-o/getsect.h>
#import <mach-o/dyld.h>
#import <mach-o/loader.h>
#import <mach-o/nlist.h>
#import <mach-o/reloc.h>
#import <mach-o/dyld_images.h>
#import <sys/utsname.h>
#import <sys/types.h>
#import <sys/sysctl.h>
#import <sys/mman.h>
#import <sys/stat.h>
#import <sys/wait.h>
#import <CoreFoundation/CoreFoundation.h>
#import "pac.h"
#import "dyld.h"
#import "sandbox.h"
#import "CoreSymbolication.h"
#import "task_utils.h"
#import "thread_utils.h"
#import "arm64.h"
vm_address_t writeStringToTask(task_t task, const char* string, size_t* lengthOut)
{
kern_return_t kr = KERN_SUCCESS;
vm_address_t remoteString = (vm_address_t)NULL;
size_t stringLen = strlen(string)+1;
kr = vm_allocate(task, &remoteString, stringLen, VM_FLAGS_ANYWHERE);
if(kr != KERN_SUCCESS)
{
printf("ERROR: Unable to memory for string %s: %s\n", string, mach_error_string(kr));
return 0;
}
kr = vm_protect(task, remoteString, stringLen, TRUE, VM_PROT_READ | VM_PROT_WRITE);
if(kr != KERN_SUCCESS)
{
vm_deallocate(task, remoteString, stringLen);
printf("ERROR: Failed to make string %s read/write: %s.\n", string, mach_error_string(kr));
return kr;
}
kr = vm_write(task, remoteString, (vm_address_t)string, stringLen);
if(kr != KERN_SUCCESS)
{
vm_deallocate(task, remoteString, stringLen);
printf("ERROR: Failed to write string %s to memory: %s\n", string, mach_error_string(kr));
return kr;
}
if(lengthOut)
{
*lengthOut = stringLen;
}
return remoteString;
}
void findRopLoop(task_t task, vm_address_t allImageInfoAddr)
{
uint32_t inst = CFSwapInt32(0x00000014);
ropLoop = (uint64_t)scanLibrariesForMemory(task, allImageInfoAddr, (char*)&inst, sizeof(inst), 4);
}
// theos on wsl2 ubuntu cannot build with @available option, this workaround to make it work
bool isiOS12OrLater() {
int mib[2] = { CTL_KERN, KERN_OSVERSION };
char str[256];
size_t size = sizeof(str);
sysctl(mib, 2, str, &size, NULL, 0);
int majorVersion = 0;
sscanf(str, "%d", &majorVersion);
return majorVersion >= 16; // iOS 12 corresponds to Darwin version 18.x.x
}
// Create an infinitely spinning pthread in target process
kern_return_t createRemotePthread(task_t task, vm_address_t allImageInfoAddr, thread_act_t* remotePthreadOut)
{
kern_return_t kr = KERN_SUCCESS;
#if __arm64e__
// GET ANY VALID THREAD STATE
mach_msg_type_number_t validThreadStateCount = ARM_THREAD_STATE64_COUNT;
struct arm_unified_thread_state validThreadState;
thread_act_array_t allThreadsForFindingValid;
mach_msg_type_number_t threadCountForFindingValid;
kr = task_threads(task, &allThreadsForFindingValid, &threadCountForFindingValid);
if(kr != KERN_SUCCESS || threadCountForFindingValid == 0)
{
printf("[createRemotePthread] ERROR: failed to get threads in task: %s\n", mach_error_string(kr));
if (kr == KERN_SUCCESS) return 1;
return kr;
}
kr = thread_get_state(allThreadsForFindingValid[0], ARM_THREAD_STATE64, (thread_state_t)&validThreadState.ts_64, &validThreadStateCount);
if(kr != KERN_SUCCESS )
{
printf("[createRemotePthread] ERROR: failed to get valid thread state: %s\n", mach_error_string(kr));
return kr;
}
vm_deallocate(mach_task_self(), (vm_offset_t)allThreadsForFindingValid, sizeof(thread_act_array_t) * threadCountForFindingValid);
#endif
// GATHER OFFSETS
__unused vm_address_t libSystemPthreadAddr = getRemoteImageAddress(task, allImageInfoAddr, "/usr/lib/system/libsystem_pthread.dylib");
uint64_t mainThread = 0;
if (isiOS12OrLater()) {
// TODO: maybe instead of this, allocate our own pthread object?
// kinda worried about side effects here, but as long our thread doesn't
// somehow trigger pthread_main_thread modifications, it should be fine
uint64_t pthread_main_thread_np = remoteDlSym(task, libSystemPthreadAddr, "_pthread_main_thread_np");
uint32_t instructions[2];
kr = task_read(task, pthread_main_thread_np, &instructions[0], sizeof(instructions));
if (kr != KERN_SUCCESS) {
printf("ERROR: Failed to find main thread (1/3)\n");
return kr;
}
uint64_t _main_thread_ptr = 0;
if (!decode_adrp_ldr(instructions[0], instructions[1], pthread_main_thread_np, &_main_thread_ptr)) {
printf("ERROR: Failed to find main thread (2/3)\n");
return 1;
}
kr = task_read(task, _main_thread_ptr, &mainThread, sizeof(mainThread));
if (kr != KERN_SUCCESS) {
printf("ERROR: Failed to find main thread (3/3)\n");
return kr;
}
}
uint64_t _pthread_set_self = remoteDlSym(task, libSystemPthreadAddr, "__pthread_set_self");
// ALLOCATE STACK
vm_address_t remoteStack64 = (vm_address_t)NULL;
kr = vm_allocate(task, &remoteStack64, STACK_SIZE, VM_FLAGS_ANYWHERE);
if(kr != KERN_SUCCESS)
{
printf("[createRemotePthread] ERROR: Unable to allocate stack memory: %s\n", mach_error_string(kr));
return kr;
}
kr = vm_protect(task, remoteStack64, STACK_SIZE, TRUE, VM_PROT_READ | VM_PROT_WRITE);
if(kr != KERN_SUCCESS)
{
vm_deallocate(task, remoteStack64, STACK_SIZE);
printf("[createRemotePthread] ERROR: Failed to make remote stack writable: %s.\n", mach_error_string(kr));
return kr;
}
thread_act_t bootstrapThread = 0;
struct arm_unified_thread_state bootstrapThreadState;
memset(&bootstrapThreadState, 0, sizeof(struct arm_unified_thread_state));
// spawn pthread to infinite loop
bootstrapThreadState.ash.flavor = ARM_THREAD_STATE64;
bootstrapThreadState.ash.count = ARM_THREAD_STATE64_COUNT;
#if __arm64e__
bootstrapThreadState.ts_64.__opaque_flags = validThreadState.ts_64.__opaque_flags;
#endif
uint64_t sp = (remoteStack64 + (STACK_SIZE / 2));
__unused uint64_t x2 = ropLoop;
#if __arm64e__
if (!(bootstrapThreadState.ts_64.__opaque_flags & __DARWIN_ARM_THREAD_STATE64_FLAGS_NO_PTRAUTH)) {
x2 = (uint64_t)make_sym_callable((void*)x2);
}
#endif
__darwin_arm_thread_state64_set_sp(bootstrapThreadState.ts_64, (void*)sp);
__darwin_arm_thread_state64_set_pc_fptr(bootstrapThreadState.ts_64, make_sym_callable((void*)_pthread_set_self));
__darwin_arm_thread_state64_set_lr_fptr(bootstrapThreadState.ts_64, make_sym_callable((void*)ropLoop)); //when done, go to infinite loop
bootstrapThreadState.ts_64.__x[0] = mainThread;
//printThreadState_state(bootstrapThreadState);
kr = thread_create_running(task, ARM_THREAD_STATE64, (thread_state_t)&bootstrapThreadState.ts_64, ARM_THREAD_STATE64_COUNT, &bootstrapThread);
if(kr != KERN_SUCCESS)
{
printf("[createRemotePthread] ERROR: Failed to create running thread: %s.\n", mach_error_string(kr));
return kr;
}
printf("[createRemotePthread] Created bootstrap thread... now waiting on finish\n");
struct arm_unified_thread_state outState;
kr = wait_for_thread(bootstrapThread, ropLoop, &outState);
if(kr != KERN_SUCCESS)
{
printf("[createRemotePthread] ERROR: failed to wait for bootstrap thread: %s\n", mach_error_string(kr));
return kr;
}
printf("[createRemotePthread] Bootstrap done!\n");
if(remotePthreadOut) *remotePthreadOut = bootstrapThread;
return kr;
}
kern_return_t arbCall(task_t task, thread_act_t targetThread, uint64_t* retOut, bool willReturn, vm_address_t funcPtr, int numArgs, ...)
{
kern_return_t kr = KERN_SUCCESS;
if(numArgs > 8)
{
printf("[arbCall] ERROR: Only 8 arguments are supported by arbCall\n");
return -2;
}
if(!targetThread)
{
printf("[arbCall] ERROR: targetThread == null\n");
return -3;
}
va_list ap;
va_start(ap, numArgs);
// suspend target thread
thread_suspend(targetThread);
// backup states of target thread
mach_msg_type_number_t origThreadStateCount = ARM_THREAD_STATE64_COUNT;
struct arm_unified_thread_state origThreadState;
kr = thread_get_state(targetThread, ARM_THREAD_STATE64, (thread_state_t)&origThreadState.ts_64, &origThreadStateCount);
if(kr != KERN_SUCCESS)
{
thread_resume(targetThread);
printf("[arbCall] ERROR: failed to save original state of target thread: %s\n", mach_error_string(kr));
return kr;
}
struct arm64_thread_full_state* origThreadFullState = thread_save_state_arm64(targetThread);
if(!origThreadFullState)
{
thread_resume(targetThread);
printf("[arbCall] ERROR: failed to backup original state of target thread\n");
return kr;
}
// prepare target thread for arbitary call
// allocate stack
vm_address_t remoteStack = (vm_address_t)NULL;
kr = vm_allocate(task, &remoteStack, STACK_SIZE, VM_FLAGS_ANYWHERE);
if(kr != KERN_SUCCESS)
{
free(origThreadFullState);
thread_resume(targetThread);
printf("[arbCall] ERROR: Unable to allocate stack memory: %s\n", mach_error_string(kr));
return kr;
}
// make stack read / write
kr = vm_protect(task, remoteStack, STACK_SIZE, TRUE, VM_PROT_READ | VM_PROT_WRITE);
if(kr != KERN_SUCCESS)
{
free(origThreadFullState);
vm_deallocate(task, remoteStack, STACK_SIZE);
thread_resume(targetThread);
printf("[arbCall] ERROR: Failed to make remote stack writable: %s.\n", mach_error_string(kr));
return kr;
}
// abort any existing syscalls by target thread, thanks to Linus Henze for this suggestion :P
thread_abort(targetThread);
// set state for arb call
struct arm_unified_thread_state newState = origThreadState;
uint64_t sp = remoteStack + (STACK_SIZE / 2);
__darwin_arm_thread_state64_set_sp(newState.ts_64, (void*)sp);
__darwin_arm_thread_state64_set_pc_fptr(newState.ts_64, make_sym_callable((void*)funcPtr));
__darwin_arm_thread_state64_set_lr_fptr(newState.ts_64, make_sym_callable((void*)ropLoop));
// write arguments into registers
for (int i = 0; i < numArgs; i++)
{
newState.ts_64.__x[i] = va_arg(ap, uint64_t);
}
kr = thread_set_state(targetThread, ARM_THREAD_STATE64, (thread_state_t)&newState.ts_64, ARM_THREAD_STATE64_COUNT);
if(kr != KERN_SUCCESS)
{
free(origThreadFullState);
vm_deallocate(task, remoteStack, STACK_SIZE);
thread_resume(targetThread);
printf("[arbCall] ERROR: failed to set state for thread: %s\n", mach_error_string(kr));
return kr;
}
printf("[arbCall] Set thread state for arbitary call\n");
//printThreadState(targetThread);
thread_act_array_t cachedThreads;
mach_msg_type_number_t cachedThreadCount;
kr = task_threads(task, &cachedThreads, &cachedThreadCount);
if (kr != KERN_SUCCESS) return kr;
suspend_threads_except_for(cachedThreads, cachedThreadCount, targetThread);
// perform arbitary call
thread_resume(targetThread);
printf("[arbCall] Started thread, waiting for it to finish...\n");
// wait for arbitary call to finish (or not)
struct arm_unified_thread_state outState;
if (willReturn)
{
kr = wait_for_thread(targetThread, ropLoop, &outState);
if(kr != KERN_SUCCESS)
{
free(origThreadFullState);
printf("[arbCall] ERROR: failed to wait for thread to finish: %s\n", mach_error_string(kr));
return kr;
}
// extract return value from state if needed
if(retOut)
{
*retOut = outState.ts_64.__x[0];
}
}
else
{
kr = wait_for_thread(targetThread, 0, &outState);
printf("[arbCall] pthread successfully did not return with code %d (%s)\n", kr, mach_error_string(kr));
}
resume_threads_except_for(cachedThreads, cachedThreadCount, targetThread);
vm_deallocate(mach_task_self(), (vm_offset_t)cachedThreads, sizeof(thread_act_array_t) * cachedThreadCount);
// release fake stack as it's no longer needed
vm_deallocate(task, remoteStack, STACK_SIZE);
if (willReturn)
{
// suspend target thread
thread_suspend(targetThread);
thread_abort(targetThread);
// restore states of target thread to what they were before the arbitary call
bool restoreSuccess = thread_restore_state_arm64(targetThread, origThreadFullState);
if(!restoreSuccess)
{
printf("[arbCall] ERROR: failed to revert to old thread state\n");
return kr;
}
// resume thread again, process should continue executing as before
//printThreadState(targetThread);
thread_resume(targetThread);
}
return kr;
}
void prepareForMagic(task_t task, vm_address_t allImageInfoAddr)
{
// FIND INFINITE LOOP ROP GADGET
static dispatch_once_t onceToken;
dispatch_once (&onceToken, ^{
findRopLoop(task, allImageInfoAddr);
});
printf("[prepareForMagic] done, ropLoop: 0x%llX\n", ropLoop);
}
bool sandboxFixup(task_t task, thread_act_t pthread, pid_t pid, const char* dylibPath, vm_address_t allImageInfoAddr)
{
int readExtensionNeeded = sandbox_check(pid, "file-read-data", SANDBOX_FILTER_PATH | SANDBOX_CHECK_NO_REPORT, dylibPath);
int executableExtensionNeeded = sandbox_check(pid, "file-map-executable", SANDBOX_FILTER_PATH | SANDBOX_CHECK_NO_REPORT, dylibPath);
int retval = 0;
vm_address_t libSystemSandboxAddr = 0;
uint64_t sandbox_extension_consumeAddr = 0;
if (readExtensionNeeded || executableExtensionNeeded) {
libSystemSandboxAddr = getRemoteImageAddress(task, allImageInfoAddr, "/usr/lib/system/libsystem_sandbox.dylib");
sandbox_extension_consumeAddr = remoteDlSym(task, libSystemSandboxAddr, "_sandbox_extension_consume");
printf("[sandboxFixup] applying sandbox extension(s)! sandbox_extension_consume: 0x%llX\n", sandbox_extension_consumeAddr);
}
if (readExtensionNeeded) {
char* extString = sandbox_extension_issue_file(APP_SANDBOX_READ, dylibPath, 0);
size_t remoteExtStringSize = 0;
vm_address_t remoteExtString = writeStringToTask(task, (const char*)extString, &remoteExtStringSize);
if(remoteExtString)
{
int64_t readExtensionRet = 0;
arbCall(task, pthread, (uint64_t*)&readExtensionRet, true, sandbox_extension_consumeAddr, 1, remoteExtString);
vm_deallocate(task, remoteExtString, remoteExtStringSize);
printf("[sandboxFixup] sandbox_extension_consume returned %lld for read extension\n", (int64_t)readExtensionRet);
retval |= (readExtensionRet <= 0);
}
}
else {
printf("[sandboxFixup] read extension not needed, skipping...\n");
}
if (executableExtensionNeeded) {
char* extString = sandbox_extension_issue_file("com.apple.sandbox.executable", dylibPath, 0);
size_t remoteExtStringSize = 0;
vm_address_t remoteExtString = writeStringToTask(task, (const char*)extString, &remoteExtStringSize);
if(remoteExtString)
{
int64_t executableExtensionRet = 0;
arbCall(task, pthread, (uint64_t*)&executableExtensionRet, true, sandbox_extension_consumeAddr, 1, remoteExtString);
vm_deallocate(task, remoteExtString, remoteExtStringSize);
printf("[sandboxFixup] sandbox_extension_consume returned %lld for executable extension\n", (int64_t)executableExtensionRet);
retval |= (executableExtensionRet <= 0);
}
}
else {
printf("[sandboxFixup] executable extension not needed, skipping...\n");
}
return retval == 0;
}
void injectDylibViaRop(task_t task, pid_t pid, const char* dylibPath, vm_address_t allImageInfoAddr)
{
prepareForMagic(task, allImageInfoAddr);
thread_act_t pthread = 0;
kern_return_t kr = createRemotePthread(task, allImageInfoAddr, &pthread);
if(kr != KERN_SUCCESS) return;
sandboxFixup(task, pthread, pid, dylibPath, allImageInfoAddr);
printf("[injectDylibViaRop] Preparation done, now injecting!\n");
// FIND OFFSETS
vm_address_t libDyldAddr = getRemoteImageAddress(task, allImageInfoAddr, "/usr/lib/system/libdyld.dylib");
uint64_t dlopenAddr = remoteDlSym(task, libDyldAddr, "_dlopen");
uint64_t dlerrorAddr = remoteDlSym(task, libDyldAddr, "_dlerror");
printf("[injectDylibViaRop] dlopen: 0x%llX, dlerror: 0x%llX\n", (unsigned long long)dlopenAddr, (unsigned long long)dlerrorAddr);
// CALL DLOPEN
size_t remoteDylibPathSize = 0;
vm_address_t remoteDylibPath = writeStringToTask(task, (const char*)dylibPath, &remoteDylibPathSize);
if(remoteDylibPath)
{
void* dlopenRet;
arbCall(task, pthread, (uint64_t*)&dlopenRet, true, dlopenAddr, 2, remoteDylibPath, RTLD_NOW);
vm_deallocate(task, remoteDylibPath, remoteDylibPathSize);
if (dlopenRet) {
printf("[injectDylibViaRop] dlopen succeeded, library handle: %p\n", dlopenRet);
}
else {
uint64_t remoteErrorString = 0;
arbCall(task, pthread, (uint64_t*)&remoteErrorString, true, dlerrorAddr, 0);
char *errorString = task_copy_string(task, remoteErrorString);
printf("[injectDylibViaRop] dlopen failed, error:\n%s\n", errorString);
free(errorString);
}
}
thread_terminate(pthread);
}