This repository was archived by the owner on Oct 18, 2020. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathheap_analysis.py
More file actions
5538 lines (4358 loc) · 219 KB
/
Copy pathheap_analysis.py
File metadata and controls
5538 lines (4358 loc) · 219 KB
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
# glibc heap analysis classes
#
# Copyright (c) 2018, Frank Block, ERNW GmbH <fblock@ernw.de>
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * The names of the contributors may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
This module implements several classes, allowing the glibc heap analysis for a
given process.
"""
from __future__ import print_function
__author__ = "Frank Block <fblock@ernw.de>"
import re
import pdb
import struct
import traceback
from numbers import Number
from builtins import str
from builtins import hex
from builtins import range
from rekall.plugins.overlays import basic
from rekall.plugins.linux import common
from rekall.plugins.linux import cpuinfo
from rekall.plugins.addrspaces.intel import InvalidAddress
from rekall.io_manager import IOManagerError
from rekall.plugins import yarascanner
from rekall.plugins import core
from rekall import addrspace
from rekall import scan
from rekall import obj
from rekall_lib import utils
#############
_PREV_INUSE = 0x1
_IS_MMAPPED = 0x2
_NON_MAIN_ARENA = 0x4
_SIZE_BITS = (_PREV_INUSE | _IS_MMAPPED | _NON_MAIN_ARENA)
# is set on HeapAnalysis instantiation
_MIN_LARGE_SIZE = None
# Probably more versions would work, especially when the corresponding vtype
# information are provided, but those are the versions we tested against
_SUPPORTED_GLIBC_VERSIONS = ['2.27', '2.26', '2.25', '2.24', '2.23', '2.22', '2.21', '2.20']
_LIBC_REGEX = '(?:^|/)libc[^a-zA-Z][^/]*\\.so'
def get_vma_for_offset(vmas, offset):
"""Returns a list with identifier and vm_area that given offset belongs to.
Expects the output from _get_vmas_for_task as argument.
"""
vma = vmas.get_containing_range(offset)
return None if vma[0] == None else vma
def get_vma_name_for_regex(vmas, regex):
"""Searches all vma names for the given regex and returns the first hit."""
if not vmas or not regex:
return None
for _, _, vm_data in vmas:
if re.search(regex, vm_data['name'], re.IGNORECASE):
return vm_data['name']
def get_libc_filename(vmas):
"""Returns the libc file name from the vma, where the _LIBC_REGEX matches.
"""
return get_vma_name_for_regex(vmas, _LIBC_REGEX)
def get_libc_range(vmas):
"""Returns the lowest and highest address for the libc vma. See also
get_mem_range_for_regex."""
return get_mem_range_for_regex(vmas, _LIBC_REGEX)
def get_mem_range_for_regex(vmas, regex):
"""Returns the lowest and highest address of memory areas belonging to the
vm_areas, the given regex matches on. The result is given as a list, where
the lowest address is the first element. Expects the output from
_get_vmas_for_task as argument."""
offsets = None
if not vmas:
return None
for vm_start, vm_end, vm_data in vmas:
if re.search(regex, vm_data['name'], re.IGNORECASE):
if not offsets:
offsets = [vm_start]
offsets.append(vm_end)
else:
if vm_start < offsets[0]:
offsets[0] = vm_start
if vm_end > offsets[1]:
offsets[1] = vm_end
return offsets
class HeapAnalysis(common.LinProcessFilter):
"""Basic abstract class for linux heap analysis.
Mostly serves the main_arena.
"""
__abstract = True
_main_heap_identifier = "[heap]"
# used to mark vm_areas residing between the [heap] and the first file or
# stack object and all other vm_areas that have no file object for
# (mmapped regions can also reside somewhere beyond the typical heap/stack
# area) note that vmas with this identifier might be empty, old thread
# stacks or vm_areas belonging to e.g. mapped files.
# A pretty reliable source for heap vm_areas is the self.heap_vmas list as
# it contains vm_areas which are identified to most probably belong to a
# heap or mmapped region.
_heap_vma_identifier = "[heap-vma]"
_pot_mmapped_vma_identifier = "[pot-mmapped-vma]"
# is normally only automatically set when using a dummy arena or the chunk
# dumper, as in those cases all chunks are walked at least two times
def activate_chunk_preservation(self):
"""Sets _preserve_chunks to True. This forces all allocated chunk
functions to store chunks in lists, which highly increases the speed
of a second walk over those chunks. This feature can be disabled
with the cmd line option disable_chunk_preservation."""
if not self._preserve_chunks and \
not self.plugin_args.disable_chunk_preservation:
self.session.logging.info(
"Chunk preservation has been activated. "
"This might consume large amounts of memory "
"depending on the chunk count. If you are low on free memory "
"space (RAM), you might want to deactivate this feature by "
"using the cmd line option disable_chunk_preservation. The "
"only downside is a longer plugin runtime.")
self._preserve_chunks = True
def _get_saved_stack_frame_pointers(self, task):
"""Returns a list of dicts, containing the ebp,esp and pid values
for each thread."""
if not task.mm:
return None
# To gather thread stacks, we examine the pt_regs struct for each
# thread and extract the saved stack frame pointers
thread_stack_offsets = []
thread_group_offset = self.profile.get_obj_offset("task_struct",
"thread_group")
for thread_group in task.thread_group.walk_list("prev"):
thread_task = self.profile.task_struct(
offset=thread_group.obj_offset - thread_group_offset,
vm=self.process_as)
pt_regs = self._get_task_pt_regs(thread_task)
thread_stack_offsets.append(dict(ebp=pt_regs.bp.v(),
esp=pt_regs.sp.v(),
pid=thread_task.pid.v()))
return thread_stack_offsets
def _get_pt_regs_offset(self):
"""Used for _get_task_pt_regs"""
# taken from arch/x86/include/asm/page_64_types.h
TOP_OF_KERNEL_STACK_PADDING = 0
if self.session.profile.get_kernel_config('CONFIG_X86_32'):
if self.session.profile.get_kernel_config('CONFIG_VM86'):
TOP_OF_KERNEL_STACK_PADDING = 16
else:
TOP_OF_KERNEL_STACK_PADDING = 8
if self.session.profile.get_kernel_config("CONFIG_KASAN"):
KASAN_STACK_ORDER = 1
else:
KASAN_STACK_ORDER = 0
if self.session.profile.metadata("arch") == 'AMD64':
THREAD_SIZE_ORDER = 2 + KASAN_STACK_ORDER
else:
THREAD_SIZE_ORDER = 1
THREAD_SIZE = self._min_pagesize << THREAD_SIZE_ORDER
return THREAD_SIZE - TOP_OF_KERNEL_STACK_PADDING
def _get_task_pt_regs(self, thread_task):
# Since sp0 is not accessible anymore on x86_64, we use this method
# See https://lore.kernel.org/patchwork/patch/828764/
# and task_pt_regs in arch/x86/include/asm/processor.h
pt_regs_offset = thread_task.stack.v() + self._pt_regs_offset
pt_regs_offset -= self.profile.get_obj_size("pt_regs")
return self.profile.pt_regs(offset=pt_regs_offset, vm=self.process_as)
# Basically the code from the proc_maps plugin but with thread specific
# enhancements
def _get_vmas_for_task(self, task):
"""Returns a list of lists, containing ["name", vm_area] pairs. """
if not task.mm:
return None
result = utils.RangedCollection()
thread_stack_offsets = self._get_saved_stack_frame_pointers(task)
if not thread_stack_offsets:
thread_stack_offsets = list()
thread_stack_offsets.append(dict(ebp=0,
esp=0,
pid=task.pid.v()))
# The first pair contains the "main" thread and the mm start_stack
# value is more reliable for identifying the relevant memory region
# than the saved frame pointers
thread_stack_offsets[0]['start_stack'] = task.mm.start_stack
heap_area = False
for vma in task.mm.mmap.walk_list("vm_next"):
data = dict()
data['vm_flags'] = ''.join(vma.vm_flags)
if vma.vm_file.dereference():
data['is_file'] = True
fname = task.get_path(vma.vm_file)
if heap_area:
heap_area = False
else:
data['is_file'] = False
fname = ""
if heap_area:
fname = self._heap_vma_identifier
else:
fname = self._pot_mmapped_vma_identifier
# main heap can have 3 or more vm_area_struct structs
if vma.vm_start <= task.mm.start_brk <= vma.vm_end or \
(task.mm.start_brk <= vma.vm_start
< vma.vm_end <= task.mm.brk) or \
vma.vm_start <= task.mm.brk <= vma.vm_end:
fname = self._main_heap_identifier
heap_area = True
else:
for offsets in thread_stack_offsets:
if (('start_stack' in list(offsets.keys()) and
vma.vm_start <= offsets['start_stack']
<= vma.vm_end) or
vma.vm_start <= offsets['esp'] <= vma.vm_end):
fname = "[stack"
pid = offsets['pid']
fname += "]" if task.pid == pid else \
":{:d}]".format(pid)
data['ebp'] = offsets['ebp']
data['esp'] = offsets['esp']
heap_area = False
data['name'] = fname
result.insert(vma.vm_start, vma.vm_end, data)
return result
def _load_libc_profile(self):
"""Loads the Libc profile for the current libc version."""
libc_version_string = None
libc_profile = None
if self.plugin_args.glibc_version:
libc_version_string = str(self.plugin_args.glibc_version)
else:
# we try to gather version information from the mapped libc lib
major_version = None
minor_version = None
match = None
libc_filename = get_libc_filename(self.vmas)
if libc_filename:
match = re.search(r'(\d+)\.(\d+)', libc_filename)
# Fallback
libc_version_string = '224'
if match and len(match.groups()) == 2:
major_version = int(match.group(1))
minor_version = int(match.group(2))
libc_version_string = str(major_version) + str(minor_version)
self.session.logging.info("Trying to load profile for version {:s}"
" from the repository."
.format(libc_version_string))
# TODO: dynamic selection of distribution specific profiles
dist = 'base'
libc_profile = None
try:
libc_profile = self.session.LoadProfile(
"glibc/{:s}/{:s}/{:s}".format(dist,
self.profile.metadata("arch"),
libc_version_string))
except IOManagerError as ex:
# gets e.g. thrown when a specified repository folder is not
# existent
self.session.logging.warn(
"Error while trying to load a repository: {:s}"
.format(str(ex)))
if not libc_profile:
# fallback: there seems to be no profile from the repository,
# so we try to load a profile internally
self.session.logging.info(
"Repository failed: Now using internal profiles.")
if not self.plugin_args.glibc_version and major_version and \
minor_version:
if major_version == 2:
if minor_version >= 26:
libc_version_string = '226'
elif minor_version == 24 or minor_version == 25:
libc_version_string = '224'
elif minor_version == 23:
libc_version_string = '223'
else:
libc_version_string = '220'
else:
self.session.logging.warn(
"Unsupported glibc major version number.")
self.session.logging.info(
"Loading internal profile for version {:s}."
.format(libc_version_string))
if self.session.profile.metadata("arch") == 'I386':
libc_profile = GlibcProfile32(version=libc_version_string,
session=self.session)
elif self.session.profile.metadata("arch") == 'AMD64':
libc_profile = GlibcProfile64(version=libc_version_string,
session=self.session)
if not libc_profile:
self.session.logging.error('Unable to load a libc profile.')
else:
self._libc_version = libc_version_string
self.profile.add_types(libc_profile.vtypes)
self.profile.add_constants(libc_profile.constants)
if all(x in list(self.profile.vtypes.keys()) for x in
['malloc_chunk', 'malloc_state',
'malloc_par', '_heap_info']):
self._libc_profile_success = True
self.profile.add_classes(dict(malloc_state=malloc_state,
_heap_info=_heap_info,
malloc_chunk=malloc_chunk))
else:
self.session.logging.error('Error while loading libc profile.')
def _check_and_report_chunksize(
self, chunk, current_border, mmapped=False):
"""Checks whether or not the current chunk
- is bigger than the given border
- smaller than the minimum size a chunk is allowed to be
- 's address is aligned.
"""
if chunk.v() + chunk.chunksize() > current_border:
self.session.logging.warn(
"Chunk at offset 0x{:x} has a size larger than the current "
"memory region. This shouldn't be the case."
.format(chunk.v()))
return False
if chunk.chunksize() < self._minsize:
if not self._check_and_report_chunk_for_being_swapped(chunk):
self.session.logging.warn(
"Chunk at offset 0x{:x} has a size smaller than MINSIZE, "
"which shouldn't be the case and indicates a problem."
.format(chunk.v()))
return False
# If the MALLOC_ALIGNMENT has been changed via compile time options,
# mmapped chunks are shifted a few bytes forward to be aligned, while
# the size of the gap is saved in the prev_size field (see also
# explanation for self._front_misalign_correction).
# This gap must be included in the calculation for aligned_ok
chunksize = chunk.chunksize() + chunk.get_prev_size() if mmapped else \
chunk.chunksize()
if not self._aligned_ok(chunksize):
self.session.logging.warn(
"The size of chunk at offset 0x{:x} is not a multiple of "
"MALLOC_ALIGNMENT, which shouldn't be the case and indicates "
"a problem.".format(chunk.v()))
return False
return True
def _check_and_report_chunk_for_being_swapped(self, chunk):
"""Tests the size field of a given chunk for being swapped."""
if not chunk:
# as we don't have any object to analyze further, we just return
# true in this case
return True
elif chunk.get_size() == 0:
# since the name for the size field for malloc_chunk changed in the
# past, we don't gather the offset for the size field via
# get_obj_offset, but use obj_size
size_offset = chunk.prev_size.obj_size
if self._check_address_for_being_swapped(chunk.v() + size_offset):
self.session.logging.warn(
"The memory page(s) belonging to the "
"chunk at offset 0x{:x} have been swapped. This will "
"lead to incorrect/incomplete results and more "
"warnings/errors.".format(chunk.v()))
return True
else:
self.session.logging.warn(
"The memory page(s) belonging to the chunk at offset "
"0x{:x} don't seem to have been swapped, but the chunk "
"has a size of 0, which shouldn't be the case and "
"will lead to incorrect/incomplete results and more "
"warnings/errors.".format(chunk.v()))
return False
def _check_address_for_being_swapped(self, address):
"""Retrieves the PTE entry information for the given address and tests
whether the page is swapped."""
for translation_descriptor in self.process_as.describe_vtop(address):
if isinstance(translation_descriptor, InvalidAddress):
return True
return False
def _check_and_report_allocated_chunk(
self, arena, chunk, next_chunk, current_border):
"""Checks if the given chunk should be in use (depending on the
PREV_INUSE bit of the next chunk), has a size > MINSIZE, is aligned,
whether or not it is part of any bin or fastbin in conjunction with
next_chunks PREV_INUSE bit and if next_chunks prev_size field has
same value as current chunk's size. This function is not intended to
be used for the "bottom chunks". It returns True if no error occurs
and if the given chunk is not part of bins or fastbins.
"""
error_base_string = (
"Found a presumably {0} chunk at offset 0x{1:x} which is however "
"{2}part of the bins. This is unexpected and might either "
"indicate an error or possibly in seldom cases be the result "
"from a race condition.")
if not self._check_and_report_chunksize(chunk, current_border):
return False
if not self._aligned_ok(self._chunk2mem(chunk)):
self.session.logging.warn(
"Chunk at offset 0x{:x} is not aligned. As chunks are normally"
" always aligned, this indicates a mistakenly chosen chunk and"
" probably results in wrong results.".format(chunk.v()))
return False
# current chunk is tested in _check_and_report_chunksize for
# being swapped
self._check_and_report_chunk_for_being_swapped(next_chunk)
if next_chunk.prev_inuse():
# for chunks in fastbins, the prev_inuse bit is not unset,
# so we don't check that here
if chunk in arena.freed_chunks:
# freed chunks shouldn't be marked as in use
self.session.logging.warn(
error_base_string.format("allocated", chunk.v(), "")
)
elif chunk not in \
(arena.freed_fast_chunks + arena.freed_tcache_chunks):
return True
else:
# current chunk seems to be freed, hence its size should equal
# next chunk's prev_size
if chunk.chunksize() != next_chunk.get_prev_size():
self.session.logging.warn(
"Chunk at offset 0x{:x} seems to be freed but its size "
"doesn't match the next chunk's prev_size value."
.format(chunk.v()))
elif chunk in \
(arena.freed_fast_chunks + arena.freed_tcache_chunks):
# fastbins/tcache chunks normally have the prev_inuse bit set
self.session.logging.warn(
"Unexpected: Found fastbin-chunk at offset 0x{0:x} which "
"prev_inuse bit is unset. This shouldn't normally be the "
"case.".format(chunk.v()))
elif chunk not in arena.freed_chunks:
# chunk is not marked as in use, but neither part of any bin
# or fastbin
self.session.logging.warn(
error_base_string.format("freed", chunk.v(), "not ")
)
return False
def _allocated_chunks_for_mmapped_chunk(self, mmap_first_chunk):
"""Returns all allocated chunks for the mmap region the given chunk
belongs to."""
if not mmap_first_chunk:
self.session.logging.warn(
"_allocated_chunks_for_mmapped_chunk has been called with "
"invalid pointer.")
return
mmap_vma = get_vma_for_offset(self.vmas, mmap_first_chunk.v())
current_border = mmap_vma[1]
# we can't check here for hitting the bottom, as mmapped regions can
# contain slack space but this test is in essence done in
# check_and_report_mmap_chunk
for curr_chunk in self.iterate_through_chunks(
mmap_first_chunk, current_border):
if self._check_and_report_mmapped_chunk(curr_chunk, mmap_vma) \
and self._check_and_report_chunksize(curr_chunk,
current_border,
mmapped=True):
yield curr_chunk
else:
# As the checks for the last MMAPPED chunk reported an error,
# we are stopping walking the MMAPPED chunks for that vm_area.
break
def get_all_mmapped_chunks(self):
"""Returns all allocated MMAPPED chunks."""
main_arena = self.get_main_arena()
if main_arena:
if main_arena.allocated_mmapped_chunks:
for chunk in main_arena.allocated_mmapped_chunks:
yield chunk
return
main_arena.allocated_mmapped_chunks = list()
for mmap_first_chunk in main_arena.mmapped_first_chunks:
for chunk in self._allocated_chunks_for_mmapped_chunk(
mmap_first_chunk):
main_arena.allocated_mmapped_chunks.append(chunk)
yield chunk
def get_aligned_address(self, address, different_align_mask=None):
"""Returns an aligned address."""
align_mask = different_align_mask or self._malloc_align_mask
aligned_address = self._address2mem(address)
aligned_address = (aligned_address + align_mask) & ~ align_mask
return self._mem2address(aligned_address)
######### code taken from malloc/malloc.c (glibc-2.23)
def _chunk2mem(self, chunk):
"""Returns the offset of the fd member (start of the data for a non
freed chunk). This is mainly used in conjunction with _aligned_ok, as
Glibc checks the alignment of chunks based on the data/fd offset."""
return (chunk.v() + self._chunk_fd_member_offset)
def _aligned_ok(self, value):
"""Returns True if the given address/size is aligned."""
return (value & self._malloc_align_mask) == 0
# essentially the request2size macro code
def get_aligned_size(self, size):
"""Returns an aligned size, which is essentially the chunk's final
size, resulting from asking Glibc for a chunk of a specific size.
E.g. calling malloc(16) will on all platforms result in a chunk with
a size > 16.
This function can be used to find chunks with a size that probably
contains the data of interest. For example: if we search for chunks
containing a struct of size 48, the resulting chunk's size can be
calculated by calling get_aligned_size(48)."""
if size + self._size_sz + self._malloc_align_mask < self._minsize:
return self._minsize & ~ self._malloc_align_mask
return (int(size + self._size_sz + self._malloc_align_mask)
& ~ self._malloc_align_mask)
# essentially an implementation of the call
# fastbin_index (request2size (MAX_FAST_SIZE)) + 1)
def _get_nfastbins(self):
"""Returns the number of fastbins. This count depends on the one hand
on the architecture and on the other hand on the MALLOC_ALIGNMENT
value."""
max_fast_size = (80 * self._size_sz) / 4
shift_bits = 4 if self._size_sz == 8 else 3
return ((self.get_aligned_size(max_fast_size) >> shift_bits) - 2) + 1
###########
def _address2mem(self, address):
"""Essentially the same as _chunk2mem but works on an address instead
of a chunk."""
return address + self._chunk_fd_member_offset
def _mem2address(self, address):
"""Reverse function of _address2mem."""
return address - self._chunk_fd_member_offset
def _check_mmap_alignment(self, address):
"""Returns True if the given address is aligned according to the
minimum pagesize."""
return (address & (self._min_pagesize - 1)) == 0
def _get_page_aligned_address(self, address):
"""Returns an address aligned to the internal pagesize.
The given address should be a number, not a chunk.
This function is primarily used in the context of MMAPPED chunks.
"""
return (address + self._min_pagesize - 1) & ~ (self._min_pagesize - 1)
def _check_for_bottom_chunks(self, chunk, heap_end):
"""Checks the current chunk for conditions normally only found on the
second last chunk of a heap, when there are more heaps following.
"""
if chunk.chunksize() <= self._minsize and \
(chunk.v() + chunk.chunksize() + (self._size_sz * 2)) == \
heap_end:
return True
return False
def _is_bottom_chunk(
self, chunk, next_chunk, current_border, is_last_heap):
"""Returns true if the given chunk is the first of the bottom
chunks, located at the end of a thread arena's heap segment, described
by a heap_info struct."""
# on multiple heaps, for all but the last heap, the old
# top chunk is divided in at least two chunks at the
# bottom, where the second last has a size of
# minimum 2 * SIZE_SZ and maximum MINSIZE the last chunk
# has a size of 2* SIZE_SZ while the size field is set
# to 0x1 (the PREV_INUSE bit is set) and the prev_size
# contains the second last chunks size
# (min: 2 * SIZE_SZ , max: MINSIZE)
#
# see the part for creating a new heap within the
# sysmalloc function in malloc/malloc.c
# For glibc-2.23 beginning with line 2417
#
# as this behavior is included since version 2.0.1 from
# 1997, it should be safe to rely on it for most glibc
# versions
# the first bottom chunk is not bigger than MINSIZE
if not chunk.chunksize() <= self._minsize:
return False
# with a different MALLOC_ALIGNMENT, there might be a gap after the
# last bottom chunk and the end of the memory region
possible_borders = [current_border]
if self._front_misalign_correction:
possible_borders.append(current_border - (self._size_sz * 2))
if not (chunk.v() + chunk.chunksize() + (self._size_sz * 2)) in \
possible_borders:
# the chunk is not on the edge to the current heap region
if chunk.chunksize() < self._minsize:
self.session.logging.warn(
"Unexpected: We hit a chunk at offset 0x{0:x} "
"with a size smaller than the default minimum "
"size for a chunk but which appears to be "
"not part of the typical end of a heap. This "
"might either indicate a fatal error, or "
"maybe a custom libc implementation/custom "
"compile time flags.".format(chunk.v()))
return False
# from here on, everything looks like we are at the bottom chunks
# The last condition also tests if there are further heaps following.
# - if not, the current chunk which is only
# size_sz * 2 bytes away from the current heap's end
# shouldn't be that small and indicates an error
#
# - heap border shouldn't normally exist
if next_chunk.chunksize() == 0 and next_chunk.prev_inuse() and \
(next_chunk.get_prev_size() == chunk.chunksize()) and \
not is_last_heap:
if len(possible_borders) > 1 and chunk.v() + chunk.chunksize() \
+ (self._size_sz * 2) == possible_borders[1]:
self._bottom_chunk_gaps[chunk.v()] = \
self._size_sz * 2
return True
else:
self.session.logging.warn(
"Unexpected: We hit a chunk at offset 0x{0:x} "
"which presumably should have been the second "
"last chunk of that heap, but some conditions "
"don't meet.".format(chunk.v()))
def _allocated_chunks_for_thread_arena(self, arena):
"""Returns all allocated chunks contained in all heaps for the given
arena, assuming the arena is not the main_arena."""
if arena.is_main_arena:
self.session.logging.warn(
"Unexpected: This method has been called with the main_arena.")
# since main_arena doesn't contain heap_infos, we return here
return
if arena.allocated_chunks:
for chunk in arena.allocated_chunks:
yield chunk
return
elif self._preserve_chunks:
arena.allocated_chunks = list()
heap_count = len(arena.heaps)
for i in list(range(heap_count)):
heap = arena.heaps[i]
current_border = heap.v() + heap.size
hit_heap_bottom = False
last_chunk = None
curr_chunk = None
for next_chunk in heap.first_chunk.next_chunk_generator():
if not curr_chunk:
curr_chunk = next_chunk
continue
last_chunk = curr_chunk
if (curr_chunk.v() + curr_chunk.chunksize()) == current_border:
# we hit the top chunk
break
elif (curr_chunk.v() + curr_chunk.chunksize()) <= \
curr_chunk.v():
self.session.logging.warn(
"The chunk at offset 0x{:x} has a size <= 0, which "
"is unexpected and indicates a problem. Since we can't"
" iterate the chunks anymore, we abort for this chunk."
.format(curr_chunk.v()))
break
elif self._is_bottom_chunk(curr_chunk,
next_chunk,
current_border,
i == (heap_count - 1)):
# we probably hit the bottom of the current heap
# which should'nt be the last one
self.session.logging.info(
"We hit the expected two chunks at the bottom "
"of a heap. This is a good sign.")
hit_heap_bottom = True
curr_chunk.is_bottom_chunk = True
if self._preserve_chunks:
arena.allocated_chunks.append(curr_chunk)
yield curr_chunk
break
# normal chunk, not located at the bottom of the heap
elif self._check_and_report_allocated_chunk(
arena, curr_chunk, next_chunk, current_border):
self._check_and_report_non_main_arena(
curr_chunk, next_chunk.prev_inuse())
if self._preserve_chunks:
arena.allocated_chunks.append(curr_chunk)
yield curr_chunk
curr_chunk = next_chunk
if not hit_heap_bottom and \
(last_chunk.v() + last_chunk.chunksize()) < current_border:
self.session.logging.warn(
"Seems like we didn't hit the top chunk or the bottom of "
"the current heap at offset: 0x{0:x}".format(heap.v()))
def _allocated_chunks_for_main_arena(self):
"""Returns all allocated chunks for the main_arena's heap.
mmap'ed regions are not included.
"""
arena = self.get_main_arena()
if arena.allocated_chunks:
for chunk in arena.allocated_chunks:
yield chunk
else:
current_border = 0
if self._preserve_chunks:
arena.allocated_chunks = list()
if arena.first_chunk and arena.first_chunk.chunksize() > 0:
# as the main heap can spread among multiple vm_areas, we take
# the system_mem value as the upper boundary
if arena.system_mem > 0:
# system_mem includes the potential gap, resulting from
# a different MALLOC_ALIGNMENT, so we subtract
# self._front_misalign_correction
current_border = arena.first_chunk.v() + arena.system_mem \
- self._front_misalign_correction
# there have been rare scenarios, in which the system_mem
# value was 0
else:
self.session.logging.warn(
"Unexpected: system_mem value of main arena is <= 0. "
"We will calculate it with the top chunk. This will "
"lead to follow up warnings regarding size "
"inconsistencies.")
current_border = arena.top.v() + arena.top.chunksize()
last_chunk = None
curr_chunk = None
for next_chunk in arena.first_chunk.next_chunk_generator():
last_chunk = curr_chunk
if not curr_chunk:
curr_chunk = next_chunk
continue
if (curr_chunk.v() + curr_chunk.chunksize()) \
== current_border:
# reached top chunk
break
else:
if self._check_and_report_allocated_chunk(
arena, curr_chunk, next_chunk, current_border):
if self._preserve_chunks:
arena.allocated_chunks.append(curr_chunk)
yield curr_chunk
curr_chunk = next_chunk
if (last_chunk.v() + last_chunk.chunksize()) < current_border:
self.session.logging.warn("Seems like we didn't hit the "
"top chunk for main_arena.")
elif arena.first_chunk and arena.first_chunk.chunksize() == 0:
if not self._libc_offset:
self.session.logging.warn(
"The first main arena chunk seems to have a zero "
"size. As we didn't find a mapped libc module, the "
"reason might be a statically linked executable. "
"Please provide offset for the malloc_par struct "
"(symbol name is 'mp_'). Another reason might be "
"swapped memory pages.")
else:
self.session.logging.warn(
"Unexpected error: The first main arena chunk "
"seems to have a zero size. The reason might be "
"swapped memory pages. Walking the chunks is aborted.")
def get_all_allocated_chunks_for_arena(self, arena):
"""Returns all allocated chunks for a given arena.
This function is basically a wrapper around
_allocated_chunks_for_main_arena and allocated_chunks_for_thread_arena.
"""
if not arena:
self.session.logging.error(
"Error: allocated_chunks_for_arena called with an empty arena")
if self.session.GetParameter("debug"):
pdb.post_mortem()
return
if arena.freed_fast_chunks is None or arena.freed_chunks is None:
self.session.logging.error(
"Unexpected error: freed chunks seem to not be initialized.")
if self.session.GetParameter("debug"):
pdb.post_mortem()
return
if arena.is_main_arena:
for i in self._allocated_chunks_for_main_arena():
yield i
else:
# not main_arena
for chunk in self._allocated_chunks_for_thread_arena(arena):
yield chunk
# at least the function depends on getting allocated chunks first and then
# freed chunks, so this order shouldn't be changed
def get_all_chunks(self):
"""Returns all chunks (allocated, freed and MMAPPED chunks)."""