-
Notifications
You must be signed in to change notification settings - Fork 0
/
.gdbinit-gef.py
9536 lines (7666 loc) · 326 KB
/
.gdbinit-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
# -*- coding: utf-8 -*-
#
#
#######################################################################################
# GEF - Multi-Architecture GDB Enhanced Features for Exploiters & Reverse-Engineers
#
# by @_hugsy_
#######################################################################################
#
# GEF is a kick-ass set of commands for X86, ARM, MIPS, PowerPC and SPARC to
# make GDB cool again for exploit dev. It is aimed to be used mostly by exploit
# devs and reversers, to provides additional features to GDB using the Python
# API to assist during the process of dynamic analysis.
#
# GEF fully relies on GDB API and other Linux-specific sources of information
# (such as /proc/<pid>). As a consequence, some of the features might not work
# on custom or hardened systems such as GrSec.
#
# It has full support for both Python2 and Python3 and works on
# * x86-32 & x86-64
# * arm v5,v6,v7
# * aarch64 (armv8)
# * mips & mips64
# * powerpc & powerpc64
# * sparc & sparc64(v9)
#
# Requires GDB 7.x compiled with Python (2.x, or 3.x)
#
# To start: in gdb, type `source /path/to/gef.py`
#
#######################################################################################
#
# gef is distributed under the MIT License (MIT)
# Copyright (c) 2013-2018 crazy rabbidz
#
# 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 NONINFRINGEMENT. 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.
#
#
from __future__ import print_function, division, absolute_import
import abc
import binascii
import codecs
import collections
import ctypes
import fcntl
import functools
import getopt
import hashlib
import imp
import inspect
import itertools
import os
import platform
import re
import shutil
import site
import socket
import string
import struct
import subprocess
import sys
import tempfile
import termios
import time
import traceback
PYTHON_MAJOR = sys.version_info[0]
if PYTHON_MAJOR == 2:
from HTMLParser import HTMLParser #pylint: disable=import-error
from cStringIO import StringIO #pylint: disable=import-error
from urllib import urlopen #pylint: disable=no-name-in-module
import ConfigParser as configparser #pylint: disable=import-error
import xmlrpclib #pylint: disable=import-error
# Compat Py2/3 hacks
def range(*args):
"""Replace range() builtin with an iterator version."""
if len(args) < 1:
raise TypeError()
start, end, step = 0, args[0], 1
if len(args) == 2: start, end = args
if len(args) == 3: start, end, step = args
for n in itertools.count(start=start, step=step):
if (step>0 and n >= end) or (step<0 and n<=end): break
yield n
FileNotFoundError = IOError #pylint: disable=redefined-builtin
ConnectionRefusedError = socket.error #pylint: disable=redefined-builtin
LEFT_ARROW = "<-"
RIGHT_ARROW = "->"
DOWN_ARROW = "\\->"
HORIZONTAL_LINE = "-"
VERTICAL_LINE = "|"
CROSS = "x"
TICK = "v"
GEF_PROMPT = "gef> "
GEF_PROMPT_ON = "\001\033[1;32m\002{0:s}\001\033[0m\002".format(GEF_PROMPT)
GEF_PROMPT_OFF = "\001\033[1;31m\002{0:s}\001\033[0m\002".format(GEF_PROMPT)
elif PYTHON_MAJOR == 3:
from html.parser import HTMLParser #pylint: disable=import-error
from io import StringIO
from urllib.request import urlopen #pylint: disable=import-error,no-name-in-module
import configparser
import xmlrpc.client as xmlrpclib #pylint: disable=import-error
# Compat Py2/3 hack
long = int
unicode = str
LEFT_ARROW = " \u2190 "
RIGHT_ARROW = " \u2192 "
DOWN_ARROW = "\u21b3"
HORIZONTAL_LINE = "\u2500"
VERTICAL_LINE = "\u2502"
CROSS = "\u2718 "
TICK = "\u2713 "
GEF_PROMPT = "gef\u27a4 "
GEF_PROMPT_ON = "\001\033[1;32m\002{0:s}\001\033[0m\002".format(GEF_PROMPT)
GEF_PROMPT_OFF = "\001\033[1;31m\002{0:s}\001\033[0m\002".format(GEF_PROMPT)
else:
raise Exception("WTF is this Python version??")
def http_get(url):
"""Basic HTTP wrapper for GET request. Return the body of the page if HTTP code is OK,
otherwise return None."""
try:
http = urlopen(url)
if http.getcode() != 200:
return None
return http.read()
except Exception:
return None
def update_gef(argv):
"""Try to update `gef` to the latest version pushed on GitHub. Return 0 on success,
1 on failure. """
gef_local = os.path.realpath(argv[0])
hash_gef_local = hashlib.sha512(open(gef_local, "rb").read()).digest()
gef_remote = "https://raw.githubusercontent.com/hugsy/gef/master/gef.py"
gef_remote_data = http_get(gef_remote)
if gef_remote_data is None:
print("[-] Failed to get remote gef")
return 1
hash_gef_remote = hashlib.sha512(gef_remote_data).digest()
if hash_gef_local == hash_gef_remote:
print("[-] No update")
else:
with open(gef_local, "wb") as f:
f.write(gef_remote_data)
print("[+] Updated")
return 0
try:
import gdb
except ImportError:
# if out of gdb, the only action allowed is to update gef.py
if len(sys.argv)==2 and sys.argv[1]=="--update":
sys.exit(update_gef(sys.argv))
print("[-] gef cannot run as standalone")
sys.exit(0)
__gef__ = None
__commands__ = []
__functions__ = []
__aliases__ = []
__config__ = {}
__watches__ = {}
__infos_files__ = []
__gef_convenience_vars_index__ = 0
__context_messages__ = []
__heap_allocated_list__ = []
__heap_freed_list__ = []
__heap_uaf_watchpoints__ = []
__pie_breakpoints__ = {}
__pie_counter__ = 1
__gef_remote__ = None
__gef_qemu_mode__ = False
__gef_default_main_arena__ = "main_arena"
__gef_int_stream_buffer__ = None
DEFAULT_PAGE_ALIGN_SHIFT = 12
DEFAULT_PAGE_SIZE = 1 << DEFAULT_PAGE_ALIGN_SHIFT
GEF_RC = os.path.join(os.getenv("HOME"), ".gef.rc")
GEF_TEMP_DIR = os.path.join(tempfile.gettempdir(), "gef")
GEF_MAX_STRING_LENGTH = 50
GDB_MIN_VERSION = (7, 7)
GDB_VERSION_MAJOR, GDB_VERSION_MINOR = [int(_) for _ in re.search(r"(\d+)[^\d]+(\d+)", gdb.VERSION).groups()]
GDB_VERSION = (GDB_VERSION_MAJOR, GDB_VERSION_MINOR)
current_elf = None
current_arch = None
if PYTHON_MAJOR==3:
lru_cache = functools.lru_cache #pylint: disable=no-member
else:
def lru_cache(maxsize = 128):
"""Port of the Python3 LRU cache mechanism provided by itertools."""
class GefLruCache(object):
"""Local LRU cache for Python2."""
def __init__(self, input_func, max_size):
self._input_func = input_func
self._max_size = max_size
self._caches_dict = {}
self._caches_info = {}
return
def cache_info(self, caller=None):
"""Return a string with statistics of cache usage."""
if caller not in self._caches_dict:
return ""
hits = self._caches_info[caller]["hits"]
missed = self._caches_info[caller]["missed"]
cursz = len(self._caches_dict[caller])
return "CacheInfo(hits={}, misses={}, maxsize={}, currsize={})".format(hits, missed, self._max_size, cursz)
def cache_clear(self, caller=None):
"""Clear a cache."""
if caller in self._caches_dict:
self._caches_dict[caller] = collections.OrderedDict()
return
def __get__(self, obj, objtype):
"""Cache getter."""
return_func = functools.partial(self._cache_wrapper, obj)
return_func.cache_clear = functools.partial(self.cache_clear, obj)
return functools.wraps(self._input_func)(return_func)
def __call__(self, *args, **kwargs):
"""Invoking the wrapped function, by attempting to get its value from cache if existing."""
return self._cache_wrapper(None, *args, **kwargs)
__call__.cache_clear = cache_clear
__call__.cache_info = cache_info
def _cache_wrapper(self, caller, *args, **kwargs):
"""Defines the caching mechanism."""
kwargs_key = "".join(map(lambda x : str(x) + str(type(kwargs[x])) + str(kwargs[x]), sorted(kwargs)))
key = "".join(map(lambda x : str(type(x)) + str(x) , args)) + kwargs_key
if caller not in self._caches_dict:
self._caches_dict[caller] = collections.OrderedDict()
self._caches_info[caller] = {"hits":0, "missed":0}
cur_caller_cache_dict = self._caches_dict[caller]
if key in cur_caller_cache_dict:
self._caches_info[caller]["hits"] += 1
return cur_caller_cache_dict[key]
self._caches_info[caller]["missed"] += 1
if self._max_size is not None:
if len(cur_caller_cache_dict) >= self._max_size:
cur_caller_cache_dict.popitem(False)
cur_caller_cache_dict[key] = self._input_func(caller, *args, **kwargs) if caller != None else self._input_func(*args, **kwargs)
return cur_caller_cache_dict[key]
return lambda input_func: functools.wraps(input_func)(GefLruCache(input_func, maxsize))
def reset_all_caches():
"""Free all caches. If an object is cached, it will have a callable attribute `cache_clear`
which will be invoked to purge the function cache."""
for mod in dir(sys.modules["__main__"]):
obj = getattr(sys.modules["__main__"], mod)
if hasattr(obj, "cache_clear"):
obj.cache_clear()
return
def gef_print(x="", *args, **kwargs):
"""Wrapper around print(), using string buffering feature."""
if __gef_int_stream_buffer__ and not is_debug():
return __gef_int_stream_buffer__.write(x + kwargs.get("end", "\n"))
return print(x, *args, **kwargs)
def bufferize(f):
"""Store the content to be printed for a function in memory, and flush it on function exit."""
@functools.wraps(f)
def wrapper(*args, **kwargs):
global __gef_int_stream_buffer__
if __gef_int_stream_buffer__:
return f(*args, **kwargs)
__gef_int_stream_buffer__ = StringIO()
try:
rv = f(*args, **kwargs)
finally:
sys.stdout.write(__gef_int_stream_buffer__.getvalue())
sys.stdout.flush()
__gef_int_stream_buffer__ = None
return rv
return wrapper
class Color:
"""Used to colorify terminal output."""
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",
"cyan" : "\033[36m",
"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, "red")
@staticmethod
def greenify(msg): return Color.colorify(msg, "green")
@staticmethod
def blueify(msg): return Color.colorify(msg, "blue")
@staticmethod
def yellowify(msg): return Color.colorify(msg, "yellow")
@staticmethod
def grayify(msg): return Color.colorify(msg, "gray")
@staticmethod
def pinkify(msg): return Color.colorify(msg, "pink")
@staticmethod
def cyanify(msg): return Color.colorify(msg, "cyan")
@staticmethod
def boldify(msg): return Color.colorify(msg, "bold")
@staticmethod
def underlinify(msg): return Color.colorify(msg, "underline")
@staticmethod
def highlightify(msg): return Color.colorify(msg, "highlight")
@staticmethod
def blinkify(msg): return Color.colorify(msg, "blink")
@staticmethod
def colorify(text, attrs):
"""Color text according to the given attributes."""
if get_gef_setting("gef.disable_color") is True: return text
colors = Color.colors
msg = [colors[attr] for attr in attrs.split() if attr in colors]
msg.append(str(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 Address:
"""GEF representation of memory addresses."""
def __init__(self, *args, **kwargs):
self.value = kwargs.get("value", 0)
self.section = kwargs.get("section", None)
self.info = kwargs.get("info", None)
self.valid = kwargs.get("valid", True)
return
def __str__(self):
value = format_address(self.value)
code_color = get_gef_setting("theme.address_code")
stack_color = get_gef_setting("theme.address_stack")
heap_color = get_gef_setting("theme.address_heap")
if self.is_in_text_segment():
return Color.colorify(value, code_color)
if self.is_in_heap_segment():
return Color.colorify(value, heap_color)
if self.is_in_stack_segment():
return Color.colorify(value, stack_color)
return value
def is_in_text_segment(self):
return (hasattr(self.info, "name") and ".text" in self.info.name) or \
(hasattr(self.section, "path") and get_filepath() == self.section.path and self.section.is_executable())
def is_in_stack_segment(self):
return hasattr(self.section, "path") and "[stack]" == self.section.path
def is_in_heap_segment(self):
return hasattr(self.section, "path") and "[heap]" == self.section.path
def dereference(self):
addr = align_address(long(self.value))
derefed = dereference(addr)
return None if derefed is None else long(derefed)
class Permission:
"""GEF representation of Linux permission."""
NONE = 0
READ = 1
WRITE = 2
EXECUTE = 4
ALL = READ | WRITE | EXECUTE
def __init__(self, **kwargs):
self.value = kwargs.get("value", 0)
return
def __or__(self, value):
return self.value | value
def __and__(self, value):
return self.value & value
def __xor__(self, value):
return self.value ^ value
def __eq__(self, value):
return self.value == value
def __ne__(self, value):
return self.value != value
def __str__(self):
perm_str = ""
perm_str += "r" if self & Permission.READ else "-"
perm_str += "w" if self & Permission.WRITE else "-"
perm_str += "x" if self & Permission.EXECUTE else "-"
return perm_str
@staticmethod
def from_info_sections(*args):
perm = Permission()
for arg in args:
if "READONLY" in arg:
perm.value += Permission.READ
if "DATA" in arg:
perm.value += Permission.WRITE
if "CODE" in arg:
perm.value += Permission.EXECUTE
return perm
@staticmethod
def from_process_maps(perm_str):
perm = Permission()
if perm_str[0] == "r":
perm.value += Permission.READ
if perm_str[1] == "w":
perm.value += Permission.WRITE
if perm_str[2] == "x":
perm.value += Permission.EXECUTE
return perm
class Section:
"""GEF representation of process memory sections."""
def __init__(self, *args, **kwargs):
self.page_start = kwargs.get("page_start")
self.page_end = kwargs.get("page_end")
self.offset = kwargs.get("offset")
self.permission = kwargs.get("permission")
self.inode = kwargs.get("inode")
self.path = kwargs.get("path")
return
def is_readable(self):
return self.permission.value and self.permission.value&Permission.READ
def is_writable(self):
return self.permission.value and self.permission.value&Permission.WRITE
def is_executable(self):
return self.permission.value and self.permission.value&Permission.EXECUTE
@property
def size(self):
if self.page_end is None or self.page_start is None:
return -1
return self.page_end - self.page_start
@property
def realpath(self):
# when in a `gef-remote` session, realpath returns the path to the binary on the local disk, not remote
return self.path if __gef_remote__ is None else "/tmp/gef/{:d}/{:s}".format(__gef_remote__, self.path)
Zone = collections.namedtuple("Zone", ["name", "zone_start", "zone_end", "filename"])
class Elf:
"""Basic ELF parsing.
Ref:
- http://www.skyfree.org/linux/references/ELF_Format.pdf
- http://refspecs.freestandards.org/elf/elfspec_ppc.pdf
- http://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi.html
"""
BIG_ENDIAN = 0
LITTLE_ENDIAN = 1
ELF_32_BITS = 0x01
ELF_64_BITS = 0x02
X86_64 = 0x3e
X86_32 = 0x03
ARM = 0x28
MIPS = 0x08
POWERPC = 0x14
POWERPC64 = 0x15
SPARC = 0x02
SPARC64 = 0x2b
AARCH64 = 0xb7
RISCV = 0xf3
ET_EXEC = 2
ET_DYN = 3
ET_CORE = 4
e_magic = b"\x7fELF"
e_class = ELF_32_BITS
e_endianness = LITTLE_ENDIAN
e_eiversion = None
e_osabi = None
e_abiversion = None
e_pad = None
e_type = ET_EXEC
e_machine = X86_32
e_version = None
e_entry = 0x00
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
def __init__(self, elf="", minimalist=False):
"""
Instantiate an ELF object. The default behavior is to create the object by parsing the ELF file.
But in some cases (QEMU-stub), we may just want a simple minimal object with default values."""
if minimalist:
return
if not os.access(elf, os.R_OK):
err("'{0}' not found/readable".format(elf))
err("Failed to get file debug information, most of gef features will not work")
return
with open(elf, "rb") as fd:
# off 0x0
self.e_magic, self.e_class, self.e_endianness, self.e_eiversion = struct.unpack(">IBBB", fd.read(7))
# adjust endianness in bin reading
endian = "<" if self.e_endianness == Elf.LITTLE_ENDIAN else ">"
# off 0x7
self.e_osabi, self.e_abiversion = struct.unpack("{}BB".format(endian), fd.read(2))
# off 0x9
self.e_pad = fd.read(7)
# off 0x10
self.e_type, self.e_machine, self.e_version = struct.unpack("{}HHI".format(endian), fd.read(8))
# off 0x18
if self.e_class == Elf.ELF_64_BITS:
# if arch 64bits
self.e_entry, self.e_phoff, self.e_shoff = struct.unpack("{}QQQ".format(endian), fd.read(24))
else:
# else arch 32bits
self.e_entry, self.e_phoff, self.e_shoff = struct.unpack("{}III".format(endian), fd.read(12))
self.e_flags, self.e_ehsize, self.e_phentsize, self.e_phnum = struct.unpack("{}HHHH".format(endian), fd.read(8))
self.e_shentsize, self.e_shnum, self.e_shstrndx = struct.unpack("{}HHH".format(endian), fd.read(6))
return
class Instruction:
"""GEF representation of a CPU instruction."""
def __init__(self, address, location, mnemo, operands):
self.address, self.location, self.mnemonic, self.operands = address, location, mnemo, operands
return
def __str__(self):
return "{:#10x} {:16} {:6} {:s}".format(self.address,
self.location,
self.mnemonic,
", ".join(self.operands))
def is_valid(self):
return "(bad)" not in self.mnemonic
class GlibcArena:
"""Glibc arena class
Ref: https://github.com/sploitfun/lsploits/blob/master/glibc/malloc/malloc.c#L1671 """
TCACHE_MAX_BINS = 0x40
def __init__(self, addr, name=__gef_default_main_arena__):
arena = gdb.parse_and_eval(addr)
malloc_state_t = cached_lookup_type("struct malloc_state")
self.__name = name
self.__arena = arena.cast(malloc_state_t)
self.__addr = long(arena.address)
return
def __getitem__(self, item):
return self.__arena[item]
def __getattr__(self, item):
return self.__arena[item]
def __int__(self):
return self.__addr
def tcachebin(self, i):
"""Return head chunk in tcache[i]."""
heap_base = HeapBaseFunction.heap_base()
addr = dereference(heap_base + 2*current_arch.ptrsize + self.TCACHE_MAX_BINS + i*current_arch.ptrsize)
if not addr:
return None
return GlibcChunk(long(addr))
def fastbin(self, i):
"""Return head chunk in fastbinsY[i]."""
addr = dereference_as_long(self.fastbinsY[i])
if addr == 0:
return None
return GlibcChunk(addr + 2 * current_arch.ptrsize)
def bin(self, i):
idx = i * 2
fd = dereference_as_long(self.bins[idx])
bw = dereference_as_long(self.bins[idx + 1])
return fd, bw
def get_next(self):
addr_next = dereference_as_long(self.next)
arena_main = GlibcArena(self.__name)
if addr_next == arena_main.__addr:
return None
return GlibcArena("*{:#x} ".format(addr_next))
def __str__(self):
top = dereference_as_long(self.top)
last_remainder = dereference_as_long(self.last_remainder)
n = dereference_as_long(self.next)
nfree = dereference_as_long(self.next_free)
sysmem = long(self.system_mem)
fmt = "Arena (base={:#x}, top={:#x}, last_remainder={:#x}, next={:#x}, next_free={:#x}, system_mem={:#x})"
return fmt.format(self.__addr, top, last_remainder, n, nfree, sysmem)
class GlibcChunk:
"""Glibc chunk class.
Ref: https://sploitfun.wordpress.com/2015/02/10/understanding-glibc-malloc/."""
def __init__(self, addr, from_base=False):
self.ptrsize = current_arch.ptrsize
if from_base:
self.chunk_base_address = addr
self.address = addr + 2 * self.ptrsize
else:
self.chunk_base_address = int(addr - 2 * self.ptrsize)
self.address = addr
self.size_addr = int(self.address - self.ptrsize)
self.prev_size_addr = self.chunk_base_address
return
def get_chunk_size(self):
return read_int_from_memory(self.size_addr) & (~0x03)
@property
def size(self):
return self.get_chunk_size()
def get_usable_size(self):
# https://github.com/sploitfun/lsploits/blob/master/glibc/malloc/malloc.c#L4537
cursz = self.get_chunk_size()
if cursz == 0: return cursz
if self.has_m_bit(): return cursz - 2 * self.ptrsize
return cursz - self.ptrsize
@property
def usable_size(self):
return self.get_usable_size()
def get_prev_chunk_size(self):
return read_int_from_memory(self.prev_size_addr)
def get_next_chunk(self):
addr = self.address + self.get_chunk_size()
return GlibcChunk(addr)
# if free-ed functions
def get_fwd_ptr(self):
return read_int_from_memory(self.address)
@property
def fwd(self):
return self.get_fwd_ptr()
fd = fwd # for compat
def get_bkw_ptr(self):
return read_int_from_memory(self.address + self.ptrsize)
@property
def bck(self):
return self.get_bkw_ptr()
bk = bck # for compat
# endif free-ed functions
def has_p_bit(self):
return read_int_from_memory(self.size_addr) & 0x01
def has_m_bit(self):
return read_int_from_memory(self.size_addr) & 0x02
def has_n_bit(self):
return read_int_from_memory(self.size_addr) & 0x04
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()
return True if next_chunk.has_p_bit() else False
def str_chunk_size_flag(self):
msg = []
msg.append("PREV_INUSE flag: {}".format(Color.greenify("On") if self.has_p_bit() else Color.redify("Off")))
msg.append("IS_MMAPPED flag: {}".format(Color.greenify("On") if self.has_m_bit() else Color.redify("Off")))
msg.append("NON_MAIN_ARENA flag: {}".format(Color.greenify("On") if self.has_n_bit() else Color.redify("Off")))
return "\n".join(msg)
def _str_sizes(self):
msg = []
failed = False
try:
msg.append("Chunk size: {0:d} ({0:#x})".format(self.get_chunk_size()))
msg.append("Usable size: {0:d} ({0:#x})".format(self.get_usable_size()))
failed = True
except gdb.MemoryError:
msg.append("Chunk size: Cannot read at {:#x} (corrupted?)".format(self.size_addr))
try:
msg.append("Previous chunk size: {0:d} ({0:#x})".format(self.get_prev_chunk_size()))
failed = True
except gdb.MemoryError:
msg.append("Previous chunk size: Cannot read at {:#x} (corrupted?)".format(self.chunk_base_address))
if failed:
msg.append(self.str_chunk_size_flag())
return "\n".join(msg)
def _str_pointers(self):
fwd = self.address
bkw = self.address + self.ptrsize
msg = []
try:
msg.append("Forward pointer: {0:#x}".format(self.get_fwd_ptr()))
except gdb.MemoryError:
msg.append("Forward pointer: {0:#x} (corrupted?)".format(fwd))
try:
msg.append("Backward pointer: {0:#x}".format(self.get_bkw_ptr()))
except gdb.MemoryError:
msg.append("Backward pointer: {0:#x} (corrupted?)".format(bkw))
return "\n".join(msg)
def str_as_alloced(self):
return self._str_sizes()
def str_as_freed(self):
return "{}\n\n{}".format(self._str_sizes(), self._str_pointers())
def flags_as_string(self):
flags = []
if self.has_p_bit():
flags.append(Color.colorify("PREV_INUSE", "red bold"))
if self.has_m_bit():
flags.append(Color.colorify("IS_MMAPPED", "red bold"))
if self.has_n_bit():
flags.append(Color.colorify("NON_MAIN_ARENA", "red bold"))
return "|".join(flags)
def __str__(self):
msg = "{:s}(addr={:#x}, size={:#x}, flags={:s})".format(Color.colorify("Chunk", "yellow bold underline"),
long(self.address),
self.get_chunk_size(),
self.flags_as_string())
return msg
def psprint(self):
msg = []
msg.append(str(self))
if self.is_used():
msg.append(self.str_as_alloced())
else:
msg.append(self.str_as_freed())
return "\n".join(msg) + "\n"
@lru_cache()
def get_libc_version():
sections = get_process_maps()
try:
for section in sections:
if "libc-" in section.path:
libc_version = tuple(int(_) for _ in
re.search(r"libc-(\d+)\.(\d+)\.so", section.path).groups())
break
else:
libc_version = 0, 0
except AttributeError:
libc_version = 0, 0
return libc_version
@lru_cache()
def get_main_arena():
try:
return GlibcArena(__gef_default_main_arena__)
except Exception as e:
err("Failed to get the main arena, heap commands may not work properly: {}".format(e))
return None
def titlify(text, color=None, msg_color=None):
"""Print a centered title."""
cols = get_terminal_size()[1]
nb = (cols - len(text) - 2)//2
if color is None:
color = __config__.get("theme.default_title_line")[0]
if msg_color is None:
msg_color = __config__.get("theme.default_title_message")[0]
msg = []
msg.append(Color.colorify("{} ".format(HORIZONTAL_LINE * nb), color))
msg.append(Color.colorify(text, msg_color))
msg.append(Color.colorify(" {}".format(HORIZONTAL_LINE * nb), color))
return "".join(msg)
def err(msg): return gef_print("{} {}".format(Color.colorify("[!]", "bold red"), msg))
def warn(msg): return gef_print("{} {}".format(Color.colorify("[*]", "bold yellow"), msg))
def ok(msg): return gef_print("{} {}".format(Color.colorify("[+]", "bold green"), msg))
def info(msg): return gef_print("{} {}".format(Color.colorify("[+]", "bold blue"), msg))
def push_context_message(level, message):
"""Push the message to be displayed the next time the context is invoked."""
global __context_messages__
if level not in ("error", "warn", "ok", "info"):
err("Invalid level '{}', discarding message".format(level))
return
__context_messages__.append((level, message))
return
def show_last_exception():
"""Display the last Python exception."""
def _show_code_line(fname, idx):
fname = os.path.expanduser(os.path.expandvars(fname))
__data = open(fname, "r").read().splitlines()
return __data[idx-1] if idx < len(__data) else ""
gef_print("")
exc_type, exc_value, exc_traceback = sys.exc_info()
gef_print(" Exception raised ".center(80, HORIZONTAL_LINE))
gef_print("{}: {}".format(Color.colorify(exc_type.__name__, "bold underline red"), exc_value))
gef_print(" Detailed stacktrace ".center(80, HORIZONTAL_LINE))
for fs in traceback.extract_tb(exc_traceback)[::-1]:
filename, lineno, method, code = fs
if not code or not code.strip():
code = _show_code_line(filename, lineno)
gef_print("""{} File "{}", line {:d}, in {}()""".format(DOWN_ARROW, Color.yellowify(filename),
lineno, Color.greenify(method)))
gef_print(" {} {}".format(RIGHT_ARROW, code))
gef_print(" Last 10 GDB commands ".center(80, HORIZONTAL_LINE))
gdb.execute("show commands")
gef_print(" Runtime environment ".center(80, HORIZONTAL_LINE))
gef_print("* GDB: {}".format(gdb.VERSION))
gef_print("* Python: {:d}.{:d}.{:d} - {:s}".format(sys.version_info.major, sys.version_info.minor,
sys.version_info.micro, sys.version_info.releaselevel))
gef_print("* OS: {:s} - {:s} ({:s}) on {:s}".format(platform.system(), platform.release(),
platform.architecture()[0],
" ".join(platform.dist()))) #pylint: disable=deprecated-method
gef_print(HORIZONTAL_LINE*80)
gef_print("")
return
def gef_pystring(x):
"""Python 2 & 3 compatibility function for strings handling."""
res = str(x, encoding="utf-8") if PYTHON_MAJOR == 3 else x
substs = [("\n","\\n"), ("\r","\\r"), ("\t","\\t"), ("\v","\\v"), ("\b","\\b"), ]
for x,y in substs: res = res.replace(x,y)
return res
def gef_pybytes(x):
"""Python 2 & 3 compatibility function for bytes handling."""
return bytes(str(x), encoding="utf-8") if PYTHON_MAJOR == 3 else x
@lru_cache()
def which(program):
"""Locate a command on the filesystem."""
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath = os.path.split(program)[0]
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 FileNotFoundError("Missing file `{:s}`".format(program))
def style_byte(b, color=True):
style = {
"nonprintable": "yellow",
"printable": "white",
"00": "gray",
"0a": "blue",
"ff": "green",
}
sbyte = "{:02x}".format(b)
if not color:
return sbyte
if sbyte in style:
st = style[sbyte]
elif chr(b) in (string.ascii_letters + string.digits + string.punctuation + " "):
st = style.get("printable")
else:
st = style.get("nonprintable")
if st:
sbyte = Color.colorify(sbyte, st)
return sbyte
def hexdump(source, length=0x10, separator=".", show_raw=False, base=0x00):
"""Return the hexdump of `src` argument.
@param source *MUST* be of type bytes or bytearray