-
Notifications
You must be signed in to change notification settings - Fork 236
/
medusa.py
executable file
·2241 lines (1950 loc) · 93.9 KB
/
medusa.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Standard library imports
import argparse
import os
import platform
import random
import readline
import re
import subprocess
import sys
import time
import traceback
from urllib.parse import urlparse
from typing import Optional, Union
# Third-party imports
import cmd2
import click
import frida
import requests
import yaml
from pick import pick
# Local application/library specific imports
from libraries.libadb import *
from libraries.Modules import *
from libraries.natives import *
from libraries.Questions import *
from libraries.soc_server import *
from utils.google_trans_new import google_translator
RED = "\033[1;31m"
BLUE = "\033[1;34m"
CYAN = "\033[1;36m"
WHITE = "\033[1;37m"
YELLOW = "\033[1;33m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD = "\033[;1m"
REVERSE = "\033[;7m"
agent_script = "agent.js"
scratchpad_module = 'modules/scratchpad.med'
medusa_logo="""
███╗ ███╗███████╗██████╗ ██╗ ██╗███████╗ █████╗
████╗ ████║██╔════╝██╔══██╗██║ ██║██╔════╝██╔══██╗
██╔████╔██║█████╗ ██║ ██║██║ ██║███████╗███████║
██║╚██╔╝██║██╔══╝ ██║ ██║██║ ██║╚════██║██╔══██║
██║ ╚═╝ ██║███████╗██████╔╝╚██████╔╝███████║██║ ██║
╚═╝ ╚═╝╚══════╝╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ (Android) Version: dev
🪼 Type help for options 🪼 \n\n
"""
class Parser(cmd2.Cmd):
base_directory = os.path.dirname(__file__)
snippets = []
packages = []
system_libraries = []
app_libraries = []
app_info = {}
show_commands = ['mods', 'categories', 'all', 'snippets']
prompt = BLUE + 'medusa➤' + RESET
_device = None
modified = False
translator = google_translator()
script = None
detached = True
pid = None
native_handler = None
native_functions = []
currentPackage = None
libname = None
modManager = ModuleManager()
package_range = ''
server = None
interactive=True
time_to_run = None
package_name = None
save_to_file = None
device_id = None
device_controller = None
class NonInteractiveTypeError(Exception):
pass
def __init__(self):
super().__init__(
allow_cli_args=False
)
self._callback = None
self.bind_to(self.observe_device_change)
@property
def device(self):
return self._device
@device.setter
def device(self, new_device):
self._device = new_device
if self._callback:
self._callback(new_device)
def bind_to(self, callback):
self._callback = callback
def observe_device_change(self, _device):
if self._device is not None:
self.prompt = f'({self._device.id}) '+ BLUE + 'medusa➤' + RESET
def refreshPackages(self, option=""):
# -a: all known packages (but excluding APEXes)
# -s: filter to only show system packages
# -3: filter to only show third party packages
if option == '-a':
self.package_range = '- Installed applications (all, excluding APEXs)'
elif option == '-s':
self.package_range = '- System / Preinstalled applicatons'
elif option == '-3':
self.package_range = '- 3rd party installed applications'
else:
self.package_range = '- All installed applications'
self.packages = []
for line in os.popen(f'adb -s {self.device.id} shell pm list packages {option}'):
self.packages.append(line.split(':')[1].strip('\n'))
def preloop(self):
self.do_reload("dummy")
parser = argparse.ArgumentParser(
prog='Medusa',
description='An extensible and modularized framework that automates processes and techniques practiced during the dynamic analysis of Android Applications.')
parser.add_argument('-r', '--recipe', help='Use this option to load a session/recipe')
parser.add_argument('--not-interactive', action='store_true', help='Run Medusa without user interaction (additional parameters required)')
parser.add_argument('-t', '--time', type=int, help='Run Medusa for T seconds without user interaction')
parser.add_argument('-p', '--package-name', help='Package name to run')
parser.add_argument('-d', '--device', help='Device to connect to')
parser.add_argument('-s', '--save', help='Filename to save the output log')
args = parser.parse_args()
num_args_set = sum(1 for arg in vars(args).values() if arg is not None)
if args.recipe:
if not args.not_interactive and num_args_set > 1:
if args.time or args.device or args.save or args.package_name:
print('Non-interactive mode arguments are ignored in interactive mode.')
else:
self.write_recipe(args.recipe)
else:
if not(args.time and args.device and args.save and args.package_name):
print('Insufficient parameters for not interactive mode. Exiting...')
exit(1)
else:
self.interactive = False
self.time_to_run = args.time
self.package_name = args.package_name
self.device_id = args.device
self.save_to_file = args.save
self.write_recipe(args.recipe)
randomized_fg = lambda: tuple(random.randint(0, 255) for _ in range(3))
click.secho(medusa_logo, fg=randomized_fg(), bold=True)
self.do_loaddevice("dummy")
if not self.interactive:
self.do_run('-f '+self.package_name)
###################################################### do_ defs start ############################################################
def do_add(self, mod) -> None:
"""
Add a module which is not indexed/added in the existing modules.
Usage:
add /full/path/to/module
"""
try:
self.modManager.add(mod)
except FileNotFoundError:
print('Module not found!')
except (AttributeError, json.decoder.JSONDecodeError):
print("Module file has an incorrect format")
def do_c(self, line) -> None:
"""Usage: c [shell command]
Run a shell command on the local host."""
subprocess.run(line, shell=True)
def do_cc(self, line) -> None:
"""
Get an adb shell to the connected device (no args)
"""
subprocess.run(f'adb -s {self.device.id} shell {line}', shell=True)
def do_clear(self, line) -> None:
"""
Clear the screen (no args)
"""
subprocess.run('clear', shell=True)
def do_compile(self, line, rs=False) -> None:
"""
Compile the current staged modules to a single js frida script. Use '-t' to add a delay.
compile [-t X], where X is a value in millisec
"""
try:
hooks = []
jni_prolog_added = False
# with open(os.path.join(self.base_directory, 'libraries', js'utils.js'), 'r') as file:
# header = file.read()
js_directory = os.path.join(self.base_directory, 'libraries', 'js')
js_files = ['globals.js', 'beautifiers.js', 'utils.js', 'android_core.js']
for filename in js_files:
js_file_path = os.path.join(js_directory, filename)
# Check if the file exists before attempting to read it
if os.path.isfile(js_file_path):
with open(js_file_path, 'r') as file:
header = file.read()
hooks.append(header)
# add delay
delay = ''
options = len(line.split())
if options == 2 and ('-t' in line.split()[0]):
delay = line.split()[1]
hooks.append("\n\nsetTimeout(function() {\n")
hooks.append("Java.perform(function() { \ntry {\nsetTimeout(displayAppInfo,500);\n")
for mod in self.modManager.staged:
if 'JNICalls' in mod.path and not jni_prolog_added:
hooks.append("""
var jnienv_addr = 0x0;
try{
Java.perform(function(){jnienv_addr = Java.vm.getEnv().handle.readPointer();});
console.log("[+] Hooked successfully, JNIEnv base address: " + jnienv_addr);
}
catch(err){
console.log('Error:'+err);
}
""")
jni_prolog_added = True
hooks.append(self.modManager.compile())
epilog = """}
catch(error){
colorLog("------------Error Log start-------------",{ c:Color.Red })
console.log(error.stack);
colorLog("------------Error Log EOF---------------",{ c:Color.Red })
} });"""
if delay != '':
hooks.append(epilog[:-1])
hooks.append("}}, {});".format(delay))
else:
hooks.append(epilog)
with open(os.path.join(self.base_directory, agent_script), 'w') as agent:
for hook_line in hooks:
agent.write('%s\n' % hook_line)
if rs:
print("\nScript has been reset\n")
else:
print("\nScript is compiled\n")
self.modified = False
except Exception as e:
print(e)
self.modified = False
def do_describe_java_class(self, line) -> None:
"""
Adds relevant code to scratchpad which will print details about a class.
Usage:
describe_java_class [class path]
"""
class_path = line.split(' ')[0]
codejs = '\n'
codejs += """console.log("-----------dumping:'""" + class_path + """'-------------------");\n"""
codejs += "console.log(describeJavaClass('" + class_path + "'));\n"
codejs += """console.log("-----------End of dumping:'""" + class_path + """'------------");"""
self.edit_scratchpad(codejs, 'a')
print(
"Stack trace have been added to the" + GREEN + " scratchpad" + RESET + " run 'compile' to include it in your final script")
def do_dexload(self, line) -> None:
"""
Force the android application to load a dex file
Usage:
dexload /device/path/to/dex
"""
try:
codejs = '\n\nJava.openClassFile("' + line.split(' ')[0] + '").load();'
self.edit_scratchpad(codejs, 'a')
except Exception as e:
print(e)
def do_enumerate(self, line) -> None:
"""
Enumerates the exported functions of a native library.
Usage: enumerate com.foo.com libname.so
Using '--attach' will attach to the already running process (gives better results)
"""
try:
libname = line.split(' ')[1].strip()
package = line.split(' ')[0].strip()
self.libname = libname
self.currentPackage = package
if libname == '' or package == '':
print('[i] Usage: exports com.foo.com libname.so')
else:
self.prepare_native("enumerateExportsJs('" + libname + "');\n")
self.native_functions = []
self.native_handler = nativeHandler(self.device)
# self.native_handler.device = self.device
if len(line.split(' ')) > 2:
if '--attach' in line.split(' ')[2]:
modules = self.native_handler.getModules(package, False)
else:
print("[i] Usage: enumerate package library [--attach]")
else:
modules = self.native_handler.getModules(package, True)
for function in modules:
self.native_functions.append(function)
self.native_functions.sort()
self.print_list(self.native_functions, "[i] Printing lib's: " + libname + " exported functions:")
except Exception as e:
print(e)
print("[i] Usage: enumerate package library [--attach]")
def do_exit(self, line) -> None:
"""
Exit MEDUSA
"""
if self.server:
self.server.stop()
agent_path = os.path.join(self.base_directory, agent_script)
scratchpad_path = os.path.join(self.base_directory, scratchpad_module)
if os.path.getsize(agent_path) != 0:
if Polar('Do you want to reset the agent script?').ask():
open(os.path.join(self.base_directory, agent_script), 'w').close()
if os.path.getsize(scratchpad_path) != 119:
if Polar('Do you want to reset the scratchpad?').ask():
self.edit_scratchpad('')
print('Bye!!')
sys.exit()
def do_export(self, line) -> None:
"""
Exports the current loaded modules and scratchpad contents for later usage.
Usage:
export 'filename'
To reload the same list of scripts, type 'medusa -r saved_file'
"""
try:
with open(line, 'w') as file:
for mod in filter(lambda mod: mod.Name != 'scratchpad', self.modManager.staged):
file.write('MODULE ' + mod.Name + '\n')
file.write(self.modManager.getModule('scratchpad').Code)
if os.path.splitext(line)[1] == '.session':
print(
f"Current session mod list saved as: {os.path.splitext(line)[0]}, use session --load to reload it")
else:
print(f'Recipe exported to dir: {os.getcwd()} as {line}')
except Exception as e:
print(e)
print("[i] Usage: export filename")
def do_get(self, line):
"""
Print the value of a class's field
Usage: get package_name full.path.to.class.field
"""
try:
package_name = line.arg_list[0]
class_field_path = line.arg_list[1]
field = class_field_path.split('.')[-1]
clazz = '.'.join(class_field_path.split('.')[:-1])
if field == '*':
codeJs = """
Java.perform(function() {
try {
var jClass = Java.use('""" + clazz + """');
var _fields = jClass.class.getFields().map(f => {
return f.toString()
})
Java.choose('""" + clazz + """', {
onMatch: function(instance) {
for(var i = 0; i < _fields.length; i++){
var field = _fields[i].substring(_fields[i].lastIndexOf(".") + 1);
console.log('var '+field+ ' ='+JSON.stringify(instance[field].value))
}
}, onComplete: function() {
}
})
}
catch(e){console.log(e)}
});
"""
else:
codeJs = """
Java.perform(function() {
var jClass = Java.use('""" + clazz + """');
Java.choose('""" + clazz + """', {
onMatch: function(instance) {
console.log('Current field value of '+instance+ ' is:'+JSON.stringify(instance."""+field+""".value));
var IterableClass = Java.use("java.lang.Iterable");
var field = jClass.class.getDeclaredField('"""+field+"""')
field.setAccessible(true);
var rvalue = field.get(instance);
try{
var isIter = Java.cast(rvalue, IterableClass);
if(isIter){
console.log('Iterable detected. Trying to dump:')
var iter = isIter.iterator();
while(iter.hasNext()){
console.log(' '+iter.next())
}
}
} catch(e){ }
try{
var hashMap = Java.cast(rvalue, Java.use('java.util.HashMap'));
if(hashMap){
console.log('Instance is a HashMap. Dumping entries:');
var entrySet = hashMap.entrySet();
var iterator = entrySet.iterator();
while (iterator.hasNext()) {
var entry = Java.cast(iterator.next(), Java.use('java.util.Map$Entry'));
var key = entry.getKey().toString();
var value = entry.getValue().toString();
console.log('Key: ' + key + ', Value: ' + value);
}
}
} catch(e){ }
}, onComplete: function() {
}
})
});
"""
self.detached = False
session = self.frida_session_handler(self.device, False, package_name)
if session is None:
print("[!] Can't create session for the given package name. Is it running ?")
script = session.create_script(codeJs)
session.on('detached', self.on_detached)
script.load()
input()
if script:
script.unload()
except Exception as e:
print(e)
def do_man(self, line) -> None:
"""
Display the manual
"""
try:
print(BOLD + """
Module Stashing / Un-Stashing:
- add [fullpath] : Adds the module, specified by the "fullpath" option, to a
list of stashed modules
- compile [-t X ms] : Compile the stashed modules. Use -t X to add X ms delay
- import [snippet] : Import a snippet to the scratchpad
- info [module name] : Display help about a module
- rem [module name] : Remove a module from the stashed ones
- reload : Reload all the medusa modules
- reset : Remove all modules from the list of the stashed ones
- search [keyword] : Search for a module containing a specific keyword in its name
- show [option]
all : Show all available modules
categories : Display the available module categories
mods : Show stashed modules
mods [category] : Display the available modules for the selected category
snippets : Display available snippets of frida scripts
- snippet [tab] : Show / display available frida script snippets
- swap old_index new_index : Change the order of modules in the compiled script
- use [module name] : Select a module to add to the final script
===================================================================================================
Hooking beyond the modules:
- hook [option]
-a [class name] : Set hooks for all the methods of the given class
-f : Initiate a dialog for hooking a Java method
-n : Initiate a dialog for hooking a native method
-r : Reset the hooks set so far
- jtrace method_path : Prints the stack trace of a method (similar to hook -f)
- pad : Edit the scratchpad using vim
- import [tab] : Import a frida script from the snippets folder
===================================================================================================
Starting a session:
- run [package name] : Initiate a Frida session and attach to the selected package
- run -f [package name] : Initiate a Frida session and spawn the selected package
- run -n [package num] : Initiate a Frida session and spawn the 3rd party package
number num (listed by "list")
===================================================================================================
Working with native libraries:
- libs (-a, -s, -j) package_name [--attach]
-a : List ALL loaded libraries
-s : List system's loaded libraries
-j : List application's Libraries
--attach : Attach to the process (default is to first run the app)
- enumerate pkg_name libname [--attach]
Enumerate a library's exported functions (e.g. enumerate com.foo.gr libfoo.so)
- load package_name full_library_path
: Force the application to load a native library
===================================================================================================
Working with the application's memory:
- memops package_name lib.so : read/write/search/dump a native library
- memmap package_name : read/dump read or dump a memory region
====================================================================================================
Getting Class and Object snapshots:
- describe_java_class full.path.to.class.name : Log details about the given class
- get package_name full.path.to.class.field : Get the current value of a field of an
instantiated java class.
====================================================================================================
Usefull utilities:
- c [command] : Run a shell command
- cc [command] : Run a shell command on the mobile device
- clear : Clear the screen
- shell : Open an interactive shell
----------------------------------------------------------------------------------------------------
- dump [package_name] : Dump the requested package name (works for most unpackers)
- list [-a, -s, -3] : List all, system or 3rd party packages
- list 'package_name' path : List data/app paths of 3rd party packages
- loaddevice : Load or reload a device
- reload [-r recipe] : Reload the modules. Use -r to load a recipe (see export command)
- status : Print Current Package/Libs/Native-Functions
- strace package_name : logs system calls, signal deliveries, and changes of process state
- type 'text' : Send a text to the device
==============================================================================================
Saving a session:
- export 'filename' : Save session modules and scripts to 'filename'.
(-) To load this file when starting medusa, add the -r option followed by the filename
(-) To load this file while running medusa, type 'reload -r filename'
""" + RESET)
except Exception as e:
print(e)
def do_hook(self, line) -> None:
"""
Hook a method or methods
Usage:
hook [options] where option can be one of the following:
-a [class name] [--color] : Set hooks for all the methods of the given class.
(optional) Use the --color option to set different color output
(default is purple)
-f : Initiate a dialog for hooking a Java method
-n : Initiate a dialog for hooking a native method
-r : Reset the hooks set so far
"""
option = line.arg_list[0]
codejs = '\n'
if option == '-f':
className = input("Enter the full name of the method(s)'s class: ")
class_uuid = str(int(time.time()))
uuid = str(int(time.time()))
codejs = """let hook_""" + uuid + """ = Java.use('""" + className + """');"""
functionName = input("Enter a method name (CTRL+C to Exit): ")
enable_backtrace = Polar('Enable backtrace?', False).ask()
while True:
try:
codejs += """
let overloadCount_""" + uuid + """ = hook_""" + class_uuid + """['""" + functionName + """'].overloads.length;
colorLog("\\nTracing " +'""" + functionName + """' + " [" + overloadCount_""" + uuid + """ + " overload(s)]",{ c: Color.Green });
for (let i = 0; i < overloadCount_""" + uuid + """; i++) {
hook_""" + class_uuid + """['""" + functionName + """'].overloads[i].implementation = function() {
colorLog("*** entered " +'""" + functionName + """',{ c: Color.Green });"""
if enable_backtrace:
codejs += """
Java.perform(function() {
let bt = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new());
console.log("Backtrace:" + bt);
}); """
codejs += """
if (arguments.length) console.log();
for (let j = 0; j < arguments.length; j++) {
console.log("arg[" + j + "]: " + arguments[j]);
}
let retval = this['""" + functionName + """'].apply(this, arguments);
console.log("retval: " + retval);
colorLog("*** exiting " + '""" + functionName + """',{ c: Color.Green });
return retval;
}
}
"""
print(f'[+] Method: {functionName} hook added !')
functionName = input("Enter a method name (CTRL+C to Exit): ")
enable_backtrace = Polar('Enable backtrace?', False).ask()
uuid = str(int(time.time()))
except KeyboardInterrupt:
self.edit_scratchpad(codejs, 'a')
print(
"\nHooks have been added to the" + GREEN + " scratchpad" + RESET + " run 'compile' to include it in your final script")
break
elif option == '-a':
aclass = line.arg_list[1]
if aclass == '':
print('[i] Usage hook -a class_name')
else:
if len(line.arg_list) > 2:
if line.arg_list[2] == '--color':
colors = ['black', 'blue', 'brown', 'cyan', 'gold', 'gray', 'green', 'lime', 'magenta', 'maroon', 'navy', 'olive', 'orange', 'pink', 'purple', 'red', 'silver', 'teal', 'white', 'yellow']
option, index = pick(colors, "Available colors:", indicator="=>", default_index=0)
self.hookall(aclass, option)
else:
self.hookall(aclass)
else:
self.hookall(aclass)
elif option == '-r':
self.scratchreset()
elif option == '-n':
self.hook_native()
else:
print("[i] Invalid option")
def do_jtrace(self, line) -> None:
"""
Prints the stacktrace of a specified function
Usage:
jtrace [full class path]
"""
function_path = line.split(' ')[0]
class_name = '.'.join(function_path.split('.')[:-1])
function_name = function_path.split('.')[-1]
codejs = '\n'
codejs += """var hook = Java.use('""" + class_name + """');"""
codejs += """
var overloadCount = hook['""" + function_name + """'].overloads.length;
for (var i = 0; i < overloadCount; i++) {
hook['""" + function_name + """'].overloads[i].implementation = function() {
colorLog("*** Entering " +'""" + function_name + """',{ c: Color.Green });
Java.perform(function() {
var bt = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new());
console.log("-----------Printing Stack Trace-------");
colorLog(bt,{c: Color.Blue});
console.log("--------------------------------------")
});
var retval = this['""" + function_name + """'].apply(this, arguments);
colorLog("*** Exiting " + '""" + function_name + """',{ c: Color.Green });
return retval;
}
}
"""
self.edit_scratchpad(codejs, 'a')
print(
"Stack trace have been added to the" + GREEN + " scratchpad" + RESET + " run 'compile' to include it in your final script")
def do_import(self, line) -> None:
"""
Imports a script from a predefined directory and adds it to the scratchpad.
Usage:
import [tab] #pressing tab will show the available scripts.
"""
try:
with open(os.path.join(self.base_directory, 'snippets', line + '.js'), 'r') as file:
data = file.read()
self.edit_scratchpad(data, 'a')
print(
"\nSnippet has been added to the" + GREEN + " scratchpad" + RESET + " run 'compile' to include it in your final script or 'pad' to edit it")
except Exception as e:
print(e)
def do_info(self, mod) -> None:
"""
Provides information about a module.
Usage:
info 'module name'
"""
for m in self.modManager.available:
if m.Name == mod:
print(m.Help)
return
def do_libs(self, line) -> None:
"""
Enumerates loaded native libraries
Usage:
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)
"""
try:
self.prepare_native("enumerateModules();")
self.system_libraries = []
self.app_libraries = []
option = line.split(' ')[0]
self.native_handler = nativeHandler(self.device)
# self.native_handler.device = self.device
package = line.split(' ')[1].strip()
self.currentPackage = package
if len(line.split(' ')) > 2:
if '--attach' in line.split(' ')[2]:
modules = self.native_handler.getModules(package, False)
else:
print("[i] Usage: libs [option] package [--attach]")
else:
modules = self.native_handler.getModules(package, True)
for library in modules:
if library.startswith('/data/app'):
self.app_libraries.append(library)
else:
self.system_libraries.append(library)
self.app_libraries.sort()
self.system_libraries.sort()
if '-a' in option:
self.print_list(self.system_libraries, "[i] Printing system loaded modules:")
self.print_list(self.app_libraries, "[i] Printing Application modules:")
elif '-s' in option:
self.print_list(self.system_libraries, "[i] Printing system loaded modules:")
elif '-j' in option:
self.print_list(self.app_libraries, "[i] Printing Application modules:")
else:
print('[i] Command was not understood.')
except Exception as e:
print(e)
print('[i] Usage: libs [option] package [--attach]')
def do_list(self, line) -> None:
"""
Set the currently working package set / get information about an installed package
list [opt]
Where opt:
-a: all known packages (but excluding APEXes)
-s: filter to only show system packages
-3: filter to only show third party packages
Get info about a package:
list package_name [path]
- Use the option path argument to return the application's installation path
Examples:
list com.example.app
list com.example.app path
list -3
"""
try:
options = len(line.split())
if options == 0:
self.init_packages()
elif options == 1 and line.split()[0] not in ['-a', '-s', '-3']:
package = line.split()[0]
if package in self.packages:
dumpsys = os.popen(f'adb -s {self.device.id} shell dumpsys package {package}')
print('- package info -')
for ln in dumpsys:
print(ln, end='')
else:
print('Invalid package')
elif options == 2 and line.split()[1] == 'path':
package = line.split()[0]
dumpsys = os.popen(f'adb -s {self.device.id} shell dumpsys package {package}')
print('-' * 20 + package + ' ' + "paths" + '-' * 20)
for ln in dumpsys:
for keyword in ["resourcePath", "codePath", "legacyNativeLibraryDir", "primaryCpuAbi"]:
if keyword in ln:
print(ln, end='')
elif options == 1:
opt = line.split()[0]
if opt == '-a':
self.init_packages('-a')
elif opt == '-s':
self.init_packages('-s')
elif opt == '-3':
self.init_packages('-3')
else:
print("Invalid option, use 'help list for options'")
except Exception as e:
print(e)
def do_load(self, line) -> None:
"""
Force the application to manually load a library in order to explore using memops.
Usage:
load package_name full_library_path
Tip: run "list package_name path" to get the application's directories
"""
self.native_handler = nativeHandler(self.device)
self.native_handler.loadLibrary(line.split()[0], line.split()[1])
def do_loaddevice(self, line) -> None:
"""
Load a device in order to interact
"""
try:
if self.interactive:
logger.info('Available devices:\n')
devices = frida.enumerate_devices()
for i in range(len(devices)):
print(f'{i}) {devices[i]}')
self.device = devices[
int(Numeric('\nEnter the index of the device to use:', lbound=0, ubound=len(devices) - 1).ask())]
self.device_controller = android_device(self.device.id)
self.device_controller.print_dev_properties()
elif self.is_remote_device(self.device_id):
self.device = frida.get_remote_device(self.device_id)
self.device_controller = android_device(self.device.id)
else:
self.device = frida.get_device(self.device_id)
self.device_controller = android_device(self.device.id)
except:
self.device = frida.get_remote_device()
if not self.interactive:
raise self.NonInteractiveTypeError("Device unreachable !")
finally:
# lets start by loading all packages and let the user to filter them out
if self.interactive:
self.init_packages('-3')
def do_memops(self, line) -> None:
"""
READ/WRITE/SEARCH process memory
Usage:
memops package_name libfoo.so
"""
self.native_handler = nativeHandler(self.device)
self.native_handler.memops(line)
def do_memscan(self, line) -> None:
"""Usage: memscan [option] package_name [nuclei template(s) (file or path)]
Where option:
-c2 scan the application's memory for c2 addresses using virus total database (need vt api key)
-s scan for secrets using regex entries from /medusa/sigs.json
-nt package_name /path/to/template(s) scan for secrets using a nuclei template
-a perform all scans
"""
try:
if len(line.split(' ')) < 2:
print("Invalid parameters given, type 'help memscan' for options")
return
if line.split(' ')[0] not in ['-c2', '-s', '-nt', '-a']:
print(f"No such an optiion {line.split(' ')[0]}. Type 'help memscan for help")
return
pkg = line.split(' ')[1]
pid = os.popen(f"adb -s {self.device.id} shell pidof {pkg}").read().strip()
if pid == "":
click.secho('Trying to start the app:', fg='green')
os.popen(
f"adb -s {self.device.id} shell monkey -p {pkg} -c 'android.intent.category.LAUNCHER 1'").read()
pid = os.popen(f"adb -s {self.device.id} shell pidof {pkg}").read().strip()
if pid == "":
click.secho("Can't find pid !", fg='red')
return
elif len(pid.split(' ')) > 1:
option, index = pick(pid.split(' '), "More than one processes found running with that name:",
indicator="=>", default_index=0)
pid = option
else:
click.secho(f'Process pid:{pid}', fg='green')
maps = os.popen(f"""adb -s {self.device.id} shell 'echo "cat /proc/{pid}/maps" | su'""").read().split('\n')
for linein in maps:
if 'dalvik-main space' in linein:
range1 = int(linein.split(' ')[0].split('-')[0], 16)
range2 = int(linein.split(' ')[0].split('-')[1], 16)
sz = range2 - range1
print(f'Starting address: {hex(range1)}, size: {range2 - range1}')
self.native_handler = nativeHandler(self.device)
self.native_handler.memraw(pkg + ' ' + pid + ' ' + hex(range1) + ' ' + str(sz), True)
hosts = []
output = []
all_strings = []
script_path = os.path.abspath(__file__)
script_dir = os.getcwd()
dump_dir = script_dir + os.path.sep + 'dump' + os.path.sep + pkg
for filename in os.listdir(dump_dir):
file_path = os.path.join(dump_dir, filename)
if os.path.isfile(file_path):
cmd = f"strings {file_path}"
result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode == 0:
output = result.stdout.decode().strip().split('\n')
for entry in output:
all_strings.append(entry)
if self.is_valid_url(entry):
hosts.append(urlparse(entry).netloc)
hosts = list(dict.fromkeys(hosts))
whitelist = script_dir + os.path.sep + 'whitelist.txt'
whitelist_urls = []
if os.path.isfile(whitelist):
with open(whitelist, 'r') as file:
whitelist_urls = file.readlines()
whitelist_urls_strip = [x.strip() for x in whitelist_urls]
hosts = [x for x in hosts if not any(y in x for y in whitelist_urls_strip)]
opt = line.split(' ')[0]
if opt == '-c2':
click.secho('Scanning for web addresses', fg='yellow')
self.check_using_vt(hosts, script_dir + os.path.sep + 'vt.key')
elif opt == '-s':
click.secho('Scanning for secrets', fg='yellow')
self.scan_for_secrets(list(dict.fromkeys(all_strings)))
elif opt == '-nt':
if len(line.split(' ')) != 3:
print('This option requires a path to the template(s)')
return
self.scan_using_nuclei_template(list(dict.fromkeys(all_strings)), line.split(' ')[2])
elif opt == '-a':
click.secho('Performing all availlable scans...', fg='yellow')
click.secho('Scanning for web addresses', fg='yellow')
self.check_using_vt(hosts, script_dir + os.path.sep + 'vt.key')
click.secho('Scanning for secrets', fg='yellow')
self.scan_for_secrets(list(dict.fromkeys(all_strings)))
else:
print("No such option...")
return
except Exception as e:
print(e)
return
def do_memmap(self, line) -> None:
"""
READ process memory
Usage:
Make sure the application is running and then type:
memmap package_name
"""
try:
pkg = line.split(' ')[0]
pid = os.popen(f"adb -s {self.device.id} shell pidof {pkg}").read().strip()