From 932a89a1e681c46fe7b58b2590598538ee89a307 Mon Sep 17 00:00:00 2001 From: iamtorsten Date: Sat, 28 Sep 2024 16:34:24 +0200 Subject: [PATCH] Remove not used plugins folder --- dbi/plugins/func.py | 38 --------- dbi/plugins/hook/b64.js | 58 -------------- dbi/plugins/hook/func.js | 79 ------------------- dbi/plugins/hook/libart.js | 4 - dbi/plugins/hook/mem.js | 38 --------- dbi/plugins/hook/stalker.js | 82 -------------------- dbi/plugins/hook/strlen.js | 15 ---- dbi/plugins/jni.py | 77 ------------------- dbi/plugins/libart.py | 37 --------- dbi/plugins/libb64.py | 49 ------------ dbi/plugins/libc.py | 48 ------------ dbi/plugins/libso.py | 40 ---------- dbi/plugins/mem.py | 60 --------------- dbi/plugins/patch.py | 149 ------------------------------------ dbi/plugins/trace_suite.py | 137 --------------------------------- 15 files changed, 911 deletions(-) delete mode 100644 dbi/plugins/func.py delete mode 100644 dbi/plugins/hook/b64.js delete mode 100644 dbi/plugins/hook/func.js delete mode 100644 dbi/plugins/hook/libart.js delete mode 100644 dbi/plugins/hook/mem.js delete mode 100644 dbi/plugins/hook/stalker.js delete mode 100644 dbi/plugins/hook/strlen.js delete mode 100644 dbi/plugins/jni.py delete mode 100644 dbi/plugins/libart.py delete mode 100644 dbi/plugins/libb64.py delete mode 100644 dbi/plugins/libc.py delete mode 100644 dbi/plugins/libso.py delete mode 100644 dbi/plugins/mem.py delete mode 100644 dbi/plugins/patch.py delete mode 100644 dbi/plugins/trace_suite.py diff --git a/dbi/plugins/func.py b/dbi/plugins/func.py deleted file mode 100644 index 1c9a777..0000000 --- a/dbi/plugins/func.py +++ /dev/null @@ -1,38 +0,0 @@ -# Plugin: Hook Function -# Description: Hooks a function inside a native library - -import sys -from emu.injector import Inject -import warnings - -warnings.filterwarnings("ignore", category=DeprecationWarning) - -# Callback function to receive messages from script -def on_message(message, data): - if message['type'] == 'send': - print(message['payload']) # Print to console - # Use 'utf-8' encoding to handle a wide range of characters - with open("dump/func_dump.txt", "a", encoding="utf-8") as f: - f.write(message['payload'] + "\n") - elif message['type'] == 'error': - print("[!] Error: {0}".format(message['stack'])) - - -target = "TikTok" -function_offset = 0x2944 -module_name = "libdelta.so" - -# Load the JavaScript file -with open("hook/func.js", "r") as f: - script_code = f.read() - -# Setup Device, Session and Source -sherlock = Inject(target=target) -device, session = sherlock.attach() -script = sherlock.source(session, script_code) - -script.on('message', on_message) -script.load() -script.exports.hookfunction(function_offset, module_name) -input("Press Enter to exit...\n") -sys.stdin.read() \ No newline at end of file diff --git a/dbi/plugins/hook/b64.js b/dbi/plugins/hook/b64.js deleted file mode 100644 index 87a77dd..0000000 --- a/dbi/plugins/hook/b64.js +++ /dev/null @@ -1,58 +0,0 @@ -function waitForLibraryAndHook(libraryName) { - var lib = Process.findModuleByName(libraryName); - if (lib) { - hookB64Functions(lib); - } else { - setTimeout(function() { waitForLibraryAndHook(libraryName); }, 100); - } -} - -function hookB64Functions(lib) { - var exports = Module.enumerateExportsSync(lib.name); - - var b64Decode = null; - var b64Encode = null; - - for (var i = 0; i < exports.length; i++) { - if (exports[i].name === "b64_decode") { - b64Decode = exports[i].address; - } else if (exports[i].name === "b64_encode") { - b64Encode = exports[i].address; - } - } - - if (b64Decode) { - Interceptor.attach(b64Decode, { - onEnter: function(args) { - var input = args[0].readCString(); - var length = args[1].toInt32(); - send({ function: 'b64_decode', input: input, length: length }); - }, - onLeave: function(retval) { - send({ function: 'b64_decode_return', retval: retval.readCString() }); - } - }); - send({ success: "Hooked b64_decode" }); - } else { - send({ error: "b64_decode not found" }); - } - - if (b64Encode) { - Interceptor.attach(b64Encode, { - onEnter: function(args) { - var input = args[0].readCString(); - var length = args[1].toInt32(); - send({ function: 'b64_encode', input: input, length: length }); - }, - onLeave: function(retval) { - send({ function: 'b64_encode_return', retval: retval.readCString() }); - } - }); - send({ success: "Hooked b64_encode" }); - } else { - send({ error: "b64_encode not found" }); - } -} - -// Start waiting for the library to be loaded and then hook functions -waitForLibraryAndHook("libb64.so"); \ No newline at end of file diff --git a/dbi/plugins/hook/func.js b/dbi/plugins/hook/func.js deleted file mode 100644 index 22754ad..0000000 --- a/dbi/plugins/hook/func.js +++ /dev/null @@ -1,79 +0,0 @@ -// Function hook -// (c) Torsten Klement - -rpc.exports = { - hookfunction: function(functionOffset, moduleName) { - console.log("Starting script to hook function at offset 0x" + functionOffset.toString(16) + " in " + moduleName + "..."); - - var module = Process.findModuleByName(moduleName); - - if (module) { - console.log("Module found: " + moduleName); - var baseAddress = module.base; - console.log("Base address of " + moduleName + ": " + baseAddress); - - // Calculate the target address by adding the offset to the base address - var targetAddress = baseAddress.add(ptr(functionOffset)); - console.log("Calculated target address: " + targetAddress); - - // Hook the function at the calculated address - Interceptor.attach(targetAddress, { - onEnter: function(args) { - var logMessage = "Function at " + targetAddress + " called.\n"; - var maxRegisters = 10; // Max registers to check for arguments (x0 to x9) - for (var i = 0; i < maxRegisters; i++) { - var regName = "x" + i; - var regValue = this.context[regName]; - - if (regValue !== undefined) { - logMessage += regName + " (arg" + (i + 1) + "): " + regValue.toString() + "\n"; - - // Attempt to decode the argument as an integer - try { - var intValue = regValue.toInt32(); - logMessage += regName + " as int: " + intValue + "\n"; - } catch (e) { - logMessage += regName + " could not be decoded as an int.\n"; - } - - // Attempt to decode the argument as a string - try { - var possibleString = regValue.readUtf8String(); - logMessage += regName + " as string: " + possibleString + "\n"; - } catch (e) { - logMessage += regName + " is not a readable string.\n"; - } - } - } - console.log(logMessage); // Log to console - send(logMessage); // Send the log message to the Python script - }, - onLeave: function(retval) { - var logMessage = "Function at " + targetAddress + " returned: " + retval.toString() + "\n"; - - // Attempt to decode the return value as an integer - try { - var retIntValue = retval.toInt32(); - logMessage += "Return value as int: " + retIntValue + "\n"; - } catch (e) { - logMessage += "Return value could not be decoded as an int.\n"; - } - - // Attempt to decode the return value as a string - try { - var retString = retval.readUtf8String(); - logMessage += "Return value as string: " + retString + "\n"; - } catch (e) { - logMessage += "Return value is not a readable string.\n"; - } - - console.log(logMessage); // Log to console - send(logMessage); // Send the log message to the Python script - } - }); - - } else { - console.log("Module not found: " + moduleName); - } - } -}; diff --git a/dbi/plugins/hook/libart.js b/dbi/plugins/hook/libart.js deleted file mode 100644 index fdfe802..0000000 --- a/dbi/plugins/hook/libart.js +++ /dev/null @@ -1,4 +0,0 @@ -var exports = Module.enumerateExportsSync("libart.so"); -exports.forEach(function(exp) { - console.log(exp.name); -}); \ No newline at end of file diff --git a/dbi/plugins/hook/mem.js b/dbi/plugins/hook/mem.js deleted file mode 100644 index 08ddffa..0000000 --- a/dbi/plugins/hook/mem.js +++ /dev/null @@ -1,38 +0,0 @@ -const libName = "libmetasec_ov.so"; -const delayBetweenDumps = 100; // Delay in milliseconds between each dump iteration - -function sendMemoryChunk(base, chunkSize) { - try { - const buffer = Memory.readByteArray(ptr(base), chunkSize); - send({ - base: base.toString(), - chunkSize: chunkSize, - data: buffer - }, buffer); // Send the buffer as the second argument - } catch (e) { - console.error("Error reading memory at " + base + ": " + e.message); - } -} - -function dumpLibraryMemory(libName) { - const baseAddress = Module.findBaseAddress(libName); - if (baseAddress === null) { - console.log("Library not found: " + libName); - return; - } - - const libRange = Process.getRangeByAddress(baseAddress); - console.log("Library base address: " + baseAddress); - console.log("Library size: " + libRange.size); - - const chunkSize = 64 * 1024; // Send 64 KB chunks - for (let i = 0; i < libRange.size; i += chunkSize) { - let size = Math.min(chunkSize, libRange.size - i); - sendMemoryChunk(baseAddress.add(i), size); - } -} - -// Set an interval to continuously dump the library memory every `delayBetweenDumps` milliseconds -setInterval(() => { - dumpLibraryMemory(libName); -}, delayBetweenDumps); diff --git a/dbi/plugins/hook/stalker.js b/dbi/plugins/hook/stalker.js deleted file mode 100644 index 1f3fbeb..0000000 --- a/dbi/plugins/hook/stalker.js +++ /dev/null @@ -1,82 +0,0 @@ -var active = true; - -// Stalker -function stalk(pattern) -{ - var type = (pattern.indexOf(' ') === -1) ? 'module' : 'objc'; - var res = new ApiResolver(type); - var matches = res.enumerateMatchesSync(pattern); - var targets = uniqBy(matches, JSON.stringify); - - targets.forEach(function(target) { - stalkFunction(target.address, target.name); - }); -} - -function uniqBy(array, key) -{ - var seen = {}; - return array.filter(function(item) { - var k = key(item); - return seen.hasOwnProperty(k) ? false : (seen[k] = true); - }); -} - -function stalkFunction(impl, name) -{ - console.log("Stalking " + name); - - Interceptor.attach(impl, { - - onEnter: function(args) { - - if (active) - return; - - var flag = {}; - this.flag = flag; - - active = true; - - Stalker.follow({ - - events: { - call: true, - ret: true, - exec: true - }, - - onCallSummary: function (summary) { - console.log(); - Object.keys(summary).forEach(function (target) { - console.log(name + " > " + DebugSymbol.fromAddress(ptr(target)).toString()); - flag[target] = true; - }); - } - - }); - }, - - onLeave: function(retval) { - var flag = this.flag; - if (flag === undefined) - return; - - // Deactivate - Stalker.unfollow(); - active = false; - } - }); -} - -if (ObjC.available) { - - stalk("*[OWSMessageSender *]"); - stalk("-[OWSMessageSender attemptToSendMessage*]"); - stalk("-[OWSMessageSender tag]"); - stalk("exports:libSystem.B.dylib!open"); - stalk("exports:*!open*"); - -} else { - send("error: Objective-C Runtime is not available!"); -} \ No newline at end of file diff --git a/dbi/plugins/hook/strlen.js b/dbi/plugins/hook/strlen.js deleted file mode 100644 index a0581d0..0000000 --- a/dbi/plugins/hook/strlen.js +++ /dev/null @@ -1,15 +0,0 @@ -try { - // Hook the strlen function - Interceptor.attach(Module.findExportByName("libc.so", "strlen"), { - onEnter: function(args) { - this.str = Memory.readUtf8String(args[0]); - send("strlen called with argument: " + this.str); - }, - onLeave: function(retval) { - send("strlen returned: " + retval.toInt32()); - } - }); - send("Frida script loaded successfully"); -} catch (error) { - send("Error: " + error.message); -} \ No newline at end of file diff --git a/dbi/plugins/jni.py b/dbi/plugins/jni.py deleted file mode 100644 index 88126fd..0000000 --- a/dbi/plugins/jni.py +++ /dev/null @@ -1,77 +0,0 @@ -# Plugin: Trace JNI Calls -# Description: Trace JNI Calls - -import sys - -from emu.injector import Inject - - -target = "" # Enter the name of the app to be monitored here. - -def on_message(message, data): - if message['type'] == 'send': - print(f"[Message from EmuTrace]: {message['payload']}") - elif message['type'] == 'error': - print(f"[Error]: {message['stack']}") - -def main(): - # Setup Device, Session and Source - sherlock = Inject(target=target) - device, session = sherlock.attach() - - # Load the JNI methods from the file - with open('jni/libart_jni.txt', 'r') as f: - jni_methods = f.readlines() - - script_code = """ - var jni_functions = %s; - - function traceJNIFunction(funcName) { - var addr = Module.findExportByName("libart.so", funcName); - if (addr) { - Interceptor.attach(addr, { - onEnter: function (args) { - console.log(funcName + " called."); - - // Check the number of arguments available - if (args.length > 0) { - // Log the arguments - for (var i = 0; i < args.length; i++) { - try { - console.log("Argument " + i + ": " + args[i].toString()); - } catch (e) { - console.log("Error accessing argument " + i + ": " + e.message); - } - } - } else { - console.log("No arguments available."); - } - }, - onLeave: function (retval) { - console.log(funcName + " returned " + retval); - } - }); - } else { - console.log("Failed to find " + funcName + " address"); - } - } - - // Iterate over the jni_functions array - for (var i = 0; i < jni_functions.length; i++) { - traceJNIFunction(jni_functions[i]); - } - - jni_functions.forEach(function(func) { - traceJNIFunction(func.trim()); - }); - """ % (jni_methods) - - script = sherlock.source(session, script_code) - script.on('message', on_message) - script.load() - - print("[*] Tracing JNI functions. Press Ctrl+C to stop.") - sys.stdin.read() - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/dbi/plugins/libart.py b/dbi/plugins/libart.py deleted file mode 100644 index 867800d..0000000 --- a/dbi/plugins/libart.py +++ /dev/null @@ -1,37 +0,0 @@ -# Plugin: libart jni -# Description: List libart jni - -import frida -import sys - -from emu.injector import Inject - -target = "" # Enter the name of the app to be monitored here. -script_file = "hook/libart.js" # Hook - - -def main(): - try: - # Load the script - with open(script_file) as f: - script_code = f.read() - - # Setup Device, Session and Source - sherlock = Inject(target=target) - device, session = sherlock.attach() - script = sherlock.source(session, script_code) - - script.load() - - # Keep the script running - print(f"[*] Hooking {target}. Press Ctrl+C to stop.") - sys.stdin.read() - except frida.ServerNotRunningError: - print("SherlockElf server is not running. Please start the SherlockElf Server on your device.") - except frida.ProcessNotFoundError: - print(f"Process '{target}' not found. Make sure the app is running.") - except Exception as e: - print(f"An unexpected error occurred: {e}") - -if __name__ == "__main__": - main() diff --git a/dbi/plugins/libb64.py b/dbi/plugins/libb64.py deleted file mode 100644 index e6b0309..0000000 --- a/dbi/plugins/libb64.py +++ /dev/null @@ -1,49 +0,0 @@ -# Plugin: Hook base64 -# Description: Hook base64 - -import frida -import sys - -from emu.injector import Inject - -target = "" # Enter the name of the app to be monitored here. -script_file = "hook/b64.js" # Hook - -def on_message(message, data): - if message['type'] == 'send': - payload = message['payload'] - if 'function' in payload: - print(f"[{payload['function']}] {payload}") - elif 'success' in payload: - print(f"[Success] {payload['success']}") - elif 'error' in payload: - print(f"[Error] {payload['error']}") - elif message['type'] == 'error': - print(f"[Script Error] {message['stack']}") - -def main(): - try: - # Load the script - with open(script_file) as f: - script_code = f.read() - - # Setup Device, Session and Source - sherlock = Inject(target=target) - device, session = sherlock.attach() - script = sherlock.source(session, script_code) - - script.on('message', on_message) - script.load() - - # Keep the script running - print(f"[*] Hooking {target}. Press Ctrl+C to stop.") - sys.stdin.read() - except frida.ServerNotRunningError: - print("SherlockElf server is not running. Please start the SherlockElf Server on your device.") - except frida.ProcessNotFoundError: - print(f"Process '{target}' not found. Make sure the app is running.") - except Exception as e: - print(f"An unexpected error occurred: {e}") - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/dbi/plugins/libc.py b/dbi/plugins/libc.py deleted file mode 100644 index d21c1ff..0000000 --- a/dbi/plugins/libc.py +++ /dev/null @@ -1,48 +0,0 @@ -# Plugin: Hook strlen -# Description: Hook strlen method - -import frida -import sys - -from emu.injector import Inject - -target = "" # Enter the name of the app to be monitored here. - -def on_message(message, data): - if message['type'] == 'send': - print(f"[Message from SherlockElf]: {message['payload']}") - with open("dump/strlen_dump.txt", "a") as f: - f.write(f'{message}\n') - elif message['type'] == 'error': - print(f"[Error]: {message['stack']}") - -def on_destroyed(): - print("[*] Script destroyed.") - -def main(): - try: - # Load the script - with open("hook/strlen.js") as f: - script_code = f.read() - - # Setup Device, Session and Source - sherlock = Inject(target=target) - device, session = sherlock.attach() - script = sherlock.source(session, script_code) - - script.on('message', on_message) - script.on('destroyed', on_destroyed) - script.load() - - # Keep the script running - print(f"[*] Hooking {target}. Press Ctrl+C to stop.") - sys.stdin.read() - except frida.ServerNotRunningError: - print("SherlockElf server is not running. Please start the SherlockElf Server on your device.") - except frida.ProcessNotFoundError: - print(f"Process '{target}' not found. Make sure the app is running.") - except Exception as e: - print(f"An unexpected error occurred: {e}") - -if __name__ == "__main__": - main() diff --git a/dbi/plugins/libso.py b/dbi/plugins/libso.py deleted file mode 100644 index 7621364..0000000 --- a/dbi/plugins/libso.py +++ /dev/null @@ -1,40 +0,0 @@ -# Plugin: Hook libso -# Description: Hook libso - -from emu.injector import Inject - -target = "" # Enter the name of the app to be monitored here. - -js_code = """ -rpc.exports = { - findModule: function (name) { - const libso = Process.findModuleByName(name); - return libso !== null; - }, - dumpSo: function (name) { - const libso = Process.findModuleByName(name); - if (libso === null) { - console.log("find moduel failed"); - return ''; - } - Memory.protect(ptr(libso.base), libso.size, 'rwx'); - const libso_buffer = ptr(libso.base).readByteArray(libso.size); - return libso_buffer; - }, -} -""" - - -def main(): - # Setup Device, Session and Source - sherlock = Inject(target=target) - device, session = sherlock.attach() - script = sherlock.source(session, js_code) - - script.load() - - # ... do more stuff - - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/dbi/plugins/mem.py b/dbi/plugins/mem.py deleted file mode 100644 index 7debf95..0000000 --- a/dbi/plugins/mem.py +++ /dev/null @@ -1,60 +0,0 @@ -# Plugin: Hook Memory -# Description: Hook memory - -import frida -import sys - -from emu.ds import disassemble_code -from datetime import datetime -from emu.injector import Inject - -target = "" # Enter the name of the app to be monitored here. -source = "mem.js" - -def on_message(message, data): - if message['type'] == 'send': - payload = message['payload'] - base = payload.get('base') - chunk_size = payload.get('chunkSize') - - if data is None: - print(f"[Error] Received memory dump from base address: {base} with chunk size: {chunk_size} bytes, but no data was received.") - else: - timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") - print(f"Received memory dump from base address: {base} with chunk size: {chunk_size} bytes") - - # Save the received memory data to a file - with open(f"bin/memory_dump_{base}_{timestamp}.bin", "wb") as f: - f.write(data) - disassemble_code(data, 0x1000) - print(f"Memory dump saved to memory_dump_{base}_{timestamp}.bin") - elif message['type'] == 'error': - print(f"[Error]: {message['stack']}") - - -def main(): - try: - # Load the script - with open(f"hook/{source}") as f: - script_code = f.read() - - # Setup Device, Session and Source - sherlock = Inject(target=target) - device, session = sherlock.attach() - script = sherlock.source(session, script_code) - - script.on('message', on_message) - script.load() - - # Keep the script running - print(f"[*] Hooking {target}. Press Ctrl+C to stop.") - sys.stdin.read() - except frida.ServerNotRunningError: - print("SherlockElf server is not running. Please start the SherlockElf Server on your device.") - except frida.ProcessNotFoundError: - print(f"Process '{target}' not found. Make sure the app is running.") - except Exception as e: - print(f"An unexpected error occurred: {e}") - -if __name__ == "__main__": - main() diff --git a/dbi/plugins/patch.py b/dbi/plugins/patch.py deleted file mode 100644 index 4660605..0000000 --- a/dbi/plugins/patch.py +++ /dev/null @@ -1,149 +0,0 @@ -# Plugin: Patch Functions -# Description: Script zum Patchen von Funktionen oder Adressen innerhalb einer nativen Android Library - -import sys - -from emu.injector import Inject - - -# JavaScript Code zum Patchen der Funktion an einer bestimmten Adresse -def generate_js_code(target_library, patches): - js_code = f""" - const targetLibrary = Module.getBaseAddress("{target_library}"); - """ - - for patch in patches: - address = patch["address"] - instructions = patch.get("instructions", []) - full_address = f"targetLibrary.add({address})" - - js_code += f""" - Interceptor.attach({full_address}, {{ - onEnter: function (args) {{ - console.log("[INFO] Hooking Instruction at Address: {full_address}"); - - """ - - for instruction in instructions: - original = instruction.get("original") - replacement = instruction.get("replace") - - # Patchen von Registeroperationen (z.B. mov, add, sub) - if "mov" in original: - reg = original.split()[1].strip(",") # z.B. x0 bei "mov x0, x1" - js_code += f""" - var original_value = this.context.{reg}; - console.log("[INFO] Originalwert von {reg}: " + original_value); - - // Patchen des Registers {reg} - this.context.{reg} = ptr("{replacement}"); - console.log("[INFO] Geänderter Wert von {reg}: " + this.context.{reg}); - """ - - elif "add" in original: - reg = original.split()[1].strip(",") - js_code += f""" - var original_value = this.context.{reg}.toInt32(); - console.log("[INFO] Originalwert von {reg}: " + original_value); - - // Addieren eines Werts zu {reg} - this.context.{reg} = ptr(original_value + {replacement}); - console.log("[INFO] Geänderter Wert von {reg}: " + this.context.{reg}); - """ - - elif "sub" in original: - reg = original.split()[1].strip(",") - js_code += f""" - var original_value = this.context.{reg}.toInt32(); - console.log("[INFO] Originalwert von {reg}: " + original_value); - - // Subtrahieren eines Werts von {reg} - this.context.{reg} = ptr(original_value - {replacement}); - console.log("[INFO] Geänderter Wert von {reg}: " + this.context.{reg}); - """ - - # Patchen von Speicheroperationen (z.B. ldr, str) - elif "ldr" in original or "str" in original: - reg = original.split()[1].strip(",") # Register, in das geladen wird oder aus dem gespeichert wird - js_code += f""" - var mem_address = this.context.{reg}; - console.log("[INFO] Speicheradresse, die gepatcht wird: " + mem_address); - - // Patchen des Werts an der Speicheradresse - Memory.writePointer(mem_address, ptr("{replacement}")); - console.log("[INFO] Neuer Wert an Speicheradresse: " + Memory.readPointer(mem_address)); - """ - - js_code += """ - }}, - onLeave: function (retval) {{ - console.log("[INFO] Rückgabewert vor dem Patch: " + retval.toInt32()); - """ - - if "return" in patch: - new_retval = patch["return"] - js_code += f""" - retval.replace({new_retval}); - console.log("[INFO] Rückgabewert nach dem Patch: " + retval.toInt32()); - """ - - js_code += """ - }} - }}); - """ - - return js_code - -# Python Funktion um die Session zu starten und die JS-Skripte zu laden -def patch_functions_in_library(target, target_library, patches): - # Setup Device, Session and Source - sherlock = Inject(target=target) - device, session = sherlock.attach() - # Generiere das JavaScript für alle Patches - js_code = generate_js_code(target_library, patches) - script = sherlock.source(session, js_code) - - script.on('message', on_message) - script.load() - print(f"[INFO] Alle Patches wurden geladen für Library {target_library}.") - - sys.stdin.read() # Halte das Skript am Laufen - -def on_message(message, data): - if message['type'] == 'send': - print("[*] {0}".format(message['payload'])) - elif message['type'] == 'error': - print("[!] {0}".format(message['stack'])) - -# Beispiel-Logik zur Verwendung der Funktionen -if __name__ == "__main__": - target_process = "" - target_library = "" # Name der zu patchenden Library - - # Beispielhafte Patches - patches = [ - { - "address": "0x1ea8", # Adresse relativ zur Basis der Library - "instructions": [ - {"original": "mov x0, x1", "replace": "0x12345678"}, # Setzt x0 auf 0x12345678 - {"original": "ldr x0, [x1]", "replace": "0x87654321"}, # Lädt 0x87654321 in x0 - ], - "return": "0x9999" # Optional: Rückgabewert ändern - }, - { - "address": "0xf000", # Adresse relativ zur Basis der Library - "instructions": [ - {"original": "add x0, #0x10", "replace": "0x20"}, # Addiert 0x20 zu x0 anstelle von 0x10 - {"original": "str x0, [x1]", "replace": "0x55555555"} # Speichert 0x55555555 in der Adresse in x1 - ] - }, - { - "address": "0xf004", # Adresse relativ zur Basis der Library - "instructions": [ - {"original": "sub sp, #0x10", "replace": "0x20"}, # Subtrahiert 0x20 von sp statt 0x10 - {"original": "ldr x2, [x3]", "replace": "0x33333333"}, # Lädt 0x33333333 in x2 - ] - } - ] - - patch_functions_in_library(target_process, target_library, patches) diff --git a/dbi/plugins/trace_suite.py b/dbi/plugins/trace_suite.py deleted file mode 100644 index 6d4a3c0..0000000 --- a/dbi/plugins/trace_suite.py +++ /dev/null @@ -1,137 +0,0 @@ -# Plugin: Trace Suite -# Description: Trace Function Flow, Register Values, Code Execution and Return Values of Android Native Libraries -# (c) 2024 Torsten Klement, torsten.klinger@googlemail.com -# MIT - -import codecs -import os -import frida -import sys - -from datetime import datetime -from colorama import Fore -from emu.injector import Inject -from emu.trace_native import load_script - - -def Print(text: str): - print( - f"{Fore.LIGHTBLUE_EX}{Fore.LIGHTCYAN_EX}{text}{Fore.LIGHTBLUE_EX}{Fore.RESET}") - -banner = """ - ___ _ _ _ ___ _ __ _____ ___ _ _ - / __| |_ ___ _ _| |___ __| |_| __| |/ _| |_ _| _ __ _ __ ___ / __|_ _(_) |_ ___ - \__ \ ' \/ -_) '_| / _ \/ _| / / _|| | _| | || '_/ _` / _/ -_) \__ \ || | | _/ -_) - |___/_||_\___|_| |_\___/\__|_\_\___|_|_| |_||_| \__,_\__\___| |___/\_,_|_|\__\___| \n\n(c) 2024 - now Torsten Klement\nContact [Skype]: https://join.skype.com/invite/ErVkPMTQZExQ\nContact [Telegram]: https://t.me/iamtorsten -""" - -Print(banner) - -# Target Application -target = "" -# Target Library -target_library = "" -# Directory to save the output files -output_dir = "trace_suite_output" -os.makedirs(output_dir, exist_ok=True) # Create the directory if it doesn't exist -os.makedirs(f"{output_dir}/{target}/{target_library.replace('.', '_')}", exist_ok=True) # Create the directory if it doesn't exist -# Hooked functions -functions = [ - {"offset": 0xebea8, "name": "FunctionA"} # Add pseudo names for clarity - # Add more functions with their offsets and names as needed -] -# Create directories for each function based on their pseudo name -for function in functions: - os.makedirs(f"{output_dir}/{target}/{target_library.replace('.', '_')}/{function['name']}", exist_ok=True) # Create the directory if it doesn't exist -# Maximal Assembly Instructions per function -# As soon as the script has recognized the last instruction, it stops and displays a message -max_instructions = 250 - - -def on_message(message, data): - if message['type'] == 'send': - payload = message['payload'] - if isinstance(payload, dict): - function_name = payload.get("function_name", "unknown") - function_offset = payload.get("function_offset", "unknown") - file_name = f'trace_suite_output.txt' - file_path = f'{output_dir}/{target}/{target_library.replace(".", "_")}/{function_name}/{file_name}' - - with codecs.open(file_path, "a", "utf-8") as f: # Use UTF-8 encoding - event = payload.get("event") - if event == "onEnter": - type = "Function Entry - Register Values" - f.write(f"[ {datetime.now()} ]\n") - f.write(f">>> {type} <<<\n") - registers = payload.get("registers", {}) - for reg, values in registers.items(): - f.write(f"{reg}:\n") - for key, value in values.items(): - f.write(f" {key}: {value}\n") - elif event == "onLeave": - type = "Function Exit - Register and Return Values" - f.write(f">>> {type} <<<\n") - registers = payload.get("registers", {}) - for reg, values in registers.items(): - f.write(f"{reg}:\n") - for key, value in values.items(): - f.write(f" {key}: {value}\n") - f.write(f"Return Value: {payload.get('retval')}\n\n") - elif event == "instruction": - address = payload.get("address") - mnemonic = payload.get("mnemonic") - opStr = payload.get("opStr") - type = f"Instruction: {address}: {mnemonic} {opStr}" - f.write(f"Instruction: {address}: {mnemonic} {opStr}\n") - - # Detect instructions that involve memory access - if "ptr [" in opStr: - # Send this instruction back to the JavaScript code for memory value extraction - mem_access = opStr.split("ptr [")[1].split("]")[0] - type = f"Memory Access Pattern: {mem_access}" - f.write(f"Memory Access Pattern: {mem_access}\n") - # We don't do any evaluation here; it's handled in the JS code - elif event == "registerChange": - type = "Register Changes Detected" - f.write(f">>> {type} <<<\n") - changes = payload.get("changes", {}) - for reg, change in changes.items(): - f.write(f"{reg}:\n") - f.write(" Before:\n") - for key, value in change["before"].items(): - f.write(f" {key}: {value}\n") - f.write(" After:\n") - for key, value in change["after"].items(): - f.write(f" {key}: {value}\n") - print(f"[INFO] Data written to {file_name}. Type: {type}") - elif message['type'] == 'error': - print(f"[ERROR] An error occurred: {message['stack']}") - - -def main(): - try: - # Load the script - script_code = load_script(target_library, functions, max_instructions) - - # Setup Device, Session and Source - sherlock = Inject(target=target) - device, session = sherlock.attach() - script = sherlock.source(session, script_code) - - script.on('message', on_message) - script.load() - - # Keep the script running - print( - f"[*] SherlockElf Trace Suite [ -> {target} -> {target_library} -> {functions} ]: Monitoring started. Press Ctrl+C to stop.") - sys.stdin.read() - except frida.ServerNotRunningError: - print("SherlockElf server is not running. Please start the SherlockElf Server on your device.") - except frida.ProcessNotFoundError: - print(f"Process '{target}' not found. Make sure the app is running.") - except Exception as e: - print(f"An unexpected error occurred: {e}") - - -if __name__ == "__main__": - main() \ No newline at end of file