-
Notifications
You must be signed in to change notification settings - Fork 0
/
gef.py
executable file
·8610 lines (6938 loc) · 296 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
# -*- 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 array
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 resource
import socket
import string
import struct
import subprocess
import sys
import tempfile
import termios
import time
import traceback
import types
PYTHON_MAJOR = sys.version_info[0]
if PYTHON_MAJOR == 2:
from HTMLParser import HTMLParser
from cStringIO import StringIO
from urllib import urlopen
import ConfigParser as configparser
import xmlrpclib
# Compat Py2/3 hacks
range = xrange
FileNotFoundError = IOError
ConnectionRefusedError = socket.error
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
from io import StringIO
from urllib.request import urlopen
import configparser
import xmlrpc.client as xmlrpclib
# 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__ = []
__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
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
___default_aliases___ = {
# WinDBG style breakpoints
"bl" : "info breakpoints",
"bc" : "delete breakpoints",
"bp" : "break",
"bd" : "disable breakpoints",
"be" : "enable breakpoints",
"da" : "x/s",
"tbp" : "tbreak",
"pa" : "advance",
"ptc" : "finish",
"uf" : "disassemble",
"kp" : "info stack",
}
GDB_MIN_VERSION = (7, 7)
GDB_VERSION_MAJOR, GDB_VERSION_MINOR = [int(_) for _ in gdb.VERSION.split(".")[:2]]
GDB_VERSION = (GDB_VERSION_MAJOR, GDB_VERSION_MINOR)
current_elf = None
current_arch = None
qemu_mode = False
if PYTHON_MAJOR==3:
lru_cache = functools.lru_cache
else:
def lru_cache(maxsize = 128):
"""Portage 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()
qemu_mode = False
return
class Color:
"""Colorify class."""
colors = {
"normal" : "\033[0m",
"gray" : "\033[1;30m",
"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."""
if get_gef_setting("gef.disable_color")==True: return text
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 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, attrs=code_color)
if self.is_in_heap_segment():
return Color.colorify(value, attrs=heap_color)
if self.is_in_stack_segment():
return Color.colorify(value, attrs=stack_color)
return value
def is_in_text_segment(self):
return (hasattr(self.info, "name") and ".text" in self.info.name) or \
(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, *args, **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."""
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.get(attr)
setattr(self, attr, value)
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
class Zone:
name = None
zone_start = None
zone_end = None
filename = None
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
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):
"""Instanciates an Elf object. The default behavior is to create the object by parsing the ELF file on FS.
But on some cases (QEMU-stub), we may just want a simply 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 instruction."""
def __init__(self, address, location, mnemo, operands):
self.address, self.location, self.mnemo, self.operands = address, location, mnemo, operands
return
def __str__(self):
return "{:#10x} {:16} {:6} {:s}".format(self.address,
self.location,
self.mnemo,
", ".join(self.operands))
def is_valid(self):
return "(bad)" not in self.mnemo
class GlibcArena:
"""Glibc arena class
Ref: https://github.com/sploitfun/lsploits/blob/master/glibc/malloc/malloc.c#L1671 """
def __init__(self, addr):
arena = gdb.parse_and_eval(addr)
malloc_state_t = cached_lookup_type("struct malloc_state")
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 dereference_as_long(self, addr):
derefed = dereference(addr)
return long(derefed.address) if derefed is not None else 0
def fastbin(self, i):
addr = self.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 = self.dereference_as_long(self.bins[idx])
bw = self.dereference_as_long(self.bins[idx + 1])
return fd, bw
def get_next(self):
addr_next = self.dereference_as_long(self.next)
arena_main = GlibcArena("main_arena")
if addr_next == arena_main.__addr:
return None
return GlibcArena("*{:#x} ".format(addr_next))
def __str__(self):
top = self.dereference_as_long(self.top)
last_remainder = self.dereference_as_long(self.last_remainder)
n = self.dereference_as_long(self.next)
nfree = self.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.start_addr = addr
self.addr = addr + 2 * self.ptrsize
else:
self.start_addr = int(addr - 2 * self.ptrsize)
self.addr = addr
self.size_addr = int(self.addr - self.ptrsize)
self.prev_size_addr = self.start_addr
return
def get_chunk_size(self):
return read_int_from_memory(self.size_addr) & (~0x03)
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
def get_prev_chunk_size(self):
return read_int_from_memory(self.prev_size_addr)
def get_next_chunk(self):
addr = self.addr + self.get_chunk_size()
return GlibcChunk(addr)
# if free-ed functions
def get_fwd_ptr(self):
return read_int_from_memory(self.addr)
@property
def fwd(self):
return self.get_fwd_ptr()
def get_bkw_ptr(self):
return read_int_from_memory(self.addr + self.ptrsize)
@property
def bck(self):
return self.get_bkw_ptr()
# endif free-ed functions
def has_P_bit(self):
"""Check for in PREV_INUSE bit
Ref: https://github.com/sploitfun/lsploits/blob/master/glibc/malloc/malloc.c#L1267"""
return read_int_from_memory(self.size_addr) & 0x01
def has_M_bit(self):
"""Check for in IS_MMAPPED bit
Ref: https://github.com/sploitfun/lsploits/blob/master/glibc/malloc/malloc.c#L1274"""
return read_int_from_memory(self.size_addr) & 0x02
def has_N_bit(self):
"""Check for in NON_MAIN_ARENA bit.
Ref: https://github.com/sploitfun/lsploits/blob/master/glibc/malloc/malloc.c#L1283"""
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.start_addr))
if failed:
msg.append(self.str_chunk_size_flag())
return "\n".join(msg)
def _str_pointers(self):
fwd = self.addr
bkw = self.addr + 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", attrs="red bold"))
if self.has_M_bit():
flags.append(Color.colorify("IS_MMAPPED", attrs="red bold"))
if self.has_N_bit():
flags.append(Color.colorify("NON_MAIN_ARENA", attrs="red bold"))
return "|".join(flags)
def __str__(self):
msg = "{:s}(addr={:#x}, size={:#x}, flags={:s})".format(Color.colorify("Chunk", attrs="yellow bold underline"),
long(self.addr),self.get_chunk_size(), self.flags_as_string())
return msg
def pprint(self):
msg = []
msg.append(str(self))
if self.is_used():
msg.append(self.str_as_alloced())
else:
msg.append(self.str_as_freed())
gdb.write("\n".join(msg) + "\n")
gdb.flush()
return
@lru_cache()
def get_main_arena():
try:
return GlibcArena("main_arena")
except Exception as e:
err("Failed to get `main_arena` symbol, heap commands may not work properly: {}".format(e))
warn("Did you install `libc6-dbg`?")
return None
def titlify(text, color=None, msg_color=None):
"""Print a title."""
cols = get_terminal_size()[1]
nb = (cols - len(text) - 4)//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(horizontal_line * nb + '[ ', attrs=color))
msg.append(Color.colorify(text, attrs=msg_color))
msg.append(Color.colorify(' ]' + horizontal_line * nb, attrs=color))
return "".join(msg)
def _xlog(text, stream, cr=True):
"""Logging core function."""
text += "\n" if cr else ""
gdb.write(text, stream)
if cr:
gdb.flush()
return 0
def err(msg, cr=True): return _xlog("{} {}".format(Color.colorify("[!]", attrs="bold red"), msg), gdb.STDERR, cr)
def warn(msg, cr=True): return _xlog("{} {}".format(Color.colorify("[*]", attrs="bold yellow"), msg), gdb.STDLOG, cr)
def ok(msg, cr=True): return _xlog("{} {}".format(Color.colorify("[+]", attrs="bold green"), msg), gdb.STDLOG, cr)
def info(msg, cr=True): return _xlog("{} {}".format(Color.colorify("[+]", attrs="bold blue"), msg), gdb.STDLOG, cr)
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 ""
print("")
exc_type, exc_value, exc_traceback = sys.exc_info()
print(" Exception raised ".center(80, horizontal_line))
print("{}: {}".format(Color.colorify(exc_type.__name__, attrs="bold underline red"), exc_value))
print(" Detailed stacktrace ".center(80, horizontal_line))
for fs in traceback.extract_tb(exc_traceback)[::-1]:
if PYTHON_MAJOR==2:
filename, lineno, method, code = fs
else:
filename, lineno, method, code = fs.filename, fs.lineno, fs.name, fs.line
if not code or len(code.strip())==0:
code = _show_code_line(filename, lineno)
print("""{} File "{}", line {:d}, in {}()""".format(down_arrow, Color.yellowify(filename),
lineno, Color.greenify(method)))
print(" {} {}".format(right_arrow, code))
print(" Last 10 GDB commands ".center(80, horizontal_line))
gdb.execute("show commands")
print(" Runtime environment ".center(80, horizontal_line))
print("* GDB: {}".format(gdb.VERSION))
print("* Python: {:d}.{:d}.{:d} - {:s}".format(sys.version_info.major, sys.version_info.minor,
sys.version_info.micro, sys.version_info.releaselevel))
print("* OS: {:s} - {:s} ({:s}) on {:s}".format(platform.system(), platform.release(),
platform.architecture()[0],
" ".join(platform.dist())))
print(horizontal_line*80)
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 FS."""
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 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
@param length is the length of items per line
@param separator is the default character to use if one byte is not printable
@param show_raw if True, do not add the line nor the text translation
@param base is the start address of the block being hexdump
@param func is the function to use to parse bytes (int for Py3, chr for Py2)
@return a string with the hexdump """
result = []
align = get_memory_alignment()*2+2 if is_alive() else 18
for i in range(0, len(source), length):
chunk = bytearray(source[i:i + length])
hexa = " ".join(["{:02x}".format(b) for b in chunk])
if show_raw:
result.append(hexa)
continue
text = "".join([chr(b) if 0x20 <= b < 0x7F else separator for b in chunk])
sym = gdb_get_location_from_symbol(base+i)
sym = "<{:s}+{:04x}>".format(*sym) if sym else ''
result.append("{addr:#0{aw}x} {sym} {data:<{dw}} {text}".format(aw=align,
addr=base+i,
sym=sym,
dw=3*length,
data=hexa,
text=text))
return "\n".join(result)
def is_debug():
"""Checks if debug mode is enabled."""
return get_gef_setting("gef.debug") == True
def disable_context(): set_gef_setting("context.enable", False)
def enable_context(): set_gef_setting("context.enable", True)
def enable_redirect_output(to_file="/dev/null"):
"""Redirect all GDB output to `to_file` parameter. By default, `to_file` redirects to `/dev/null`."""
gdb.execute("set logging overwrite")
gdb.execute("set logging file {:s}".format(to_file))
gdb.execute("set logging redirect on")
gdb.execute("set logging on")
return
def disable_redirect_output():
"""Disable the output redirection, if any."""
gdb.execute("set logging redirect off")
gdb.execute("set logging off")
return
def get_gef_setting(name):
"""Read globally gef settings. Returns None if not found. A valid config setting can never return None,
but False, 0 or "". So using None as a retval on error is fine."""
global __config__
key = __config__.get(name, None)
if not key:
return None
return __config__[name][0]
def set_gef_setting(name, value, _type=None, _desc=None):
"""Set globally gef settings. Raise ValueError if `name` doesn't exist and `type` and `desc`
are not provided."""
global __config__
if name not in __config__: