-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathptenum.py
More file actions
2645 lines (2219 loc) · 108 KB
/
ptenum.py
File metadata and controls
2645 lines (2219 loc) · 108 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
# This module allows to enumerate and analyze all PTEs for a given process.
#
# MIT License
#
# Copyright (c) 2023 Frank Block, <research@f-block.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Some parts are taken from Rekall https://github.com/google/rekall
# Code is marked accordingly.
#
# Rekall Memory Forensics
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Authors:
# Mike Auty
# Michael Cohen
# Jordi Sanchez
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
"""This module allows to enumerate and analyze all PTEs for a given process and
can e.g. be used to get all executable pages for a given process. For a concrete
implementation see PteMalfind.
References:
https://insinuator.net/2021/12/release-of-pte-analysis-plugins-for-volatility-3/
https://github.com/f-block/DFRWS-USA-2019
https://dfrws.org/presentation/windows-memory-forensics-detecting-unintentionally-hidden-injected-code-by-examining-page-table-entries/
"""
from __future__ import annotations
import struct, logging, textwrap
from builtins import object
from past.utils import old_div
from typing import Dict, Tuple, Generator, List, Type, Optional
from functools import wraps, cached_property, lru_cache, cache
from volatility3.framework.renderers import format_hints
from volatility3.framework.objects import utility, StructType
from volatility3.plugins.windows import pslist, vadinfo, info
from volatility3.framework import interfaces, constants, exceptions, symbols, objects
from volatility3.framework.interfaces.objects import ObjectInterface
vollog = logging.getLogger(__name__)
state_enum = { 'HARD': 1,
'TRANS': 2,
'SOFT': 3,
'SOFTZERO': 4,
'PROTOPOINT': 5,
'SUBSEC': 6,
'PROTOVAD': 7
}
state_enum_rev = { 1: 'HARD',
2: 'TRANS',
3: 'SOFT',
4: 'SOFTZERO',
5: 'PROTOPOINT',
6: 'SUBSEC',
7: 'PROTOVAD'
}
state_to_mmpte = { 1: '_MMPTE_HARDWARE',
2: '_MMPTE_TRANSITION',
3: '_MMPTE_SOFTWARE',
4: '_MMPTE_SOFTWARE',
5: '_MMPTE_PROTOTYPE',
6: '_MMPTE_SUBSECTION',
7: '_MMPTE_PROTOTYPE'
}
# These are not officially documented. Taken from
# https://reactos.org/wiki/Techwiki:Memory_management_in_the_Windows_XP_kernel
mm_prot_enum = { 0: 'MM_ZERO_ACCESS',
1: 'MM_READONLY',
2: 'MM_EXECUTE',
3: 'MM_EXECUTE_READ',
4: 'MM_READWRITE',
5: 'MM_WRITECOPY',
6: 'MM_EXECUTE_READWRITE',
7: 'MM_EXECUTE_WRITECOPY'
}
def verify_initialized(func):
"""Function decorator: Verifies whether or not the PteEnumerator instance is
already initialized."""
@wraps(func)
def wrapper_verify(self, *args, **kwargs):
if not self._already_initialized:
vollog.error("Error occured while calling function {:s}:"
"PteEnumerator not yet initialized. Aborting ..."
.format(func.__name__))
return
return func(self, *args, **kwargs)
return wrapper_verify
def args_not_none(func):
"""Function decorator: Tests all positional arguments for being None, and
returns None if they are."""
@wraps(func)
def wrapper_args_not_none(*args, **kwargs):
for arg in args:
if arg is None:
return None
return func(*args, **kwargs)
return wrapper_args_not_none
def args_not_valid(func):
"""Function decorator: Simply tests for "not arg" and returns None if so."""
@wraps(func)
def wrapper_args_not_valid(*args, **kwargs):
for arg in args:
if not arg:
return None
return func(*args, **kwargs)
return wrapper_args_not_valid
class MMPTE(StructType):
"""Class for pretty-printing MMPTE structs."""
@staticmethod
def _ssn(name):
"""Strips symbol name"""
return name.split(constants.BANG)[1]
def __repr__(self):
result = "[" + self._ssn(self.vol.type_name) + "] @ " + hex(self.vol.offset) + "\n"
for member, data in sorted(self.vol.members.items(), key=lambda x: x[1][0]):
type_name = self._ssn(data[1].vol.type_name)
if 'pointer' in type_name:
try:
dest = self.member(member).dereference()
type_name += " to " + hex(dest.vol.offset) + " (" + self._ssn(dest.vol.type_name) + ")"
except Exception:
pass
elif 'bitfield' in type_name:
bit_string = " (bits {:d}-{:d})".format(data[1].vol.start_bit,data[1].vol.end_bit)
bit_length = data[1].vol.end_bit - data[1].vol.start_bit
if bit_length == 1:
bit_string = " (bit {:d})".format(data[1].vol.start_bit)
type_name = hex(self.member(member)) + " " + type_name + bit_string
elif 'long' in type_name:
type_name = hex(self.member(member)) + " " + type_name
result += " " + hex(data[0]) + " " + member + " " + type_name + "\n"
return result
class PteRun(object):
"""This class is used to represent a certain PTE and offers
functions/properties to analyze it."""
# These are fallback defaults, but should be set by PteEnumerator
# during initialization
_PAGE_BITS = 16
# For an explanation, see comment in PteEnumerator._init_variables
_SOFT_SWIZZLE_MASK = None
_INVALID_SWAP_OFFSET = None
_INVALID_SWAP_MASK = None
_TRANS_SWIZZLE_MASK = None
_INVALID_TRANS_OFFSET = None
_INVALID_TRANS_MASK = None
# PteRun must be initialized either with an instance of PteEnumerator or
# with a Volatility context
def __init__(self, init_obj: "Either instance of PteEnumerator or context",
proc, vaddr, length=None, phys_offset=None,
pte_value=None, pte_paddr=None, is_proto=None, state=None,
proto_ptr_run=None, is_exec=None, has_proto_set=None,
orig_pte_value=None, orig_pte_is_sub_ptr=None,
is_proto_ptr=None, pid=None, pte_vaddr=None,
data_layer=None, pte_layer=None, swap_offset=None,
pagefile_idx=None):
self._proc = proc
self._vaddr = vaddr
self._length = length
# Currently, it either points to the memory_layer or a swap_layer
self._phys_offset = phys_offset
self._swap_offset = swap_offset
self._pagefile_idx = pagefile_idx
self._pte_value = pte_value
# Physical address of PTE
self._pte_paddr = pte_paddr
# Virtual address of PTE; Note: Currently only set for prototype PTEs
self._pte_vaddr = pte_vaddr
# is_proto is set for PrototypePTEs: PTEs not part of the MMU PTEs but
# part of _SUBSECTION objects
self._is_proto = is_proto
# has_proto_set is set for MMU PTEs that have the Prototype flag set
# in their MMPFN entry
self._has_proto_set = has_proto_set
self._orig_pte_value = orig_pte_value
self._orig_pte_is_sub_ptr = orig_pte_is_sub_ptr
# is_proto_ptr is set for MMU PTEs that either directly (PROTOPOINT)
# or indirectly (PROTOVAD) point to a Prototype PTE
self._is_proto_ptr = is_proto_ptr
self._state = state
self._proto_ptr_run = proto_ptr_run
self._is_exec = is_exec
# Layer to read page content from; typically either phys or swap_layer
self._data_layer = data_layer
# Layer to read PTE from; PTEs can also be paged
self._pte_layer = pte_layer
self._ptenum_handle = None
self._context = None
if init_obj is None:
vollog.warning("Initializing PteRun without an init_obj is not"
"supported and will break some functionality.")
elif isinstance(init_obj, PteEnumerator):
self._ptenum_handle = init_obj
else:
self._context = init_obj
@property
def proc(self) -> ObjectInterface:
"""Returns:
The process associated with this PteRun instance."""
return self._proc
@property
def proc_layer(self) -> interfaces.layers.TranslationLayerInterface:
"""Returns:
The layer for the process associated with this PTE."""
if not self.proc:
return None
if self.ptenum_handle:
proc_offset = self.proc.vol.offset
if proc_offset in self.ptenum_handle._proc_layer_dict:
return self.ptenum_handle._proc_layer_dict[proc_offset]
else:
layer_name = self.proc.add_process_layer()
return self.ptenum_handle.context.layers[layer_name]
if self._context:
layer_name = self.proc.add_process_layer()
return self._context.layers[layer_name]
return None
@property
def vaddr(self) -> int:
"""Returns:
The virtual address that resolved to this PTE."""
return self._vaddr
@property
def pid(self) -> int:
"""Returns:
The PID for the process associated with this PTE."""
if not self.proc:
return None
return int(self.proc.UniqueProcessId)
@property
def length(self) -> int:
"""Returns the size of the described page."""
return self._length
@property
def phys_offset(self) -> int:
"""The offset within the dumped RAM."""
if self._TRANS_SWIZZLE_MASK and self.state == 'TRANS' and \
not (self._TRANS_SWIZZLE_MASK & self.pte_value):
return self._phys_offset & self._INVALID_TRANS_MASK
return self._phys_offset
@property
def swap_offset(self) -> int:
"""The offset within the corresponding Pagefile."""
# For an explanation, see comment in PteEnumerator._init_variables
if self._swap_offset is None:
return None
if self._SOFT_SWIZZLE_MASK and \
not (self._SOFT_SWIZZLE_MASK & self.pte_value):
if self._swap_offset == self._INVALID_SWAP_OFFSET:
return None
else:
return self._swap_offset & self._INVALID_SWAP_MASK
return self._swap_offset
@property
def pagefile_idx(self) -> int:
"""The Pagefile number (there can be up to 16)."""
return self._pagefile_idx
@property
def data_layer(self) -> interfaces.layers.TranslationLayerInterface:
"""The layer to read the page's content from."""
return self._data_layer
@property
def pte_layer(self) -> interfaces.layers.TranslationLayerInterface:
"""The layer containing the PTE."""
return self._pte_layer
@property
def pte_value(self) -> int:
"""Returns:
This PTE's value."""
return self._pte_value
@property
def pte_paddr(self) -> int:
"""Returns:
The Physical (or pagefile) address of this PTE."""
return self._pte_paddr
@property
def is_proto(self) -> bool:
"""is_proto is set for PrototypePTEs: PTEs not part of the MMU PTEs but
belonging to _SUBSECTION objects."""
return self._is_proto
@cached_property
def pfn(self) -> int:
"""Returns:
The Page Frame Number for this PTE (if applicable)."""
if self._phys_offset is None:
return None
return self._phys_offset >> \
(self.ptenum_handle._PAGE_BITS if self.ptenum_handle else 12)
def _set_modified_characteristics(self):
# First we check if they have not been set already
if self._has_proto_set is not None and \
self._orig_pte_is_sub_ptr is not None and \
self._orig_pte_value is not None:
return
if self.pfn is None or not self.ptenum_handle:
return
mod_chr_dict = \
self.ptenum_handle._get_modified_page_characteristics(self.pfn)
self._has_proto_set = mod_chr_dict['has_proto_set']
self._orig_pte_value = mod_chr_dict['orig_pte']
self._orig_pte_is_sub_ptr = mod_chr_dict['orig_pte_is_sub_ptr']
@property
def has_proto_set(self) -> bool:
"""has_proto_set is set for MMU PTEs that have the Prototype flag set
in their MMPFN entry."""
if self._has_proto_set is None:
self._set_modified_characteristics()
return self._has_proto_set
@property
def orig_pte_value(self) -> int:
"""Returns the OriginalPte value of the current page's MMPFN
entry."""
if self._orig_pte_value is None:
self._set_modified_characteristics()
# We currently need this value only for orig_pte_is_sub_ptr and also
# only if the PrototypePte flag is set, so this value is only in this
# case gathered and set through _set_modified_characteristics.
return self._orig_pte_value
@property
def orig_pte_is_sub_ptr(self) -> bool:
"""Returns True if the OriginalPte state of the current page's MMPFN
entry is _MMPTE_SUBSECTION. This means for pages belonging to mapped
image files, that they are not yet modified."""
if self._orig_pte_is_sub_ptr is None:
self._set_modified_characteristics()
return self._orig_pte_is_sub_ptr
@property
def is_proto_ptr(self) -> bool:
"""is_proto_ptr is set for MMU PTEs that either directly (PROTOPOINT)
or indirectly (PROTOVAD) point to a Prototype PTE"""
return self._is_proto_ptr
@property
def proto_ptr_run(self) -> PteRun:
"""If this PTE is a ProtoType PTE, there should be a proto-pointer PTE
pointing to this PTE. This function returns this proto-pointer PTE."""
return self._proto_ptr_run
@property
def ptenum_handle(self) -> PteEnumerator:
"""Returns:
A handle to the PteEnumerator instance, this PTE has been
initialized with.
Note: Depending on the way PteEnumerator is used, this handle might
have already been initialized for another process, so a call to
init_for_proc might be necessary.
The other functions/properties of PteRun do already take this into
account, so there is no special handling necessary.
"""
return self._ptenum_handle
@property
def context(self) -> interfaces.context.ContextInterface:
return self._context
@property
def state(self) -> str:
"""Returns:
The PTE's state as string, according to state_enum_rev."""
return state_enum_rev[self._state] if self._state else 'Undetermined'
@property
def pte_vaddr(self) -> int:
"""Returns:
The virtual address of this PTE.
Note: This value is currently only pre-set for prototype PTEs, so we
resolve it dynamically upon call."""
if self._pte_vaddr:
return self._pte_vaddr
if not self.ptenum_handle:
vollog.warning("Without ptenum context, resolving the PTE's "
"virtual address is currently not supported.")
return self._pte_vaddr
if self._pte_paddr is None:
return self._pte_vaddr
_, pte_vaddr = self.ptenum_handle.ptov(self._pte_paddr)
self._pte_vaddr = pte_vaddr
return self._pte_vaddr
@cached_property
def is_executable(self) -> bool:
"""Returns:
Whether or not the described page is executable."""
# The prototype PTE can have a different protection value than the
# mapped view in a process, so we first check for the protection of the
# proto-pointer, as this protection supersedes the one of the prototype PTE.
if self.is_proto and self._proto_ptr_run and \
self._proto_ptr_run._is_exec is not None:
return self._proto_ptr_run._is_exec
return self._is_exec
@property
def is_data_available(self) -> bool:
"""Returns True if there is a readable physical page (from RAM), or
if the page has been paged out and the corresponding Pagefile has been
provided."""
return bool((self.phys_offset is not None or
self.swap_offset is not None) and self.data_layer)
@property
def is_swapped(self) -> bool:
"""Returns:
True if the page has been swapped to compressed memory/pagefile."""
return self._state == 3
@property
def is_mapped(self) -> bool:
"""Returns:
True if the page's state is HARDWARE or TRANSITION,
otherwise False."""
return self._state in [1, 2]
@cached_property
def is_unmodified_img_page(self) -> bool:
"""Returns:
True if this page belongs to an image file and this page is yet
not modified.
False otherwise.
It returns None if the page does not belong to an image file.
"""
try:
if PteEnumerator.vad_contains_image_file(self.get_vad()[2]):
return self.orig_pte_is_sub_ptr
except:
pass
return None
@cached_property
def is_empty(self) -> bool:
"""Checks if this page belongs to valid physical page and does not
contain only zeroes.
Returns None if there is no physical page associated with this PteRun,
True if the physical page consists only of null bytes and
False otherwise"""
if not self.is_data_available:
return None
if self._length <= 0x1000 and self.ptenum_handle:
return self.read() == self.ptenum_handle._ALL_ZERO_PAGE
else:
return self.read() == b"\x00" * self._length
def get_mmpte(self) -> ObjectInterface:
"""Returns:
A _MMPTE_$STATE instance according to this PteRun's state."""
if not (self._pte_paddr is not None and self._state and self._pte_layer):
return None
if self.ptenum_handle:
struct_string = \
self.ptenum_handle.symbol_table + \
constants.BANG + \
state_to_mmpte[self._state]
return self.ptenum_handle.context.object(
struct_string,
offset = self._pte_paddr,
layer_name = self.pte_layer.name)
else:
return None
def get_mmpfn_entry(self) -> ObjectInterface:
"""Returns:
The MMPFN entry for this PteRun if it has an associated physical
page."""
if self._phys_offset is None:
return None
if self.ptenum_handle:
return self.ptenum_handle.mmpfn_db[self.pfn]
else:
# TODO return entry with self.context
return None
@lru_cache(maxsize=64)
def get_vad(self) -> Tuple[int, int, ObjectInterface]:
"""Returns:
The VAD associated with this PteRun instance in a tuple:
(vad_start, vad_end, MMVAD)"""
if self.vaddr is None:
return (None, None, None)
if self.ptenum_handle:
return self.ptenum_handle.get_vad_for_vaddr(self.vaddr, self.proc)
else:
for vad in self.proc.get_vad_root().traverse():
vad_start = vad.get_start()
vad_end = vad.get_end()
if vad_start <= self.vaddr <= vad_end:
return (vad_start, vad_end, vad)
return (None, None, None)
def get_iso_pte(self) -> PteRun:
if self.ptenum_handle:
return self.ptenum_handle.resolve_iso_pte_by_vaddr(self.vaddr)
return None
def read(self, rel_off: int = None, length: int = None, **kwargs) -> bytes:
"""
params:
rel_off: Start reading at the given relative offset.
length: Only read "length" bytes.
Returns:
The page's content, described by this PteRun."""
if rel_off is None:
rel_off = 0
if rel_off >= self.length:
vollog.warning("Given relative offset is bigger than current page. "
"Resetting to 0.")
rel_off = 0
if length is None:
length = self.length
if (rel_off + length) > self.length:
vollog.debug("Data to be read lies outside this page: "
f"rel_off: {rel_off:d} length: {length:d}. Fixing...")
length = self.length - rel_off
if not self.is_data_available and self.vaddr is not None:
# We didn't find a corresponding physical/swap address, so we try a
# last resort effort to get some data via Volatility.
try:
return self.proc_layer.read(self._vaddr + rel_off,
length,
**kwargs)
except Exception:
vollog.warning("No data found for Process {:d} at vaddr: "
"0x{:x}.".format(self.pid, self._vaddr))
# For swapped pages, idx 0 is typically the first pagefile,
# idx 1 the swapfile (if no further pagefile is active)
# and idx 2 refers to the virtual store for compressed
# memory: https://www.fireeye.com/blog/threat-research/2019/08/finding-evil-in-windows-ten-compressed-memory-part-two.html
if self._pagefile_idx == 2:
vollog.warning("The page is most likely contained "
"within compressed memory. Currently, "
"there is no support for this in "
"Volatility3.")
return None
offset = self._phys_offset if self._phys_offset is not None \
else self.swap_offset
offset += rel_off
try:
return self._data_layer.read(offset, length, **kwargs)
except Exception:
vollog.warning("Failed to retrieve data for Process {:d} at "
"vaddr: 0x{:x}.".format(self.pid, self._vaddr))
return b''
def __repr__(self) -> str:
"""Pretty printing PteRun instance."""
result = "PteRun:\n"
result += "PID: " + ("{:d}".format(self.pid) if isinstance(self.pid, int) else "Undetermined") + "\n"
result += "vaddr: " + ("0x{:x}".format(self._vaddr) if isinstance(self._vaddr, int) else "None") + "\n"
if self.is_swapped:
result += "swap_offset: " + ("0x{:x}".format(self.swap_offset) if self.swap_offset is not None else "None") + "\n"
result += "pagefile_idx: " + ("{:d}".format(self.pagefile_idx) if self.pagefile_idx is not None else "None") + "\n"
else:
result += "phys_offset: " + ("0x{:x}".format(self.phys_offset) if self.phys_offset is not None else "None") + "\n"
result += "length: " + ("0x{:x}".format(self._length) if self._length else "None") + "\n"
result += "pte_value: " + ("0x{:x}".format(self._pte_value) if isinstance(self._pte_value, int) else "None") + "\n"
result += "pte_paddr: " + ("0x{:x}".format(self._pte_paddr) if isinstance(self._pte_paddr, int) else "None") + "\n"
result += "pte_vaddr: " + ("0x{:x}".format(self.pte_vaddr) if isinstance(self.pte_vaddr, int) else "None") + "\n"
result += "is_proto: {0}".format("Undetermined" if self._is_proto is None else self._is_proto) + "\n"
result += "is_proto_ptr: {0}".format("Undetermined" if self._is_proto_ptr is None else self._is_proto_ptr) + "\n"
result += "has_proto_set: {0}".format("Undetermined" if self.has_proto_set is None else self.has_proto_set) + "\n"
result += "orig_pte_value: {0}".format("Undetermined" if self.orig_pte_value is None else "0x{:x}".format(self.orig_pte_value)) + "\n"
result += "orig_pte_is_sub_ptr: {0}".format("Undetermined" if self.orig_pte_is_sub_ptr is None else self.orig_pte_is_sub_ptr) + "\n"
result += "state: {0}".format(self.state) + "\n"
result += "is_exec: {0}".format("Undetermined" if self._is_exec is None else self._is_exec) + "\n"
if self.is_proto and self._proto_ptr_run:
result += "Page is for this process executable: {0}".format(self.is_executable) + "\n"
result += "\nProtopointer (the actual MMU PTE):\n"
result += textwrap.indent(repr(self.proto_ptr_run), ' ')
return result
def get_full_string_repr(self) -> str:
"""Returns:
The PteRun and MMPTE represantions for this PteRun, also for
any potential proto-pointer."""
result = "Internal PteRun representation:\n"
result += "==============================\n"
result += repr(self)
result += "\n"
mmpte = self.get_mmpte()
if mmpte:
result += "MMPTE struct:\n"
result += "=============\n"
result += repr(self.get_mmpte())
if self.is_proto and self._proto_ptr_run:
proto_mmpte = self.proto_ptr_run.get_mmpte()
if proto_mmpte:
result += "\nCorresponding ProtoPointer:\n"
result += "---------------------------\n"
result += textwrap.indent(
repr(self.proto_ptr_run.get_mmpte()), ' ')
result += "\n"
return result
class SubsecProtoWrapper(object):
"""Helper class for enumerating all ProtoType PTEs of all Subsections
associated with a given VAD, especially because the Prototype PTEs pointed
to by vad.FirstPrototypePte do not always cover the whole memory area."""
def __init__(self, vad, page_bits, pte_size, *args, **kwargs):
self._PTE_SIZE = pte_size
self._PAGE_BITS = page_bits
self.range = None
self.index_list = None
if "Subsection" in vad.vol.members.keys():
self.subsec = vad.Subsection
self.is_last = False
def _init_subsec(self) -> None:
first_subsec = self.subsec.dereference()
last = first_subsec.PtesInSubsection - 1
self.range = [0, last]
self.index_list = [(0, last, first_subsec)]
def _calc_pteaddr(self, subsec: ObjectInterface, idx: int) -> int:
return subsec.SubsectionBase + (idx * self._PTE_SIZE)
def get_pteaddr_for_vaddr(self,
vad: ObjectInterface,
vad_start: int,
vad_end: int,
vaddr: int) -> int:
# In most yet observed cases, the Subsection-PTEs are contiguous,
# so while there are multiple Subsections, each one points with
# their SubsectionBase pointer into a big contiguous array of PTEs.
# This means that in those cases, the VAD covers all PTEs with its
# FirstPrototypePte and LastContiguousPte pointers. This way of
# accessing PTEs is also way faster, since we don't have to walk
# Subsections for every vaddr.
# There are, however, cases, where not all PTEs are contiguous (e.g.
# an open log file that gets larger).
# In these cases we have to walk the Subsections in order to get
# the correct PTE since it is not part of the contiguous PTEs,
# referenced by the VAD.
if vaddr > vad_end:
vollog.warning("Given vaddr exceeds range of VAD: vaddr 0x{:x} "
"vadrange: 0x{:x} - 0x{:x}"
.format(vaddr, vad_start, vad_end))
return None
idx = (vaddr - vad_start) >> self._PAGE_BITS
if "FirstPrototypePte" in vad.vol.members.keys():
pte_addr = vad.FirstPrototypePte + (idx * self._PTE_SIZE)
if pte_addr <= vad.LastContiguousPte:
return pte_addr
if not self.subsec:
vollog.warning("No Subsection available for vaddr 0x{:x}, this "
"shouldn't happen.".format(vaddr))
return None
if not self.range:
self._init_subsec()
# As there might be subviews and hence, our PTE may not be referenced
# by the contiguous pointers, we have to calculate the offset for those
# cases.
pointer_diff = old_div(
(vad.FirstPrototypePte - self.index_list[0][2].SubsectionBase),
self._PTE_SIZE)
idx += pointer_diff
if self.range[0] <= idx <= self.range[1]:
for base_idx, end, subsec in self.index_list:
if base_idx <= idx <= end:
return self._calc_pteaddr(subsec, idx - base_idx)
vollog.info("No Subsection found for the given index: 0x{:x} "
"and vaddr: 0x{:x}. Potentially not yet populated "
"SUBSECTIONs for a growing file.".format(idx, vaddr))
return None
elif self.is_last:
vollog.info("No Subsection found for the given index: 0x{:x} "
"and vaddr: 0x{:x}. Potentially not yet populated "
"SUBSECTIONs for a growing file.".format(idx, vaddr))
return None
# idx belongs to a subsection, we have not enumerated so far
base_idx, last_idx, subsec = self.index_list[-1]
curr_idx = last_idx + 1
subsec = subsec.NextSubsection
while subsec != 0:
subsec = subsec.dereference()
pte_count = subsec.PtesInSubsection
last_idx = curr_idx + pte_count - 1
self.index_list.append((curr_idx, last_idx, subsec))
self.range[1] = last_idx
if idx <= last_idx:
return self._calc_pteaddr(subsec, idx - curr_idx)
curr_idx += pte_count
subsec = subsec.NextSubsection
self.is_last = True
# Ending here means we didn't find the PTE for the given index.
vollog.info("No Subsection found for the given index. "
"Index: 0x{:x}, last enumerated index: 0x{:x}, vaddr: "
"0x{:x}. Potentially not yet populated SUBSECTIONs "
"for a growing file.".format(idx, last_idx, vaddr))
return None
def get_all_subsec_pteaddr(self) -> Generator[int]:
"""Returns every PTE address for each subsection in the list."""
if not self.range:
self._init_subsec()
for base_idx, last_idx, subsec in self.index_list:
subsec_base = subsec.SubsectionBase
pte_count = last_idx - base_idx + 1
for idx in range(0, pte_count, 1):
yield subsec_base + (idx * self._PTE_SIZE)
# curr_idx is only been kept for index_list resp. get_pteaddr_for_vaddr
curr_idx = last_idx + 1
subsec = subsec.NextSubsection
while subsec != 0:
subsec = subsec.dereference()
pte_count = subsec.PtesInSubsection
subsec_base = subsec.SubsectionBase
last_idx = curr_idx + pte_count - 1
self.index_list.append((curr_idx, last_idx, subsec))
self.range[1] = last_idx
for idx in range(0, pte_count, 1):
yield subsec_base + (idx * self._PTE_SIZE)
curr_idx += pte_count
subsec = subsec.NextSubsection
# We support versions 1 and 2
framework_version = constants.VERSION_MAJOR
if framework_version == 1:
kernel_layer_name = 'primary'
elif framework_version == 2:
kernel_layer_name = 'kernel'
else:
# The highest major version we currently support.
raise RuntimeError(f"Framework interface version {framework_version} is "
"currently not supported.")
class PteEnumerator(object):
"""This class allows to access and analyze all PTEs
(MMU and Prototype PTEs) of a given process, by walking the paging
structures."""
_mmpfn_db_raw = None
# class variable; decreases significantly RAM consumption in the context of
# enumerate_ptes_for_processes
_subsec_dict = dict()
_resolved_dtbs = dict()
_vad_dict = dict()
_proc_layer_dict = dict()
_protect_values = None
def __init__(self, *args, **kwargs):
self.dtb = None
self.proc_layer = None
self.phys_layer = None
self._swap_layer_count = None
self._swap_layer_base_str = None
self._invalid_pte_mask = None
self._valid_mask = 1
self.arch_os = None
self.arch_proc = None
self._mmpte_size = None
self._PAGE_BITS = None
self.kernel = None
self.proc = None
self.pid = None
self.is_wow64 = None
# Reference to the vadlist for the current process.
# In essence a pointer into _vad_dict.
self._proc_vads = list()
self._already_initialized = False
# This is set correctly in _init_variables, and is here only
# a just-in-case thing.
self._highest_user_addr = 0x7ffffffeffff
if kwargs:
self.context = kwargs.get('context', None)
self.config = kwargs.get('config', None)
if 'proc' in kwargs:
self.init_for_proc(kwargs['proc'])
def _read_pte_value(self, layer, addr):
pte = None
try:
pte_raw = layer.read(addr, self._PTE_SIZE)
pte = struct.unpack('<Q', pte_raw)[0]
except exceptions.InvalidAddressException:
pass
return pte
# static implementation of get_protection from class MMVAD_SHORT
@staticmethod
def _get_protection(protect, protect_values, winnt_protections):
"""Get the VAD's protection constants as a string."""
try:
value = protect_values[protect]
except IndexError:
value = 0
names = []
for name, mask in winnt_protections.items():
if value & mask != 0:
names.append(name)
return "|".join(names)
@lru_cache(maxsize=32)
def _get_subsec_protection(self, protect):
if not self._protect_values:
self._protect_values = vadinfo.VadInfo.protect_values(context = self.context,
layer_name = self.kernel.layer_name,
symbol_table = self.kernel.symbol_table_name)
return self._get_protection(protect, self._protect_values, vadinfo.winnt_protections)
@staticmethod
def _get_subsec_for_vad(vad: ObjectInterface) -> ObjectInterface:
if not "Subsection" in vad.vol.members:
return None
return vad.Subsection.dereference()
@staticmethod
def _get_ca_for_subsec(subsec: ObjectInterface) -> ObjectInterface:
if not subsec:
return None
return subsec.ControlArea.dereference()
@classmethod
def _get_ca_for_vad(cls, vad: ObjectInterface) -> ObjectInterface:
return cls._get_ca_for_subsec(cls._get_subsec_for_vad(vad))
@staticmethod
@args_not_valid
def _get_fileptr_for_ca(control_area: ObjectInterface) -> ObjectInterface:
if control_area.FilePointer.Value:
return control_area.FilePointer
return None
@staticmethod
@args_not_valid
def _get_section_object_for_fileptr(file_ptr: ObjectInterface
) -> ObjectInterface:
file_obj = file_ptr.dereference().cast("_FILE_OBJECT")
if file_obj.SectionObjectPointer:
return file_obj.SectionObjectPointer.dereference().cast(
"_SECTION_OBJECT_POINTERS")
return None
@classmethod
def vad_contains_data_file(cls, vad: ObjectInterface) -> bool:
"""Returns:
True if the given VAD has a valid DataSectionObject pointer."""
if not cls.vad_contains_image_file(vad) and \
vad.get_private_memory() == 0:
ca = cls._get_ca_for_vad(vad)
file_ptr = cls._get_fileptr_for_ca(ca)
sec_obj_poi = cls._get_section_object_for_fileptr(file_ptr)
if sec_obj_poi:
return ca.vol.offset == sec_obj_poi.DataSectionObject
return False
@staticmethod
def _get_vad_type(vad: ObjectInterface) -> int:
# this case happens for PTEs not belonging to any VAD (orphaned pages)
if isinstance(vad, int):
return -1