forked from iGio90/frick
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
2873 lines (2516 loc) · 100 KB
/
main.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
#######################################################################################
#
# frick is distributed under the MIT License (MIT)
# Copyright (c) 2018 Giovanni - iGio90 - Rocca
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
#
import atexit
import binascii
import re
import capstone
import fcntl
import frida
import imp
import json
import os
import script
import shutil
import six
import struct
import sys
import termios
import time
import unicorn
import webbrowser
import readline as readline
from threading import Thread
_python3 = sys.version_info.major == 3
class Printer(object):
def __init__(self):
self.sleep = 1 / 10
self.lines = []
if _python3:
Thread(target=self.loop, daemon=True).start()
else:
t = Thread(target=self.loop)
t.setDaemon(True)
t.start()
def append(self, what):
self.lines.append(what)
def loop(self):
while True:
while len(self.lines) > 0:
print(self.lines.pop(0))
time.sleep(self.sleep)
def log(what):
apix = Color.colorify('>', 'red highlight')
if type(what) is str:
try:
what = int(what)
except:
try:
what = int(what, 16)
except:
pass
try:
what.index('\n')
ml = True
except:
ml = False
if not ml:
printer.append('-%s %s' % (apix, what))
else:
printer.append(what)
return
t = type(what)
if t is int:
c = 'green highlight'
if cli.frida_script is not None and cli.frida_script.exports.ivp(what):
c = 'red highlight'
if what < 0:
v = hex((what + (1 << 32)) % (1 << 32))
else:
v = hex(what)
printer.append('-%s %s (%s)' % (apix, Color.colorify(v, c), Color.colorify(str(what), 'bold')))
elif t is six.text_type:
printer.append('-%s %s' % (apix, what.encode('ascii', 'ignore')))
else:
printer.append(what)
def log_multicol(what):
row, cols = FridaCli.get_terminal_size()
f_rows = []
h_iter = 0
max = cols / 75
row = ''
while len(what) > 0:
if row == '':
row += what[h_iter].pop(0)
else:
row += '\t\t' + what[h_iter].pop(0)
if len(what[h_iter]) == 0:
what.pop(h_iter)
else:
h_iter += 1
if h_iter == max or len(what) <= h_iter:
f_rows.append(row)
h_iter = 0
row = ''
printer.append('\n'.join(f_rows))
class Arch(object):
def __init__(self):
self.unicorn_arch = None
self.unicorn_mode = None
self.capstone_arch = None
self.capstone_mode = None
def get_unicorn_constants(self):
return None
def get_registers(self):
return []
def get_capstone_arch(self):
return self.capstone_arch
def get_capstone_mode(self):
return self.capstone_mode
def get_unicorn_arch(self):
return self.unicorn_arch
def get_unicorn_mode(self):
return self.unicorn_mode
def set_capstone_arch(self, arch):
self.capstone_arch = arch
def set_capstone_mode(self, mode):
self.capstone_mode = mode
def set_unicorn_arch(self, arch):
self.unicorn_arch = arch
def set_unicorn_mode(self, mode):
self.unicorn_mode = mode
class Arm(Arch):
def __init__(self):
super(Arm, self).__init__()
self.unicorn_arch = unicorn.UC_ARCH_ARM
self.unicorn_mode = unicorn.UC_MODE_ARM
self.capstone_arch = capstone.CS_ARCH_ARM
self.capstone_mode = capstone.CS_MODE_ARM
def get_unicorn_constants(self):
return unicorn.arm_const
def get_registers(self):
r = []
for i in range(0, 13):
r.append('r' + str(i))
r += ['sp', 'pc', 'lr']
return r
class CommandManager(object):
def __init__(self, cli):
self.cli = cli
self._map = {}
def init(self):
current_module = sys.modules[__name__]
for key in dir(current_module):
attr = getattr(current_module, key)
if isinstance(attr, type):
try:
if issubclass(attr, Command):
cmd = attr(self.cli)
info = cmd.get_command_info()
if info is not None:
if 'target' in info:
self._map[info['target']] = cmd
else:
self._map[info['name']] = cmd
if 'shortcuts' in info:
for sh in info['shortcuts']:
self._map[sh] = cmd
except:
continue
def __handle_add_value__(self, key, value):
if key.startswith('$'):
# we want to write on registers with short hands
reg = key[1:].lower()
val = Registers(self.cli).__internal_write__(reg, value)
if val is not None:
printer.append('%s (%u)' % (Color.colorify('0x%x' % val, 'green highlight'), val))
return val
self.cli.context_manager.add_value(key, value)
return value
def handle_command(self, p):
p = p.split(' ')
base = p[0]
args = p[1:]
if len(args) > 0 and args[0] == '=':
if base in self._map:
log('can\'t assign value %s' % base)
return None
fm = args[1:]
if len(fm) > 0:
tst_method = fm[0]
if tst_method in self._map:
val = self.__internal_handle_command(tst_method, fm[1:], True)
if val is None:
val = 0
return self.__handle_add_value__(base, val)
else:
formatted_args = self._format_args(fm)
if len(formatted_args) > 1:
ev = ''
for a in formatted_args:
ev += '%s ' % str(a)
try:
return self.__handle_add_value__(base, eval(ev))
except:
log('failed to evaluate value')
else:
return self.__handle_add_value__(base, formatted_args[0])
return None
return self.__internal_handle_command(base, args)
def parse_sub(self, info, args):
if 'sub' in info and len(args) > 0:
for sub in info['sub']:
found = False
if args[0] == sub['name'] or ('target' in sub and args[0] == sub['target']):
found = True
elif 'shortcuts' in sub and args[0] in sub['shortcuts']:
found = True
if found:
return sub
return None
def _format_args(self, args):
ret = []
for i in range(0, len(args)):
ev = self.try_eval(args[i])
if type(ev) is not int and type(ev) is not str:
ev = args[i]
if str(ev).startswith('0x'):
try:
ev = int(args[i], 16)
except:
pass
while True:
try:
i = str(ev).index('$')
tst = ev[i + 1:].lower()
try:
tst = ev[:tst.index(' ')]
except:
pass
if tst in self.cli.context_manager.get_context():
ev = ev.replace('$%s' % tst, self.cli.context_manager.get_context()[tst]['value'])
ev = self.try_eval(ev)
except:
break
c_val = self.cli.context_manager.get_value(str(ev))
if c_val is not None:
ev = c_val
try:
ev = int(args[i])
except:
pass
ret.append(ev)
return ret
def try_eval(self, what):
try:
return eval(what)
except:
return what
def __internal_handle_command(self, base, args, store=False):
try:
command = self._map[base]
except:
command = None
if command is None:
log('command not found')
return None
info = command.get_command_info()
s_info = info
f_exec = None
s_args = args
while True:
s_info = self.parse_sub(s_info, s_args)
if s_info is not None:
info = s_info
try:
if 'target' in s_info:
f_exec = getattr(command, '__%s__' % s_info['target'])
else:
f_exec = getattr(command, '__%s__' % s_info['name'])
except:
pass
s_args = s_args[1:]
else:
break
args = s_args
if 'args' in info:
min_args = info['args']
if min_args > len(args):
log('not enough arguments')
# todo print help
return
if f_exec is None:
try:
if 'target' in info:
f_exec = getattr(command, '__%s__' % info['target'])
else:
f_exec = getattr(command, '__%s__' % info['name'])
except:
pass
if f_exec is None:
log('no functions found for %s' % info['name'])
return None
else:
formatted_args = self._format_args(args)
try:
data = f_exec(formatted_args)
if data is not None:
nn = 'name'
if 'target' in info:
nn = 'target'
if not store:
try:
f_exec = getattr(command, '__%s_result__' % info[nn])
f_exec(data)
except:
pass
else:
try:
f_exec = getattr(command, '__%s_store__' % info[nn])
data = f_exec(data)
except:
pass
return data
except Exception as e:
log('error while running command %s: %s' % (info['name'], e))
return None
class ContextManager(object):
def __init__(self, cli):
self._cli = cli
self.base = 0x0
self.arch = None
self.pointer_size = 0x0
self.context_offset = 0x0
self.context = None
self.target_package = ''
self.target_module = ''
self.target_offsets = {}
self.target_virtual_offsets = {}
self.dtinit_target_offsets = {}
self.values = {}
self.once = {}
def add_target_offset(self, offset, name=''):
if offset in self.target_offsets:
return None
self.target_offsets[offset] = name
return offset
def add_target_virtual_offset(self, offset):
if offset in self.target_virtual_offsets:
return None
self.target_virtual_offsets[offset] = offset
return offset
def add_dtinit_target_offset(self, offset, name=''):
self.dtinit_target_offsets[offset] = name
def add_value(self, key, value):
self.values[key] = value
def apply_arch(self, arch):
p_arch = self.arch
if arch == 'arm':
self.arch = Arm()
self.add_value('arch', arch)
if p_arch is not None and self.arch is not None:
# copy capstone stuffs from previous arch, we could be in the point
# we had set a cs arch/mode and p_arch will hold an abstract Arch with just cs info
if p_arch.capstone_arch is not None:
self.arch.capstone_arch = p_arch.capstone_arch
if p_arch.capstone_mode is not None:
self.arch.capstone_mode = p_arch.capstone_mode
if p_arch.unicorn_arch is not None:
self.arch.unicorn_arch = p_arch.unicorn_arch
if p_arch.unicorn_mode is not None:
self.arch.unicorn_mode = p_arch.unicorn_mode
return self.arch
def apply_once(self, what, once_arr):
if len(once_arr) is 0:
del self.once[what]
else:
self.once[what] = once_arr
def apply_pointer_size(self, pointer_size):
self.pointer_size = pointer_size
def clean(self):
self.target_offsets = {}
self.target_virtual_offsets = {}
self.context = None
self.context_offset = 0x0
def is_offset_in_targets(self, offset):
return offset in self.target_offsets or \
offset in self.target_virtual_offsets or \
offset in self.dtinit_target_offsets
def on(self, what):
Thread(target=self.__on__, kwargs={'what': what}).start()
def __on__(self, *args, **kwargs):
what = kwargs['what']
if what in self.once:
for c in self.once[what]:
self._cli.cmd_manager.handle_command(c)
def set_base(self, base):
self.base = base
self.add_value('base', base)
def set_context(self, offset, context):
self.context_offset = offset
self.context = context
def set_target(self, package, module):
self.target_package = package
self.target_module = module
def get_arch(self):
return self.arch
def get_base(self):
return self.base
def get_context(self):
return self.context
def get_context_offset(self):
return self.context_offset
def get_pointer_size(self):
return self.pointer_size
def get_target_module(self):
return self.target_module
def get_target_offsets(self):
return self.target_offsets
def get_dtinit_target_offsets(self):
return self.dtinit_target_offsets
def get_value(self, key):
if key in self.values:
return self.values[key]
return None
def set_arch(self, arch):
self.arch = arch
def print_context(self):
self._cli.context_title('registers')
if self.arch is not None:
all_registers = self.arch.get_registers()
else:
all_registers = self.context.keys()
for r in all_registers:
have_sub = False
if 'sub' in self.context[r]:
have_sub = True
value = Color.colorify(self.context[r]['value'], 'red highlight')
else:
value = Color.colorify(self.context[r]['value'], 'green highlight')
reg_name = r.upper()
while len(reg_name) < 4:
reg_name += ' '
p = '%s: %s' % (Color.colorify(reg_name, 'bold'), value)
if have_sub:
subs = self.context[r]['sub']
for i in range(0, len(subs)):
if i != len(subs) - 1:
p += ' -> %s' % Color.colorify(subs[i], 'red highligh')
else:
p += ' -> %s' % Color.colorify(subs[i], 'green highligh')
printer.append(p)
def save(self):
if os.path.exists('.session'):
shutil.copy('.session', '.session_old')
os.remove('.session')
ext = ''
if self._cli.context_manager.get_arch() is not None:
ext += 'set cs arch ' + str(self._cli.context_manager.get_arch().get_capstone_arch()) + '\n'
ext += 'set cs mode ' + str(self._cli.context_manager.get_arch().get_capstone_mode()) + '\n'
ext += 'set uc arch ' + str(self._cli.context_manager.get_arch().get_unicorn_arch()) + '\n'
ext += 'set uc mode ' + str(self._cli.context_manager.get_arch().get_unicorn_mode()) + '\n'
if len(self.target_offsets) > 0:
for t in self.target_offsets:
ext += 'add %s %s\n' % (str(t), self.target_offsets[t])
if len(self.target_offsets) > 0:
for t in self.dtinit_target_offsets:
ext += 'add dtinit %s %s\n' % (str(t), self.target_offsets[t])
if len(self.once) > 0:
for what, arr in self.once.items():
ext += 'once %s\n' % str(what)
ext += '\n'.join(arr)
ext += '\nend\n'
if self.target_package is not '':
ext += 'attach %s %s\n' % (self.target_package, self.target_module)
if ext is not '':
with open('.session', 'w') as f:
f.write(ext)
log('session saved')
else:
log('add offsets or target package before using \'save\'')
def load(self):
self._cli.on_load()
if not os.path.exists('.session'):
log('session file not found. use \'save\' to save offsets and target for the next cycle')
return
self.clean()
with open('.session', 'r') as f:
f = f.read().split('\n')
while len(f) > 0:
l = f.pop(0)
if l == '' or l.startswith('#'):
continue
if l.startswith('once'):
once_arr = []
l = l.split(' ')
what = l[1]
while True:
l = f.pop(0)
if l == 'end':
break
once_arr.append(l)
if what != 'init':
what = int(what)
self.once[what] = once_arr
Once(self._cli).__once_result__([what, len(once_arr)])
else:
self._cli.cmd_manager.handle_command(l)
class Color:
"""
Colorify class.
by @hugsy
https://github.com/hugsy/gef/blob/master/gef.py#L325
"""
colors = {
"normal": "\033[0m",
"gray": "\033[1;38;5;240m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"pink": "\033[35m",
"bold": "\033[1m",
"underline": "\033[4m",
"underline_off": "\033[24m",
"highlight": "\033[3m",
"highlight_off": "\033[23m",
"blink": "\033[5m",
"blink_off": "\033[25m",
}
@staticmethod
def redify(msg):
return Color.colorify(msg, attrs="red")
@staticmethod
def greenify(msg):
return Color.colorify(msg, attrs="green")
@staticmethod
def blueify(msg):
return Color.colorify(msg, attrs="blue")
@staticmethod
def yellowify(msg):
return Color.colorify(msg, attrs="yellow")
@staticmethod
def grayify(msg):
return Color.colorify(msg, attrs="gray")
@staticmethod
def pinkify(msg):
return Color.colorify(msg, attrs="pink")
@staticmethod
def boldify(msg):
return Color.colorify(msg, attrs="bold")
@staticmethod
def underlinify(msg):
return Color.colorify(msg, attrs="underline")
@staticmethod
def highlightify(msg):
return Color.colorify(msg, attrs="highlight")
@staticmethod
def blinkify(msg):
return Color.colorify(msg, attrs="blink")
@staticmethod
def colorify(text, attrs):
"""Color a text following the given attributes."""
colors = Color.colors
msg = [colors[attr] for attr in attrs.split() if attr in colors]
msg.append(text)
if colors["highlight"] in msg: msg.append(colors["highlight_off"])
if colors["underline"] in msg: msg.append(colors["underline_off"])
if colors["blink"] in msg: msg.append(colors["blink_off"])
msg.append(colors["normal"])
return "".join(msg)
class Command(object):
def __init__(self, cli):
self.cli = cli
def get_command_info(self):
return None
class Add(Command):
def get_command_info(self):
return {
'name': 'add',
'info': 'add offset from base 0x0 in arg0 with optional name for this target in other args',
'args': 1,
'sub': [
{
'name': 'pointer',
'info': 'add a virtual address in arg0 with optional name in other args',
'args': 1,
'shortcuts': [
'ptr', 'p'
]
},
{
'name': 'dtinit',
'info': 'mark this target as dt_init function. on android we leak the base before dlopen',
'args': 1,
'shortcuts': ['dti', 'init']
}
]
}
def __add__(self, args):
ptr = args[0]
name = ''
if len(args) > 1:
for a in args[1:]:
name += str(a) + ' '
if self.cli.context_manager.add_target_offset(ptr, name) is not None:
if self.cli.frida_script is not None:
self.cli.frida_script.exports.add(ptr)
return [1, ptr]
return [0, ptr]
def __add_result__(self, result):
if result[0] > 0:
log('%s added to target offsets' % Color.colorify('0x%x' % result[1], 'red highlight'))
else:
log('%s is already on targets list' % Color.colorify('0x%x' % result[1], 'red highlight'))
def __dtinit__(self, args):
ptr = args[0]
name = ''
if len(args) > 1:
for a in args[1:]:
name += str(a) + ' '
self.cli.context_manager.add_dtinit_target_offset(ptr, name)
return ptr
def __dtinit_result__(self, result):
log('%s added to %s target offsets' % (Color.colorify('0x%x' % result, 'red highlight'),
(Color.colorify('dtinit', 'green highlight'))))
def __pointer__(self, args):
if self.cli.context_manager.add_target_virtual_offset(args[0]) is not None:
if self.cli.frida_script is not None:
self.cli.frida_script.exports.addv(args[0])
return args[0]
return None
def __pointer_result__(self, result):
log('%s added to target offsets' % Color.colorify('0x%x' % result, 'red highlight'))
class Attach(Command):
def get_command_info(self):
return {
'name': 'attach',
'args': 1,
'info': 'attach to target package name in arg0 with target module name in arg1',
'shortcuts': [
'att'
]
}
def __attach__(self, args):
package = args[0]
module = args[1]
if not module.endswith('.so'):
module += '.so'
if self.cli.frida_device is None:
if not self.cli.bind_device(5):
log('failed to connected to remote frida server')
return None
pid = self.cli.frida_device.spawn(package)
self.cli.frida_process = self.cli.frida_device.attach(pid)
log("frida %s" % Color.colorify('attached', 'bold'))
self.cli.frida_script = self.cli.frida_process.create_script(script.get_script(
pid,
module,
self.cli.context_manager.get_target_offsets(),
self.cli.context_manager.get_dtinit_target_offsets()
))
log("script %s" % Color.colorify('injected', 'bold'))
self.cli.frida_device.resume(package)
self.cli.frida_script.on('message', self.cli.on_frida_message)
self.cli.frida_script.on('destroyed', self.cli.on_frida_script_destroyed)
self.cli.frida_script.load()
self.cli.context_manager.set_target(package, module)
return None
class Backtrace(Command):
def get_command_info(self):
return {
'name': 'backtrace',
'info': '',
'shortcuts': [
'bt'
]
}
def __backtrace__(self, args):
if self.cli.context_manager.get_context() is not None:
return self.cli.frida_script.exports.bt()
def __backtrace_result__(self, result):
if len(result) > 0:
self.cli.context_title('backtrace')
for b in result:
name = ''
if 'name' in b and b['name'] is not None:
name = b['name'] + ' '
if 'moduleName' in b and b['moduleName'] is not None:
name += '' + b['moduleName']
printer.append('%s\t%s' % (Color.colorify(b['address'], 'red highlight'), name))
def __backtrace_store__(self, data):
return None
class DeStruct(Command):
def get_command_info(self):
return {
'name': 'destruct',
'info': 'read at address arg0 for len arg1 and optional depth arg2',
'args': 2,
'shortcuts': [
'ds', 'des'
]
}
def __destruct__(self, args):
depth = self.cli.context_manager.get_pointer_size() * 4
if len(args) > 2:
depth = args[2]
if depth % 8 != 0:
return 'depth must be multiple of 8'
try:
data = self.cli.frida_script.exports.mr(args[0], args[1])
result = self._recursive(data, depth)
lines = self._get_lines(result, 0)
return '\n'.join(lines)
except:
return None
def __destruct_store__(self, data):
return None
def __destruct_result__(self, result):
log(result)
def _get_lines(self, arr, depth):
result = []
while len(arr) > 0:
line = ' ' * depth
obj = arr.pop(0)
if 'value' in obj:
dec = obj['decimal']
if dec != 0x0 and dec != 0xfffffff:
line += '%s' % Color.colorify(obj['value'], 'green highlight')
else:
line += obj['value']
result.append(line)
elif 'ptr' in obj:
line += Color.colorify(obj['ptr'], 'red highlight')
result.append(line)
if 'tree' in obj and obj['tree'] is not None:
result += self._get_lines(obj['tree'], depth + 1)
return result
def _recursive(self, data, depth):
_struct = []
while len(data) > 0:
chunk_size = self.cli.context_manager.get_pointer_size()
if len(data) < chunk_size:
break
chunk = data[0:chunk_size]
i_val = struct.unpack('>L', chunk)[0]
if i_val < 255:
_struct.append({'value': '0x%s' % (binascii.hexlify(chunk).decode('utf8')), 'decimal': i_val})
else:
val = struct.unpack('<L', data[0:chunk_size])[0]
try:
read = depth
if depth < self.cli.context_manager.get_pointer_size() * 2:
read = self.cli.context_manager.get_pointer_size()
sd = self.cli.frida_script.exports.mr(val, read)
if sd is not None:
obj = {'ptr': '0x%x' % val}
if depth >= self.cli.context_manager.get_pointer_size() * 2:
obj['tree'] = self._recursive(sd, depth / 2)
_struct.append(obj)
data = data[chunk_size:]
continue
except:
pass
_struct.append({'value': '0x%s' % (binascii.hexlify(chunk).decode('utf8')), 'decimal': i_val})
data = data[chunk_size:]
return _struct
class DisAssembler(Command):
def get_command_info(self):
return {
'name': 'disasm',
'args': 1,
'info': 'disassemble the given hex payload in arg0 or a pointer in arg0 with len in arg1',
'shortcuts': [
'd', 'dis'
]
}
def __disasm__(self, args):
if self.cli.context_manager.get_base() == 0:
log('a target attached is needed before using disasm')
return None
if self.cli.context_manager.get_arch() is None:
log('this arch is not yet supported :( - but you can still use set command to manually configure')
return None
else:
cs = capstone.Cs(self.cli.context_manager.get_arch().get_capstone_arch(),
self.cli.context_manager.get_arch().get_capstone_mode())
cs.detail = True
l = 0
if not _python3:
if type(args[0]) is unicode:
args[0] = args[0].encode('ascii', 'ignore')
if type(args[0]) is str:
l = 32
b = binascii.unhexlify(args[0])
off = 0
if len(args) > 1:
off = args[1]
elif type(args[0]) is bytes:
b = args[0]
off = args[1]
else:
l = 32
if len(args) > 1:
l = args[1]
b = Memory(self.cli)._internal_read_data_(args[0], l)[1]
off = args[0]
ret = []
t_s = 0
for i in cs.disasm(b, off):
if l > 0 and t_s > 0:
t_s += i.size
if t_s > l:
break
if cli.context_manager.get_context_offset() == i.address \
or cli.context_manager.get_context_offset() + 1 == i.address:
if l > 0:
t_s += 1
ret.append(self.instr_line(i, cs))
return ret
def __disasm_result__(self, result):
self.cli.context_title('disasm')
log('\n'.join(result))
def __disasm_store__(self, data):
return None
@staticmethod
def instr_line(i, cs):
isbs = binascii.hexlify(i.bytes).decode('utf8')
if len(isbs) < cli.context_manager.get_pointer_size() * 2:
isbs += ' ' * ((cli.context_manager.get_pointer_size() * 2) - len(isbs))
ret = []
faddr = '0x%x' % i.address
if cli.context_manager.get_context_offset() == i.address \
or cli.context_manager.get_context_offset() + 1 == i.address:
faddr = ' ' + Color.colorify(faddr, 'red highlight')
is_jmp = False
if len(i.groups) > 0:
if 1 in i.groups or 149 in i.groups or (len(i.groups) == 1 and 150 in i.groups):
is_jmp = True
if is_jmp:
pst = False
if cli.frida_script is not None:
for op in i.operands:
if op.type == 2:
s_off = int(cli.to_x_32(op.imm), 16)
try:
dbgs = cli.frida_script.exports.dbgsfa(s_off)
if dbgs is not None:
sy = ' (%s - %s)' % (Color.colorify(dbgs['name'], 'red highlight'),
Color.colorify(dbgs['moduleName'], 'bold'))
else:
sy = ''
pst = True
ret.append("%s:\t%s\t%s\t%s%s" % (faddr,
Color.colorify(isbs, 'yellow highlight'),
Color.colorify(i.mnemonic.upper(), 'blue bold'),
i.op_str, sy))
except:
pass
try:
deep = cli.frida_script.exports.mr(s_off, 8)
except:
deep = None
if deep is not None:
t = 0