/
corefile.py
1640 lines (1299 loc) · 55.4 KB
/
corefile.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 -*-
"""Read information from Core Dumps.
Core dumps are extremely useful when writing exploits, even outside of
the normal act of debugging things.
Using Corefiles to Automate Exploitation
----------------------------------------
For example, if you have a trivial buffer overflow and don't want to
open up a debugger or calculate offsets, you can use a generated core
dump to extract the relevant information.
.. code-block:: c
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void win() {
system("sh");
}
int main(int argc, char** argv) {
char buffer[64];
strcpy(buffer, argv[1]);
}
.. code-block:: shell
$ gcc crash.c -m32 -o crash -fno-stack-protector
.. code-block:: python
from pwn import *
# Generate a cyclic pattern so that we can auto-find the offset
payload = cyclic(128)
# Run the process once so that it crashes
process(['./crash', payload]).wait()
# Get the core dump
core = Coredump('./core')
# Our cyclic pattern should have been used as the crashing address
assert pack(core.eip) in payload
# Cool! Now let's just replace that value with the address of 'win'
crash = ELF('./crash')
payload = fit({
cyclic_find(core.eip): crash.symbols.win
})
# Get a shell!
io = process(['./crash', payload])
io.sendline(b'id')
print(io.recvline())
# uid=1000(user) gid=1000(user) groups=1000(user)
Module Members
----------------------------------------
"""
from __future__ import absolute_import
from __future__ import division
import collections
import ctypes
import glob
import gzip
import re
import os
import socket
import subprocess
import tempfile
from io import BytesIO, StringIO
import elftools
from elftools.common.py3compat import bytes2str
from elftools.common.utils import roundup
from elftools.common.utils import struct_parse
from elftools.construct import CString
from pwnlib import atexit
from pwnlib.context import context
from pwnlib.elf.datatypes import *
from pwnlib.elf.elf import ELF
from pwnlib.log import getLogger
from pwnlib.tubes.process import process
from pwnlib.tubes.ssh import ssh_channel
from pwnlib.tubes.tube import tube
from pwnlib.util.fiddling import b64d
from pwnlib.util.fiddling import enhex
from pwnlib.util.fiddling import unhex
from pwnlib.util.misc import read
from pwnlib.util.misc import write
from pwnlib.util.packing import pack
from pwnlib.util.packing import unpack_many
log = getLogger(__name__)
prstatus_types = {
'i386': elf_prstatus_i386,
'amd64': elf_prstatus_amd64,
'arm': elf_prstatus_arm,
'aarch64': elf_prstatus_aarch64
}
prpsinfo_types = {
32: elf_prpsinfo_32,
64: elf_prpsinfo_64,
}
siginfo_types = {
32: elf_siginfo_32,
64: elf_siginfo_64
}
# Slightly modified copy of the pyelftools version of the same function,
# until they fix this issue:
# https://github.com/eliben/pyelftools/issues/93
def iter_notes(self):
""" Iterates the list of notes in the segment.
"""
offset = self['p_offset']
end = self['p_offset'] + self['p_filesz']
while offset < end:
note = struct_parse(
self.elffile.structs.Elf_Nhdr,
self.stream,
stream_pos=offset)
note['n_offset'] = offset
offset += self.elffile.structs.Elf_Nhdr.sizeof()
self.stream.seek(offset)
# n_namesz is 4-byte aligned.
disk_namesz = roundup(note['n_namesz'], 2)
note['n_name'] = bytes2str(
CString('').parse(self.stream.read(disk_namesz)))
offset += disk_namesz
desc_data = bytes2str(self.stream.read(note['n_descsz']))
note['n_desc'] = desc_data
offset += roundup(note['n_descsz'], 2)
note['n_size'] = offset - note['n_offset']
yield note
class Mapping(object):
"""Encapsulates information about a memory mapping in a :class:`Corefile`.
"""
def __init__(self, core, name, start, stop, flags, page_offset):
self._core=core
#: :class:`str`: Name of the mapping, e.g. ``'/bin/bash'`` or ``'[vdso]'``.
self.name = name or ''
#: :class:`int`: First mapped byte in the mapping
self.start = start
#: :class:`int`: First byte after the end of hte mapping
self.stop = stop
#: :class:`int`: Size of the mapping, in bytes
self.size = stop-start
#: :class:`int`: Offset in pages in the mapped file
self.page_offset = page_offset or 0
#: :class:`int`: Mapping flags, using e.g. ``PROT_READ`` and so on.
self.flags = flags
@property
def path(self):
""":class:`str`: Alias for :attr:`.Mapping.name`"""
return self.name
@property
def address(self):
""":class:`int`: Alias for :data:`Mapping.start`."""
return self.start
@property
def permstr(self):
""":class:`str`: Human-readable memory permission string, e.g. ``r-xp``."""
flags = self.flags
return ''.join(['r' if flags & 4 else '-',
'w' if flags & 2 else '-',
'x' if flags & 1 else '-',
'p'])
def __str__(self):
return '%x-%x %s %x %s' % (self.start,self.stop,self.permstr,self.size,self.name)
def __repr__(self):
return '%s(%r, start=%#x, stop=%#x, size=%#x, flags=%#x, page_offset=%#x)' \
% (self.__class__.__name__,
self.name,
self.start,
self.stop,
self.size,
self.flags,
self.page_offset)
def __int__(self):
return self.start
@property
def data(self):
""":class:`str`: Memory of the mapping."""
return self._core.read(self.start, self.size)
def __getitem__(self, item):
if isinstance(item, slice):
start = int(item.start or self.start)
stop = int(item.stop or self.stop)
# Negative slices...
if start < 0:
start += self.stop
if stop < 0:
stop += self.stop
if not (self.start <= start <= stop <= self.stop):
log.error("Byte range [%#x:%#x] not within range [%#x:%#x]",
start, stop, self.start, self.stop)
data = self._core.read(start, stop-start)
if item.step == 1:
return data
return data[::item.step]
return self._core.read(item, 1)
def __contains__(self, item):
if isinstance(item, Mapping):
return (self.start <= item.start) and (item.stop <= self.stop)
return self.start <= item < self.stop
def find(self, sub, start=None, end=None):
"""Similar to str.find() but works on our address space"""
if start is None:
start = self.start
if end is None:
end = self.stop
result = self.data.find(sub, start-self.address, end-self.address)
if result == -1:
return result
return result + self.address
def rfind(self, sub, start=None, end=None):
"""Similar to str.rfind() but works on our address space"""
if start is None:
start = self.start
if end is None:
end = self.stop
result = self.data.rfind(sub, start-self.address, end-self.address)
if result == -1:
return result
return result + self.address
class Corefile(ELF):
r"""Enhances the information available about a corefile (which is an extension
of the ELF format) by permitting extraction of information about the mapped
data segments, and register state.
Registers can be accessed directly, e.g. via ``core_obj.eax`` and enumerated
via :data:`Corefile.registers`.
Memory can be accessed directly via :meth:`.read` or :meth:`.write`, and also
via :meth:`.pack` or :meth:`.unpack` or even :meth:`.string`.
Arguments:
core: Path to the core file. Alternately, may be a :class:`.process` instance,
and the core file will be located automatically.
::
>>> c = Corefile('./core')
>>> hex(c.eax)
'0xfff5f2e0'
>>> c.registers
{'eax': 4294308576,
'ebp': 1633771891,
'ebx': 4151132160,
'ecx': 4294311760,
'edi': 0,
'edx': 4294308700,
'eflags': 66050,
'eip': 1633771892,
'esi': 0,
'esp': 4294308656,
'orig_eax': 4294967295,
'xcs': 35,
'xds': 43,
'xes': 43,
'xfs': 0,
'xgs': 99,
'xss': 43}
Mappings can be iterated in order via :attr:`Corefile.mappings`.
::
>>> Corefile('./core').mappings
[Mapping('/home/user/pwntools/crash', start=0x8048000, stop=0x8049000, size=0x1000, flags=0x5, page_offset=0x0),
Mapping('/home/user/pwntools/crash', start=0x8049000, stop=0x804a000, size=0x1000, flags=0x4, page_offset=0x1),
Mapping('/home/user/pwntools/crash', start=0x804a000, stop=0x804b000, size=0x1000, flags=0x6, page_offset=0x2),
Mapping(None, start=0xf7528000, stop=0xf7529000, size=0x1000, flags=0x6, page_offset=0x0),
Mapping('/lib/i386-linux-gnu/libc-2.19.so', start=0xf7529000, stop=0xf76d1000, size=0x1a8000, flags=0x5, page_offset=0x0),
Mapping('/lib/i386-linux-gnu/libc-2.19.so', start=0xf76d1000, stop=0xf76d2000, size=0x1000, flags=0x0, page_offset=0x1a8),
Mapping('/lib/i386-linux-gnu/libc-2.19.so', start=0xf76d2000, stop=0xf76d4000, size=0x2000, flags=0x4, page_offset=0x1a9),
Mapping('/lib/i386-linux-gnu/libc-2.19.so', start=0xf76d4000, stop=0xf76d5000, size=0x1000, flags=0x6, page_offset=0x1aa),
Mapping(None, start=0xf76d5000, stop=0xf76d8000, size=0x3000, flags=0x6, page_offset=0x0),
Mapping(None, start=0xf76ef000, stop=0xf76f1000, size=0x2000, flags=0x6, page_offset=0x0),
Mapping('[vdso]', start=0xf76f1000, stop=0xf76f2000, size=0x1000, flags=0x5, page_offset=0x0),
Mapping('/lib/i386-linux-gnu/ld-2.19.so', start=0xf76f2000, stop=0xf7712000, size=0x20000, flags=0x5, page_offset=0x0),
Mapping('/lib/i386-linux-gnu/ld-2.19.so', start=0xf7712000, stop=0xf7713000, size=0x1000, flags=0x4, page_offset=0x20),
Mapping('/lib/i386-linux-gnu/ld-2.19.so', start=0xf7713000, stop=0xf7714000, size=0x1000, flags=0x6, page_offset=0x21),
Mapping('[stack]', start=0xfff3e000, stop=0xfff61000, size=0x23000, flags=0x6, page_offset=0x0)]
Examples:
Let's build an example binary which should eat ``R0=0xdeadbeef``
and ``PC=0xcafebabe``.
If we run the binary and then wait for it to exit, we can get its
core file.
>>> context.clear(arch='arm')
>>> shellcode = shellcraft.mov('r0', 0xdeadbeef)
>>> shellcode += shellcraft.mov('r1', 0xcafebabe)
>>> shellcode += 'bx r1'
>>> address = 0x41410000
>>> elf = ELF.from_assembly(shellcode, vma=address)
>>> io = elf.process(env={'HELLO': 'WORLD'})
>>> io.poll(block=True)
-11
You can specify a full path a la ``Corefile('/path/to/core')``,
but you can also just access the :attr:`.process.corefile` attribute.
There's a lot of behind-the-scenes logic to locate the corefile for
a given process, but it's all handled transparently by Pwntools.
>>> core = io.corefile
The core file has a :attr:`exe` property, which is a :class:`.Mapping`
object. Each mapping can be accessed with virtual addresses via subscript, or
contents can be examined via the :attr:`.Mapping.data` attribute.
>>> core.exe # doctest: +ELLIPSIS
Mapping('/.../step3', start=..., stop=..., size=0x1000, flags=0x..., page_offset=...)
>>> hex(core.exe.address)
'0x41410000'
The core file also has registers which can be accessed direclty.
Pseudo-registers :attr:`pc` and :attr:`sp` are available on all architectures,
to make writing architecture-agnostic code more simple.
If this were an amd64 corefile, we could access e.g. ``core.rax``.
>>> core.pc == 0xcafebabe
True
>>> core.r0 == 0xdeadbeef
True
>>> core.sp == core.r13
True
We may not always know which signal caused the core dump, or what address
caused a segmentation fault. Instead of accessing registers directly, we
can also extract this information from the core dump via :attr:`fault_addr`
and :attr:`signal`.
On QEMU-generated core dumps, this information is unavailable, so we
substitute the value of PC. In our example, that's correct anyway.
>>> core.fault_addr == 0xcafebabe
True
>>> core.signal
11
Core files can also be generated from running processes.
This requires GDB to be installed, and can only be done with native processes.
Getting a "complete" corefile requires GDB 7.11 or better.
>>> elf = ELF(which('bash-static'))
>>> context.clear(binary=elf)
>>> env = dict(os.environ)
>>> env['HELLO'] = 'WORLD'
>>> io = process(elf.path, env=env)
>>> io.sendline(b'echo hello')
>>> io.recvline()
b'hello\n'
The process is still running, but accessing its :attr:`.process.corefile` property
automatically invokes GDB to attach and dump a corefile.
>>> core = io.corefile
>>> io.close()
The corefile can be inspected and read from, and even exposes various mappings
>>> core.exe # doctest: +ELLIPSIS
Mapping('.../bin/bash-static', start=..., stop=..., size=..., flags=..., page_offset=...)
>>> core.exe.data[0:4]
b'\x7fELF'
It also supports all of the features of :class:`ELF`, so you can :meth:`.read`
or :meth:`.write` or even the helpers like :meth:`.pack` or :meth:`.unpack`.
Don't forget to call :meth:`.ELF.save` to save the changes to disk.
>>> core.read(elf.address, 4)
b'\x7fELF'
>>> core.pack(core.sp, 0xdeadbeef)
>>> core.save()
Let's re-load it as a new :attr:`Corefile` object and have a look!
>>> core2 = Corefile(core.path)
>>> hex(core2.unpack(core2.sp))
'0xdeadbeef'
Various other mappings are available by name, for the first segment of:
* :attr:`.exe` the executable
* :attr:`.libc` the loaded libc, if any
* :attr:`.stack` the stack mapping
* :attr:`.vvar`
* :attr:`.vdso`
* :attr:`.vsyscall`
On Linux, 32-bit Intel binaries should have a VDSO section via :attr:`vdso`.
Since our ELF is statically linked, there is no libc which gets mapped.
>>> core.vdso.data[:4]
b'\x7fELF'
>>> core.libc
But if we dump a corefile from a dynamically-linked binary, the :attr:`.libc`
will be loaded.
>>> process('bash').corefile.libc # doctest: +ELLIPSIS
Mapping('/.../libc-....so', start=0x..., stop=0x..., size=0x..., flags=..., page_offset=...)
The corefile also contains a :attr:`.stack` property, which gives
us direct access to the stack contents. On Linux, the very top of the stack
should contain two pointer-widths of NULL bytes, preceded by the NULL-
terminated path to the executable (as passed via the first arg to ``execve``).
>>> core.stack # doctest: +ELLIPSIS
Mapping('[stack]', start=0x..., stop=0x..., size=0x..., flags=0x6, page_offset=0x0)
When creating a process, the kernel puts the absolute path of the binary and some
padding bytes at the end of the stack. We can look at those by looking at
``core.stack.data``.
>>> size = len('/bin/bash-static') + 8
>>> core.stack.data[-size:]
b'bin/bash-static\x00\x00\x00\x00\x00\x00\x00\x00\x00'
We can also directly access the environment variables and arguments, via
:attr:`.argc`, :attr:`.argv`, and :attr:`.env`.
>>> 'HELLO' in core.env
True
>>> core.string(core.env['HELLO'])
b'WORLD'
>>> core.getenv('HELLO')
b'WORLD'
>>> core.argc
1
>>> core.argv[0] in core.stack
True
>>> core.string(core.argv[0]) # doctest: +ELLIPSIS
b'.../bin/bash-static'
Corefiles can also be pulled from remote machines via SSH!
>>> s = ssh(user='travis', host='example.pwnme', password='demopass')
>>> _ = s.set_working_directory()
>>> elf = ELF.from_assembly(shellcraft.trap())
>>> path = s.upload(elf.path)
>>> _ =s.chmod('+x', path)
>>> io = s.process(path)
>>> io.wait(1)
-1
>>> io.corefile.signal == signal.SIGTRAP # doctest: +SKIP
True
Make sure fault_addr synthesis works for amd64 on ret.
>>> context.clear(arch='amd64')
>>> elf = ELF.from_assembly('push 1234; ret')
>>> io = elf.process()
>>> io.wait(1)
>>> io.corefile.fault_addr
1234
Corefile.getenv() works correctly, even if the environment variable's
value contains embedded '='. Corefile is able to find the stack, even
if the stack pointer doesn't point at the stack.
>>> elf = ELF.from_assembly(shellcraft.crash())
>>> io = elf.process(env={'FOO': 'BAR=BAZ'})
>>> io.wait(1)
>>> core = io.corefile
>>> core.getenv('FOO')
b'BAR=BAZ'
>>> core.sp == 0
True
>>> core.sp in core.stack
False
Corefile gracefully handles the stack being filled with garbage, including
argc / argv / envp being overwritten.
>>> context.clear(arch='i386')
>>> assembly = '''
... LOOP:
... mov dword ptr [esp], 0x41414141
... pop eax
... jmp LOOP
... '''
>>> elf = ELF.from_assembly(assembly)
>>> io = elf.process()
>>> io.wait(2)
>>> core = io.corefile
[!] End of the stack is corrupted, skipping stack parsing (got: 41414141)
>>> core.argc, core.argv, core.env
(0, [], {})
>>> core.stack.data.endswith(b'AAAA')
True
>>> core.fault_addr == core.sp
True
"""
_fill_gaps = False
def __init__(self, *a, **kw):
#: The NT_PRSTATUS object.
self.prstatus = None
#: The NT_PRPSINFO object
self.prpsinfo = None
#: The NT_SIGINFO object
self.siginfo = None
#: :class:`list`: A list of :class:`.Mapping` objects for each loaded memory region
self.mappings = []
#: :class:`int`: A :class:`Mapping` corresponding to the stack
self.stack = None
"""
Environment variables read from the stack.
Keys are the environment variable name, values are the memory
address of the variable.
Use :meth:`.getenv` or :meth:`.string` to retrieve the textual value.
Note: If ``FOO=BAR`` is in the environment, ``self.env['FOO']`` is the address of the string ``"BAR\x00"``.
"""
self.env = {}
#: :class:`int`: Pointer to envp on the stack
self.envp_address = 0
#: :class:`list`: List of addresses of arguments on the stack.
self.argv = []
#: :class:`int`: Pointer to argv on the stack
self.argv_address = 0
#: :class:`int`: Number of arguments passed
self.argc = 0
#: :class:`int`: Pointer to argc on the stack
self.argc_address = 0
# Pointer to the executable filename on the stack
self.at_execfn = 0
# Pointer to the entry point
self.at_entry = 0
try:
super(Corefile, self).__init__(*a, **kw)
except IOError:
log.warning("No corefile. Have you set /proc/sys/kernel/core_pattern?")
raise
self.load_addr = 0
self._address = 0
if self.elftype != 'CORE':
log.error("%s is not a valid corefile" % self.file.name)
if self.arch not in prstatus_types:
log.warn_once("%s does not use a supported corefile architecture, registers are unavailable" % self.file.name)
prstatus_type = prstatus_types.get(self.arch)
prpsinfo_type = prpsinfo_types.get(self.bits)
siginfo_type = siginfo_types.get(self.bits)
with log.waitfor("Parsing corefile...") as w:
self._load_mappings()
for segment in self.segments:
if not isinstance(segment, elftools.elf.segments.NoteSegment):
continue
# Note that older versions of pyelftools (<=0.24) are missing enum values
# for NT_PRSTATUS, NT_PRPSINFO, NT_AUXV, etc.
# For this reason, we have to check if note.n_type is any of several values.
for note in iter_notes(segment):
if not isinstance(note.n_desc, bytes):
note['n_desc'] = note.n_desc.encode('latin1')
# Try to find NT_PRSTATUS.
if prstatus_type and \
note.n_descsz == ctypes.sizeof(prstatus_type) and \
note.n_type in ('NT_GNU_ABI_TAG', 'NT_PRSTATUS'):
self.NT_PRSTATUS = note
self.prstatus = prstatus_type.from_buffer_copy(note.n_desc)
# Try to find NT_PRPSINFO
if prpsinfo_type and \
note.n_descsz == ctypes.sizeof(prpsinfo_type) and \
note.n_type in ('NT_GNU_ABI_TAG', 'NT_PRPSINFO'):
self.NT_PRPSINFO = note
self.prpsinfo = prpsinfo_type.from_buffer_copy(note.n_desc)
# Try to find NT_SIGINFO so we can see the fault
if note.n_type in (0x53494749, 'NT_SIGINFO'):
self.NT_SIGINFO = note
self.siginfo = siginfo_type.from_buffer_copy(note.n_desc)
# Try to find the list of mapped files
if note.n_type in (constants.NT_FILE, 'NT_FILE'):
with context.local(bytes=self.bytes):
self._parse_nt_file(note)
# Try to find the auxiliary vector, which will tell us
# where the top of the stack is.
if note.n_type in (constants.NT_AUXV, 'NT_AUXV'):
self.NT_AUXV = note
with context.local(bytes=self.bytes):
self._parse_auxv(note)
if not self.stack and self.mappings:
self.stack = self.mappings[-1].stop
if self.stack and self.mappings:
for mapping in self.mappings:
if self.stack in mapping or self.stack == mapping.stop:
mapping.name = '[stack]'
self.stack = mapping
break
else:
log.warn('Could not find the stack!')
self.stack = None
with context.local(bytes=self.bytes, log_level='warn'):
try:
self._parse_stack()
except ValueError:
# If there are no environment variables, we die by running
# off the end of the stack.
pass
# Corefiles generated by QEMU do not have a name for the
# main module mapping.
# Fetching self.exe will cause this to be auto-populated,
# and is a no-op in other cases.
self.exe
# Print out the nice display for the user
self._describe_core()
def _parse_nt_file(self, note):
t = tube()
t.unrecv(note.n_desc)
count = t.unpack()
page_size = t.unpack()
starts = []
addresses = {}
for i in range(count):
start = t.unpack()
end = t.unpack()
offset = t.unpack()
starts.append((start, offset))
for i in range(count):
filename = t.recvuntil(b'\x00', drop=True)
if not isinstance(filename, str):
filename = filename.decode('utf-8')
(start, offset) = starts[i]
for mapping in self.mappings:
if mapping.start == start:
mapping.name = filename
mapping.page_offset = offset
self.mappings = sorted(self.mappings, key=lambda m: m.start)
vvar = vdso = vsyscall = False
for mapping in reversed(self.mappings):
if mapping.name:
continue
if not vsyscall and mapping.start == 0xffffffffff600000:
mapping.name = '[vsyscall]'
vsyscall = True
continue
if mapping.start == self.at_sysinfo_ehdr \
or (not vdso and mapping.size in [0x1000, 0x2000]
and mapping.flags == 5
and self.read(mapping.start, 4) == b'\x7fELF'):
mapping.name = '[vdso]'
vdso = True
continue
if not vvar and mapping.size == 0x2000 and mapping.flags == 4:
mapping.name = '[vvar]'
vvar = True
continue
@property
def vvar(self):
""":class:`Mapping`: Mapping for the vvar section"""
for m in self.mappings:
if m.name == '[vvar]':
return m
@property
def vdso(self):
""":class:`Mapping`: Mapping for the vdso section"""
for m in self.mappings:
if m.name == '[vdso]':
return m
@property
def vsyscall(self):
""":class:`Mapping`: Mapping for the vsyscall section"""
for m in self.mappings:
if m.name == '[vsyscall]':
return m
@property
def libc(self):
""":class:`Mapping`: First mapping for ``libc.so``"""
expr = r'libc\b.*so$'
for m in self.mappings:
if not m.name:
continue
basename = os.path.basename(m.name)
if re.match(expr, basename):
return m
@property
def exe(self):
""":class:`Mapping`: First mapping for the executable file."""
# Finding the executable mapping requires knowing the entry point
# from the auxv
if not self.at_entry:
return None
# The entry point may not be in the first segment of a given file,
# but we want to find the first segment of the file -- not the segment that
# contains the entrypoint.
first_segment_for_name = {}
for m in self.mappings:
first_segment_for_name.setdefault(m.name, m)
# Find which segment conains the entry point
for m in self.mappings:
if m.start <= self.at_entry < m.stop:
if not m.name and self.at_execfn:
m.name = self.string(self.at_execfn)
if not isinstance(m.name, str):
m.name = m.name.decode('utf-8')
return first_segment_for_name.get(m.name, m)
@property
def pid(self):
""":class:`int`: PID of the process which created the core dump."""
if self.prstatus:
return int(self.prstatus.pr_pid)
@property
def ppid(self):
""":class:`int`: Parent PID of the process which created the core dump."""
if self.prstatus:
return int(self.prstatus.pr_ppid)
@property
def signal(self):
""":class:`int`: Signal which caused the core to be dumped.
Example:
>>> elf = ELF.from_assembly(shellcraft.trap())
>>> io = elf.process()
>>> io.wait(1)
>>> io.corefile.signal == signal.SIGTRAP
True
>>> elf = ELF.from_assembly(shellcraft.crash())
>>> io = elf.process()
>>> io.wait(1)
>>> io.corefile.signal == signal.SIGSEGV
True
"""
if self.siginfo:
return int(self.siginfo.si_signo)
if self.prstatus:
return int(self.prstatus.pr_cursig)
@property
def fault_addr(self):
""":class:`int`: Address which generated the fault, for the signals
SIGILL, SIGFPE, SIGSEGV, SIGBUS. This is only available in native
core dumps created by the kernel. If the information is unavailable,
this returns the address of the instruction pointer.
Example:
>>> elf = ELF.from_assembly('mov eax, 0xdeadbeef; jmp eax', arch='i386')
>>> io = elf.process()
>>> io.wait(1)
>>> io.corefile.fault_addr == io.corefile.eax == 0xdeadbeef
True
"""
if not self.siginfo:
return getattr(self, 'pc', 0)
fault_addr = int(self.siginfo.sigfault_addr)
# The fault_addr is zero if the crash occurs due to a
# "protection fault", e.g. a dereference of 0x4141414141414141
# because this is technically a kernel address.
#
# A protection fault does not set "fault_addr" in the siginfo.
# (http://elixir.free-electrons.com/linux/v4.14-rc8/source/kernel/signal.c#L1052)
#
# Since a common use for corefiles is to spray the stack with a
# cyclic pattern to find the offset to get control of $PC,
# check for a "ret" instruction ("\xc3").
#
# If we find a RET at $PC, extract the "return address" from the
# top of the stack.
if fault_addr == 0 and self.siginfo.si_code == 0x80:
try:
code = self.read(self.pc, 1)
RET = b'\xc3'
if code == RET:
fault_addr = self.unpack(self.sp)
except Exception:
# Could not read $rsp or $rip
pass
return fault_addr
# No embedded siginfo structure, so just return the
# current instruction pointer.
@property
def _pc_register(self):
name = {
'i386': 'eip',
'amd64': 'rip',
}.get(self.arch, 'pc')
return name
@property
def pc(self):
""":class:`int`: The program counter for the Corefile
This is a cross-platform way to get e.g. ``core.eip``, ``core.rip``, etc.
"""
return self.registers.get(self._pc_register, None)
@property
def _sp_register(self):
name = {
'i386': 'esp',
'amd64': 'rsp',
}.get(self.arch, 'sp')
return name
@property
def sp(self):
""":class:`int`: The stack pointer for the Corefile
This is a cross-platform way to get e.g. ``core.esp``, ``core.rsp``, etc.
"""
return self.registers.get(self._sp_register, None)
def _describe(self):
pass
def _describe_core(self):
gnu_triplet = '-'.join(map(str, (self.arch, self.bits, self.endian)))
fields = [
repr(self.path),
'%-10s %s' % ('Arch:', gnu_triplet),
'%-10s %#x' % ('%s:' % self._pc_register.upper(), self.pc or 0),
'%-10s %#x' % ('%s:' % self._sp_register.upper(), self.sp or 0),
]
if self.exe and self.exe.name:
fields += [
'%-10s %s' % ('Exe:', '%r (%#x)' % (self.exe.name, self.exe.address))
]
if self.fault_addr:
fields += [
'%-10s %#x' % ('Fault:', self.fault_addr)
]
log.info_once('\n'.join(fields))
def _load_mappings(self):
for s in self.segments:
if s.header.p_type != 'PT_LOAD':
continue
mapping = Mapping(self,
None,
s.header.p_vaddr,
s.header.p_vaddr + s.header.p_memsz,
s.header.p_flags,
None)
self.mappings.append(mapping)
def _parse_auxv(self, note):
t = tube()
t.unrecv(note.n_desc)
for i in range(0, note.n_descsz, context.bytes * 2):
key = t.unpack()
value = t.unpack()
# The AT_EXECFN entry is a pointer to the executable's filename
# at the very top of the stack, followed by a word's with of
# NULL bytes. For example, on a 64-bit system...
#
# 0x7fffffffefe8 53 3d 31 34 33 00 2f 62 69 6e 2f 62 61 73 68 00 |S=14|3./b|in/b|ash.|
# 0x7fffffffeff8 00 00 00 00 00 00 00 00 |....|....| | |
if key == constants.AT_EXECFN:
self.at_execfn = value
value = value & ~0xfff
value += 0x1000
self.stack = value
if key == constants.AT_ENTRY:
self.at_entry = value
if key == constants.AT_PHDR:
self.at_phdr = value
if key == constants.AT_BASE:
self.at_base = value
if key == constants.AT_SYSINFO_EHDR:
self.at_sysinfo_ehdr = value
def _parse_stack(self):
# Get a copy of the stack mapping
stack = self.stack
if not stack:
return
# If the stack does not end with zeroes, something is very wrong.
if not stack.data.endswith(b'\x00' * context.bytes):
log.warn_once("End of the stack is corrupted, skipping stack parsing (got: %s)",
enhex(self.data[-context.bytes:]))
return