forked from hugsy/gef
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gef.py
11367 lines (9183 loc) · 394 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.
#
# Since January 2020, GEF solely support GDB compiled with Python3 and was tested on
# * x86-32 & x86-64
# * arm v5,v6,v7
# * aarch64 (armv8)
# * mips & mips64
# * powerpc & powerpc64
# * sparc & sparc64(v9)
#
# For GEF with Python2 (only) support was moved to the GEF-Legacy
# (https://github.com/hugsy/gef-legacy)
#
# To start: in gdb, type `source /path/to/gef.py`
#
#######################################################################################
#
# gef is distributed under the MIT License (MIT)
# Copyright (c) 2013-2021 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.
import abc
import argparse
import binascii
import codecs
import collections
import ctypes
import functools
import hashlib
import importlib
import inspect
import itertools
import json
import os
import platform
import re
import shutil
import site
import socket
import string
import struct
import subprocess
import sys
import tempfile
import time
import traceback
import configparser
import xmlrpc.client as xmlrpclib
import warnings
from functools import lru_cache
from io import StringIO
from urllib.request import urlopen
LEFT_ARROW = " \u2190 "
RIGHT_ARROW = " \u2192 "
DOWN_ARROW = "\u21b3"
HORIZONTAL_LINE = "\u2500"
VERTICAL_LINE = "\u2502"
CROSS = "\u2718 "
TICK = "\u2713 "
BP_GLYPH = "\u25cf"
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)
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 master branch.
Return 0 on success, 1 on failure. """
ver = "dev" if "--dev" in argv[2:] else "master"
latest_gef_data = http_get("https://raw.githubusercontent.com/hugsy/gef/{}/scripts/gef.sh".format(ver,))
if latest_gef_data is None:
print("[-] Failed to get remote gef")
return 1
fd, fname = tempfile.mkstemp(suffix=".sh")
os.write(fd, latest_gef_data)
os.close(fd)
retcode = subprocess.run(["bash", fname, ver], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode
os.unlink(fname)
return retcode
try:
import gdb # pylint: disable=
except ImportError:
# if out of gdb, the only action allowed is to update gef.py
if len(sys.argv) == 2 and sys.argv[1].lower() in ("--update", "--upgrade"):
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_current_arena__ = "main_arena"
__gef_int_stream_buffer__ = None
__gef_redirect_output_fd__ = None
DEFAULT_PAGE_ALIGN_SHIFT = 12
DEFAULT_PAGE_SIZE = 1 << DEFAULT_PAGE_ALIGN_SHIFT
GEF_RC = os.getenv("GEF_RC") or 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 = tuple(map(int, re.search(r"(\d+)[^\d]+(\d+)", gdb.VERSION).groups()))
current_elf = None
current_arch = None
libc_args_definitions = {}
highlight_table = {}
ANSI_SPLIT_RE = r"(\033\[[\d;]*m)"
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."""
global __gef_current_arena__
for mod in dir(sys.modules["__main__"]):
obj = getattr(sys.modules["__main__"], mod)
if hasattr(obj, "cache_clear"):
obj.cache_clear()
__gef_current_arena__ = "main_arena"
return
def highlight_text(text):
"""
Highlight text using highlight_table { match -> color } settings.
If RegEx is enabled it will create a match group around all items in the
highlight_table and wrap the specified color in the highlight_table
around those matches.
If RegEx is disabled, split by ANSI codes and 'colorify' each match found
within the specified string.
"""
if not highlight_table:
return text
if get_gef_setting("highlight.regex"):
for match, color in highlight_table.items():
text = re.sub("(" + match + ")", Color.colorify("\\1", color), text)
return text
ansiSplit = re.split(ANSI_SPLIT_RE, text)
for match, color in highlight_table.items():
for index, val in enumerate(ansiSplit):
found = val.find(match)
if found > -1:
ansiSplit[index] = val.replace(match, Color.colorify(match, color))
break
text = "".join(ansiSplit)
ansiSplit = re.split(ANSI_SPLIT_RE, text)
return "".join(ansiSplit)
def gef_print(x="", *args, **kwargs):
"""Wrapper around print(), using string buffering feature."""
x = highlight_text(x)
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__, __gef_redirect_output_fd__
if __gef_int_stream_buffer__:
return f(*args, **kwargs)
__gef_int_stream_buffer__ = StringIO()
try:
rv = f(*args, **kwargs)
finally:
redirect = get_gef_setting("context.redirect")
if redirect.startswith("/dev/pts/"):
if not __gef_redirect_output_fd__:
# if the FD has never been open, open it
fd = open(redirect, "wt")
__gef_redirect_output_fd__ = fd
elif redirect != __gef_redirect_output_fd__.name:
# if the user has changed the redirect setting during runtime, update the state
__gef_redirect_output_fd__.close()
fd = open(redirect, "wt")
__gef_redirect_output_fd__ = fd
else:
# otherwise, keep using it
fd = __gef_redirect_output_fd__
else:
fd = sys.stdout
__gef_redirect_output_fd__ = None
if __gef_redirect_output_fd__ and fd.closed:
# if the tty was closed, revert back to stdout
fd = sys.stdout
__gef_redirect_output_fd__ = None
set_gef_setting("context.redirect", "")
fd.write(__gef_int_stream_buffer__.getvalue())
fd.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",
"light_gray" : "\033[0;37m",
"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 light_grayify(msg):return Color.colorify(msg, "light_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(int(self.value))
derefed = dereference(addr)
return None if derefed is None else int(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
"""
LITTLE_ENDIAN = 1
BIG_ENDIAN = 2
ELF_32_BITS = 0x01
ELF_64_BITS = 0x02
ELF_MAGIC = 0x7f454c46
X86_64 = 0x3e
X86_32 = 0x03
ARM = 0x28
MIPS = 0x08
POWERPC = 0x14
POWERPC64 = 0x15
SPARC = 0x02
SPARC64 = 0x2b
AARCH64 = 0xb7
RISCV = 0xf3
IA64 = 0x32
ET_RELOC = 1
ET_EXEC = 2
ET_DYN = 3
ET_CORE = 4
OSABI_SYSTEMV = 0x00
OSABI_HPUX = 0x01
OSABI_NETBSD = 0x02
OSABI_LINUX = 0x03
OSABI_SOLARIS = 0x06
OSABI_AIX = 0x07
OSABI_IRIX = 0x08
OSABI_FREEBSD = 0x09
OSABI_OPENBSD = 0x0C
e_magic = ELF_MAGIC
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
self.fd = open(elf, "rb")
# off 0x0
self.e_magic, self.e_class, self.e_endianness, self.e_eiversion = struct.unpack(">IBBB", self.read(7))
# adjust endianness in bin reading
endian = endian_str()
# off 0x7
self.e_osabi, self.e_abiversion = struct.unpack("{}BB".format(endian), self.read(2))
# off 0x9
self.e_pad = self.read(7)
# off 0x10
self.e_type, self.e_machine, self.e_version = struct.unpack("{}HHI".format(endian), self.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), self.read(24))
else:
# else arch 32bits
self.e_entry, self.e_phoff, self.e_shoff = struct.unpack("{}III".format(endian), self.read(12))
self.e_flags, self.e_ehsize, self.e_phentsize, self.e_phnum = struct.unpack("{}IHHH".format(endian), self.read(10))
self.e_shentsize, self.e_shnum, self.e_shstrndx = struct.unpack("{}HHH".format(endian), self.read(6))
self.phdrs = []
for i in range(self.e_phnum):
self.phdrs.append(Phdr(self, self.e_phoff + self.e_phentsize * i))
self.shdrs = []
for i in range(self.e_shnum):
self.shdrs.append(Shdr(self, self.e_shoff + self.e_shentsize * i))
if self.fd:
self.fd.close()
self.fd = None
return
def read(self, size):
return self.fd.read(size)
def seek(self, off):
self.fd.seek(off, 0)
def is_valid(self):
return self.e_magic == Elf.ELF_MAGIC
class Phdr:
PT_NULL = 0
PT_LOAD = 1
PT_DYNAMIC = 2
PT_INTERP = 3
PT_NOTE = 4
PT_SHLIB = 5
PT_PHDR = 6
PT_TLS = 7
PT_LOOS = 0x60000000
PT_GNU_EH_FRAME = 0x6474e550
PT_GNU_STACK = 0x6474e551
PT_GNU_RELRO = 0x6474e552
PT_LOSUNW = 0x6ffffffa
PT_SUNWBSS = 0x6ffffffa
PT_SUNWSTACK = 0x6ffffffb
PT_HISUNW = 0x6fffffff
PT_HIOS = 0x6fffffff
PT_LOPROC = 0x70000000
PT_HIPROC = 0x7fffffff
PF_X = 1
PF_W = 2
PF_R = 4
p_type = None
p_flags = None
p_offset = None
p_vaddr = None
p_paddr = None
p_filesz = None
p_memsz = None
p_align = None
def __init__(self, elf, off):
if not elf:
return None
elf.seek(off)
endian = endian_str()
if elf.e_class == Elf.ELF_64_BITS:
self.p_type, self.p_flags, self.p_offset = struct.unpack("{}IIQ".format(endian), elf.read(16))
self.p_vaddr, self.p_paddr = struct.unpack("{}QQ".format(endian), elf.read(16))
self.p_filesz, self.p_memsz, self.p_align = struct.unpack("{}QQQ".format(endian), elf.read(24))
else:
self.p_type, self.p_offset = struct.unpack("{}II".format(endian), elf.read(8))
self.p_vaddr, self.p_paddr = struct.unpack("{}II".format(endian), elf.read(8))
self.p_filesz, self.p_memsz, self.p_flags, self.p_align = struct.unpack("{}IIII".format(endian), elf.read(16))
class Shdr:
SHT_NULL = 0
SHT_PROGBITS = 1
SHT_SYMTAB = 2
SHT_STRTAB = 3
SHT_RELA = 4
SHT_HASH = 5
SHT_DYNAMIC = 6
SHT_NOTE = 7
SHT_NOBITS = 8
SHT_REL = 9
SHT_SHLIB = 10
SHT_DYNSYM = 11
SHT_NUM = 12
SHT_INIT_ARRAY = 14
SHT_FINI_ARRAY = 15
SHT_PREINIT_ARRAY = 16
SHT_GROUP = 17
SHT_SYMTAB_SHNDX = 18
SHT_NUM = 19
SHT_LOOS = 0x60000000
SHT_GNU_ATTRIBUTES = 0x6ffffff5
SHT_GNU_HASH = 0x6ffffff6
SHT_GNU_LIBLIST = 0x6ffffff7
SHT_CHECKSUM = 0x6ffffff8
SHT_LOSUNW = 0x6ffffffa
SHT_SUNW_move = 0x6ffffffa
SHT_SUNW_COMDAT = 0x6ffffffb
SHT_SUNW_syminfo = 0x6ffffffc
SHT_GNU_verdef = 0x6ffffffd
SHT_GNU_verneed = 0x6ffffffe
SHT_GNU_versym = 0x6fffffff
SHT_HISUNW = 0x6fffffff
SHT_HIOS = 0x6fffffff
SHT_LOPROC = 0x70000000
SHT_HIPROC = 0x7fffffff
SHT_LOUSER = 0x80000000
SHT_HIUSER = 0x8fffffff
SHF_WRITE = 1
SHF_ALLOC = 2
SHF_EXECINSTR = 4
SHF_MERGE = 0x10
SHF_STRINGS = 0x20
SHF_INFO_LINK = 0x40
SHF_LINK_ORDER = 0x80
SHF_OS_NONCONFORMING = 0x100
SHF_GROUP = 0x200
SHF_TLS = 0x400
SHF_COMPRESSED = 0x800
SHF_RELA_LIVEPATCH = 0x00100000
SHF_RO_AFTER_INIT = 0x00200000
SHF_ORDERED = 0x40000000
SHF_EXCLUDE = 0x80000000
sh_name = None
sh_type = None
sh_flags = None
sh_addr = None
sh_offset = None
sh_size = None
sh_link = None
sh_info = None
sh_addralign = None
sh_entsize = None
def __init__(self, elf, off):
if elf is None:
return None
elf.seek(off)
endian = endian_str()
if elf.e_class == Elf.ELF_64_BITS:
self.sh_name, self.sh_type, self.sh_flags = struct.unpack("{}IIQ".format(endian), elf.read(16))
self.sh_addr, self.sh_offset = struct.unpack("{}QQ".format(endian), elf.read(16))
self.sh_size, self.sh_link, self.sh_info = struct.unpack("{}QII".format(endian), elf.read(16))
self.sh_addralign, self.sh_entsize = struct.unpack("{}QQ".format(endian), elf.read(16))
else:
self.sh_name, self.sh_type, self.sh_flags = struct.unpack("{}III".format(endian), elf.read(12))
self.sh_addr, self.sh_offset = struct.unpack("{}II".format(endian), elf.read(8))
self.sh_size, self.sh_link, self.sh_info = struct.unpack("{}III".format(endian), elf.read(12))
self.sh_addralign, self.sh_entsize = struct.unpack("{}II".format(endian), elf.read(8))
stroff = elf.e_shoff + elf.e_shentsize * elf.e_shstrndx
if elf.e_class == Elf.ELF_64_BITS:
elf.seek(stroff + 16 + 8)
offset = struct.unpack("{}Q".format(endian), elf.read(8))[0]
else:
elf.seek(stroff + 12 + 4)
offset = struct.unpack("{}I".format(endian), elf.read(4))[0]
elf.seek(offset + self.sh_name)
self.sh_name = ""
while True:
c = ord(elf.read(1))
if c == 0:
break
self.sh_name += chr(c)
return
class Instruction:
"""GEF representation of a CPU instruction."""
def __init__(self, address, location, mnemo, operands, opcodes):
self.address, self.location, self.mnemonic, self.operands, self.opcodes = address, location, mnemo, operands, opcodes
return
# Allow formatting an instruction with {:o} to show opcodes.
# The number of bytes to display can be configured, e.g. {:4o} to only show 4 bytes of the opcodes
def __format__(self, format_spec):
if len(format_spec) == 0 or format_spec[-1] != "o":
return str(self)
if format_spec == "o":
opcodes_len = len(self.opcodes)
else:
opcodes_len = int(format_spec[:-1])
opcodes_text = "".join("{:02x}".format(b) for b in self.opcodes[:opcodes_len])
if opcodes_len < len(self.opcodes):
opcodes_text += "..."
return "{:#10x} {:{:d}} {:16} {:6} {:s}".format(self.address,
opcodes_text,
opcodes_len * 2 + 3,
self.location,
self.mnemonic,
", ".join(self.operands))
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
@lru_cache()
def search_for_main_arena():
global __gef_current_arena__
malloc_hook_addr = parse_address("(void *)&__malloc_hook")
if is_x86():
addr = align_address_to_size(malloc_hook_addr + current_arch.ptrsize, 0x20)
elif is_arch(Elf.AARCH64) or is_arch(Elf.ARM):
addr = malloc_hook_addr - current_arch.ptrsize*2 - MallocStateStruct("*0").struct_size
else:
raise OSError("Cannot find main_arena for {}".format(current_arch.arch))
__gef_current_arena__ = "*0x{:x}".format(addr)
return addr
class MallocStateStruct:
"""GEF representation of malloc_state from https://github.com/bminor/glibc/blob/glibc-2.28/malloc/malloc.c#L1658"""
def __init__(self, addr):
try:
self.__addr = parse_address("&{}".format(addr))
except gdb.error:
warn("Could not parse address '&{}' when searching malloc_state struct, "
"using '&main_arena' instead".format(addr))
self.__addr = search_for_main_arena()
self.num_fastbins = 10
self.num_bins = 254
self.int_size = cached_lookup_type("int").sizeof
self.size_t = cached_lookup_type("size_t")
if not self.size_t:
ptr_type = "unsigned long" if current_arch.ptrsize == 8 else "unsigned int"
self.size_t = cached_lookup_type(ptr_type)
# Account for separation of have_fastchunks flag into its own field
# within the malloc_state struct in GLIBC >= 2.27
# https://sourceware.org/git/?p=glibc.git;a=commit;h=e956075a5a2044d05ce48b905b10270ed4a63e87
# Be aware you could see this change backported into GLIBC release
# branches.
if get_libc_version() >= (2, 27):
self.fastbin_offset = align_address_to_size(self.int_size * 3, 8)
else:
self.fastbin_offset = self.int_size * 2
return
# struct offsets
@property
def addr(self):
return self.__addr
@property
def fastbins_addr(self):
return self.__addr + self.fastbin_offset
@property
def top_addr(self):
return self.fastbins_addr + self.num_fastbins * current_arch.ptrsize
@property
def last_remainder_addr(self):
return self.top_addr + current_arch.ptrsize
@property
def bins_addr(self):
return self.last_remainder_addr + current_arch.ptrsize
@property
def next_addr(self):
return self.bins_addr + self.num_bins * current_arch.ptrsize + self.int_size * 4
@property
def next_free_addr(self):
return self.next_addr + current_arch.ptrsize
@property
def system_mem_addr(self):
return self.next_free_addr + current_arch.ptrsize * 2
@property
def struct_size(self):
return self.system_mem_addr + current_arch.ptrsize * 2 - self.__addr
# struct members
@property
def fastbinsY(self):
return self.get_size_t_array(self.fastbins_addr, self.num_fastbins)
@property
def top(self):
return self.get_size_t_pointer(self.top_addr)
@property
def last_remainder(self):
return self.get_size_t_pointer(self.last_remainder_addr)
@property
def bins(self):
return self.get_size_t_array(self.bins_addr, self.num_bins)
@property
def next(self):
return self.get_size_t_pointer(self.next_addr)
@property
def next_free(self):
return self.get_size_t_pointer(self.next_free_addr)
@property
def system_mem(self):
return self.get_size_t(self.system_mem_addr)
# helper methods
def get_size_t(self, addr):
return dereference(addr).cast(self.size_t)
def get_size_t_pointer(self, addr):
size_t_pointer = self.size_t.pointer()
return dereference(addr).cast(size_t_pointer)
def get_size_t_array(self, addr, length):
size_t_array = self.size_t.array(length)
return dereference(addr).cast(size_t_array)
def __getitem__(self, item):
return getattr(self, item)
class GlibcHeapInfo:
"""Glibc heap_info struct
See https://github.com/bminor/glibc/blob/glibc-2.34/malloc/arena.c#L64"""
def __init__(self, addr):
self.__addr = addr if type(addr) is int else parse_address(addr)
self.size_t = cached_lookup_type("size_t")
if not self.size_t:
ptr_type = "unsigned long" if current_arch.ptrsize == 8 else "unsigned int"
self.size_t = cached_lookup_type(ptr_type)
@property
def addr(self):
return self.__addr
@property
def ar_ptr_addr(self):
return self.addr
@property
def prev_addr(self):
return self.ar_ptr_addr + current_arch.ptrsize
@property
def size_addr(self):
return self.prev_addr + current_arch.ptrsize
@property
def mprotect_size_addr(self):
return self.size_addr + self.size_t.sizeof
@property
def ar_ptr(self):
return self._get_size_t_pointer(self.ar_ptr_addr)
@property
def prev(self):
return self._get_size_t_pointer(self.prev_addr)
@property
def size(self):
return self._get_size_t(self.size_addr)
@property
def mprotect_size(self):
return self._get_size_t(self.mprotect_size_addr)
# helper methods
def _get_size_t_pointer(self, addr):
size_t_pointer = self.size_t.pointer()
return dereference(addr).cast(size_t_pointer)
def _get_size_t(self, addr):
return dereference(addr).cast(self.size_t)
class GlibcArena:
"""Glibc arena class
Ref: https://github.com/sploitfun/lsploits/blob/master/glibc/malloc/malloc.c#L1671"""
def __init__(self, addr, name=None):
self.__name = name or __gef_current_arena__
try:
arena = gdb.parse_and_eval(addr)
malloc_state_t = cached_lookup_type("struct malloc_state")
self.__arena = arena.cast(malloc_state_t)
self.__addr = int(arena.address)
self.struct_size = malloc_state_t.sizeof
except:
self.__arena = MallocStateStruct(addr)
self.__addr = self.__arena.addr
try:
self.top = int(self.top)
self.last_remainder = int(self.last_remainder)
self.n = int(self.next)
self.nfree = int(self.next_free)
self.sysmem = int(self.system_mem)
except gdb.error as e:
err("Glibc arena: {}".format(e))
return
def __getitem__(self, item):
return self.__arena[item]
def __getattr__(self, item):
return self.__arena[item]
def __int__(self):
return self.__addr