-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
elf.py
2456 lines (1915 loc) · 87.6 KB
/
elf.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
"""Exposes functionality for manipulating ELF files
Stop hard-coding things! Look them up at runtime with :mod:`pwnlib.elf`.
Example Usage
-------------
.. code-block:: python
>>> e = ELF('/bin/cat')
>>> print(hex(e.address)) #doctest: +SKIP
0x400000
>>> print(hex(e.symbols['write'])) #doctest: +SKIP
0x401680
>>> print(hex(e.got['write'])) #doctest: +SKIP
0x60b070
>>> print(hex(e.plt['write'])) #doctest: +SKIP
0x401680
You can even patch and save the files.
.. code-block:: python
>>> e = ELF('/bin/cat')
>>> e.read(e.address+1, 3)
b'ELF'
>>> e.asm(e.address, 'ret')
>>> e.save('/tmp/quiet-cat')
>>> disasm(open('/tmp/quiet-cat','rb').read(1))
' 0: c3 ret'
Module Members
--------------
"""
from __future__ import absolute_import
from __future__ import division
import collections
import gzip
import mmap
import os
import re
import six
import subprocess
import tempfile
from six import BytesIO
from collections import namedtuple, defaultdict
from elftools.elf.constants import P_FLAGS
from elftools.elf.constants import SHN_INDICES
from elftools.elf.descriptions import describe_e_type
from elftools.elf.elffile import ELFFile
from elftools.elf.enums import ENUM_GNU_PROPERTY_X86_FEATURE_1_FLAGS
from elftools.elf.gnuversions import GNUVerDefSection
from elftools.elf.relocation import RelocationSection, RelrRelocationSection
from elftools.elf.sections import SymbolTableSection
from elftools.elf.segments import InterpSegment
# See https://github.com/Gallopsled/pwntools/issues/1189
try:
from elftools.elf.enums import ENUM_P_TYPE
except ImportError:
from elftools.elf.enums import ENUM_P_TYPE_BASE as ENUM_P_TYPE
import intervaltree
from pwnlib import adb
from pwnlib import qemu
from pwnlib.asm import *
from pwnlib.context import LocalContext
from pwnlib.context import context
from pwnlib.elf.config import kernel_configuration
from pwnlib.elf.config import parse_kconfig
from pwnlib.elf.datatypes import constants
from pwnlib.elf.maps import CAT_PROC_MAPS_EXIT
from pwnlib.elf.plt import emulate_plt_instructions
from pwnlib.log import getLogger
from pwnlib.term import text
from pwnlib.tubes.process import process
from pwnlib.util import misc
from pwnlib.util import packing
from pwnlib.util.fiddling import unhex
from pwnlib.util.misc import align, align_down, which
from pwnlib.util.sh_string import sh_string
log = getLogger(__name__)
__all__ = ['load', 'ELF']
def _iter_symbols(sec):
# Cache result of iter_symbols.
if not hasattr(sec, '_symbols'):
sec._symbols = list(sec.iter_symbols())
return iter(sec._symbols)
class Function(object):
"""Encapsulates information about a function in an :class:`.ELF` binary.
Arguments:
name(str): Name of the function
address(int): Address of the function
size(int): Size of the function, in bytes
elf(ELF): Encapsulating ELF object
"""
def __init__(self, name, address, size, elf=None):
#: Name of the function
self.name = name
#: Address of the function in the encapsulating ELF
self.address = address
#: Size of the function, in bytes
self.size = size
#: Encapsulating ELF object
self.elf = elf
def __repr__(self):
return '%s(name=%r, address=%#x, size=%#x, elf=%r)' % (
self.__class__.__name__,
self.name,
self.address,
self.size,
self.elf
)
def __flat__(self):
return packing.pack(self.address)
def disasm(self):
return self.elf.disasm(self.address, self.size)
def load(*args, **kwargs):
"""Compatibility wrapper for pwntools v1"""
return ELF(*args, **kwargs)
class dotdict(dict):
"""Wrapper to allow dotted access to dictionary elements.
Is a real :class:`dict` object, but also serves up keys as attributes
when reading attributes.
Supports recursive instantiation for keys which contain dots.
Example:
>>> x = pwnlib.elf.elf.dotdict()
>>> isinstance(x, dict)
True
>>> x['foo'] = 3
>>> x.foo
3
>>> x['bar.baz'] = 4
>>> x.bar.baz
4
"""
def __missing__(self, name):
if isinstance(name, (bytes, bytearray)):
name = packing._decode(name)
return self[name]
raise KeyError(name)
def __getattr__(self, name):
if name in self:
return self[name]
name_dot = name + '.'
name_len = len(name_dot)
subkeys = {k[name_len:]: self[k] for k in self if k.startswith(name_dot)}
if subkeys:
return dotdict(subkeys)
raise AttributeError(name)
class ELF(ELFFile):
"""Encapsulates information about an ELF file.
Example:
.. code-block:: python
>>> bash = ELF(which('bash'))
>>> hex(bash.symbols['read'])
0x41dac0
>>> hex(bash.plt['read'])
0x41dac0
>>> u32(bash.read(bash.got['read'], 4))
0x41dac6
>>> print(bash.disasm(bash.plt.read, 16))
0: ff 25 1a 18 2d 00 jmp QWORD PTR [rip+0x2d181a] # 0x2d1820
6: 68 59 00 00 00 push 0x59
b: e9 50 fa ff ff jmp 0xfffffffffffffa60
"""
# These class-level intitializers are only for ReadTheDocs
bits = 32
bytes = 4
path = '/path/to/the/file'
symbols = {}
got = {}
plt = {}
functions = {}
endian = 'little'
address = 0x400000
linker = None
# Whether to fill gaps in memory with zeroed pages
_fill_gaps = True
def __init__(self, path, checksec=True):
# elftools uses the backing file for all reads and writes
# in order to permit writing without being able to write to disk,
# mmap() the file.
#: :class:`file`: Open handle to the ELF file on disk
self.file = open(path,'rb')
#: :class:`mmap.mmap`: Memory-mapped copy of the ELF file on disk
self.mmap = mmap.mmap(self.file.fileno(), 0, access=mmap.ACCESS_COPY)
super(ELF,self).__init__(self.mmap)
#: :class:`str`: Path to the file
self.path = packing._need_text(os.path.abspath(path))
#: :class:`dotdict` of ``name`` to ``address`` for all symbols in the ELF
self.symbols = dotdict()
#: :class:`dotdict` of ``name`` to ``address`` for all Global Offset Table (GOT) entries
self.got = dotdict()
#: :class:`dotdict` of ``name`` to ``address`` for all Procedure Linkage Table (PLT) entries
self.plt = dotdict()
#: :class:`dotdict` of ``name`` to :class:`.Function` for each function in the ELF
self.functions = dotdict()
#: :class:`dict`: Linux kernel configuration, if this is a Linux kernel image
self.config = {}
#: :class:`tuple`: Linux kernel version, if this is a Linux kernel image
self.version = (0,)
#: :class:`str`: Linux kernel build commit, if this is a Linux kernel image
self.build = ''
#: :class:`str`: Endianness of the file (e.g. ``'big'``, ``'little'``)
self.endian = {
'ELFDATANONE': 'little',
'ELFDATA2LSB': 'little',
'ELFDATA2MSB': 'big'
}[self['e_ident']['EI_DATA']]
#: :class:`int`: Bit-ness of the file
self.bits = self.elfclass
#: :class:`int`: Pointer width, in bytes
self.bytes = self.bits // 8
#: :class:`str`: Architecture of the file (e.g. ``'i386'``, ``'arm'``).
#:
#: See: :attr:`.ContextType.arch`
self.arch = self.get_machine_arch()
if isinstance(self.arch, (bytes, six.text_type)):
self.arch = self.arch.lower()
self._sections = None
self._segments = None
#: IntervalTree which maps all of the loaded memory segments
self.memory = intervaltree.IntervalTree()
self._populate_memory()
# Is this a native binary? Should we be checking QEMU?
try:
with context.local(arch=self.arch):
#: Whether this ELF should be able to run natively
self.native = context.native
except AttributeError:
# The architecture may not be supported in pwntools
self.native = False
self._address = 0
if self.elftype != 'DYN':
for seg in self.iter_segments_by_type('PT_LOAD'):
addr = seg.header.p_vaddr
if addr == 0:
continue
if addr < self._address or self._address == 0:
self._address = addr
self.load_addr = self._address
# Try to figure out if we have a kernel configuration embedded
IKCFG_ST=b'IKCFG_ST'
for start in self.search(IKCFG_ST):
start += len(IKCFG_ST)
stop = next(self.search(b'IKCFG_ED'))
fileobj = BytesIO(self.read(start, stop-start))
# Python gzip throws an exception if there is non-Gzip data
# after the Gzip stream.
#
# Catch the exception, and just deal with it.
with gzip.GzipFile(fileobj=fileobj) as gz:
config = gz.read()
if config:
self.config = parse_kconfig(config.decode())
#: ``True`` if the ELF is a statically linked executable
self.statically_linked = bool(self.elftype == 'EXEC' and self.load_addr)
#: ``True`` if the ELF is an executable
self.executable = bool(self.elftype == 'EXEC')
for seg in self.iter_segments_by_type('PT_INTERP'):
self.executable = True
#: ``True`` if the ELF is statically linked
self.statically_linked = False
#: Path to the linker for the ELF
self.linker = self.read(seg.header.p_vaddr, seg.header.p_memsz)
self.linker = self.linker.rstrip(b'\x00')
#: Operating system of the ELF
self.os = 'linux'
if self.linker and self.linker.startswith(b'/system/bin/linker'):
self.os = 'android'
#: ``True`` if the ELF is a shared library
self.library = not self.executable and self.elftype == 'DYN'
try:
self._populate_symbols()
except Exception as e:
log.warn("Could not populate symbols: %s", e)
try:
self._populate_got()
except Exception as e:
log.warn("Could not populate GOT: %s", e)
try:
self._populate_plt()
except Exception as e:
log.warn("Could not populate PLT: %s", e)
self._populate_synthetic_symbols()
self._populate_functions()
self._populate_kernel_version()
if checksec:
self._describe()
self._libs = None
self._maps = None
@staticmethod
@LocalContext
def from_assembly(assembly, *a, **kw):
"""from_assembly(assembly) -> ELF
Given an assembly listing, return a fully loaded ELF object
which contains that assembly at its entry point.
Arguments:
assembly(str): Assembly language listing
vma(int): Address of the entry point and the module's base address.
Example:
>>> e = ELF.from_assembly('nop; foo: int 0x80', vma = 0x400000)
>>> e.symbols['foo'] = 0x400001
>>> e.disasm(e.entry, 1)
' 400000: 90 nop'
>>> e.disasm(e.symbols['foo'], 2)
' 400001: cd 80 int 0x80'
"""
return ELF(make_elf_from_assembly(assembly, *a, **kw))
@staticmethod
@LocalContext
def from_bytes(bytes, *a, **kw):
r"""from_bytes(bytes) -> ELF
Given a sequence of bytes, return a fully loaded ELF object
which contains those bytes at its entry point.
Arguments:
bytes(str): Shellcode byte string
vma(int): Desired base address for the ELF.
Example:
>>> e = ELF.from_bytes(b'\x90\xcd\x80', vma=0xc000)
>>> print(e.disasm(e.entry, 3))
c000: 90 nop
c001: cd 80 int 0x80
"""
return ELF(make_elf(bytes, extract=False, *a, **kw))
def process(self, argv=[], *a, **kw):
"""process(argv=[], *a, **kw) -> process
Execute the binary with :class:`.process`. Note that ``argv``
is a list of arguments, and should not include ``argv[0]``.
Arguments:
argv(list): List of arguments to the binary
*args: Extra arguments to :class:`.process`
**kwargs: Extra arguments to :class:`.process`
Returns:
:class:`.process`
"""
p = process
if context.os == 'android':
p = adb.process
return p([self.path] + argv, *a, **kw)
def debug(self, argv=[], *a, **kw):
"""debug(argv=[], *a, **kw) -> tube
Debug the ELF with :func:`.gdb.debug`.
Arguments:
argv(list): List of arguments to the binary
*args: Extra arguments to :func:`.gdb.debug`
**kwargs: Extra arguments to :func:`.gdb.debug`
Returns:
:class:`.tube`: See :func:`.gdb.debug`
"""
import pwnlib.gdb
return pwnlib.gdb.debug([self.path] + argv, *a, **kw)
def _describe(self, *a, **kw):
log.info_once(
'%s\n%-12s%s-%s-%s\n%s',
repr(self.path),
'Arch:',
self.arch,
self.bits,
self.endian,
self.checksec(*a, **kw)
)
def get_machine_arch(self):
return {
('EM_X86_64', 64): 'amd64',
('EM_X86_64', 32): 'amd64', # x32 ABI
('EM_386', 32): 'i386',
('EM_486', 32): 'i386',
('EM_ARM', 32): 'arm',
('EM_AARCH64', 64): 'aarch64',
('EM_MIPS', 32): 'mips',
('EM_MIPS', 64): 'mips64',
('EM_PPC', 32): 'powerpc',
('EM_PPC64', 64): 'powerpc64',
('EM_SPARC32PLUS', 32): 'sparc',
('EM_SPARCV9', 64): 'sparc64',
('EM_IA_64', 64): 'ia64',
('EM_RISCV', 32): 'riscv32',
('EM_RISCV', 64): 'riscv64',
}.get((self['e_machine'], self.bits), self['e_machine'])
@property
def entry(self):
""":class:`int`: Address of the entry point for the ELF"""
return self.address + (self.header.e_entry - self.load_addr)
entrypoint = entry
start = entry
@property
def elftype(self):
""":class:`str`: ELF type (``EXEC``, ``DYN``, etc)"""
return describe_e_type(self.header.e_type).split()[0]
def iter_segments(self):
# Yield and cache all the segments in the file
if self._segments is None:
self._segments = [self.get_segment(i) for i in range(self.num_segments())]
return iter(self._segments)
@property
def segments(self):
"""
:class:`list`: A list of :class:`elftools.elf.segments.Segment` objects
for the segments in the ELF.
"""
return list(self.iter_segments())
def iter_segments_by_type(self, t):
"""
Yields:
Segments matching the specified type.
"""
for seg in self.iter_segments():
if t == seg.header.p_type or t in str(seg.header.p_type):
yield seg
def iter_notes(self):
"""
Yields:
All the notes in the PT_NOTE segments. Each result is a dictionary-
like object with ``n_name``, ``n_type``, and ``n_desc`` fields, amongst
others.
"""
for seg in self.iter_segments_by_type('PT_NOTE'):
for note in seg.iter_notes():
yield note
def iter_properties(self):
"""
Yields:
All the GNU properties in the PT_NOTE segments. Each result is a dictionary-
like object with ``pr_type``, ``pr_datasz``, and ``pr_data`` fields.
"""
for note in self.iter_notes():
if note.n_type != 'NT_GNU_PROPERTY_TYPE_0':
continue
for prop in note.n_desc:
yield prop
def get_segment_for_address(self, address, size=1):
"""get_segment_for_address(address, size=1) -> Segment
Given a virtual address described by a ``PT_LOAD`` segment, return the
first segment which describes the virtual address. An optional ``size``
may be provided to ensure the entire range falls into the same segment.
Arguments:
address(int): Virtual address to find
size(int): Number of bytes which must be available after ``address``
in **both** the file-backed data for the segment, and the memory
region which is reserved for the data.
Returns:
Either returns a :class:`.segments.Segment` object, or ``None``.
"""
for seg in self.iter_segments_by_type("PT_LOAD"):
mem_start = seg.header.p_vaddr
mem_stop = seg.header.p_memsz + mem_start
if not (mem_start <= address <= address+size < mem_stop):
continue
offset = self.vaddr_to_offset(address)
file_start = seg.header.p_offset
file_stop = seg.header.p_filesz + file_start
if not (file_start <= offset <= offset+size < file_stop):
continue
return seg
return None
def iter_sections(self):
# Yield and cache all the sections in the file
if self._sections is None:
self._sections = [self.get_section(i) for i in range(self.num_sections())]
return iter(self._sections)
@property
def sections(self):
"""
:class:`list`: A list of :class:`elftools.elf.sections.Section` objects
for the segments in the ELF.
"""
return list(self.iter_sections())
@property
def dwarf(self):
"""DWARF info for the elf"""
return self.get_dwarf_info()
@property
def sym(self):
""":class:`dotdict`: Alias for :attr:`.ELF.symbols`"""
return self.symbols
@property
def address(self):
""":class:`int`: Address of the lowest segment loaded in the ELF.
When updated, the addresses of the following fields are also updated:
- :attr:`~.ELF.symbols`
- :attr:`~.ELF.got`
- :attr:`~.ELF.plt`
- :attr:`~.ELF.functions`
However, the following fields are **NOT** updated:
- :attr:`~.ELF.segments`
- :attr:`~.ELF.sections`
Example:
>>> bash = ELF('/bin/bash')
>>> read = bash.symbols['read']
>>> text = bash.get_section_by_name('.text').header.sh_addr
>>> bash.address += 0x1000
>>> read + 0x1000 == bash.symbols['read']
True
>>> text == bash.get_section_by_name('.text').header.sh_addr
True
"""
return self._address
@address.setter
def address(self, new):
delta = new-self._address
update = lambda x: x+delta
self.symbols = dotdict({k:update(v) for k,v in self.symbols.items()})
self.plt = dotdict({k:update(v) for k,v in self.plt.items()})
self.got = dotdict({k:update(v) for k,v in self.got.items()})
for f in self.functions.values():
f.address += delta
# Update our view of memory
memory = intervaltree.IntervalTree()
for begin, end, data in self.memory:
memory.addi(update(begin),
update(end),
data)
self.memory = memory
self._address = update(self.address)
def section(self, name):
"""section(name) -> bytes
Gets data for the named section
Arguments:
name(str): Name of the section
Returns:
:class:`str`: String containing the bytes for that section
"""
return self.get_section_by_name(name).data()
@property
def rwx_segments(self):
""":class:`list`: List of all segments which are writeable and executable.
See:
:attr:`.ELF.segments`
"""
if not self.nx:
return self.writable_segments
wx = P_FLAGS.PF_X | P_FLAGS.PF_W
return [s for s in self.segments if s.header.p_flags & wx == wx]
@property
def executable_segments(self):
""":class:`list`: List of all segments which are executable.
See:
:attr:`.ELF.segments`
"""
if not self.nx:
return list(self.segments)
return [s for s in self.segments if s.header.p_flags & P_FLAGS.PF_X]
@property
def writable_segments(self):
""":class:`list`: List of all segments which are writeable.
See:
:attr:`.ELF.segments`
"""
return [s for s in self.segments if s.header.p_flags & P_FLAGS.PF_W]
@property
def non_writable_segments(self):
""":class:`list`: List of all segments which are NOT writeable.
See:
:attr:`.ELF.segments`
"""
return [s for s in self.segments if not s.header.p_flags & P_FLAGS.PF_W]
@property
def libs(self):
"""Dictionary of {path: address} for every library loaded for this ELF."""
if self._libs is None:
self._populate_libraries()
return self._libs
@property
def maps(self):
"""Dictionary of {name: address} for every mapping in this ELF's address space."""
if self._maps is None:
self._populate_libraries()
return self._maps
@property
def libc(self):
""":class:`.ELF`: If this :class:`.ELF` imports any libraries which contain ``'libc[.-]``,
and we can determine the appropriate path to it on the local
system, returns a new :class:`.ELF` object pertaining to that library.
If not found, the value will be :const:`None`.
"""
for lib in self.libs:
if '/libc.' in lib or '/libc-' in lib:
return ELF(lib)
def _populate_libraries(self):
"""
>>> from os.path import exists
>>> bash = ELF(which('bash'))
>>> all(map(exists, bash.libs.keys()))
True
>>> any(map(lambda x: 'libc' in x, bash.libs.keys()))
True
"""
# Patch some shellcode into the ELF and run it.
maps = self._patch_elf_and_read_maps()
self._maps = maps
self._libs = {}
for lib, address in maps.items():
# Filter out [stack] and such from the library listings
if lib.startswith('['):
continue
# Any existing files we can just use
if os.path.exists(lib):
self._libs[lib] = address
# Try etc/qemu-binfmt, as per Ubuntu
if not self.native:
ld_prefix = qemu.ld_prefix()
qemu_lib = os.path.join(ld_prefix, lib)
qemu_lib = os.path.realpath(qemu_lib)
if os.path.exists(qemu_lib):
self._libs[qemu_lib] = address
def _patch_elf_and_read_maps(self):
r"""patch_elf_and_read_maps(self) -> dict
Read ``/proc/self/maps`` as if the ELF were executing.
This is done by replacing the code at the entry point with shellcode which
dumps ``/proc/self/maps`` and exits, and **actually executing the binary**.
Returns:
A ``dict`` mapping file paths to the lowest address they appear at.
Does not do any translation for e.g. QEMU emulation, the raw results
are returned.
If there is not enough space to inject the shellcode in the segment
which contains the entry point, returns ``{}``.
Doctests:
These tests are just to ensure that our shellcode is correct.
>>> for arch in CAT_PROC_MAPS_EXIT:
... context.clear()
... with context.local(arch=arch):
... sc = shellcraft.cat2("/proc/self/maps")
... sc += shellcraft.exit()
... sc = asm(sc)
... sc = enhex(sc)
... assert sc == CAT_PROC_MAPS_EXIT[arch], (arch, sc)
"""
# Get our shellcode
sc = CAT_PROC_MAPS_EXIT.get(self.arch, None)
if sc is None:
log.error("Cannot patch /proc/self/maps shellcode into %r binary", self.arch)
sc = unhex(sc)
# Ensure there is enough room in the segment where the entry point resides
# in order to inject our shellcode.
seg = self.get_segment_for_address(self.entry, len(sc))
if not seg:
log.warn_once("Could not inject code to determine memory mapping for %r: Not enough space", self)
return {}
# Create our temporary file
# NOTE: We cannot use "with NamedTemporaryFile() as foo", because we cannot
# execute the file while the handle is open.
fd, path = tempfile.mkstemp()
# Close the file descriptor so that it may be executed
os.close(fd)
# Save off a copy of the ELF
self.save(path)
# Load a new copy of the ELF at the temporary file location
old = self.read(self.entry, len(sc))
try:
self.write(self.entry, sc)
self.save(path)
finally:
# Restore the original contents
self.write(self.entry, old)
# Make the file executable
os.chmod(path, 0o755)
# Run a copy of it, get the maps
try:
with context.silent:
io = process(path)
data = packing._decode(io.recvall(timeout=2))
except Exception:
log.warn_once("Injected /proc/self/maps code did not execute correctly")
return {}
# Swap in the original ELF name
data = data.replace(path, self.path)
# All we care about in the data is the load address of each file-backed mapping,
# or each kernel-supplied mapping.
#
# For quick reference, the data looks like this:
# 7fcb025f2000-7fcb025f3000 r--p 00025000 fe:01 3025685 /lib/x86_64-linux-gnu/ld-2.23.so
# 7fcb025f3000-7fcb025f4000 rw-p 00026000 fe:01 3025685 /lib/x86_64-linux-gnu/ld-2.23.so
# 7fcb025f4000-7fcb025f5000 rw-p 00000000 00:00 0
# 7ffe39cd4000-7ffe39cf6000 rw-p 00000000 00:00 0 [stack]
# 7ffe39d05000-7ffe39d07000 r--p 00000000 00:00 0 [vvar]
result = {}
for line in data.splitlines():
if '/' in line:
index = line.index('/')
elif '[' in line:
index = line.index('[')
else:
continue
address, _ = line.split('-', 1)
address = int(address, 0x10)
name = line[index:]
result.setdefault(name, address)
# Remove the temporary file, best-effort
os.unlink(path)
return result
def _populate_functions(self):
"""Builds a dict of 'functions' (i.e. symbols of type 'STT_FUNC')
by function name that map to a tuple consisting of the func address and size
in bytes.
"""
for sec in self.sections:
if not isinstance(sec, SymbolTableSection):
continue
for sym in _iter_symbols(sec):
# Avoid duplicates
if sym.name in self.functions:
continue
if sym.entry.st_info['type'] == 'STT_FUNC' and sym.entry.st_size != 0:
name = sym.name
if name not in self.symbols:
continue
addr = self.symbols[name]
size = sym.entry.st_size
self.functions[name] = Function(name, addr, size, self)
def _populate_symbols(self):
"""
>>> bash = ELF(which('bash'))
>>> bash.symbols['_start'] == bash.entry
True
"""
# Populate all of the "normal" symbols from the symbol tables
for section in self.sections:
if not isinstance(section, SymbolTableSection):
continue
for symbol in _iter_symbols(section):
value = symbol.entry.st_value
if not value:
continue
self.symbols[symbol.name] = value
def _populate_synthetic_symbols(self):
"""Adds symbols from the GOT and PLT to the symbols dictionary.
Does not overwrite any existing symbols, and prefers PLT symbols.
Synthetic plt.xxx and got.xxx symbols are added for each PLT and
GOT entry, respectively.
Example:bash.
>>> bash = ELF(which('bash'))
>>> bash.symbols.wcscmp == bash.plt.wcscmp
True
>>> bash.symbols.wcscmp == bash.symbols.plt.wcscmp
True
>>> bash.symbols.stdin == bash.got.stdin
True
>>> bash.symbols.stdin == bash.symbols.got.stdin
True
"""
for symbol, address in self.plt.items():
self.symbols.setdefault(symbol, address)
self.symbols['plt.' + symbol] = address
for symbol, address in self.got.items():
self.symbols.setdefault(symbol, address)
self.symbols['got.' + symbol] = address
def _populate_got(self):
"""Loads the symbols for all relocations.
>>> libc = ELF(which('bash')).libc
>>> assert 'strchrnul' in libc.got
>>> assert 'memcpy' in libc.got
>>> assert libc.got.strchrnul != libc.got.memcpy
"""
# Statically linked implies no relocations, since there is no linker
# Could always be self-relocating like Android's linker *shrug*
if self.statically_linked:
return
revsymbols = defaultdict(list)
for name, addr in self.symbols.items():
revsymbols[addr].append(name)
for section in self.sections:
# We are only interested in relocations
if not isinstance(section, (RelocationSection, RelrRelocationSection)):
continue
# Only get relocations which link to another section (for symbols)
if section.header.sh_link == SHN_INDICES.SHN_UNDEF:
continue
symbols = self.get_section(section.header.sh_link)
for rel in section.iter_relocations():
sym_idx = rel.entry.r_info_sym
if not sym_idx and rel.is_RELA():
# TODO: actually resolve relocations
relocated = rel.entry.r_addend # sufficient for now
symnames = revsymbols[relocated]
for symname in symnames:
self.got[symname] = rel.entry.r_offset
continue
symbol = symbols.get_symbol(sym_idx)
if symbol and symbol.name:
self.got[symbol.name] = rel.entry.r_offset
if self.arch == 'mips':
try:
self._populate_mips_got()
except Exception as e:
log.warn("Could not populate MIPS GOT: %s", e)
if not self.got:
log.warn("Did not find any GOT entries")
def _populate_mips_got(self):
self._mips_got = {}
strings = self.get_section(self.header.e_shstrndx)