-
Notifications
You must be signed in to change notification settings - Fork 3
/
.gdbinit-gef.py
10900 lines (8804 loc) · 381 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
#######################################################################################
# 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-2022 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 configparser
import ctypes
import enum
import functools
import hashlib
import importlib
import inspect
import itertools
import json
import os
import pathlib
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 warnings
from functools import lru_cache
from io import StringIO, TextIOWrapper
from types import ModuleType
from typing import (Any, ByteString, Callable, Dict, Generator, Iterable,
Iterator, List, NoReturn, Optional, Sequence, Set, Tuple, Type,
Union)
from urllib.request import urlopen
def http_get(url: str) -> Optional[bytes]:
"""Basic HTTP wrapper for GET request. Return the body of the page if HTTP code is OK,
otherwise return None."""
try:
http = urlopen(url)
return http.read() if http.getcode() == 200 else None
except Exception:
return None
def update_gef(argv: List[str]) -> int:
"""Try to update `gef` to the latest version pushed on GitHub main branch.
Return 0 on success, 1 on failure. """
ver = "dev" if "--dev" in argv else GEF_DEFAULT_BRANCH
latest_gef_data = http_get(f"https://raw.githubusercontent.com/hugsy/gef/{ver}/scripts/gef.sh")
if not latest_gef_data:
print("[-] Failed to get remote gef")
return 1
with tempfile.NamedTemporaryFile(suffix=".sh") as fd:
fd.write(latest_gef_data)
fd.flush()
fpath = pathlib.Path(fd.name)
return subprocess.run(["bash", fpath, ver], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL).returncode
try:
import gdb # type:ignore
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[2:]))
print("[-] gef cannot run as standalone")
sys.exit(0)
GDB_MIN_VERSION = (8, 0)
GDB_VERSION = tuple(map(int, re.search(r"(\d+)[^\d]+(\d+)", gdb.VERSION).groups()))
PYTHON_MIN_VERSION = (3, 6)
PYTHON_VERSION = sys.version_info[0:2]
DEFAULT_PAGE_ALIGN_SHIFT = 12
DEFAULT_PAGE_SIZE = 1 << DEFAULT_PAGE_ALIGN_SHIFT
GEF_RC = (pathlib.Path(os.getenv("GEF_RC", "")).absolute()
if os.getenv("GEF_RC")
else pathlib.Path().home() / ".gef.rc")
GEF_TEMP_DIR = os.path.join(tempfile.gettempdir(), "gef")
GEF_MAX_STRING_LENGTH = 50
LIBC_HEAP_MAIN_ARENA_DEFAULT_NAME = "main_arena"
ANSI_SPLIT_RE = r"(\033\[[\d;]*m)"
LEFT_ARROW = " ← "
RIGHT_ARROW = " → "
DOWN_ARROW = "↳"
HORIZONTAL_LINE = "─"
VERTICAL_LINE = "│"
CROSS = "✘ "
TICK = "✓ "
BP_GLYPH = "●"
GEF_PROMPT = "gef➤ "
GEF_PROMPT_ON = f"\001\033[1;32m\002{GEF_PROMPT}\001\033[0m\002"
GEF_PROMPT_OFF = f"\001\033[1;31m\002{GEF_PROMPT}\001\033[0m\002"
PATTERN_LIBC_VERSION = re.compile(rb"glibc (\d+)\.(\d+)")
GEF_DEFAULT_BRANCH = "main"
GEF_EXTRAS_DEFAULT_BRANCH = "main"
gef : "Gef"
__registered_commands__ : List[Type["GenericCommand"]] = []
__registered_functions__ : List[Type["GenericFunction"]] = []
__registered_architectures__ : Dict[Union["Elf.Abi", str], Type["Architecture"]] = {}
__registered_file_formats__ : Set[ Type["FileFormat"] ] = set()
def reset_all_caches() -> None:
"""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()
gef.reset_caches()
return
def reset() -> None:
global gef
arch = None
if "gef" in locals().keys():
reset_all_caches()
arch = gef.arch
del gef
gef = Gef()
gef.setup()
if arch:
gef.arch = arch
return
def highlight_text(text: str) -> str:
"""
Highlight text using `gef.ui.highlight_table` { match -> color } settings.
If RegEx is enabled it will create a match group around all items in the
`gef.ui.highlight_table` and wrap the specified color in the `gef.ui.highlight_table`
around those matches.
If RegEx is disabled, split by ANSI codes and 'colorify' each match found
within the specified string.
"""
global gef
if not gef.ui.highlight_table:
return text
if gef.config["highlight.regex"]:
for match, color in gef.ui.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 gef.ui.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(*args: str, end="\n", sep=" ", **kwargs: Any) -> None:
"""Wrapper around print(), using string buffering feature."""
parts = [highlight_text(a) for a in args]
if gef.ui.stream_buffer and not is_debug():
gef.ui.stream_buffer.write(sep.join(parts) + end)
return
print(*parts, sep=sep, end=end, **kwargs)
return
def bufferize(f: Callable) -> Callable:
"""Store the content to be printed for a function in memory, and flush it on function exit."""
@functools.wraps(f)
def wrapper(*args: Any, **kwargs: Any) -> Any:
global gef
if gef.ui.stream_buffer:
return f(*args, **kwargs)
gef.ui.stream_buffer = StringIO()
try:
rv = f(*args, **kwargs)
finally:
redirect = gef.config["context.redirect"]
if redirect.startswith("/dev/pts/"):
if not gef.ui.redirect_fd:
# if the FD has never been open, open it
fd = open(redirect, "wt")
gef.ui.redirect_fd = fd
elif redirect != gef.ui.redirect_fd.name:
# if the user has changed the redirect setting during runtime, update the state
gef.ui.redirect_fd.close()
fd = open(redirect, "wt")
gef.ui.redirect_fd = fd
else:
# otherwise, keep using it
fd = gef.ui.redirect_fd
else:
fd = sys.stdout
gef.ui.redirect_fd = None
if gef.ui.redirect_fd and fd.closed:
# if the tty was closed, revert back to stdout
fd = sys.stdout
gef.ui.redirect_fd = None
gef.config["context.redirect"] = ""
fd.write(gef.ui.stream_buffer.getvalue())
fd.flush()
gef.ui.stream_buffer = None
return rv
return wrapper
#
# Helpers
#
def p8(x: int, s: bool = False, e: Optional["Endianness"] = None) -> bytes:
"""Pack one byte respecting the current architecture endianness."""
endian = e or gef.arch.endianness
return struct.pack(f"{endian}B", x) if not s else struct.pack(f"{endian:s}b", x)
def p16(x: int, s: bool = False, e: Optional["Endianness"] = None) -> bytes:
"""Pack one word respecting the current architecture endianness."""
endian = e or gef.arch.endianness
return struct.pack(f"{endian}H", x) if not s else struct.pack(f"{endian:s}h", x)
def p32(x: int, s: bool = False, e: Optional["Endianness"] = None) -> bytes:
"""Pack one dword respecting the current architecture endianness."""
endian = e or gef.arch.endianness
return struct.pack(f"{endian}I", x) if not s else struct.pack(f"{endian:s}i", x)
def p64(x: int, s: bool = False, e: Optional["Endianness"] = None) -> bytes:
"""Pack one qword respecting the current architecture endianness."""
endian = e or gef.arch.endianness
return struct.pack(f"{endian}Q", x) if not s else struct.pack(f"{endian:s}q", x)
def u8(x: bytes, s: bool = False, e: Optional["Endianness"] = None) -> int:
"""Unpack one byte respecting the current architecture endianness."""
endian = e or gef.arch.endianness
return struct.unpack(f"{endian}B", x)[0] if not s else struct.unpack(f"{endian:s}b", x)[0]
def u16(x: bytes, s: bool = False, e: Optional["Endianness"] = None) -> int:
"""Unpack one word respecting the current architecture endianness."""
endian = e or gef.arch.endianness
return struct.unpack(f"{endian}H", x)[0] if not s else struct.unpack(f"{endian:s}h", x)[0]
def u32(x: bytes, s: bool = False, e: Optional["Endianness"] = None) -> int:
"""Unpack one dword respecting the current architecture endianness."""
endian = e or gef.arch.endianness
return struct.unpack(f"{endian}I", x)[0] if not s else struct.unpack(f"{endian:s}i", x)[0]
def u64(x: bytes, s: bool = False, e: Optional["Endianness"] = None) -> int:
"""Unpack one qword respecting the current architecture endianness."""
endian = e or gef.arch.endianness
return struct.unpack(f"{endian}Q", x)[0] if not s else struct.unpack(f"{endian:s}q", x)[0]
def is_ascii_string(address: int) -> bool:
"""Helper function to determine if the buffer pointed by `address` is an ASCII string (in GDB)"""
try:
return gef.memory.read_ascii_string(address) is not None
except Exception:
return False
def is_alive() -> bool:
"""Check if GDB is running."""
try:
return gdb.selected_inferior().pid > 0
except Exception:
return False
#
# Decorators
#
def only_if_gdb_running(f: Callable) -> Callable:
"""Decorator wrapper to check if GDB is running."""
@functools.wraps(f)
def wrapper(*args: Any, **kwargs: Any) -> Any:
if is_alive():
return f(*args, **kwargs)
else:
warn("No debugging session active")
return wrapper
def only_if_gdb_target_local(f: Callable) -> Callable:
"""Decorator wrapper to check if GDB is running locally (target not remote)."""
@functools.wraps(f)
def wrapper(*args: Any, **kwargs: Any) -> Any:
if not is_remote_debug():
return f(*args, **kwargs)
else:
warn("This command cannot work for remote sessions.")
return wrapper
def deprecated(solution: str = "") -> Callable:
"""Decorator to add a warning when a command is obsolete and will be removed."""
def decorator(f: Callable) -> Callable:
@functools.wraps(f)
def wrapper(*args: Any, **kwargs: Any) -> Any:
caller = inspect.stack()[1]
caller_file = pathlib.Path(caller.filename)
caller_loc = caller.lineno
msg = f"{caller_file.name}:L{caller_loc} '{f.__name__}' is deprecated and will be removed in a feature release. "
if not gef:
print(msg)
elif gef.config["gef.show_deprecation_warnings"] is True:
if solution:
msg += solution
warn(msg)
return f(*args, **kwargs)
if not wrapper.__doc__:
wrapper.__doc__ = ""
wrapper.__doc__ += f"\r\n`{f.__name__}` is **DEPRECATED** and will be removed in the future.\r\n{solution}"
return wrapper
return decorator
def experimental_feature(f: Callable) -> Callable:
"""Decorator to add a warning when a feature is experimental."""
@functools.wraps(f)
def wrapper(*args: Any, **kwargs: Any) -> Any:
warn("This feature is under development, expect bugs and unstability...")
return f(*args, **kwargs)
return wrapper
def only_if_events_supported(event_type: str) -> Callable:
"""Checks if GDB supports events without crashing."""
def wrap(f: Callable) -> Callable:
def wrapped_f(*args: Any, **kwargs: Any) -> Any:
if getattr(gdb, "events") and getattr(gdb.events, event_type):
return f(*args, **kwargs)
warn("GDB events cannot be set")
return wrapped_f
return wrap
class classproperty(property):
"""Make the attribute a `classproperty`."""
def __get__(self, cls, owner):
return classmethod(self.fget).__get__(None, owner)()
def FakeExit(*args: Any, **kwargs: Any) -> NoReturn:
raise RuntimeWarning
sys.exit = FakeExit
def parse_arguments(required_arguments: Dict[Union[str, Tuple[str, str]], Any],
optional_arguments: Dict[Union[str, Tuple[str, str]], Any]) -> Callable:
"""Argument parsing decorator."""
def int_wrapper(x: str) -> int: return int(x, 0)
def decorator(f: Callable) -> Optional[Callable]:
def wrapper(*args: Any, **kwargs: Any) -> Callable:
parser = argparse.ArgumentParser(prog=args[0]._cmdline_, add_help=True)
for argname in required_arguments:
argvalue = required_arguments[argname]
argtype = type(argvalue)
if argtype is int:
argtype = int_wrapper
argname_is_list = not isinstance(argname, str)
assert not argname_is_list and isinstance(argname, str)
if not argname_is_list and argname.startswith("-"):
# optional args
if argtype is bool:
parser.add_argument(argname, action="store_true" if argvalue else "store_false")
else:
parser.add_argument(argname, type=argtype, required=True, default=argvalue)
else:
if argtype in (list, tuple):
nargs = "*"
argtype = type(argvalue[0])
else:
nargs = "?"
# positional args
parser.add_argument(argname, type=argtype, default=argvalue, nargs=nargs)
for argname in optional_arguments:
if isinstance(argname, str) and not argname.startswith("-"):
# refuse positional arguments
continue
argvalue = optional_arguments[argname]
argtype = type(argvalue)
if isinstance(argname, str):
argname = [argname,]
if argtype is int:
argtype = int_wrapper
if argtype is bool:
parser.add_argument(*argname, action="store_true" if argvalue else "store_false")
else:
parser.add_argument(*argname, type=argtype, default=argvalue)
parsed_args = parser.parse_args(*(args[1:]))
kwargs["arguments"] = parsed_args
return f(*args, **kwargs)
return wrapper
return decorator
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: str) -> str: return Color.colorify(msg, "red")
@staticmethod
def greenify(msg: str) -> str: return Color.colorify(msg, "green")
@staticmethod
def blueify(msg: str) -> str: return Color.colorify(msg, "blue")
@staticmethod
def yellowify(msg: str) -> str: return Color.colorify(msg, "yellow")
@staticmethod
def grayify(msg: str) -> str: return Color.colorify(msg, "gray")
@staticmethod
def light_grayify(msg: str) -> str: return Color.colorify(msg, "light_gray")
@staticmethod
def pinkify(msg: str) -> str: return Color.colorify(msg, "pink")
@staticmethod
def cyanify(msg: str) -> str: return Color.colorify(msg, "cyan")
@staticmethod
def boldify(msg: str) -> str: return Color.colorify(msg, "bold")
@staticmethod
def underlinify(msg: str) -> str: return Color.colorify(msg, "underline")
@staticmethod
def highlightify(msg: str) -> str: return Color.colorify(msg, "highlight")
@staticmethod
def blinkify(msg: str) -> str: return Color.colorify(msg, "blink")
@staticmethod
def colorify(text: str, attrs: str) -> str:
"""Color text according to the given attributes."""
if gef.config["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, **kwargs: Any) -> None:
self.value: int = kwargs.get("value", 0)
self.section: "Section" = kwargs.get("section", None)
self.info: "Zone" = kwargs.get("info", None)
return
def __str__(self) -> str:
value = format_address(self.value)
code_color = gef.config["theme.address_code"]
stack_color = gef.config["theme.address_stack"]
heap_color = gef.config["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 __int__(self) -> int:
return self.value
def is_in_text_segment(self) -> bool:
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) -> bool:
return hasattr(self.section, "path") and "[stack]" == self.section.path
def is_in_heap_segment(self) -> bool:
return hasattr(self.section, "path") and "[heap]" == self.section.path
def dereference(self) -> Optional[int]:
addr = align_address(int(self.value))
derefed = dereference(addr)
return None if derefed is None else int(derefed)
@property
def valid(self) -> bool:
return any(map(lambda x: x.page_start <= self.value < x.page_end, gef.memory.maps))
class Permission(enum.Flag):
"""GEF representation of Linux permission."""
NONE = 0
EXECUTE = 1
WRITE = 2
READ = 4
ALL = 7
def __str__(self) -> str:
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: str) -> "Permission":
perm = Permission(0)
for arg in args:
if "READONLY" in arg: perm |= Permission.READ
if "DATA" in arg: perm |= Permission.WRITE
if "CODE" in arg: perm |= Permission.EXECUTE
return perm
@staticmethod
def from_process_maps(perm_str: str) -> "Permission":
perm = Permission(0)
if perm_str[0] == "r": perm |= Permission.READ
if perm_str[1] == "w": perm |= Permission.WRITE
if perm_str[2] == "x": perm |= Permission.EXECUTE
return perm
class Section:
"""GEF representation of process memory sections."""
def __init__(self, **kwargs: Any) -> None:
self.page_start: int = kwargs.get("page_start", 0)
self.page_end: int = kwargs.get("page_end", 0)
self.offset: int = kwargs.get("offset", 0)
self.permission: Permission = kwargs.get("permission", Permission(0))
self.inode: int = kwargs.get("inode", 0)
self.path: str = kwargs.get("path", "")
return
def is_readable(self) -> bool:
return (self.permission & Permission.READ) != 0
def is_writable(self) -> bool:
return (self.permission & Permission.WRITE) != 0
def is_executable(self) -> bool:
return (self.permission & Permission.EXECUTE) != 0
@property
def size(self) -> int:
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) -> str:
# when in a `gef-remote` session, realpath returns the path to the binary on the local disk, not remote
return self.path if gef.session.remote is None else f"/tmp/gef/{gef.session.remote:d}/{self.path}"
def __str__(self) -> str:
return (f"Section(page_start={self.page_start:#x}, page_end={self.page_end:#x}, "
f"permissions={self.permission!s})")
Zone = collections.namedtuple("Zone", ["name", "zone_start", "zone_end", "filename"])
class Endianness(enum.Enum):
LITTLE_ENDIAN = 1
BIG_ENDIAN = 2
def __str__(self) -> str:
return "<" if self == Endianness.LITTLE_ENDIAN else ">"
def __repr__(self) -> str:
return self.name
def __int__(self) -> int:
return self.value
class FileFormatSection:
misc: Any
class FileFormat:
name: str
path: pathlib.Path
entry_point: int
checksec: Dict[str, bool]
sections: List[FileFormatSection]
def __init__(self, path: Union[str, pathlib.Path]) -> None:
raise NotImplemented
def __init_subclass__(cls: Type["FileFormat"], **kwargs):
global __registered_file_formats__
super().__init_subclass__(**kwargs)
required_attributes = ("name", "entry_point", "is_valid", "checksec",)
for attr in required_attributes:
if not hasattr(cls, attr):
raise NotImplementedError(f"File format '{cls.__name__}' is invalid: missing attribute '{attr}'")
__registered_file_formats__.add(cls)
return
@classmethod
def is_valid(cls, path: pathlib.Path) -> bool:
raise NotImplemented
def __str__(self) -> str:
return f"{self.name}('{self.path.absolute()}', entry @ {self.entry_point:#x})"
class Elf(FileFormat):
"""Basic ELF parsing.
Ref:
- http://www.skyfree.org/linux/references/ELF_Format.pdf
- https://refspecs.linuxfoundation.org/elf/elfspec_ppc.pdf
- https://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi.html
"""
class Class(enum.Enum):
ELF_32_BITS = 0x01
ELF_64_BITS = 0x02
ELF_MAGIC = 0x7f454c46
class Abi(enum.Enum):
X86_64 = 0x3e
X86_32 = 0x03
ARM = 0x28
MIPS = 0x08
POWERPC = 0x14
POWERPC64 = 0x15
SPARC = 0x02
SPARC64 = 0x2b
AARCH64 = 0xb7
RISCV = 0xf3
IA64 = 0x32
M68K = 0x04
class Type(enum.Enum):
ET_RELOC = 1
ET_EXEC = 2
ET_DYN = 3
ET_CORE = 4
class OsAbi(enum.Enum):
SYSTEMV = 0x00
HPUX = 0x01
NETBSD = 0x02
LINUX = 0x03
SOLARIS = 0x06
AIX = 0x07
IRIX = 0x08
FREEBSD = 0x09
OPENBSD = 0x0C
e_magic: int = ELF_MAGIC
e_class: "Elf.Class" = Class.ELF_32_BITS
e_endianness: Endianness = Endianness.LITTLE_ENDIAN
e_eiversion: int
e_osabi: "Elf.OsAbi"
e_abiversion: int
e_pad: bytes
e_type: "Elf.Type" = Type.ET_EXEC
e_machine: Abi = Abi.X86_32
e_version: int
e_entry: int
e_phoff: int
e_shoff: int
e_flags: int
e_ehsize: int
e_phentsize: int
e_phnum: int
e_shentsize: int
e_shnum: int
e_shstrndx: int
path: pathlib.Path
phdrs : List["Phdr"]
shdrs : List["Shdr"]
name: str = "ELF"
__checksec : Dict[str, bool]
def __init__(self, path: Union[str, pathlib.Path]) -> None:
"""Instantiate an ELF object. A valid ELF must be provided, or an exception will be thrown."""
if isinstance(path, str):
self.path = pathlib.Path(path).expanduser()
elif isinstance(path, pathlib.Path):
self.path = path
else:
raise TypeError
if not self.path.exists():
raise FileNotFoundError(f"'{self.path}' not found/readable, most gef features will not work")
self.__checksec = {}
with self.path.open("rb") as self.fd:
# off 0x0
self.e_magic, e_class, e_endianness, self.e_eiversion = self.read_and_unpack(">IBBB")
if self.e_magic != Elf.ELF_MAGIC:
# The ELF is corrupted, GDB won't handle it, no point going further
raise RuntimeError("Not a valid ELF file (magic)")
self.e_class, self.e_endianness = Elf.Class(e_class), Endianness(e_endianness)
if self.e_endianness != gef.arch.endianness:
warn("Unexpected endianness for architecture")
endian = self.e_endianness
# off 0x7
e_osabi, self.e_abiversion = self.read_and_unpack(f"{endian}BB")
self.e_osabi = Elf.OsAbi(e_osabi)
# off 0x9
self.e_pad = self.read(7)
# off 0x10
e_type, e_machine, self.e_version = self.read_and_unpack(f"{endian}HHI")
self.e_type, self.e_machine = Elf.Type(e_type), Elf.Abi(e_machine)
# off 0x18
if self.e_class == Elf.Class.ELF_64_BITS:
self.e_entry, self.e_phoff, self.e_shoff = self.read_and_unpack(f"{endian}QQQ")
else:
self.e_entry, self.e_phoff, self.e_shoff = self.read_and_unpack(f"{endian}III")
self.e_flags, self.e_ehsize, self.e_phentsize, self.e_phnum = self.read_and_unpack(f"{endian}IHHH")
self.e_shentsize, self.e_shnum, self.e_shstrndx = self.read_and_unpack(f"{endian}HHH")
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))
return
def read(self, size: int) -> bytes:
return self.fd.read(size)
def read_and_unpack(self, fmt: str) -> Tuple[Any, ...]:
size = struct.calcsize(fmt)
data = self.fd.read(size)
return struct.unpack(fmt, data)
def seek(self, off: int) -> None:
self.fd.seek(off, 0)
def __str__(self) -> str:
return f"ELF('{self.path.absolute()}', {self.e_class.name}, {self.e_machine.name})"
def __repr__(self) -> str:
return f"ELF('{self.path.absolute()}', {self.e_class.name}, {self.e_machine.name})"
@property
def entry_point(self) -> int:
return self.e_entry
@classmethod
def is_valid(cls, path: pathlib.Path) -> bool:
return u32(path.open("rb").read(4), e = Endianness.BIG_ENDIAN) == Elf.ELF_MAGIC
@property
def checksec(self) -> Dict[str, bool]:
"""Check the security property of the ELF binary. The following properties are:
- Canary
- NX
- PIE
- Fortify
- Partial/Full RelRO.
Return a dict() with the different keys mentioned above, and the boolean
associated whether the protection was found."""
if not self.__checksec:
def __check_security_property(opt: str, filename: str, pattern: str) -> bool:
cmd = [readelf,]
cmd += opt.split()
cmd += [filename,]
lines = gef_execute_external(cmd, as_list=True)
for line in lines:
if re.search(pattern, line):
return True
return False
abspath = str(self.path.absolute())
readelf = gef.session.constants["readelf"]
self.__checksec["Canary"] = __check_security_property("-rs", abspath, r"__stack_chk_fail") is True
has_gnu_stack = __check_security_property("-W -l", abspath, r"GNU_STACK") is True
if has_gnu_stack:
self.__checksec["NX"] = __check_security_property("-W -l", abspath, r"GNU_STACK.*RWE") is False
else:
self.__checksec["NX"] = False
self.__checksec["PIE"] = __check_security_property("-h", abspath, r":.*EXEC") is False
self.__checksec["Fortify"] = __check_security_property("-s", abspath, r"_chk@GLIBC") is True
self.__checksec["Partial RelRO"] = __check_security_property("-l", abspath, r"GNU_RELRO") is True
self.__checksec["Full RelRO"] = self.__checksec["Partial RelRO"] and __check_security_property("-d", abspath, r"BIND_NOW") is True
return self.__checksec
@classproperty
@deprecated("use `Elf.Abi.X86_64`")
def X86_64(cls) -> int: return Elf.Abi.X86_64.value # pylint: disable=no-self-argument
@classproperty
@deprecated("use `Elf.Abi.X86_32`")
def X86_32(cls) -> int : return Elf.Abi.X86_32.value # pylint: disable=no-self-argument
@classproperty
@deprecated("use `Elf.Abi.ARM`")
def ARM(cls) -> int : return Elf.Abi.ARM.value # pylint: disable=no-self-argument
@classproperty
@deprecated("use `Elf.Abi.MIPS`")
def MIPS(cls) -> int : return Elf.Abi.MIPS.value # pylint: disable=no-self-argument
@classproperty
@deprecated("use `Elf.Abi.POWERPC`")
def POWERPC(cls) -> int : return Elf.Abi.POWERPC.value # pylint: disable=no-self-argument
@classproperty
@deprecated("use `Elf.Abi.POWERPC64`")
def POWERPC64(cls) -> int : return Elf.Abi.POWERPC64.value # pylint: disable=no-self-argument
@classproperty
@deprecated("use `Elf.Abi.SPARC`")
def SPARC(cls) -> int : return Elf.Abi.SPARC.value # pylint: disable=no-self-argument
@classproperty
@deprecated("use `Elf.Abi.SPARC64`")
def SPARC64(cls) -> int : return Elf.Abi.SPARC64.value # pylint: disable=no-self-argument
@classproperty
@deprecated("use `Elf.Abi.AARCH64`")
def AARCH64(cls) -> int : return Elf.Abi.AARCH64.value # pylint: disable=no-self-argument
@classproperty
@deprecated("use `Elf.Abi.RISCV`")
def RISCV(cls) -> int : return Elf.Abi.RISCV.value # pylint: disable=no-self-argument
class Phdr:
class Type(enum.IntEnum):
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_GNU_PROPERTY = 0x6474e553
PT_LOSUNW = 0x6ffffffa
PT_SUNWBSS = 0x6ffffffa
PT_SUNWSTACK = 0x6ffffffb
PT_HISUNW = PT_HIOS = 0x6fffffff
PT_LOPROC = 0x70000000
PT_ARM_EIDX = 0x70000001
PT_MIPS_ABIFLAGS= 0x70000003
PT_HIPROC = 0x7fffffff
UNKNOWN_PHDR = 0xffffffff
@classmethod
def _missing_(cls, _:int) -> Type:
return cls.UNKNOWN_PHDR
class Flags(enum.IntFlag):
PF_X = 1
PF_W = 2
PF_R = 4
p_type: "Phdr.Type"
p_flags: "Phdr.Flags"
p_offset: int
p_vaddr: int
p_paddr: int
p_filesz: int
p_memsz: int
p_align: int
def __init__(self, elf: Elf, off: int) -> None:
if not elf:
return
elf.seek(off)