Skip to content

Commit

Permalink
More native functionality added, socket hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
Ch0pin committed Sep 18, 2020
1 parent 40df0fd commit dd0bc86
Show file tree
Hide file tree
Showing 5 changed files with 191 additions and 15 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ It's functionality can be summarised as follows:

### Updates:

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

By issuing **medusa> memops** **package_name** **module_name**, the framework can be used to perform read/write operations in the process memory.

Expand Down
5 changes: 2 additions & 3 deletions libraries/defs.py
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,7 @@ def do_help(self,line):
===================================================================================================
SCRIPT OPERATIONS:
- export : Save the current module list (and extra hooks) to 'recipe.txt'
- compile : Compile the modules to a frida script
- hook [option]
Expand All @@ -906,15 +907,13 @@ def do_help(self,line):
NATIVE OPERATIONS:
- memops package_name library : Read Process Memory
- memops package_name library : READ/WRITE/SEARCH process memory
- libs (-a, -s, -j) package_name [--attach]
-a : List ALL loaded libraries
-s : List System loaded libraries
-j : List Application's Libraries
--attach : Attach to the process (Default is spawn)
- enumerate pkg_name libname [--attach]
Enumerate a library's exported functions (e.g. - enumerate com.foo.gr libfoo)
Expand Down
3 changes: 2 additions & 1 deletion libraries/native.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,5 +55,6 @@ function enumerateModules(){
}

Java.perform(function() {
enumerateModules();
enumerateExportsJs('libmyso2.so');

});
112 changes: 102 additions & 10 deletions libraries/natives.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class nativeHandler():
modules = []
device = None
script = None
prompt_ = WHITE+'|' +GREEN+'(E)xit '+ WHITE+ '|'+GREEN+ 'r@offset ' + WHITE+'|' +GREEN+ 'w@offset '+ WHITE+'|' +GREEN+'⏎ '+ WHITE+ '|' + GREEN + '? (help)' +WHITE + '|:'
prompt_ = WHITE+'|' +GREEN+'(E)xit '+ WHITE+ '|'+GREEN+ 'r@offset ' + WHITE+'|' +GREEN+ 'w@offset '+ WHITE+'|' +GREEN+'⏎ '+ WHITE+ '|' +GREEN+ 'scan '+ WHITE+'|'+ GREEN + '(h)elp' +WHITE + '|:'


def __init__(self,device):
Expand Down Expand Up @@ -76,13 +76,19 @@ def memops(self,line):
try:

args = line.split(' ')

if len(args)<2:
print('Usage: readmem package_name libfoo.so')
return


package = args[0]
lib = args[1]



prolog = 'Java.perform(function () {\n\n'
prolog += 'var module = Process.findModuleByName("'+lib+'");\n'
prolog += 'var p_foo = Module.findBaseAddress("'+lib+'");'+"""
if (!p_foo) {
console.log("Could not find module....");
Expand Down Expand Up @@ -119,8 +125,17 @@ def memops(self,line):
bytesx = self.form_bytes(in_bytes)
print("Bytes in:{}".format(bytesx))
self.write_memory(cmd[2:],script,session,codejs,prolog,epilog,payload,bytesx)
elif cmd.startswith('?'):
elif cmd.startswith('h'):
self.display_help()
elif cmd.startswith('scan'):
in_bytes = input("Enter a text or byte array in form of bytes(DE 00 11 ?? ?? BE AF):")
if in_bytes.startswith('bytes('):
pattern = in_bytes[6:].strip(')')
else:
pattern = self.form_scan_input(in_bytes)
print("BYTES IN: {}".format(pattern))

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


cmd = input(self.prompt_)
Expand All @@ -129,13 +144,73 @@ def memops(self,line):
except Exception as e:
print(e)


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

try:
codejs = "var module = Process.findModuleByName('"+lib+"');"
codejs += "var pattern = '"+pattern+"';"
codejs += """
var ranges = Process.enumerateRangesSync({protection: 'r--', coalesce: true});
var range;
var baseAddress = parseInt(module.base,16);
var endAddress = module.size + baseAddress;
console.log('Module base address:'+module.base);
console.log('Module end Address: 0x'+endAddress.toString(16));
function processNext(){
range = ranges.pop();
if(!range){
// we are done
return;
}
var rangeAddress = parseInt(range.base,16);
if (baseAddress <= rangeAddress)
{
//console.log('IN RANGE');
Memory.scan(range.base, range.size, pattern, {
onMatch: function(address, size){
if(rangeAddress <= endAddress){
var offset = parseInt(address,16)-baseAddress
console.log('[+] Pattern found at: ' + address.toString() + ' Dec Offset:' + offset.toString(16));
}
},
onError: function(reason){
console.log('[!] There was an error scanning memory');
},
onComplete: function(){
processNext();
}
});
}
}
processNext();
"""
script = session.create_script(codejs)
script.load()

except Exception as e:
print(e)


def display_help(self):
print("""Availlable commands:
exit: exit memops
r@offset: read @ offet (e.g. r@beaf)
Return: read next 296 bytes
w@offset: write @ offset (e.g. w@beaf)
(E)xit: Exit memops
r@offset: Read @ offet (e.g. r@beaf)
Return: Read next 296 bytes
w@offset: Write @ offset (e.g. w@beaf)
scan: Scan a memory region for a pattern
?: Display this message
""")

Expand Down Expand Up @@ -191,14 +266,21 @@ def read_memory(self,offset, script_in,session_in,codejs_in,prolog_in,epilog_in,
arithemetic_offset_tmp = hex(int(offset_in,16)+296)
arithemetic_offset = hex(int(arithemetic_offset,16) + int(offset_in,16))

print(arithemetic_offset)
print(BLUE+'[+] Offset:' + arithemetic_offset+RESET)

payload += '\nvar address = p_foo.add('+str(arithemetic_offset)+');'
payload += """
var baseAddress = parseInt(p_foo,16);
var endAddress = baseAddress + module.size;
"""
payload += '\nvar offset = '+str(arithemetic_offset);
payload += """\nvar buf = Memory.readByteArray(ptr(address),296);
if(buf) console.log('Base Address:'+p_foo+' Dumping at:'+address+' Offset:'+offset.toString(16));
console.log(hexdump(buf, {offset: 0, length:296, header: true, ansi: false
}));"""
if(buf){
console.log('Address Range:'+p_foo+' --> '+endAddress.toString(16));
console.log('Module Size:' + module.size+' Dumping at:'+address);
console.log(hexdump(buf, {offset: 0, length:296, header: true, ansi: false
}))};"""
codejs = prolog + payload + epilog
script = session.create_script(codejs)
script.load()
Expand All @@ -213,6 +295,16 @@ def read_memory(self,offset, script_in,session_in,codejs_in,prolog_in,epilog_in,

return cmd

def form_scan_input(self,scan_str):
ret = ''
for letter in scan_str:
bt = str(hex(ord(letter)))[2:]
if not scan_str.endswith(letter):
ret += bt + ' '
else:
ret += bt
return ret


def form_bytes(self,bytes):
return '[%s]' % ','.join(["0x%02x" % int(x, 16) for x in bytes.split(' ')])
Expand Down
84 changes: 84 additions & 0 deletions modules/sockets/socket_monitor_2.med
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#Description: 'Monitor calls to socket operations'
#Help: https://codeshare.frida.re/@ninjadiary/frinja---sockets/
-webSocketClient constructor
-send

#Code:


console.log('-----------------Author: secretdiary.ninja-----------------');


var sock = Java.use("java.net.Socket");

// Socket.bind()
sock.bind.implementation = function(localAddress){
console.log("Socket.bind("+localAddress.toString()+")");
sock.bind.call(this, localAddress);
}

// Socket.connect(endPoint)
sock.connect.overload("java.net.SocketAddress").implementation = function(endPoint){
console.log("Socket.connect("+endPoint.toString()+")");
sock.connect.overload("java.net.SocketAddress").call(this, endPoint);
}

// Socket.connect(endPoint, timeout)
sock.connect.overload("java.net.SocketAddress", "int").implementation = function(endPoint, tmout){
console.log("Socket.connect("+endPoint.toString()+", Timeout: "+tmout+")");
sock.connect.overload("java.net.SocketAddress", "int").call(this, endPoint, tmout);
}

// Socket.getInetAddress()
sock.getInetAddress.implementation = function(){
ret = sock.getInetAddress.call(this);
console.log(ret.toString()+" Socket.getInetAddress()");
return ret;
}

// Socket.getInputStream()
sock.getInputStream.implementation = function(){
console.log("Socket.getInputStream()");
return sock.getInputStream.call(this);
}

// Socket.getOutputStream()
sock.getOutputStream.implementation = function(){
console.log("Socket.getOutputStream()");
return sock.getOutputStream.call(this);
}

sock.$init.overload().implementation = function(){
console.log("new Socket() called");
this.$init.overload().call(this);
}

// new Socket(inetAddress, port)
sock.$init.overload("java.net.InetAddress", "int").implementation = function(inetAddress, port){
console.log("new Socket('"+inetAddress.toString()+"', "+port+") called");
this.$init.overload("java.net.InetAddress", "int").call(this, inetAddress, port);
}

// new Socket(inetAddress address, port, localInetAddress, localPort)
sock.$init.overload("java.net.InetAddress", "int","java.net.InetAddress", "int").implementation = function(inetAddress, port, localInet, localPort){
console.log("new Socket(RemoteInet: '"+inetAddress.toString()+"', RemotePort"+port+", LocalInet: '"+localInet+"', LocalPort: "+localPort+") called");
this.$init.overload("java.net.InetAddress", "int","java.net.InetAddress", "int").call(this, inetAddress, port);
}

// new Socket(Proxy)
sock.$init.overload("java.net.Proxy").implementation = function(proxy){
console.log("new Socket(Proxy: '"+proxy.toString()+"') called");
this.$init.overload("java.net.Proxy").call(this, proxy);
}

// new Socket(SocketImp)
sock.$init.overload("java.net.SocketImpl").implementation = function(si){
console.log("new Socket(SocketImpl: '"+si.toString()+"') called");
this.$init.overload("java.net.SocketImpl").call(this, si);
}

// new Socket(host, port, localInetAddr, localPort)
sock.$init.overload("java.lang.String", "int", "java.net.InetAddress", "int").implementation = function(host,port, localInetAddress, localPort){
console.log("new Socket(Host: '"+host+"', RemPort: "+port+", LocalInet: '"+localInetAddress+"', localPort: "+localPort+") called");
this.$init.overload("java.lang.String", "int", "java.net.InetAddress", "int").call(this, si);
}

0 comments on commit dd0bc86

Please sign in to comment.