forked from hugsy/gef
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gef.py
3519 lines (2625 loc) · 100 KB
/
gef.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
################################################################################################################
# GEF - Multi-Architecture GDB Enhanced Features for Exploiters & Reverse-Engineers
#
# by @_hugsy_
#
# GEF provides additional functions to GDB using its powerful Python API. Some
# functions were inspired by PEDA (https://github.com/longld/peda) which is totally
# awesome *but* is x86 (32/64bits) specific, whereas GEF supports almost all archs
# supported by GDB.
#
# Notes:
# * Since GEF relies on /proc for mapping addresses in memory or other features, it
# cannot work on hardened configurations (such as GrSec)
# * GEF supports kernel debugging in a limit way (please report crashes & bugs)
#
# Tested on
# * x86-32/x86-64 (even though you should totally use `gdb-peda` (https://github.com/longld/peda) instead)
# * armv6/armv7/armv8 (untested)
# * mips32
# * powerpc32/powerpc64
# * sparc
#
#
# Tested on gdb 7.x / python 2.6 & 2.7 & 3.x
#
# To start: in gdb, type `source /path/to/gef.py`
#
#
# ToDo:
# - add explicit actions for flags (jumps/overflow/negative/etc)
#
#
from __future__ import print_function
import math
import struct
import subprocess
import functools
import sys
import re
import tempfile
import os
import binascii
import getopt
import gdb
if sys.version_info.major == 2:
from HTMLParser import HTMLParser
import itertools
from cStringIO import StringIO
from urllib import urlopen
# Compat Py2/3 hacks
range = xrange
PYTHON_MAJOR = 2
elif sys.version_info.major == 3:
from html.parser import HTMLParser
from io import StringIO
from urllib.request import urlopen
# Compat Py2/3 hack
long = int
FileNotFoundError = IOError
PYTHON_MAJOR = 3
else:
raise Exception("WTF is this Python version??")
__aliases__ = {}
__config__ = {}
NO_COLOR = False
__infos_files__ = []
class GefGenericException(Exception):
def __init__(self, value):
self.message = value
return
def __str__(self):
return repr(self.message)
class GefMissingDependencyException(GefGenericException): pass
class GefUnsupportedMode(GefGenericException): pass
class GefUnsupportedOS(GefGenericException): pass
# https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
class memoize(object):
"""Custom Memoize class with resettable cache"""
def __init__(self, func):
self.func = func
self.is_memoized = True
self.cache = {}
return
def __call__(self, *args):
if args not in self.cache:
value = self.func(*args)
self.cache[args] = value
return value
return self.func(*args)
def __repr__(self):
return self.func.__doc__
def __get__(self, obj, objtype):
fn = functools.partial(self.__call__, obj)
fn.reset = self._reset
return fn
def reset(self):
self.cache = {}
return
def reset_all_caches():
for s in dir(sys.modules['__main__']):
o = getattr(sys.modules['__main__'], s)
if hasattr(o, "is_memoized") and o.is_memoized:
o.reset()
return
# let's get fancy
class Color:
GRAY = "\033[1;30m"
NORMAL = "\x1b[0m"
RED = "\x1b[31m"
GREEN = "\x1b[32m"
YELLOW = "\x1b[33m"
BLUE = "\x1b[34m"
BOLD = "\x1b[1m"
UNDERLINE = "\x1b[4m"
@staticmethod
def redify(msg): return Color.RED + msg + Color.NORMAL if not NO_COLOR else ""
@staticmethod
def greenify(msg): return Color.GREEN + msg + Color.NORMAL if not NO_COLOR else ""
@staticmethod
def blueify(msg): return Color.BLUE + msg + Color.NORMAL if not NO_COLOR else ""
@staticmethod
def yellowify(msg): return Color.YELLOW + msg + Color.NORMAL if not NO_COLOR else ""
@staticmethod
def boldify(msg): return Color.BOLD + msg + Color.NORMAL if not NO_COLOR else ""
# helpers
class Address:
pass
class Permission:
READ = 4
WRITE = 2
EXECUTE = 1
def __init__(self, *args, **kwargs):
self.value = 0
return
def __str__(self):
perm_str = ""
perm_str += "r" if self.value & Permission.READ else "-"
perm_str += "w" if self.value & Permission.WRITE else "-"
perm_str += "x" if self.value & Permission.EXECUTE else "-"
return perm_str
@staticmethod
def from_info_sections(*args):
p = Permission()
for arg in args:
if "READONLY" in arg:
p.value += Permission.READ
if "DATA" in arg:
p.value += Permission.WRITE
if "CODE" in arg:
p.value += Permission.EXECUTE
return p
@staticmethod
def from_process_maps(perm_str):
p = Permission()
if perm_str[0] == "r":
p.value += Permission.READ
if perm_str[1] == "w":
p.value += Permission.WRITE
if perm_str[2] == "x":
p.value += Permission.EXECUTE
return p
class Section:
page_start = None
page_end = None
offset = None
permission = None
inode = None
path = None
def __init__(self, *args, **kwargs):
attrs = ["page_start", "page_end", "offset", "permission", "inode", "path"]
for attr in attrs:
value = kwargs[attr] if attr in kwargs else None
setattr(self, attr, value)
return
class Zone:
name = None
zone_start = None
zone_end = None
filename = None
class Elf:
e_magic = None
e_class = None
e_endianness = None
e_eiversion = None
e_osabi = None
e_abiversion = None
e_pad = None
e_type = None
e_machine = None
e_version = None
e_entry = None
e_phoff = None
e_shoff = None
e_flags = None
e_ehsize = None
e_phentsize = None
e_phnum = None
e_shentsize = None
e_shnum = None
e_shstrndx = None
class GlibcChunk:
def __init__(self, addr=None):
"""Init `addr` as a chunk"""
self.addr = addr if addr else process_lookup_path("heap").page_start
self.arch = get_memory_alignment()/8
self.start_addr = self.addr - 2*self.arch
self.size_addr = self.addr - self.arch
return
# if alloc-ed functions
def get_chunk_size(self):
return read_int_from_memory( self.size_addr ) & (~0x03)
def get_usable_size(self):
return self.get_chunk_size() - 2*self.arch
def get_prev_chunk_size(self):
return read_int_from_memory( self.start_addr )
def get_next_chunk(self):
addr = self.start_addr + self.get_chunk_size() + 2*self.arch
return GlibcChunk(addr)
# endif alloc-ed functions
# if free-ed functions
def get_fwd_ptr(self):
return read_int_from_memory( self.addr )
def get_bkw_ptr(self):
return read_int_from_memory( self.addr+self.arch )
# endif free-ed functions
def has_P_bit(self):
"""Check for in PREV_INUSE bit"""
return read_int_from_memory( self.size_addr ) & 0x01
def has_M_bit(self):
"""Check for in IS_MMAPPED bit"""
return read_int_from_memory( self.size_addr ) & 0x02
def is_used(self):
"""
Check if the current block is used by:
- checking the M bit is true
- or checking that next chunk PREV_INUSE flag is true
"""
if self.has_M_bit():
return True
next_chunk = self.get_next_chunk()
if next_chunk.has_P_bit():
return True
return False
def str_as_alloced(self):
msg = ""
msg+= "Chunk size: {0:d} ({0:#x})".format( self.get_chunk_size() ) + "\n"
msg+= "Usable size: {0:d} ({0:#x})".format( self.get_usable_size() ) + "\n"
msg+= "Previous chunk size: {0:d} ({0:#x})".format( self.get_prev_chunk_size() ) + "\n"
msg+= "PREV_INUSE flag: "
msg+= Color.greenify("On") if self.has_P_bit() else Color.redify("Off")
msg+= "\n"
msg+= "IS_MMAPPED flag: "
msg+= Color.greenify("On") if self.has_M_bit() else Color.redify("Off")
return msg
def str_as_freeed(self):
msg = ""
msg+= "Chunk size: {0:d} ({0:#x})".format( self.get_chunk_size() ) + "\n"
msg+= "Previous chunk size: {0:d} ({0:#x})".format( self.get_prev_chunk_size() ) + "\n"
msg+= "Forward pointer: {0:#x}".format( self.get_fwd_ptr() ) + "\n"
msg+= "Backward pointer: {0:#x}".format( self.get_bkw_ptr() )
return msg
def __str__(self):
msg = "====================[ %s ]====================\n"
if not self.is_used():
msg%= Color.boldify(Color.greenify("Chunk (free): ") + "%#x" % self.start_addr)
msg+= self.str_as_freeed()
else:
msg%= Color.boldify(Color.redify("Chunk (used): ") + "%#x" % self.start_addr)
msg+= self.str_as_alloced()
return msg
def titlify(msg):
return "{0}[{1} {3} {2}]{0}".format('='*30, Color.RED, Color.NORMAL, msg)
def err(msg):
print((Color.BOLD+Color.RED+"[!]"+Color.NORMAL+" "+msg))
return
def warn(msg):
print((Color.BOLD+Color.YELLOW+"[*]"+Color.NORMAL+" "+msg))
return
def ok(msg):
print((Color.BOLD+Color.GREEN+"[+]"+Color.NORMAL+" "+msg))
return
def info(msg):
print((Color.BOLD+Color.BLUE+"[+]"+Color.NORMAL+" "+msg))
return
def hexdump(src, l=0x10, sep='.', show_raw=False, base=0x00):
res = []
for i in range(0, len(src), l):
s = src[i:i+l]
hexa = ''
isMiddle = False
for h in range(0,len(s)):
if h == l/2:
hexa += ' '
h = s[h]
if not isinstance(h, int):
h = ord(h)
h = hex(h).replace('0x','')
if len(h) == 1:
h = '0'+h
hexa += h + ' '
hexa = hexa.strip(' ')
text = ''
for c in s:
if not isinstance(c, int):
c = ord(c)
if 0x20 <= c < 0x7F:
text += chr(c)
else:
text += sep
if show_raw:
res.append(('%-'+str(l*(2+1)+1)+'s') % (hexa))
else:
res.append(('%08X: %-'+str(l*(2+1)+1)+'s |%s|') % (i+base, hexa, text))
return '\n'.join(res)
def gef_obsolete_function(func):
def new_func(*args, **kwargs):
warn("Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning)
return func(*args, **kwargs)
new_func.__name__ = func.__name__
new_func.__doc__ = func.__doc__
new_func.__dict__.update(func.__dict__)
return new_func
def gef_execute(command, as_list=False):
output = []
lines = gdb.execute(command, to_string=True).splitlines()
for line in lines:
if line.startswith("=>"): line = line[2:]
line = line.lstrip().rstrip()
address, content = line.split(" ", 1)
address = long(address, 16)
output.append( (address, content) )
return output
def gef_disassemble(addr, nb_insn, from_top=False):
dis_start_addr = addr if from_top else addr-(2*nb_insn)
cmd = "x/%di %#x" % (nb_insn, dis_start_addr)
lines = gdb.execute(cmd, to_string=True).splitlines()
lines = [ l.replace("=>", "").replace("\t", " ").replace(":", " ").strip() for l in lines if "(bad)" not in l ]
l = []
patt = re.compile(r'^(0x[0-9a-f]{,16})(.*)$', flags=re.IGNORECASE)
for line in lines:
parts = [ x for x in re.split(patt, line) if len(x)>0 ]
addr = int(parts[0], 16)
code = parts[1].strip()
l.append( (addr, code) )
return l
def gef_execute_external(command, as_list=False):
if as_list :
return subprocess.check_output(command,
stderr=subprocess.STDOUT,
shell=True).splitlines()
else:
res = subprocess.check_output(command,
stderr=subprocess.STDOUT,
shell=True)
return str(res, encoding="ascii" )
def disassemble_parse(name, filter_opcode=None):
lines = [x.split(":", 1) for x in gdb_exec("disassemble %s" % name).split('\n') if "0x" in x]
dis = []
for address, opcode in lines:
try:
address = address.replace("=>", " ").strip()
address = long(address.split(" ")[0], 16)
i = opcode.find("#")
if i != -1:
opcode = opcode[:i]
i = opcode.find("<")
if i != -1:
opcode = opcode[:i]
opcode = opcode.strip()
if filter_opcode is None or filter_opcode in opcode:
dis.append( (address, opcode) )
except:
continue
return dis
def get_frame():
return gdb.selected_inferior()
@memoize
def get_arch():
return gdb.execute("show architecture", to_string=True).strip().split(" ")[7][:-1]
######################[ ARM specific ]######################
def arm_registers():
return ["$r0 ", "$r1 ", "$r2 ", "$r3 ", "$r4 ", "$r5 ", "$r6 ",
"$r7 ", "$r8 ", "$r9 ", "$r10 ", "$r11 ", "$r12 ", "$sp ",
"$lr ", "$pc ", "$cpsr", ]
def arm_nop_insn():
# http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0041c/Caccegih.html
# mov r0,r0
return b"\x00\x00\xa0\xe1"
def arm_return_register():
return "$r0"
######################[ Intel x86-64 specific ]######################
def x86_64_registers():
return [ "$rax ", "$rcx ", "$rdx ", "$rbx ", "$rsp ", "$rbp ", "$rsi ",
"$rdi ", "$rip ", "$r8 ", "$r9 ", "$r10 ", "$r11 ", "$r12 ",
"$r13 ", "$r14 ", "$r15 ",
"$cs ", "$ss ", "$ds ", "$es ", "$fs ", "$gs ", "$eflags", ]
def x86_64_nop_insn():
return b'\x90'
def x86_64_return_register():
return "$rax"
######################[ Intel x86-32 specific ]######################
def x86_32_registers():
return [ "$eax ", "$ecx ", "$edx ", "$ebx ", "$esp ", "$ebp ", "$esi ",
"$edi ", "$eip ", "$cs ", "$ss ", "$ds ", "$es ",
"$fs ", "$gs ", "$eflags", ]
def x86_32_nop_insn():
return b'\x90'
def x86_32_return_register():
return "$eax"
######################[ PowerPC specific ]######################
def powerpc_registers():
return ["$r0 ", "$r1 ", "$r2 ", "$r3 ", "$r4 ", "$r5 ", "$r6 ", "$r7 ",
"$r8 ", "$r9 ", "$r10 ", "$r11 ", "$r12 ", "$r13 ", "$r14 ", "$r15 ",
"$r16 ", "$r17 ", "$r18 ", "$r19 ", "$r20 ", "$r21 ", "$r22 ", "$r23 ",
"$r24 ", "$r25 ", "$r26 ", "$r27 ", "$r28 ", "$r29 ", "$r30 ", "$r31 ",
"$pc ", "$msr ", "$cr ", "$lr ", "$ctr ", "$xer ", "$trap" ]
def powerpc_nop_insn():
# http://www.ibm.com/developerworks/library/l-ppc/index.html
# nop
return b'\x60\x00\x00\x00'
def powerpc_return_register():
return "$r0"
######################[ SPARC specific ]######################
def sparc_registers():
return ["$g0 ", "$g1 ", "$g2 ", "$g3 ", "$g4 ", "$g5 ", "$g6 ", "$g7 ",
"$o0 ", "$o1 ", "$o2 ", "$o3 ", "$o4 ", "$o5 ",
"$l0 ", "$l1 ", "$l2 ", "$l3 ", "$l4 ", "$l5 ", "$l6 ", "$l7 ",
"$i0 ", "$i1 ", "$i2 ", "$i3 ", "$i4 ", "$i5 ",
"$pc ", "$sp ", "$fp ", "$psr", ]
def sparc_nop_insn():
# http://www.cse.scu.edu/~atkinson/teaching/sp05/259/sparc.pdf
# sethi 0, %g0
return b'\x00\x00\x00\x00'
def sparc_return_register():
return "$i0"
######################[ MIPS specific ]######################
def mips_registers():
# http://vhouten.home.xs4all.nl/mipsel/r3000-isa.html
return ["$r0 ", "$r1 ", "$r2 ", "$r3 ", "$r4 ", "$r5 ", "$r6 ", "$r7 ",
"$r8 ", "$r9 ", "$r10 ", "$r11 ", "$r12 ", "$r13 ", "$r14 ", "$r15 ",
"$r16 ", "$r17 ", "$r18 ", "$r19 ", "$r20 ", "$r21 ", "$r22 ", "$r23 ",
"$r24 ", "$r25 ", "$r26 ", "$r27 ", "$r28 ", "$r29 ", "$r30 ", "$r31 ",
"$pc ", "$sp ", "$hi ", "$lo ", "$fir ", "$ra ", "$gp ", ]
def mips_nop_insn():
# https://en.wikipedia.org/wiki/MIPS_instruction_set
# sll $0,$0,0
return b"\x00\x00\x00\x00"
def mips_return_register():
return "$r2"
@memoize
def all_registers():
if is_arm(): return arm_registers()
elif is_x86_32(): return x86_32_registers()
elif is_x86_64(): return x86_64_registers()
elif is_powerpc(): return powerpc_registers()
elif is_sparc(): return sparc_registers()
elif is_mips(): return mips_registers()
raise GefUnsupportedOS("OS type is currently not supported: %s" % get_arch())
@memoize
def nop_insn():
if is_arm(): return arm_nop_insn()
elif is_x86_32(): return x86_32_nop_insn()
elif is_x86_64(): return x86_64_nop_insn()
elif is_powerpc(): return powerpc_nop_insn()
elif is_sparc(): return sparc_nop_insn()
elif is_mips(): return mips_nop_insn()
raise GefUnsupportedOS("OS type is currently not supported: %s" % get_arch())
@memoize
def return_register():
if is_arm(): return arm_return_register()
elif is_x86_32(): return x86_32_return_register()
elif is_x86_64(): return x86_64_return_register()
elif is_powerpc(): return powerpc_return_register()
elif is_sparc(): return sparc_return_register()
elif is_mips(): return mips_return_register()
raise GefUnsupportedOS("OS type is currently not supported: %s" % get_arch())
def write_memory(address, buffer, length=0x10):
return gdb.selected_inferior().write_memory(address, buffer, length)
def read_memory(addr, length=0x10):
if PYTHON_MAJOR == 2:
return gdb.selected_inferior().read_memory(addr, length)
else:
return gdb.selected_inferior().read_memory(addr, length).tobytes()
def read_int_from_memory(addr):
arch = get_memory_alignment()/8
mem = read_memory( addr, arch)
fmt = endian_str()+"I" if arch==4 else endian_str()+"Q"
return struct.unpack( fmt, mem)[0]
def which(program):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
raise IOError("Missing file `%s`" % program)
def read_memory_until_null(address, max_length=-1):
i = 0
if PYTHON_MAJOR == 2:
buf = ''
while True:
try:
c = read_memory(address + i, 1)[0]
if c == '\x00':
break
buf += c
i += 1
if max_length > 0 and i == max_length:
break
except:
break
return buf
else:
buf = []
while True:
try:
c = read_memory(address + i, 1)[0]
if c == 0x00:
break
buf.append( c )
i += 1
if max_length > 0 and i == max_length:
break
except:
break
return bytes(buf)
def is_readable_string(address):
"""
Here we will assume that a readable string is
a consecutive byte array whose
* last element is 0x00
* and values for each byte is [0x07, 0x7F[
"""
buffer = read_memory_until_null(address)
if len(buffer) == 0:
return False
valid_ascii_charset = [0x09, 0x0a, 0x0d, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a,
0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46,
0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54,
0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62,
0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,
0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e]
if PYTHON_MAJOR == 2:
for c in buffer:
if ord(c) not in valid_ascii_charset:
return False
else:
for c in buffer:
if c not in valid_ascii_charset:
return False
return len(buffer) > 1
def read_string(address, max_length=-1):
if not is_readable_string(address):
raise ValueError("Content at address `%#x` is not a string" % address)
buf = read_memory_until_null(address, max_length)
replaced_chars = [ (b"\n",b"\\n"), (b"\r",b"\\r"), (b"\t",b"\\t"), (b"\"",b"\\\"")]
for f,t in replaced_chars:
buf = buf.replace(f, t)
return buf
def is_alive():
try:
pid = get_frame().pid
return pid > 0
except gdb.error as e:
return False
return False
def get_register(regname):
"""
Get register value. Exception will be raised if expression cannot be parse.
This function won't catch on purpose.
@param regname: expected register
@return register value
"""
t = gdb.lookup_type("unsigned long")
reg = gdb.parse_and_eval(regname)
return long( reg.cast(t) )
def get_register_ex(regname):
t = gdb.execute("info register %s" % regname, to_string=True)
for v in t.split(" "):
v = v.strip()
if v.startswith("0x"):
return long(v.strip().split("\t",1)[0], 16)
return 0
def get_pc():
try:
return get_register("$pc")
except:
return get_register_ex("$pc")
def get_sp():
try:
return get_register("$sp")
except:
return get_register_ex("$sp")
@memoize
def get_pid():
return get_frame().pid
@memoize
def get_filename():
return gdb.current_progspace().filename
@memoize
def get_process_maps():
sections = []
try:
pid = get_pid()
f = open('/proc/%d/maps' % pid)
while True:
line = f.readline()
if len(line) == 0:
break
line = line.strip()
addr, perm, off, dev, rest = line.split(" ", 4)
rest = rest.split(" ", 1)
if len(rest) == 1:
inode = rest[0]
pathname = ""
else:
inode = rest[0]
pathname = rest[1].replace(' ', '')
addr_start, addr_end = addr.split("-")
addr_start, addr_end = long(addr_start, 16), long(addr_end, 16)
off = long(off, 16)
perm = Permission.from_process_maps(perm)
section = Section(page_start = addr_start,
page_end = addr_end,
offset = off,
permission = perm,
inode = inode,
path = pathname)
sections.append( section )
except IOError:
sections = get_info_sections()
return sections
@memoize
def get_info_sections():
sections = []
stream = StringIO(gdb.execute("maintenance info sections", to_string=True))
while True:
line = stream.readline()
if len(line) == 0:
break
line = re.sub('\s+',' ', line.strip())
try:
blobs = [x.strip() for x in line.split(' ')]
index = blobs[0][1:-1]
addr_start, addr_end = [ long(x, 16) for x in blobs[1].split("->") ]
at = blobs[2]
off = long(blobs[3][:-1], 16)
path = blobs[4]
inode = ""
perm = Permission.from_info_sections(blobs[5:])
section = Section(page_start = addr_start,
page_end = addr_end,
offset = off,
permission = perm,
inode = inode,
path = path)
sections.append( section )
except IndexError:
continue
except ValueError:
continue
return sections
def get_info_files():
global __infos_files__
cmd = gdb.execute("info files", to_string=True)
lines = cmd.split("\n")
if len(lines) < len(__infos_files__):
return __infos_files__
for line in lines:
line = line.strip().rstrip()
if len(line) == 0:
break
if not line.startswith("0x"):
continue
blobs = [x.strip() for x in line.split(' ')]
addr_start = long(blobs[0], 16)
addr_end = long(blobs[2], 16)
section_name = blobs[4]
if len(blobs) == 7:
filename = blobs[6]
else:
filename = get_filename()
info = Zone()
info.name = section_name
info.zone_start = addr_start
info.zone_end = addr_end
info.filename = filename
# print("adding %s (%#x-%#x) in %s" % (info.name, info.zone_start, info.zone_end, info.filename))
__infos_files__.append( info )
return __infos_files__
def process_lookup_address(address):
if not is_alive():
err("Process is not running")
return None
if is_x86_64() or is_x86_32() :
if is_in_x86_kernel(address):
return None
for sect in get_process_maps():
if sect.page_start <= address < sect.page_end:
return sect
return None
def process_lookup_path(name, perm=Permission.READ|Permission.WRITE|Permission.EXECUTE):
if not is_alive():
err("Process is not running")
return None
for sect in get_process_maps():
if name in sect.path and sect.perm.value & perm:
return sect
return None
def file_lookup_address(address):
for info in get_info_files():
if info.zone_start <= address < info.zone_end:
return info
return None
def lookup_address(address):
addr = Address()
for attr in ["value", "section", "info"]:
setattr(addr, attr, None)
addr.value = address
sect = process_lookup_address(address)
info = file_lookup_address(address)
if sect is None and info is None:
# i.e. there is no info on this address
return None
if sect:
addr.section = sect
if info:
addr.info = info
return addr
def XOR(data, key):
return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in zip(data, itertools.cycle(key)))
def ishex(pattern):
if pattern.startswith("0x") or pattern.startswith("0X"):
pattern = pattern[2:]
charset = "0123456789abcdefABCDEF"
return all( c in charset for c in pattern )
# dirty hack, from https://github.com/longld/peda
def define_user_command(cmd, code):
if sys.version_info.major == 3:
commands = bytes( "define {0}\n{1}\nend".format(cmd, code), "UTF-8" )
else:
commands = "define {0}\n{1}\nend".format(cmd, code)
fd, fname = tempfile.mkstemp()
os.write(fd, commands)
os.close(fd)
gdb.execute("source %s" % fname)
os.unlink(fname)
return