forked from iGio90/frick
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
973 lines (856 loc) · 30 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
#######################################################################################
#
# 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 fcntl
import frida
import json
import os
import script
import six
import struct
import sys
import termios
import readline as readline
from pprint import pprint
from threading import Thread
def log(what):
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:
print('-> %s' % what)
else:
print(what)
return
t = type(what)
if t is int:
print('-> 0x%x (%u)' % (what, what))
elif t is unicode:
print('-> %s' % what.encode('ascii', 'ignore'))
else:
pprint(what)
class Arch(object):
def get_registers(self):
return []
class Arm(Arch):
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:
self._map[info['name']] = cmd
if 'shortcuts' in info:
for sh in info['shortcuts']:
self._map[sh] = cmd
except:
continue
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:])
if val is None:
val = 0
self.cli.context_manager.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:
self.cli.context_manager.add_value(base, eval(ev))
except:
log('failed to evaluate value')
else:
self.cli.context_manager.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']:
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 str(ev).startswith('0x'):
try:
ev = int(args[i], 16)
except:
pass
while True:
try:
i = str(ev).index('$')
tst = ev[i + 1:i + 3].lower()
if tst in self.cli.context_manager.get_context():
ev = ev.replace('$%s' % tst, self.cli.context_manager.get_context()[tst]['value'])
continue
tst = ev[i + 1:i + 4].lower()
if tst in self.cli.context_manager.get_context():
ev = ev.replace('$%s' % tst, self.cli.context_manager.get_context()[tst]['value'])
except:
break
ev = self.try_eval(ev)
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):
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:
f_exec = getattr(command, '__%s__' % s_info['name'])
except:
break
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:
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:
log(data)
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.context_offset = 0x0
self.context = None
self.target_package = ''
self.target_module = ''
self.target_offsets = {}
self.values = {}
def add_target_offset(self, offset, name=''):
self.target_offsets[offset] = name
def add_value(self, key, value):
self.values[key] = value
def apply_arch(self, arch):
if arch == 'arm':
self.arch = Arm()
return self.arch
def clean(self):
self.target_offsets = {}
self.context = None
self.context_offset = 0x0
def set_base(self, base):
self.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_base(self):
return self.base
def get_context(self):
return self.context
def get_context_offset(self):
return self.context_offset
def get_target_offsets(self):
return self.target_offsets
def get_value(self, key):
if key in self.values:
return self.values[key]
return None
def print_context(self):
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')
print(p)
def save(self):
if os.path.exists('.session'):
os.remove('.session')
ext = ''
if len(self.target_offsets) > 0:
ext += 'add '
for t in self.target_offsets:
ext += '%s ' % str(t)
if self.target_package is not '':
ext += '\nattach %s %s' % (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):
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()
for l in f.split('\n'):
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 following args',
'args': 1
}
def __add__(self, args):
ptr = args[0]
name = ''
if len(args) > 1:
for a in args[1:]:
name += str(a) + ' '
self.cli.context_manager.add_target_offset(ptr, name)
log('%s added to target offsets' % Color.colorify('0x%x' % ptr, 'red highlight'))
if self.cli.frida_script is not None:
self.cli.frida_script.exports.add(ptr)
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'
pid = self.cli.frida_device.spawn([package])
process = self.cli.frida_device.attach(pid)
log("frida %s" % Color.colorify('attached', 'bold'))
self.cli.frida_script = process.create_script(script.get_script(
module, self.cli.context_manager.get_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.load()
self.cli.context_manager.set_target(package, module)
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 = 32
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.mrs(args[0], args[1])
result = self._recursive(data, depth)
lines = self._get_lines(result, 0)
return '\n'.join(lines)
except:
return None
def _get_lines(self, arr, depth):
result = []
while len(arr) > 0:
line = ''
for i in range(0, depth):
line += ' '
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 = 4
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)), 'decimal': i_val})
else:
val = struct.unpack('<L', data[0:chunk_size])[0]
try:
read = depth
if depth < 8:
read = 4
sd = self.cli.frida_script.exports.mrs(val, read)
if sd is not None:
obj = {'ptr': '0x%x' % val}
if depth >= 8:
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)), 'decimal': i_val})
data = data[chunk_size:]
return _struct
class Help(Command):
def get_command_info(self):
return {
'name': 'help',
'shortcuts': [
'h'
]
}
def __help__(self, args):
self.print_commands_list()
def print_commands_list(self):
c_map = {}
for cmd in self.cli.cmd_manager._map.values():
cmd_info = cmd.get_command_info()
c_map[cmd_info['name']] = cmd
result = self.recursive_help(c_map, 0)
log('\n'.join(result))
def recursive_help(self, cmd_map, depth):
result = []
for what in sorted(cmd_map):
if depth == 0:
cmd_info = cmd_map[what].get_command_info()
else:
cmd_info = cmd_map[what]
st = self.get_command_help_line(cmd_info, depth)
result.append(st)
if 'sub' in cmd_info:
sub_map = {}
for s in cmd_info['sub']:
sub_map[s['name']] = s
result += self.recursive_help(sub_map, depth + 1)
if depth == 0:
result.append('')
return result
def get_command_help_line(self, cmd_info, depth):
cmd_name = cmd_info['name']
st = ''
for i in range(0, depth):
st += ' '
st += Color.colorify(cmd_name, 'pink highlight')
if 'shortcuts' in cmd_info:
shortcuts = cmd_info['shortcuts']
st += ' (%s)' % Color.colorify((','.join(shortcuts)), 'green highlight')
if 'info' in cmd_info:
st += '\n'
for i in range(0, depth):
st += ' '
st += '%s' % cmd_info['info']
return st
class Memory(Command):
def get_command_info(self):
return {
'name': 'memory',
'args': 1,
'info': 'memory operations',
'shortcuts': [
'mem', 'm'
],
'sub': [
{
'name': 'read',
'args': 2,
'info': 'read bytes from address in arg0 for len in arg1',
'shortcuts': ['rd', 'r'],
'sub': [
{
'name': 'pointer',
'info': 'read a pointer from address in arg0',
'args': 1,
'shortcuts': [
'p', 'ptr'
]
}
]
},
{
'name': 'write',
'args': 2,
'info': 'write into address arg0 the bytes in args... (de ad be ef)',
'shortcuts': ['wr', 'w'],
}
]
}
def __read__(self, args):
try:
self.cli.frida_script.exports.mr(args[0], args[1])
except Exception as e:
log('failed to read data from device: %s' % e)
return None
def __pointer__(self, args):
try:
data = self.cli.frida_script.exports.rp(args[0])
except Exception as e:
log('failed to read data from device: %s' % e)
return None
return data
def __write__(self, args):
try:
print(''.join(args[1:]))
data = self.cli.frida_script.exports.mw(args[0], ''.join(args[1:]))
except Exception as e:
log('failed to write data to device: %s' % e)
return None
return data
class Print(Command):
def get_command_info(self):
return {
'name': 'print',
'args': 1,
'shortcuts': [
'p', 'pr'
]
}
def __print__(self, args):
if len(args) > 1:
ev = ''
for a in args:
ev += '%s ' % str(a)
try:
return eval(ev)
except:
log('failed to evaluate value')
return None
else:
return args[0]
class Registers(Command):
def get_command_info(self):
return {
'name': 'registers',
'shortcuts': [
'r', 'reg', 'regs'
],
'info': 'interact with registers',
'sub': [
{
'name': 'write',
'shortcuts': ['wr', 'w'],
'args': 2,
'info': 'write in register arg0 the value arg1'
}
]
}
def __registers__(self, args):
try:
self.cli.frida_script.exports.sc()
except:
pass
def __write__(self, args):
reg = args[0].lower()
if reg in self.cli.context_manager.get_context():
try:
what = args[1]
if isinstance(what, str):
what = int('0x%s' % what, 16)
v = self.cli.frida_script.exports.rw(reg, what)
if v is not None:
return '%s (%u)' % (Color.colorify('0x%x' % args[1], 'green highlight'), args[1])
else:
return 'failed to write into register %s' % reg
except Exception as e:
return 'failed to write into register %s - %s' % (reg, e)
return '%s - register not found' % (Color.colorify(reg, 'bold'))
class Quit(Command):
def get_command_info(self):
return {
'name': 'quit',
'args': 0,
'shortcuts': [
'q'
]
}
def __quit__(self, args):
sys.exit()
class Run(Command):
def get_command_info(self):
return {
'name': 'run',
'info': 'continue the execution of the process to the next target offset',
'shortcuts': [
'continue', 'cont', 'start', 'go', 'next', 'c'
]
}
def __run__(self, args):
self.cli.frida_script.exports.c()
return None
class Session(Command):
def get_command_info(self):
return {
'name': 'session',
'args': 1,
'shortcuts': [
's', 'ss'
],
'sub': [
{
'name': 'save',
'info': 'saves current target offsets, package and module to be immediatly executed with \'load\'',
'shortcuts': [
's', 'sv'
]
},
{
'name': 'load',
'info': 'load session from previously saved information',
'shortcuts': [
'l', 'ld'
]
}
]
}
def __load__(self, args):
self.cli.context_manager.load()
return None
def __save__(self, args):
self.cli.context_manager.save()
return None
class FridaCli(object):
def __init__(self):
self.frida_device = frida.get_usb_device(5)
self.frida_script = None
self.cmd_manager = CommandManager(self)
self.context_manager = ContextManager(self)
def start(self):
self.cmd_manager.init()
log('%s started - GL HF!' % Color.colorify('frick', 'green highligh'))
readline.parse_and_bind('tab: complete')
hist = os.path.join(os.environ['HOME'], '.frick_history')
try:
readline.read_history_file(hist)
except IOError:
pass
atexit.register(readline.write_history_file, hist)
while True:
inp = raw_input('')
if len(inp) > 0:
self.cmd_manager.handle_command(inp)
def hexdump(self, data, offset=0):
b_to_h = lambda b: ' '.join('%02x' % i for i in six.iterbytes(b))
result = []
while len(data) > 0:
chunk_size = 16
if len(data) < chunk_size:
chunk_size = len(data)
hexline = ''
n = data[0:chunk_size]
y = 0
while len(n) > 0:
ptr_min = 4
if len(n) >= ptr_min:
try:
i_val = struct.unpack('>L', n[0:4])[0]
if i_val < 255:
ptr = struct.unpack('<L', n[0:4])[0]
if self.frida_script.exports.ivp(ptr):
hexline += '%s' % Color.colorify(b_to_h(n[0:4]).upper(), 'red highlight')
n = n[ptr_min:]
y += 4
if y % 8 == 0:
hexline += ' '
else:
hexline += ' '
continue
except:
pass
else:
ptr_min = len(n)
var_hex = b_to_h(n[0:ptr_min])
var_i = int('0x%s' % ''.join(var_hex.split(' ')), 16)
if var_i > 0:
hexline += '%s' % Color.colorify(var_hex.upper(), 'green highlight')
else:
hexline += '%s' % var_hex.upper()
n = n[ptr_min:]
y += ptr_min
if y % 8 == 0:
hexline += ' '
else:
hexline += ' '
diff = 16 - y
while diff > 0:
hexline += ' '
diff -= 1
address = Color.colorify(('%08x' % (offset + (16 * len(result)))).upper(), 'yellow highlight')
tail = ''
for i in range(0, chunk_size):
char = data[i:i+1]
if ord(char) < 32 or ord(char) > 126:
tail += '.'
continue
t = ''
try:
t = data[i:i+1].decode('ascii')
except:
pass
if len(t) < 1:
t = '.'
tail += t
tail = Color.colorify(tail.replace('\n', '.').replace('\t', '.').replace(' ', '.'),
'yellow highlight')
result.append('%s: %s%s' % (address, hexline, tail))
data = data[chunk_size:]
if len(result) > 0:
self.context_title('0x%x' % offset)
print('\n'.join(result))
@staticmethod
def get_terminal_size():
"""Return the current terminal size."""
try:
cmd = struct.unpack("hh", fcntl.ioctl(1, termios.TIOCGWINSZ, "1234"))
tty_rows, tty_columns = int(cmd[0]), int(cmd[1])
return tty_rows, tty_columns
except OSError:
return 600, 100
@staticmethod
def context_title(m):
row, cols = FridaCli.get_terminal_size()
if not m:
print(Color.colorify('-' * cols, 'blue bold'))
else:
trail_len = len(m) + 8
title = ""
title += Color.colorify("{:{padd}<{width}}[ ".format("", width=cols - trail_len, padd='-'),
attrs='blue highlight')
title += Color.colorify(m, 'highlight')
title += Color.colorify(" ]{:{padd}<4}".format("", padd='-'),
attrs='blue highlight')
print(title)
@staticmethod
def on_frida_message(message, data):
if 'payload' in message:
parts = message['payload'].split(':::')
try:
id = int(parts[0])
except:
id = -1
if id < 0:
log(message)
return
if id == 0:
cli.context_manager.set_base(int(parts[1], 16))
if cli.context_manager.apply_arch(parts[2]) is not None:
log('target arch: %s' % Color.colorify(parts[2], 'green bold'))
log('target base at %s' % Color.colorify('0x%x' % cli.context_manager.get_base(), 'red highlight'))
elif id == 1:
log('attached to %s' % Color.colorify(parts[1], 'red highlight'))
elif id == 2:
cli.context_manager.set_context(int(parts[1]), json.loads(parts[2]))
name = cli.context_manager.get_target_offsets()[int(parts[1])]
if name is not '':
cli.context_title('%s - 0x%x' % (name, cli.context_manager.get_context_offset()))
else:
cli.context_title('0x%x' % (cli.context_manager.get_context_offset()))
cli.context_manager.print_context()
elif id == 3:
offset = int(parts[1], 16)
Thread(target=cli.hexdump, args=(data, offset)).start()
else:
log(message)
if __name__ == '__main__':
global cli
cli = FridaCli()
cli.start()