├── LICENSE ├── README.md └── scripts ├── IOKit.js ├── bypass_apple_certificate_pinning.js ├── dasd_schedule_activity.js ├── jetsamctl.js ├── libdispatch.js ├── mach_msg.js ├── objc_msg.js ├── os_log.js └── stalker.js /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Frida Scripts 2 | 3 | Collection of Frida scripts that turned out to be helpful for reverse-engineering :) 4 | The goal of these scripts is to be rather generic and provide you with insights about 5 | larger closed-source projects. 6 | 7 | ## iOS 8 | 9 | * [libdispatch.js](scripts/libdispatch.js) hooks iOS Grand Central Dispatch (GCD). 10 | This is useful to show thread creation. When printing a backtrace, you can even get an idea of 11 | the overall program flow. Prints might be out of order on high load, i.e., when attaching it 12 | to `CommCenter`, but it works quite well. Tested on iOS 13.3-14.4. 13 | 14 | 15 | * [mach_msg.js](scripts/mach_msg.js) hooks iOS Mach messages. 16 | Almost everything is a Mach message on iOS, from Cross-Process Communication (XPC) to 17 | IOKit driver calls in the kernel. Might be a bit verbose, tunable via two parameters to 18 | truncate messages and skip XPC. Tested on iOS 13.3-14.4. 19 | 20 | * [iotracy.js](https://github.com/robre/frida-scripts) hooks IOKit. 21 | External repo, not included here, by robre. 22 | -------------------------------------------------------------------------------- /scripts/IOKit.js: -------------------------------------------------------------------------------- 1 | /* 2 | Hook into IOKit + HID to inspect drivers during runtime. 3 | 4 | Usage: 5 | 6 | * Attach to existing daemon 7 | frida -U your_target --no-pause -l IOKit.js 8 | 9 | * Start with new daemon 10 | frida -U -f /bin/your_target --no-pause -l IOKit.js 11 | 12 | */ 13 | 14 | // Print returned ports 15 | var debug_returns = false; 16 | 17 | // Allow to set mappings between Mach ports and 18 | // IOUserClients as retrieved via launching script 19 | var mappings = []; 20 | 21 | var info = Memory.alloc(16); 22 | var table = Memory.alloc(16); 23 | var tableCount = Memory.alloc(16); 24 | var tree = Memory.alloc(16); 25 | var treeCount = Memory.alloc(16); 26 | 27 | // step 1: get addresses for kernel functions 28 | const libsystem_kernel = Process.getModuleByName('libsystem_kernel.dylib'); 29 | var addr_mach_task_self = libsystem_kernel.getExportByName('mach_task_self'); 30 | var addr_mach_port_space_info = libsystem_kernel.getExportByName('mach_port_space_info'); 31 | var addr_mach_port_kobject = libsystem_kernel.getExportByName('mach_port_kobject'); 32 | var addr_mach_port_kobject_description = libsystem_kernel.getExportByName('mach_port_kobject_description'); 33 | 34 | // step 2: create NativeFunctions 35 | var mach_task_self = new NativeFunction(addr_mach_task_self, 'int', []); 36 | var mach_port_space_info = new NativeFunction(addr_mach_port_space_info, 'int', ['int', 'pointer', 'pointer', 'pointer', 'pointer', 'pointer']); 37 | var mach_port_kobject = new NativeFunction(addr_mach_port_kobject, 'int', ['int', 'int', 'pointer', 'pointer']) 38 | var mach_port_kobject_description = new NativeFunction(addr_mach_port_kobject_description, 'int', ['int', 'int', 'pointer', 'pointer', 'pointer']) 39 | 40 | // step 3: retrieve task for daemon 41 | var taskself = mach_task_self(); 42 | console.log("mach_task_self:", taskself); 43 | 44 | // step 4: retrieve mach space info which gets us the task table 45 | var ret = mach_port_space_info(taskself, info, table, tableCount, tree, treeCount); 46 | 47 | // step 5: print task table. There are tableCount entries. 48 | const tableBaseAddr = table.readPointer(); 49 | var kotype = Memory.alloc(32); 50 | var kaddr = Memory.alloc(32); 51 | var desc = Memory.alloc(32); 52 | 53 | for (var i=0; i \t\t\t' + name); 191 | // } 192 | // console.log('\n'); 193 | 194 | // Create frida hook 195 | var addr = Process.getModuleByName('IOKit').getExportByName(name); 196 | Interceptor.attach(addr, { 197 | onEnter: function(args) { 198 | log_call(name, args, arglist); 199 | }, 200 | onLeave: function(retval) { 201 | ret_call(name, retval, arglist); 202 | } 203 | }); 204 | } 205 | 206 | // global variables 207 | var output = 0; 208 | var outputCnt = 0; 209 | var outputStruct = 0; 210 | var outputStructCnt = 0; 211 | var masterPort = 0; 212 | 213 | function log_call(fname, args, arglist) { 214 | // Print function name as a header. 215 | console.log('{^-^} ' + fname + ':'); 216 | // Go through all arguments and print them 217 | // either directly or dereference the address 218 | // if it is a pointer and the count is given 219 | for (var i=0; i> mach_msg_bits msgh_bits: 0x' + value.readU32().toString(16).padStart(8,'0')); 300 | console.log('\t>> mach_msg_size_t msgh_size: 0x' + value.add(4).readU32().toString(16).padStart(8,'0')); 301 | 302 | const machport = '\t>> mach_port_t msgh_remote_port: 0x' + value.add(8).readU32().toString(16).padStart(8,'0'); 303 | if (mapping == undefined || mapping[1] == undefined) { 304 | console.log(machport); 305 | } 306 | else { 307 | console.log(machport + ' ==> ' + mapping[1]); 308 | } 309 | 310 | console.log('\t>> mach_port_t msgh_local_port: 0x' + value.add(12).readU32().toString(16).padStart(8,'0')); 311 | console.log('\t>> mach_msg_size_t msgh_reserved: 0x' + value.add(16).readU32().toString(16).padStart(8,'0')); 312 | console.log('\t>> mach_msg_id_t msgh_id: 0x' + value.add(20).readU32().toString(16).padStart(8,'0')); 313 | // console.log(s + '\n' + hexdump(value)); 314 | continue; 315 | } 316 | // else { 317 | // console.log(s + type); 318 | // } 319 | } 320 | // non-pointer (*) types 321 | // print port names here (except from lookup pointer in MasterPort, which is the old one) 322 | else if ((type == 'mach_port_t' || type == 'io_registry_entry_t' || type == 'io_object_t') && ! fname.includes('IOMasterPort')) { 323 | const mapping = mappings.find(function (el) { return el[0] == parseInt(value) }); 324 | if (mapping != undefined && mapping[1] != undefined) { 325 | console.log(s + value + ' => ' + mapping[1]); 326 | } else { 327 | // if we don't know the mapping, get it 328 | let entry = parseInt(value); 329 | mach_port_kobject_description(taskself, entry, kotype, kaddr, desc); 330 | let desc_val = desc.readUtf8String(); 331 | mappings.push([entry, desc_val]); 332 | console.log(s + value + ', added new mapping ' + desc_val); 333 | } 334 | continue; 335 | } 336 | else if (type.includes('CFStringRef')) { 337 | console.log(s + new ObjC.Object(value)); 338 | continue; 339 | } 340 | else if (type.includes('CFDictionaryRef')) { 341 | // Frida can handle CFDictionaries natively as Objective-C objects 342 | console.log(s + cfdict + '\nDict: \n' + new ObjC.Object(value)); 343 | continue; 344 | } 345 | else if (type.includes('io_string_t')) { 346 | console.log(s + value.readUtf8String()); 347 | continue; 348 | } 349 | 350 | // If anything went wrong, 351 | // just print the memory location. 352 | console.log(s + value); 353 | } 354 | // print a newline at the end 355 | console.log(''); 356 | 357 | 358 | } 359 | 360 | function ret_call(fname, retval, arglist) { 361 | 362 | 363 | // print the outputs, only filled on return 364 | if (arglist.includes('void *outputStruct')) { // size_t 365 | if (outputStructCnt != 0x0) { 366 | let size = outputStructCnt.readU32(); //U64? 367 | console.log('< outputStruct: \n' + hexdump(outputStruct.readByteArray(size)) + '\n'); 368 | } 369 | } 370 | if (arglist.includes('uint64_t *output')) { // size_t 371 | let size = parseInt(outputCnt); 372 | if (size != 0) { 373 | console.log('< output: \n' + hexdump(output.readByteArray(size)) + '\n'); 374 | } 375 | } 376 | 377 | if (debug_returns) { 378 | console.log('debugging returns!') 379 | // print the mach port that the service is going to use 380 | if (fname.includes('IOIteratorNext')) { 381 | if (retval != 0x0) { 382 | console.log('< io_service_t ' + retval + '\n'); 383 | } 384 | } 385 | 386 | // print the mach port that the service is going to use, 387 | // also push it to the service map 388 | if (fname.includes('IORegistryEntryFromPath')) { 389 | if (retval != 0x0) { 390 | let entry = parseInt(retval); 391 | mach_port_kobject_description(taskself, entry, kotype, kaddr, desc); 392 | let desc_val = desc.readUtf8String(); 393 | console.log('< io_registry_entry_t ' + retval + ', port description: ' + desc_val + '\n'); 394 | mappings.push([entry, desc_val]); 395 | } 396 | } 397 | 398 | // IOMasterPort - save it for lookup 399 | if (arglist.includes('mach_port_t *masterPort')) { 400 | console.log('< masterPort: ' + new NativePointer(masterPort.readU32()) + '\n'); //cast to nativeptr for hex 401 | } 402 | } 403 | 404 | } 405 | 406 | // var addr_mach = Module.getExportByName('libSystem.B.dylib', 'mach_msg'); 407 | // Interceptor.attach(addr_mach, { 408 | // onEnter: function(args) { 409 | // const name = 'mach_msg'; 410 | // const arglist = ['mach_msg_header_t *msg', 'mach_msg_option_t option', 'mach_msg_size_t send_size', 'mach_msg_size_t rcv_size', 'mach_port_name_t rcv_name', 'mach_msg_timeout_t timeout', 'mach_port_name_t notify']; 411 | // log_call(name, args, arglist); 412 | // } 413 | // }); 414 | -------------------------------------------------------------------------------- /scripts/bypass_apple_certificate_pinning.js: -------------------------------------------------------------------------------- 1 | // global TLS certificate pinning bypass, also works on Apple's domains 2 | // 3 | // frida -U trustd --load bypass_apple_certificate_pinning.js 4 | 5 | 6 | // just tell we're using a different domain that's not pinned 7 | const domain = ObjC.classes.NSString.alloc().initWithString_("google.com") 8 | 9 | const queryForDomain = ObjC.classes.SecPinningDb['- queryForDomain:'].implementation 10 | Interceptor.attach(queryForDomain, { 11 | onEnter(args) { 12 | let oldDomain = new ObjC.Object(args[2]) 13 | console.log(`-[SecPinningDb queryForDomain:${oldDomain}] -- replacing with new domain to bypass pinning`) 14 | args[2] = domain 15 | } 16 | }); 17 | 18 | console.log("ready!") -------------------------------------------------------------------------------- /scripts/dasd_schedule_activity.js: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | // Usage: 4 | // frida [-U] dasd --load dasd_schedule_activity.js 5 | // Then trigger an activity... 6 | // 7 | // https://bryce.co/running-xpc-activities-on-demand/ 8 | 9 | // +[_DASDaemon sharedInstance] 10 | var sharedInstance = ObjC.classes._DASDaemon.sharedInstance(); 11 | sharedInstance = new ObjC.Object(sharedInstance); 12 | console.log("Got DASDaemon instance: " + sharedInstance); 13 | 14 | function run_activity(activity_name) { 15 | const {NSString, NSArray} = ObjC.classes; 16 | const activity_string = NSString['stringWithString:'](activity_name); 17 | const activity_array = NSArray.alloc().initWithObject_(activity_string); 18 | 19 | sharedInstance.forceRunActivities_(activity_array); 20 | console.log("ran activity"); 21 | } 22 | 23 | //run_activity("com.apple.CacheDelete.daily"); 24 | console.log("Now call e.g. `run_activity('com.apple.CacheDelete.daily')`"); 25 | -------------------------------------------------------------------------------- /scripts/jetsamctl.js: -------------------------------------------------------------------------------- 1 | // attach this to a process with the entitlement `com.apple.private.memorystatus`, 2 | // e.g., dasd: 3 | // `frida -U dasd -l jetsamctl.js` 4 | 5 | const memorystatus_control_addr = Process.getModuleByName('libsystem_kernel.dylib').getExportByName('memorystatus_control'); 6 | const memorystatus_control = new NativeFunction(memorystatus_control_addr, 'int', ['int', 'int', 'int', 'pointer', 'int']); 7 | const MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT = 6; 8 | 9 | 10 | function setMemoryLimit(pid, limitMb) { 11 | // returns 0 if ok, -1 if not permitted 12 | console.log('returned: ' + memorystatus_control(MEMORYSTATUS_CMD_SET_JETSAM_TASK_LIMIT, pid, limitMb, new NativePointer(0), 0)); 13 | } 14 | 15 | console.log('run setMemoryLimit(pid, limit in megabytes)'); 16 | console.log('Find out pid with Frida: Process.id'); -------------------------------------------------------------------------------- /scripts/libdispatch.js: -------------------------------------------------------------------------------- 1 | /* 2 | Grand Central Dispatch (GCD) is provided by libdispatch. It represents threads within 3 | a process on iOS. For example, `dispatch_async(queue, block)` takes a dispatch queue 4 | with a name and a block that defines execution including a function. 5 | 6 | Since even our debug prints are threaded, prints can occur out of order, 7 | so we have to combine them into one logging statement. 8 | 9 | libdispatch is open-sourced by Apple: https://opensource.apple.com/tarballs/libdispatch/ 10 | 11 | 12 | Usage: 13 | 14 | * Attach to existing daemon 15 | frida -U your_target --no-pause -l libdispatch.js 16 | 17 | * Start with new daemon 18 | frida -U -f /bin/your_target --no-pause -l libdispatch.js 19 | 20 | */ 21 | 22 | 23 | /* 24 | libdispatch helper functions 25 | */ 26 | 27 | // Print the NSStackBlock function we're going to invoke. 28 | 29 | function print_block_invoke(dispatch_block) { 30 | // Is at offset 0x10. Only the least significant are relevant. 31 | return `Callback function: ${DebugSymbol.fromAddress(dispatch_block.add(0x10).readPointer())}\n`; 32 | } 33 | 34 | // Get name of a queue 35 | const libdispatch = Process.getModuleByName('libdispatch.dylib'); 36 | const _dispatch_queue_get_label_addr = libdispatch.getExportByName('dispatch_queue_get_label'); 37 | const _dispatch_queue_get_label = new NativeFunction(_dispatch_queue_get_label_addr, "pointer", ["pointer"]); 38 | function print_queue_label(dispatch_queue) { 39 | return `Calling queue: ${_dispatch_queue_get_label(dispatch_queue).readUtf8String()}\n`; 40 | } 41 | 42 | function print_backtrace(ctx) { 43 | return 'Backtrace:\n' + 44 | Thread.backtrace(ctx, Backtracer.ACCURATE) 45 | .map(DebugSymbol.fromAddress).join('\n') + '\n'; 46 | } 47 | 48 | // Hook async dispatching. We do the backtrace in the thread *before* dispatch_async 49 | // was called, so we're off by one. 50 | const _dispatch_async_addr = libdispatch.getExportByName('dispatch_async'); 51 | Interceptor.attach(_dispatch_async_addr, { 52 | onEnter: function(args) { 53 | console.log('dispatch_async\n' + 54 | print_queue_label(args[0]) + 55 | print_block_invoke(args[1]) + 56 | print_backtrace(this.context)); 57 | }, 58 | }); 59 | 60 | // Dispatching sync. Used a lot during service creation. 61 | const _dispatch_sync_addr = libdispatch.getExportByName('dispatch_sync'); 62 | Interceptor.attach(_dispatch_sync_addr, { 63 | onEnter: function(args) { 64 | console.log('dispatch_sync\n' + 65 | print_queue_label(args[0]) + 66 | print_block_invoke(args[1]) + 67 | print_backtrace(this.context)); 68 | }, 69 | }); 70 | 71 | // Dispatch queue creation 72 | const _dispatch_queue_create_addr = libdispatch.getExportByName('dispatch_queue_create'); 73 | Interceptor.attach(_dispatch_queue_create_addr, { 74 | onEnter: function(args) { 75 | console.log('dispatch_queue_create\n' + 76 | 'Label: ' + args[0].readUtf8String() + '\n' + 77 | print_backtrace(this.context));; 78 | }, 79 | }); 80 | 81 | // Hook time dispatching, but this only gives time constraints so it shouldn't be relevant for us. 82 | const _dispatch_time_addr = libdispatch.getExportByName('dispatch_time'); 83 | Interceptor.attach(_dispatch_time_addr, { 84 | onEnter: function(args) { 85 | console.log('dispatch_time\n'); 86 | }, 87 | }); 88 | 89 | // Delayed dispatching 90 | const _dispatch_after_addr = libdispatch.getExportByName('dispatch_after'); 91 | Interceptor.attach(_dispatch_after_addr, { 92 | onEnter: function(args) { 93 | console.log('dispatch_after\n' + 94 | //'in ' + args[0].readDouble() + 'ms' + 95 | print_queue_label(args[1]) + 96 | print_block_invoke(args[2]) + 97 | print_backtrace(this.context)); 98 | }, 99 | }); 100 | 101 | /* 102 | // hooking this leads to freezing the target process, hence it's disabled... 103 | const _dispatch_once_addr = Module.getExportByName('libdispatch.dylib', 'dispatch_once'); 104 | Interceptor.attach(_dispatch_once_addr, { 105 | onEnter: function(args) { 106 | console.log('dispatch_once\n' + 107 | print_block_invoke(args[1]) + 108 | print_backtrace(this.context)); 109 | }, 110 | }); 111 | */ -------------------------------------------------------------------------------- /scripts/mach_msg.js: -------------------------------------------------------------------------------- 1 | /* 2 | Mach messages are used everywhere :) This script only prints them and doesn't do any 3 | deserialization. But it should be quite helpful to see how a target interacts with 4 | other system components and the kernel. Executables might use plain Mach messages, but 5 | usually, they call that via XPC, IOKit, etc. 6 | 7 | Might produce some out-of-order outputs on high load, be a bit careful with what you 8 | see and how you interpret it ;) 9 | 10 | Reconfigure how many bytes are printed and if XPC should be included. 11 | 12 | Since even our debug prints are threaded, prints can occur out of order. 13 | 14 | Usage: 15 | 16 | * Attach to existing daemon 17 | frida -U your_target --no-pause -l mach_msg.js 18 | 19 | * Start with new daemon 20 | frida -U -f /bin/your_target --no-pause -l mach_msg.js 21 | 22 | */ 23 | 24 | /* 25 | Configure options here! 26 | */ 27 | var mach_truncate_size = 0x100; 28 | var mach_remove_xpc = false; 29 | 30 | 31 | 32 | var _mach_msg_addr = Process.getModuleByName('libSystem.B.dylib').getExportByName('mach_msg'); 33 | 34 | // Using some global variables here for onEnter vs. onLeave, works most of the time... 35 | var _mach_msg_body_ptr; 36 | var _mach_msg_rcv_size; 37 | var _mach_msg_snd_size; 38 | var _mach_is_xpc = false; 39 | 40 | 41 | Interceptor.attach(_mach_msg_addr, { 42 | 43 | // parse what we send 44 | onEnter: function(args) { 45 | 46 | _mach_is_xpc = false; 47 | _mach_msg_body_ptr = args[0].add(0x18); 48 | if (mach_remove_xpc && _mach_msg_body_ptr.readU32() == 1079529539) { // Integer corresponding to "CPX@" 49 | console.log(' * mach_msg(XPC, skipping for perf)'); 50 | _mach_is_xpc = true; 51 | } else { 52 | console.log(' * mach_msg(msg: ' + args[0] + ', option: ' + args[1] + ', send_size: ' + 53 | args[2] + ', rcv_size: ' + args[3] + ', rcv_name: ' + args[4] + '...)'); 54 | 55 | // get send_size bytes of body 56 | _mach_msg_snd_size = parseInt(args[2]); 57 | if (_mach_msg_snd_size > 0 && _mach_msg_snd_size < mach_truncate_size) { 58 | console.log(' v---- mach_msg input ----'); 59 | console.log(_mach_msg_body_ptr.readByteArray(_mach_msg_snd_size)); 60 | } else if (_mach_msg_snd_size > 0) { 61 | console.log(' v---- mach_msg input (truncated) ----'); 62 | console.log(_mach_msg_body_ptr.readByteArray(mach_truncate_size)); 63 | } 64 | 65 | // keep receive_size info for later 66 | _mach_msg_rcv_size = parseInt(this.context.x3); 67 | } 68 | }, 69 | 70 | // parse what we receive in response 71 | // as far as I understand the original mach_msg body is overwritten on return 72 | onLeave: function(r) { 73 | 74 | //console.log(r); // it's only 0x0 for success, not interesting to print 75 | 76 | if ( ! (mach_remove_xpc && _mach_is_xpc)) { // skip XPC messages if mach_remove_xpc=true and _mach_is_xpc=true 77 | 78 | if (_mach_msg_rcv_size > 0 && _mach_msg_rcv_size < mach_truncate_size) { 79 | console.log(' v---- mach_msg output ----'); 80 | console.log(_mach_msg_body_ptr.readByteArray(_mach_msg_rcv_size)); 81 | } else if (_mach_msg_rcv_size > 0) { 82 | console.log(' v---- mach_msg output (truncated) ----'); 83 | console.log(_mach_msg_body_ptr.readByteArray(mach_truncate_size)); 84 | } 85 | } 86 | } 87 | }); 88 | -------------------------------------------------------------------------------- /scripts/objc_msg.js: -------------------------------------------------------------------------------- 1 | /* 2 | Prints all Objective-C calls (without arguments). 3 | Huge performance impact, handle with care. 4 | */ 5 | 6 | const _objc_msgSend = Module.getGlobalExportByName('objc_msgSend'); 7 | Interceptor.attach(_objc_msgSend, { 8 | onEnter: function(args) { 9 | console.log(`objc_msgSend(${(new ObjC.Object(args[0])).$className}, ${args[1].readCString()})`); 10 | }, 11 | }); 12 | 13 | console.log('logging all objective-c calls...') -------------------------------------------------------------------------------- /scripts/os_log.js: -------------------------------------------------------------------------------- 1 | /* 2 | Function that prints OS Log args. 3 | 4 | Apple's clang emits built-in calls to create the OS log buffer of the correct size and 5 | then also fill in the OS Log buffer. Before creating the built-in calls, OS Log takes 6 | a format string and a variable number of arguments. clang then emits the buffer size 7 | along with the instructions to fill the stack buffer. To this end, it first parses 8 | the format string and builds an internal layout struct it fills with the arguments 9 | (compile time). Then, clang iterates over the layout struct items and emits instructions 10 | that end up in the binary. 11 | 12 | CGBuiltin.cpp: Builtin::BI__builtin_os_log_format 13 | OSLog.cpp: clang::analyze_os_log::computeOSLogBufferLayout 14 | PrintfFormatString.cpp: clang::analyze_format_string::ParsePrintfString 15 | 16 | This might be done to accelerate log message parsing, and we can use the open part 17 | of the implementation to name things correctly. 18 | 19 | At runtime, the logs are parsed by `libsystem_trace.dylib`, and the most important 20 | part of the parser is contained in `os_log_impl_flatten_and_send`. Many parts in the 21 | code don't contain symbols and it's difficult to call into this with Frida. 22 | 23 | Items are defined in OSLog.h as follows: 24 | 4 Bits kind (upper nibble) 25 | 0 ScalarKind 26 | 1 CountKind 27 | 2 StringKind 28 | 3 PointerKind 29 | 4 ObjCObjKind 30 | 4 Bits Public/Private (lower nibble), we ignore this to print them all 31 | 32 | As defined in HandlePrintfSpecifier, each of these has different cases to handle: 33 | * "%f", "%d"... scalar and can be 4 bytes or even 1 bytes -- everything else is 8 bytes 34 | * "%s" pointer to null-terminated string 35 | * "%.*s" strlen (arg), pointer to string 36 | * "%.16s" strlen (non-arg), pointer to string 37 | * "%.*P" len (arg), pointer to data 38 | * "%.16P" len (non-arg), pointer to data 39 | * "%@" pointer to objc object 40 | 41 | There are a lot of types to handle, including length modifiers etc. in these format strings. 42 | We mostly care about printing the numbers at all, it's a bit quick&dirty. Handling them all 43 | might take too much time. 44 | 45 | */ 46 | 47 | const kind = { 48 | ScalarKind: 0, 49 | CountKind: 1, 50 | StringKind: 2, 51 | PointerKind: 3, 52 | ObjCObjKind: 4 53 | } 54 | 55 | const NSString = ObjC.classes.NSString; 56 | 57 | function printLog(args) { 58 | // Parse the null-terminated format string 59 | let StringArg = args[3].readCString(); 60 | let BufAddr = args[4]; 61 | let BufLen = parseInt(args[5]); 62 | 63 | // The Buffer starts with two bytes: a summary byte and numArgs. 64 | let numArgs = BufAddr.add(1).readU8(); 65 | 66 | if (numArgs == 0) { 67 | return StringArg; 68 | } 69 | 70 | // Can't use the format string as is due to stuff like "%{private}s", "%{bluetooth:OI_STATUS}u", etc. 71 | // Just replace everything in {} as we ignore public/private. 72 | StringArg = StringArg.replaceAll(/%({.*?})/g, '%'); 73 | 74 | // Mostly normal format strings that we can match now, item by item. 75 | // In our case it's easier to iterate through the format string, as the raw buffer sometimes has 76 | // composed values that we want to combine and then replace one format string value with it. 77 | // For simplicity, we assume any characters are valid length modifiers (see FormatString.h). 78 | // We consider all conversion modifiers (see PrintfFormatString.cpp). 79 | let formatStringItems = StringArg.match(/%({.*?})?.*?([%AEFGXacdefginopsuxCSP@mbryDOUZ])/g) 80 | if (formatStringItems == null) { 81 | return StringArg; 82 | } 83 | 84 | // Skip first two bytes: summary and numArgs 85 | let bufferOffset = 2; 86 | let itemCount = 0; 87 | 88 | formatStringItems.forEach((variable) => { 89 | // each item has: [1b type] [1b length] [entry value] 90 | let argDescriptor = BufAddr.add(bufferOffset).readU8(); 91 | let argKind = argDescriptor >> 4; 92 | let argSize = BufAddr.add(bufferOffset + 1).readU8(); 93 | 94 | // StringKind, ObjcObjKind, PointerKind are all very similar 8-byte types 95 | if (argKind == kind.StringKind) { 96 | let value = BufAddr.add(bufferOffset + 2).readPointer(); 97 | if (value != 0) { 98 | StringArg = StringArg.replace(variable, value.readCString()); 99 | } 100 | } else if (argKind == kind.PointerKind) { 101 | let value = BufAddr.add(bufferOffset + 2).readPointer(); 102 | if (value != 0) { 103 | StringArg = StringArg.replace(variable, value.toString(16)); 104 | } 105 | 106 | } else if (argKind == kind.ObjCObjKind) { 107 | let value = BufAddr.add(bufferOffset + 2).readPointer(); 108 | if (value != 0) { 109 | let c = new ObjC.Object(value); 110 | StringArg = StringArg.replace(variable, c.description()); 111 | } 112 | } 113 | // CountKind describes size of next element, which is StringKind or PointerKind. 114 | // CountKind is 4 bytes long. 115 | // StringKind and PointerKind then point to a String or Pointer and at that position we want 116 | // to read as many bytes as the count indicated. 117 | else if (argKind == kind.CountKind) { 118 | let value = BufAddr.add(bufferOffset + 2).readU32(); 119 | let pointsToKind = BufAddr.add(bufferOffset + 2 + 4).readU8() >> 4; 120 | let pointerValue = BufAddr.add(bufferOffset + 2 + 4 + 2).readPointer(); 121 | 122 | if (pointerValue != 0) { 123 | if (pointsToKind == kind.PointerKind) { 124 | StringArg = StringArg.replace(variable, hexdump(pointerValue, {length: value, header: false, ansi: false})); 125 | } else if (pointsToKind == kind.StringKind) { 126 | StringArg = StringArg.replace(variable, pointerValue.readCString(value)); 127 | } 128 | } else { 129 | StringArg = StringArg.replace(variable, 'null'); 130 | } 131 | 132 | // advance buffer by PointerKind/StringKind 133 | bufferOffset += 8 + 2; 134 | } 135 | // ScalarKind are regular numbers but can have different sizes 136 | else if (argKind == kind.ScalarKind) { 137 | let value; 138 | 139 | // read as many bytes as the ScalarKind has 140 | if (argSize == 1) { 141 | value = BufAddr.add(bufferOffset + 2).readU8(); 142 | } else if (argSize == 4) { 143 | value = BufAddr.add(bufferOffset + 2).readU32(); 144 | } else if (argSize == 8) { 145 | value = BufAddr.add(bufferOffset + 2).readPointer(); 146 | } 147 | 148 | // differentiate between hex vs decimal output 149 | if (/[xX]/.test(variable)) { 150 | StringArg = StringArg.replace(variable, value.toString(16)); // preserve hex strings 151 | } 152 | // '%0.*d' consists of two ScalarKinds where the first is number of digits 153 | else if(variable === '%0.*d') { 154 | let realValue = BufAddr.add(bufferOffset + 2 + 4 + 2).readU32(); 155 | StringArg = StringArg.replace(variable, realValue); 156 | bufferOffset += 4 + 2; // advance buffer 157 | } 158 | // signed integers 159 | else if (variable === '%d' || variable === '%i') { 160 | StringArg = StringArg.replace(variable, (value << 32) >> 32); 161 | } 162 | else { 163 | StringArg = StringArg.replace(variable, value); 164 | } 165 | 166 | // TODO readability would be improved by adding further special cases here, 167 | // such as %f etc. or even considering length modifiers 168 | 169 | } 170 | bufferOffset += argSize + 2; // advance offset by item description + length 171 | itemCount++; 172 | }); 173 | 174 | // Debugging in case there's some unsupported types 175 | if (bufferOffset != BufLen) { 176 | console.error(`LOG ERROR buffer offset ${bufferOffset} does not match provided buffer length ${BufLen}!`); 177 | console.error(BufAddr.readByteArray(BufLen)); 178 | console.error(formatStringItems); 179 | console.error(args[3].readCString()); 180 | } 181 | 182 | return StringArg; 183 | } 184 | 185 | // Fake that all log types are enabled 186 | const libsystem_trace = Process.getModuleByName('libsystem_trace.dylib'); 187 | const isEnabledFunc = libsystem_trace.getExportByName('os_log_type_enabled'); 188 | Interceptor.attach(isEnabledFunc, { 189 | onLeave: function (ret) { 190 | ret.replace(1); 191 | } 192 | }); 193 | 194 | // Hook all log levels and print them in different colors 195 | const log_default = libsystem_trace.getExportByName('_os_log_impl') 196 | const log_fault = libsystem_trace.getExportByName('_os_log_fault_impl') 197 | const log_debug = libsystem_trace.getExportByName('_os_log_debug_impl') 198 | const log_error = libsystem_trace.getExportByName('_os_log_error_impl') 199 | 200 | Interceptor.attach(log_default, { 201 | onEnter: function (args) { 202 | console.log(printLog(args)); 203 | }, 204 | }); 205 | 206 | Interceptor.attach(log_fault, { 207 | onEnter: function (args) { 208 | console.error(printLog(args)); 209 | }, 210 | }); 211 | 212 | Interceptor.attach(log_debug, { 213 | onEnter: function (args) { 214 | console.log(`\x1b[34m${printLog(args)}\x1b[0m`); // print debug in blue 215 | }, 216 | }); 217 | 218 | Interceptor.attach(log_error, { 219 | onEnter: function (args) { 220 | console.error(printLog(args)); 221 | }, 222 | }); 223 | 224 | console.log('PRINT ALL THE LOGS! \\o/'); 225 | -------------------------------------------------------------------------------- /scripts/stalker.js: -------------------------------------------------------------------------------- 1 | console.log("loading"); 2 | 3 | const f = Module.getGlobalExportByName('open'); 4 | 5 | Interceptor.attach(f, { 6 | onEnter: function(args) { 7 | console.log('entered function'); 8 | Stalker.follow({ 9 | events: { 10 | // only collect coverage for newly encountered blocks 11 | compile: true, 12 | //call: true, 13 | }, 14 | onReceive: function (events) { 15 | const bbs = Stalker.parse(events, { 16 | stringify: false, 17 | annotate: false 18 | }); 19 | console.log("Stalker trace: \n" + bbs.flat().map(DebugSymbol.fromAddress).join('\n')); 20 | } 21 | }); 22 | }, 23 | onLeave: function(retval) { 24 | Stalker.unfollow(); 25 | Stalker.flush(); // this is important to get all events 26 | } 27 | }); 28 | 29 | 30 | console.log("loaded"); 31 | --------------------------------------------------------------------------------