Skip to content

Commit

Permalink
added option to dump libs from memory
Browse files Browse the repository at this point in the history
  • Loading branch information
Ch0pin committed Nov 5, 2020
1 parent f7df405 commit a7b5c8a
Show file tree
Hide file tree
Showing 11 changed files with 147 additions and 23 deletions.
16 changes: 12 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,21 +218,29 @@ Import the recipe by simply typing:

### ChangeLog:

**05/11/2020:**

Added option to dump a specific module from memory

**05/10/2020:**

- Introducing **Medusa Agent**, to load and explore dex or jar files dropped by APKs:

<img src="https://user-images.githubusercontent.com/4659186/95062556-1096bb00-06f5-11eb-9dda-62bfacaa0570.png" alt="medusa_agent" width="230" height="430" />

- Spoof the Notification Listeners

- Hook notification events

- Fixes to dynamic code loading module

- Patch an apk by turning the debug flag to true




**04/11/2020:** More native hook options added:

- Hook by offset
- Hook by pattern



**16/09/2020:** READ/WRITE/SEARCH process memory

Expand Down
19 changes: 14 additions & 5 deletions libraries/defs.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,12 @@ def do_status(self,line):

def hook_native(self):
library = input('[?] Libary name:').strip()
function = input('[?] Function name:').strip()
function = input('[?] Function name or Offset (e.g 0x1234):').strip()
number_of_args = input('[?] Number of arguments (Insert 0 to disable trace):')
backtraceEnable = input('[?] Enable backtrace (yes/no):')
hexdumpEnable = input('[?] Enable memory read (yes/no):')

header = ''

argread = ''

for i in range(int(number_of_args)):
Expand Down Expand Up @@ -150,8 +151,15 @@ def hook_native(self):
else:
tracejs = ''

if function.startswith('0x'):
header = "Interceptor.attach(Module.findBaseAddress('"+library+"').add("+function+"), {"
else:
header = "Interceptor.attach(Module.getExportByName('"+library+"', '"+function+"'), {"

codejs = """Interceptor.attach(Module.getExportByName('"""+library+"""', '"""+function+"""'), {

#codejs = """Interceptor.attach(Module.getExportByName('"""+library+"""', '"""+function+"""'), {

codejs = header + """
onEnter: function(args) {
console.log();
colorLog("[--->] Entering Native function: " +" """+ function+"""",{ c: Color.Red });"""+argread+tracejs+"""
Expand Down Expand Up @@ -316,12 +324,13 @@ def complete_libs(self, text, line, begidx, endidx):
def scratchreset(self):

scratch_reset = input('Do you want to reset the scratchpad ? (yes/no) ')
scratchpad = """#Description: 'Use this module to add your hooks'

if 'yes' in scratch_reset:
scratchpad = """#Description: 'Use this module to add your hooks'
#Help: "N/A"
#Code:
"""
if 'yes' in scratch_reset:
with open('modules/scratchpad.med','w') as scratch:
scratch.write(scratchpad)

Expand Down
65 changes: 65 additions & 0 deletions libraries/memops.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
rpc.exports = {

memorydump: function (address, size) {
Memory.protect(ptr(address), size, "rwx");
var a = Memory.readByteArray(ptr(address),size-1000);
// var baseAddress = parseInt(address,16);
// var endAddress = baseAddress + size;

// Process.enumerateRanges('r--').forEach(function (range) {
// try {
// Memory.scanSync(address, range.size, "??").forEach(function (match) {
// var curent = parceInt(match.address);

// if(curent >= baseAddress && curent <= endAddress)

// if (range.file && range.file.path
// && (// range.file.path.startsWith("/data/app/") ||
// range.file.path.startsWith("/data/dalvik-cache/") ||
// range.file.path.startsWith("/system/"))) {
// return;
// }

// if (verify(match.address, range, false)) {
// var dex_size = match.address.add(0x20).readUInt();
// result.push({
// "addr": match.address,
// "size": dex_size
// });
// }
// });





// console.log('pointer: Address: '+address + ' Size:'+size)
return a;
},

moduleaddress: function (lib){
try{

var ret = [];
var module = Process.findModuleByName(lib);
var address = Module.findBaseAddress(lib);
var sz = module.size;


// console.log('Address: '+address + ' Size:'+sz)

ret.push({
"addr": address,
"size": sz
});
return ret;
}
catch(err){
console.log('[!] Error: '+err);
}



},

};
2 changes: 1 addition & 1 deletion libraries/native.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,4 @@ function enumerateModules(){

Java.perform(function() {
enumerateModules();
});
});
33 changes: 31 additions & 2 deletions libraries/natives.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import frida
import time
import sys

import click

RED = "\033[1;31m"
BLUE = "\033[1;34m"
Expand Down Expand Up @@ -141,14 +141,43 @@ def memops(self,line):
print("BYTES IN: {}".format(pattern))

self.scan_memory(lib,pattern,session,script)


elif cmd.startswith('dump'):
script.unload()
print("dumping....")
self.dump(session,lib)

cmd = input(self.prompt_)

script.unload()
except Exception as e:
print(e)

#############################

def dump(self,session,lib):

try:

path = '.'
script = session.create_script(open("libraries/memops.js").read())
script.load()
api = script.exports

dump_area = api.moduleaddress(lib)
for area in dump_area:
bs = api.memorydump(area["addr"],area["size"])

with open(lib + ".dat", 'wb') as out:
out.write(bs)
click.secho('[+] dump saved to {}.dat'.format(lib), fg='green')

except Exception as e:
click.secho("[Except] - {}:".format(e), bg='red')





def scan_memory(self,lib,pattern,session,script):

Expand Down
6 changes: 3 additions & 3 deletions medusa.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import readline
import os
import cmd

import click
from libraries.defs import *

p = parser()
Expand All @@ -29,7 +29,7 @@
except Exception as e:
print(e)

print(BOLD+GREEN+"""
click.secho("""
Welcome to:
███▄ ▄███▓▓█████ ▓█████▄ █ ██ ██████ ▄▄▄
Expand All @@ -40,7 +40,7 @@
░ ▒░ ░ ░░░ ▒░ ░ ▒▒▓ ▒ ░▒▓▒ ▒ ▒ ▒ ▒▓▒ ▒ ░ ▒▒ ▓▒█░
░ ░ ░ ░ ░ ░ ░ ▒ ▒ ░░▒░ ░ ░ ░ ░▒ ░ ░ ▒ ▒▒ ░
░ ░ ░ ░ ░ ░ ░░░ ░ ░ ░ ░ ░ ░ ▒
░ ░ ░ ░ ░ ░ ░ ░\n\n\n Type help for options\n\n"""+RESET)
░ ░ ░ ░ ░ ░ ░ ░\n\n\n Type help for options\n\n""",fg='green')



Expand Down
1 change: 1 addition & 0 deletions modules/JNICalls/FindClass.med
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ The array type signature of the array class java.lang.Object[] is:
}
})


16 changes: 16 additions & 0 deletions modules/JNICalls/GetByteArrayRegion.med
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#Description: 'void Get<PrimitiveType>ArrayRegion(JNIEnv *env, ArrayType array,jsize start, jsize len, const NativeType *buf)'

#Help: A family of functions that copies back a region of a primitive array from a buffer.

#Code:

Interceptor.attach(getJNIFunctionAdress(jnienv_addr,"GetByteArrayRegion"),{
onEnter: function(args){

var bytebuffer = Memory.readUtf8String(args[4]);


console.log("GetByteArrayRegion :");
colorLog(bytebuffer,{c: Color.Green});
}
})
3 changes: 3 additions & 0 deletions modules/JNICalls/NewStringUTF.med
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

Interceptor.attach(getJNIFunctionAdress(jnienv_addr,"NewStringUTF"),{
onEnter: function(args){
var trace = Thread.backtrace(this.context, Backtracer.ACCURATE);
for (var j in trace)
colorLog('\t b_trace->'+DebugSymbol.fromAddress( trace[j]),{c: Color.Blue});
var str = Memory.readCString(args[1]);
colorLog('[+] NewStringUTF: '+str,{c:Color.Gray});
}
Expand Down
1 change: 1 addition & 0 deletions modules/JNICalls/SetByteArrayRegion.med
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ Interceptor.attach(getJNIFunctionAdress(jnienv_addr,"SetByteArrayRegion"),{
onEnter: function(args){

var bytebuffer = Memory.readUtf8String(args[4]);

console.log("SetByteArrayRegion :");
colorLog(bytebuffer,{c: Color.Green});
}
Expand Down
8 changes: 0 additions & 8 deletions script_lib/hook_by_offset.js

This file was deleted.

0 comments on commit a7b5c8a

Please sign in to comment.