forked from williballenthin/INDXParse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MFT.py
executable file
·1435 lines (1196 loc) · 49.3 KB
/
MFT.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
#!/bin/python
# This file is part of INDXParse.
#
# Copyright 2011 Will Ballenthin <william.ballenthin@mandiant.com>
# while at Mandiant <http://www.mandiant.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Version v.1.1.8
import array
import os
import sys
import struct
import logging
from datetime import datetime
from collections import OrderedDict # python 2.7 only
from BinaryParser import Block
from BinaryParser import Nestable
from BinaryParser import memoize
from BinaryParser import align
from BinaryParser import ParseException
from BinaryParser import OverrunBufferException
from BinaryParser import read_byte
from BinaryParser import read_word
from BinaryParser import read_dword
from Progress import NullProgress
class INDXException(Exception):
"""
Base Exception class for INDX parsing.
"""
def __init__(self, value):
"""
Constructor.
Arguments:
- `value`: A string description.
"""
super(INDXException, self).__init__()
self._value = value
def __str__(self):
return "INDX Exception: %s" % (self._value)
class FixupBlock(Block):
def __init__(self, buf, offset, parent):
super(FixupBlock, self).__init__(buf, offset)
def fixup(self, num_fixups, fixup_value_offset):
fixup_value = self.unpack_word(fixup_value_offset)
for i in range(0, num_fixups - 1):
fixup_offset = 512 * (i + 1) - 2
check_value = self.unpack_word(fixup_offset)
if check_value != fixup_value:
logging.warning("Bad fixup at %s", hex(self.offset() + fixup_offset))
continue
new_value = self.unpack_word(fixup_value_offset + 2 + 2 * i)
self.pack_word(fixup_offset, new_value)
check_value = self.unpack_word(fixup_offset)
logging.debug("Fixup verified at %s and patched from %s to %s.",
hex(self.offset() + fixup_offset),
hex(fixup_value), hex(check_value))
class INDEX_ENTRY_FLAGS:
"""
sizeof() == WORD
"""
INDEX_ENTRY_NODE = 0x1
INDEX_ENTRY_END = 0x2
INDEX_ENTRY_SPACE_FILLER = 0xFFFF
class INDEX_ENTRY_HEADER(Block, Nestable):
def __init__(self, buf, offset, parent):
super(INDEX_ENTRY_HEADER, self).__init__(buf, offset)
self.declare_field("word", "length", 0x8)
self.declare_field("word", "key_length")
self.declare_field("word", "index_entry_flags") # see INDEX_ENTRY_FLAGS
self.declare_field("word", "reserved")
@staticmethod
def structure_size(buf, offset, parent):
return 0x10
def __len__(self):
return 0x10
def is_index_entry_node(self):
return self.index_entry_flags() & INDEX_ENTRY_FLAGS.INDEX_ENTRY_NODE
def is_index_entry_end(self):
return self.index_entry_flags() & INDEX_ENTRY_FLAGS.INDEX_ENTRY_END
def is_index_entry_space_filler(self):
return self.index_entry_flags() & INDEX_ENTRY_FLAGS.INDEX_ENTRY_SPACE_FILLER
class MFT_INDEX_ENTRY_HEADER(INDEX_ENTRY_HEADER):
"""
Index used by the MFT for INDX attributes.
"""
def __init__(self, buf, offset, parent):
super(MFT_INDEX_ENTRY_HEADER, self).__init__(buf, offset, parent)
self.declare_field("qword", "mft_reference", 0x0)
class SECURE_INDEX_ENTRY_HEADER(INDEX_ENTRY_HEADER):
"""
Index used by the $SECURE file indices SII and SDH
"""
def __init__(self, buf, offset, parent):
super(SECURE_INDEX_ENTRY_HEADER, self).__init__(buf, offset, parent)
self.declare_field("word", "data_offset", 0x0)
self.declare_field("word", "data_length")
self.declare_field("dword", "reserved")
class INDEX_ENTRY(Block, Nestable):
"""
NOTE: example structure. See the more specific classes below.
Probably do not instantiate.
"""
def __init__(self, buf, offset, parent):
super(INDEX_ENTRY, self).__init__(buf, offset)
self.declare_field(INDEX_ENTRY_HEADER, "header", 0x0)
self.add_explicit_field(0x10, "string", "data")
def data(self):
start = self.offset() + 0x10
end = start + self.header().key_length()
return self._buf[start:end]
@staticmethod
def structure_size(buf, offset, parent):
return read_word(buf, offset + 0x8)
def __len__(self):
return self.header().length()
def is_valid(self):
return True
class MFT_INDEX_ENTRY(Block, Nestable):
"""
Index entry for the MFT directory index $I30, attribute type 0x90.
"""
def __init__(self, buf, offset, parent):
super(MFT_INDEX_ENTRY, self).__init__(buf, offset)
self.declare_field(MFT_INDEX_ENTRY_HEADER, "header", 0x0)
self.declare_field(FilenameAttribute, "filename_information")
@staticmethod
def structure_size(buf, offset, parent):
return read_word(buf, offset + 0x8)
def __len__(self):
return self.header().length()
def is_valid(self):
# this is a bit of a mess, but it should work
recent_date = datetime(1990, 1, 1, 0, 0, 0)
future_date = datetime(2025, 1, 1, 0, 0, 0)
try:
fn = self.filename_information()
except:
return False
if not fn:
return False
try:
return fn.modified_time() > recent_date and \
fn.accessed_time() > recent_date and \
fn.changed_time() > recent_date and \
fn.created_time() > recent_date and \
fn.modified_time() < future_date and \
fn.accessed_time() < future_date and \
fn.changed_time() < future_date and \
fn.created_time() < future_date
except ValueError:
return False
class SII_INDEX_ENTRY(Block, Nestable):
"""
Index entry for the $SECURE:$SII index.
"""
def __init__(self, buf, offset, parent):
super(SII_INDEX_ENTRY, self).__init__(buf, offset)
self.declare_field(SECURE_INDEX_ENTRY_HEADER, "header", 0x0)
self.declare_field("dword", "security_id")
@staticmethod
def structure_size(buf, offset, parent):
return read_word(buf, offset + 0x8)
def __len__(self):
return self.header().length()
def is_valid(self):
# TODO(wb): test
return 1 < self.header().length() < 0x30 and \
1 < self.header().key_lenght() < 0x20
class SDH_INDEX_ENTRY(Block, Nestable):
"""
Index entry for the $SECURE:$SDH index.
"""
def __init__(self, buf, offset, parent):
super(SDH_INDEX_ENTRY, self).__init__(buf, offset)
self.declare_field(SECURE_INDEX_ENTRY_HEADER, "header", 0x0)
self.declare_field("dword", "hash")
self.declare_field("dword", "security_id")
@staticmethod
def structure_size(buf, offset, parent):
return read_word(buf, offset + 0x8)
def __len__(self):
return self.header().length()
def is_valid(self):
# TODO(wb): test
return 1 < self.header().length() < 0x30 and \
1 < self.header().key_lenght() < 0x20
class INDEX_HEADER_FLAGS:
SMALL_INDEX = 0x0 # MFT: INDX_ROOT only
LARGE_INDEX = 0x1 # MFT: requires INDX_ALLOCATION
LEAF_NODE = 0x1
INDEX_NODE = 0x2
NODE_MASK = 0x1
class INDEX_HEADER(Block, Nestable):
def __init__(self, buf, offset, parent):
super(INDEX_HEADER, self).__init__(buf, offset)
self.declare_field("dword", "entries_offset", 0x0)
self.declare_field("dword", "index_length")
self.declare_field("dword", "allocated_size")
self.declare_field("byte", "index_header_flags") # see INDEX_HEADER_FLAGS
# then 3 bytes padding/reserved
@staticmethod
def structure_size(buf, offset, parent):
return 0x1C
def __len__(self):
return 0x1C
def is_small_index(self):
return self.index_header_flags() & INDEX_HEADER_FLAGS.SMALL_INDEX
def is_large_index(self):
return self.index_header_flags() & INDEX_HEADER_FLAGS.LARGE_INDEX
def is_leaf_node(self):
return self.index_header_flags() & INDEX_HEADER_FLAGS.LEAF_NODE
def is_index_node(self):
return self.index_header_flags() & INDEX_HEADER_FLAGS.INDEX_NODE
def is_NODE_MASK(self):
return self.index_header_flags() & INDEX_HEADER_FLAGS.NODE_MASK
class INDEX(Block, Nestable):
def __init__(self, buf, offset, parent, index_entry_class):
self._INDEX_ENTRY = index_entry_class
super(INDEX, self).__init__(buf, offset)
self.declare_field(INDEX_HEADER, "header", 0x0)
self.add_explicit_field(self.header().entries_offset(),
INDEX_ENTRY, "entries")
slack_start = self.header().entries_offset() + self.header().index_length()
self.add_explicit_field(slack_start, INDEX_ENTRY, "slack_entries")
@staticmethod
def structure_size(buf, offset, parent):
return read_dword(buf, offset + 0x8)
def __len__(self):
return self.header().allocated_size()
def entries(self):
"""
A generator that returns each INDEX_ENTRY associated with this node.
"""
offset = self.header().entries_offset()
if offset == 0:
logging.debug("No entries in this allocation block.")
return
while offset <= self.header().index_length() - 0x52:
logging.debug("Entry has another entry after it.")
e = self._INDEX_ENTRY(self._buf, self.offset() + offset, self)
offset += e.length()
yield e
logging.debug("No more entries.")
def slack_entries(self):
"""
A generator that yields INDEX_ENTRYs found in the slack space
associated with this header.
"""
offset = self.header().index_length()
try:
while offset <= self.header().allocated_size - 0x52:
try:
logging.debug("Trying to find slack entry at %s.", hex(offset))
e = self._INDEX_ENTRY(self._buf, offset, self)
if e.is_valid():
logging.debug("Slack entry is valid.")
offset += e.length() or 1
yield e
else:
logging.debug("Slack entry is invalid.")
raise ParseException("Not a deleted entry")
except ParseException:
logging.debug("Scanning one byte forward.")
offset += 1
except struct.error:
logging.debug("Slack entry parsing overran buffer.")
pass
def INDEX_ROOT(Block, Nestable):
def __init__(self, buf, offset, parent):
super(INDEX_ROOT, self).__init__(buf, offset)
self.declare_field("dword", "type", 0x0)
self.declare_field("dword", "collation_rule")
self.declare_field("dword", "index_record_size_bytes")
self.declare_field("byte", "index_record_size_clusters")
self.declare_field("byte", "unused1")
self.declare_field("byte", "unused2")
self.declare_field("byte", "unused3")
self._index_offset = self.current_field_offset()
self.add_explicit_field(self._index_offset, INDEX, "index")
def index(self):
return INDEX(self._buf, self.offset(self._index_offset),
self, MFT_INDEX_ENTRY)
@staticmethod
def structure_size(buf, offset, parent):
return 0x10 + INDEX.structure_size(buf, offset + 0x10, parent)
def __len__(self):
return 0x10 + len(self.index())
class NTATTR_STANDARD_INDEX_HEADER(Block):
def __init__(self, buf, offset, parent):
logging.debug("INDEX NODE HEADER at %s.", hex(offset))
super(NTATTR_STANDARD_INDEX_HEADER, self).__init__(buf, offset)
self.declare_field("dword", "entry_list_start", 0x0)
self.declare_field("dword", "entry_list_end")
self.declare_field("dword", "entry_list_allocation_end")
self.declare_field("dword", "flags")
self.declare_field("binary", "list_buffer", \
self.entry_list_start(),
self.entry_list_allocation_end() - self.entry_list_start())
def entries(self):
"""
A generator that returns each INDX entry associated with this node.
"""
offset = self.entry_list_start()
if offset == 0:
return
# 0x52 is an approximate size of a small index entry
while offset <= self.entry_list_end() - 0x52:
e = IndexEntry(self._buf, self.offset() + offset, self)
offset += e.length()
yield e
def slack_entries(self):
"""
A generator that yields INDX entries found in the slack space
associated with this header.
"""
offset = self.entry_list_end()
try:
# 0x52 is an approximate size of a small index entry
while offset <= self.entry_list_allocation_end() - 0x52:
try:
e = SlackIndexEntry(self._buf, offset, self)
if e.is_valid():
offset += e.length() or 1
yield e
else:
raise ParseException("Not a deleted entry")
except ParseException:
# ensure we're always moving forward
offset += 1
except struct.error:
pass
class IndexRootHeader(Block):
def __init__(self, buf, offset, parent):
logging.debug("INDEX ROOT HEADER at %s.", hex(offset))
super(IndexRootHeader, self).__init__(buf, offset)
self.declare_field("dword", "type", 0x0)
self.declare_field("dword", "collation_rule")
self.declare_field("dword", "index_record_size_bytes")
self.declare_field("byte", "index_record_size_clusters")
self.declare_field("byte", "unused1")
self.declare_field("byte", "unused2")
self.declare_field("byte", "unused3")
self._node_header_offset = self.current_field_offset()
def node_header(self):
return NTATTR_STANDARD_INDEX_HEADER(self._buf,
self.offset() + self._node_header_offset,
self)
class IndexRecordHeader(FixupBlock):
def __init__(self, buf, offset, parent):
logging.debug("INDEX RECORD HEADER at %s.", hex(offset))
super(IndexRecordHeader, self).__init__(buf, offset, parent)
self.declare_field("dword", "magic", 0x0)
self.declare_field("word", "usa_offset")
self.declare_field("word", "usa_count")
self.declare_field("qword", "lsn")
self.declare_field("qword", "vcn")
self._node_header_offset = self.current_field_offset()
self.fixup(self.usa_count(), self.usa_offset())
def node_header(self):
return NTATTR_STANDARD_INDEX_HEADER(self._buf,
self.offset() + self._node_header_offset,
self)
class INDEX_ALLOCATION(FixupBlock):
def __init__(self, buf, offset, parent):
"""
TODO(wb): figure out what we're doing with the fixups!
"""
super(INDEX_ALLOCATION, self).__init__(buf, offset, parent)
self.declare_field("dword", "magic", 0x0)
self.declare_field("word", "usa_offset")
self.declare_field("word", "usa_count")
self.declare_field("qword", "lsn")
self.declare_field("qword", "vcn")
self._index_offset = self.current_field_offset()
self.add_explicit_field(self._index_offset, INDEX, "index")
# TODO(wb): we do not want to modify data here.
# best to make a copy and use that.
# Until then, this is not a nestable structure.
self.fixup(self.usa_count(), self.usa_offset())
def index(self):
return INDEX(self._buf, self.offset(self._index_offset),
self, MFT_INDEX_ENTRY)
@staticmethod
def structure_size(buf, offset, parent):
return 0x30 + INDEX.structure_size(buf, offset + 0x10, parent)
def __len__(self):
return 0x30 + len(self.index())
class IndexEntry(Block):
def __init__(self, buf, offset, parent):
logging.debug("INDEX ENTRY at %s.", hex(offset))
super(IndexEntry, self).__init__(buf, offset)
self.declare_field("qword", "mft_reference", 0x0)
self.declare_field("word", "length")
self.declare_field("word", "filename_information_length")
self.declare_field("dword", "flags")
self.declare_field("binary", "filename_information_buffer", \
self.current_field_offset(),
self.filename_information_length())
self.declare_field("qword", "child_vcn",
align(self.current_field_offset(), 0x8))
def filename_information(self):
return FilenameAttribute(self._buf,
self.offset() + self._off_filename_information_buffer,
self)
class StandardInformationFieldDoesNotExist(Exception):
def __init__(self, msg):
self._msg = msg
def __str__(self):
return "Standard Information attribute field does not exist: %s" % (self._msg)
class StandardInformation(Block):
# TODO(wb): implement sizing so we can make this nestable
def __init__(self, buf, offset, parent):
logging.debug("STANDARD INFORMATION ATTRIBUTE at %s.", hex(offset))
super(StandardInformation, self).__init__(buf, offset)
self.declare_field("filetime", "created_time", 0x0)
self.declare_field("filetime", "modified_time")
self.declare_field("filetime", "changed_time")
self.declare_field("filetime", "accessed_time")
self.declare_field("dword", "attributes")
self.declare_field("binary", "reserved", self.current_field_offset(), 0xC)
# self.declare_field("dword", "owner_id", 0x30) # Win2k+, NTFS 3.x
# self.declare_field("dword", "security_id") # Win2k+, NTFS 3.x
# self.declare_field("qword", "quota_charged") # Win2k+, NTFS 3.x
# self.declare_field("qword", "usn") # Win2k+, NTFS 3.x
# Can't implement this unless we know the NTFS version in use
#@staticmethod
#def structure_size(buf, offset, parent):
# return 0x42 + (read_byte(buf, offset + 0x40) * 2)
# Can't implement this unless we know the NTFS version in use
#def __len__(self):
# return 0x42 + (self.filename_length() * 2)
def owner_id(self):
"""
This is an explicit method because it may not exist in OSes under Win2k
@raises StandardInformationFieldDoesNotExist
"""
try:
return self.unpack_dword(0x30)
except OverrunBufferException:
raise StandardInformationFieldDoesNotExist("Owner ID")
def security_id(self):
"""
This is an explicit method because it may not exist in OSes under Win2k
@raises StandardInformationFieldDoesNotExist
"""
try:
return self.unpack_dword(0x34)
except OverrunBufferException:
raise StandardInformationFieldDoesNotExist("Security ID")
def quota_charged(self):
"""
This is an explicit method because it may not exist in OSes under Win2k
@raises StandardInformationFieldDoesNotExist
"""
try:
return self.unpack_dword(0x38)
except OverrunBufferException:
raise StandardInformationFieldDoesNotExist("Quota Charged")
def usn(self):
"""
This is an explicit method because it may not exist in OSes under Win2k
@raises StandardInformationFieldDoesNotExist
"""
try:
return self.unpack_dword(0x40)
except OverrunBufferException:
raise StandardInformationFieldDoesNotExist("USN")
class FilenameAttribute(Block, Nestable):
def __init__(self, buf, offset, parent):
logging.debug("FILENAME ATTRIBUTE at %s.", hex(offset))
super(FilenameAttribute, self).__init__(buf, offset)
self.declare_field("qword", "mft_parent_reference", 0x0)
self.declare_field("filetime", "created_time")
self.declare_field("filetime", "modified_time")
self.declare_field("filetime", "changed_time")
self.declare_field("filetime", "accessed_time")
self.declare_field("qword", "physical_size")
self.declare_field("qword", "logical_size")
self.declare_field("dword", "flags")
self.declare_field("dword", "reparse_value")
self.declare_field("byte", "filename_length")
self.declare_field("byte", "filename_type")
self.declare_field("wstring", "filename", 0x42, self.filename_length())
@staticmethod
def structure_size(buf, offset, parent):
return 0x42 + (read_byte(buf, offset + 0x40) * 2)
def __len__(self):
return 0x42 + (self.filename_length() * 2)
class SlackIndexEntry(IndexEntry):
def __init__(self, buf, offset, parent):
"""
Constructor.
Arguments:
- `buf`: Byte string containing NTFS INDX file
- `offset`: The offset into the buffer at which the block starts.
- `parent`: The parent NTATTR_STANDARD_INDEX_HEADER block,
which links to this block.
"""
super(SlackIndexEntry, self).__init__(buf, offset, parent)
def is_valid(self):
# this is a bit of a mess, but it should work
recent_date = datetime(1990, 1, 1, 0, 0, 0)
future_date = datetime(2025, 1, 1, 0, 0, 0)
try:
fn = self.filename_information()
except:
return False
if not fn:
return False
try:
return fn.modified_time() > recent_date and \
fn.accessed_time() > recent_date and \
fn.changed_time() > recent_date and \
fn.created_time() > recent_date and \
fn.modified_time() < future_date and \
fn.accessed_time() < future_date and \
fn.changed_time() < future_date and \
fn.created_time() < future_date
except ValueError:
return False
class Runentry(Block, Nestable):
def __init__(self, buf, offset, parent):
super(Runentry, self).__init__(buf, offset)
logging.debug("RUNENTRY @ %s.", hex(offset))
self.declare_field("byte", "header")
self._offset_length = self.header() >> 4
self._length_length = self.header() & 0x0F
self.declare_field("binary",
"length_binary",
self.current_field_offset(), self._length_length)
self.declare_field("binary",
"offset_binary",
self.current_field_offset(), self._offset_length)
@staticmethod
def structure_size(buf, offset, parent):
b = read_byte(buf, offset)
return (b >> 4) + (b & 0x0F) + 1
def __len__(self):
return 0x1 + (self._length_length + self._offset_length)
def is_valid(self):
return self._offset_length > 0 and self._length_length > 0
def lsb2num(self, binary):
count = 0
ret = 0
for b in binary:
ret += ord(b) << (8 * count)
count += 1
return ret
def lsb2signednum(self, binary):
count = 0
ret = 0
working = []
is_negative = (ord(binary[-1]) & (1 << 7) != 0)
if is_negative:
working = [ord(b) ^ 0xFF for b in binary]
else:
working = [ord(b) for b in binary]
for b in working:
ret += b << (8 * count)
count += 1
if is_negative:
ret += 1
ret *= -1
return ret
def offset(self):
# TODO(wb): make this run_offset
return self.lsb2signednum(self.offset_binary())
def length(self):
# TODO(wb): make this run_offset
return self.lsb2num(self.length_binary())
class Runlist(Block):
def __init__(self, buf, offset, parent):
super(Runlist, self).__init__(buf, offset)
logging.debug("RUNLIST @ %s.", hex(offset))
@staticmethod
def structure_size(buf, offset, parent):
length = 0
while True:
b = read_byte(buf, offset + length)
length += 1
if b == 0:
return length
length += (b >> 4) + (b & 0x0F)
def __len__(self):
return sum(map(len, self._entries()))
def _entries(self, length=None):
ret = []
offset = self.offset()
entry = Runentry(self._buf, offset, self)
while entry.header() != 0 and \
(not length or offset < self.offset() + length) and \
entry.is_valid():
ret.append(entry)
offset += len(entry)
entry = Runentry(self._buf, offset, self)
return ret
def runs(self, length=None):
"""
Yields tuples (volume offset, length).
Recall that the entries are relative to one another
"""
last_offset = 0
for e in self._entries(length=length):
current_offset = last_offset + e.offset()
current_length = e.length()
last_offset = current_offset
yield (current_offset, current_length)
class ATTR_TYPE:
STANDARD_INFORMATION = 0x10
FILENAME_INFORMATION = 0x30
DATA = 0x80
INDEX_ROOT = 0x90
INDEX_ALLOCATION = 0xA0
class Attribute(Block, Nestable):
TYPES = {
16: "$STANDARD INFORMATION",
32: "$ATTRIBUTE LIST",
48: "$FILENAME INFORMATION",
64: "$OBJECT ID/$VOLUME VERSION",
80: "$SECURITY DESCRIPTOR",
96: "$VOLUME NAME",
112: "$VOLUME INFORMATION",
128: "$DATA",
144: "$INDEX ROOT",
160: "$INDEX ALLOCATION",
176: "$BITMAP",
192: "$SYMBOLIC LINK",
208: "$REPARSE POINT/$EA INFORMATION",
224: "$EA",
256: "$LOGGED UTILITY STREAM",
}
FLAGS = {
0x01: "readonly",
0x02: "hidden",
0x04: "system",
0x08: "unused-dos",
0x10: "directory-dos",
0x20: "archive",
0x40: "device",
0x80: "normal",
0x100: "temporary",
0x200: "sparse",
0x400: "reparse-point",
0x800: "compressed",
0x1000: "offline",
0x2000: "not-indexed",
0x4000: "encrypted",
0x10000000: "has-indx",
0x20000000: "has-view-index",
}
def __init__(self, buf, offset, parent):
super(Attribute, self).__init__(buf, offset)
logging.debug("ATTRIBUTE @ %s.", hex(offset))
self.declare_field("dword", "type")
self.declare_field("dword", "size") # this value must rounded up to 0x8 byte alignment
self.declare_field("byte", "non_resident")
self.declare_field("byte", "name_length")
self.declare_field("word", "name_offset")
self.declare_field("word", "flags")
self.declare_field("word", "instance")
if self.non_resident() > 0:
self.declare_field("qword", "lowest_vcn", 0x10)
self.declare_field("qword", "highest_vcn")
self.declare_field("word", "runlist_offset")
self.declare_field("byte", "compression_unit")
self.declare_field("byte", "reserved1")
self.declare_field("byte", "reserved2")
self.declare_field("byte", "reserved3")
self.declare_field("byte", "reserved4")
self.declare_field("byte", "reserved5")
self.declare_field("qword", "allocated_size")
self.declare_field("qword", "data_size")
self.declare_field("qword", "initialized_size")
self.declare_field("qword", "compressed_size")
else:
self.declare_field("dword", "value_length", 0x10)
self.declare_field("word", "value_offset")
self.declare_field("byte", "value_flags")
self.declare_field("byte", "reserved")
self.declare_field("binary", "value",
self.value_offset(), self.value_length())
@staticmethod
def structure_size(buf, offset, parent):
s = read_dword(buf, offset + 0x4)
return s + (8 - (s % 8))
def __len__(self):
return self.size()
def runlist(self):
return Runlist(self._buf, self.offset() + self.runlist_offset(), self)
def size(self):
s = self.unpack_dword(self._off_size)
return s + (8 - (s % 8))
def name(self):
return self.unpack_wstring(self.name_offset(), self.name_length())
class MFT_RECORD_FLAGS:
MFT_RECORD_IN_USE = 0x1
MFT_RECORD_IS_DIRECTORY = 0x2
def MREF(mft_reference):
"""
Given a MREF/mft_reference, return the record number part.
"""
return mft_reference & 0xFFFFFFFFFFFF
def MSEQNO(mft_reference):
"""
Given a MREF/mft_reference, return the sequence number part.
"""
return (mft_reference >> 48) & 0xFFFF
class MFTRecord(FixupBlock):
"""
Implementation note: cannot be nestable due to fixups.
"""
def __init__(self, buf, offset, parent, inode=None):
super(MFTRecord, self).__init__(buf, offset, parent)
logging.debug("MFTRECORD @ %s.", hex(offset))
self.declare_field("dword", "magic")
self.declare_field("word", "usa_offset")
self.declare_field("word", "usa_count")
self.declare_field("qword", "lsn")
self.declare_field("word", "sequence_number")
self.declare_field("word", "link_count")
self.declare_field("word", "attrs_offset")
self.declare_field("word", "flags")
self.declare_field("dword", "bytes_in_use")
self.declare_field("dword", "bytes_allocated")
self.declare_field("qword", "base_mft_record")
self.declare_field("word", "next_attr_instance")
self.declare_field("word", "reserved")
self.declare_field("dword", "mft_record_number")
self.inode = inode or self.mft_record_number()
self.fixup(self.usa_count(), self.usa_offset())
def attributes(self):
offset = self.attrs_offset()
while self.unpack_dword(offset) != 0 and \
self.unpack_dword(offset) != 0xFFFFFFFF and \
offset + self.unpack_dword(offset + 4) <= self.offset() + self.bytes_in_use():
a = Attribute(self._buf, offset, self)
offset += len(a)
yield a
def attribute(self, attr_type):
for a in self.attributes():
if a.type() == attr_type:
return a
def is_directory(self):
return self.flags() & MFT_RECORD_FLAGS.MFT_RECORD_IS_DIRECTORY
def is_active(self):
return self.flags() & MFT_RECORD_FLAGS.MFT_RECORD_IN_USE
# this a required resident attribute
def filename_information(self):
"""
MFT Records may have more than one FN info attribute,
each with a different type of filename (8.3, POSIX, etc.)
This function returns the attribute with the most complete name,
that is, it tends towards Win32, then POSIX, and then 8.3.
"""
fn = None
for a in self.attributes():
# TODO optimize to self._buf here
if a.type() == ATTR_TYPE.FILENAME_INFORMATION:
try:
value = a.value()
check = FilenameAttribute(value, 0, self)
if check.filename_type() == 0x0001 or \
check.filename_type() == 0x0003:
return check
fn = check
except Exception:
pass
return fn
# this a required resident attribute
def standard_information(self):
try:
attr = self.attribute(ATTR_TYPE.STANDARD_INFORMATION)
return StandardInformation(attr.value(), 0, self)
except AttributeError:
return None
def data_attribute(self):
"""
Returns None if the default $DATA attribute does not exist
"""
for attr in self.attributes():
if attr.type() == ATTR_TYPE.DATA and attr.name() == "":
return attr
def slack_data(self):
"""
Returns A binary string containing the MFT record slack.
"""
return self._buf[self.offset()+self.bytes_in_use():self.offset() + 1024].tostring()
def active_data(self):
"""
Returns A binary string containing the MFT record slack.
"""
return self._buf[self.offset():self.offset() + self.bytes_in_use()].tostring()
class NTFSFile():
def __init__(self, options):
if type(options) == dict:
self.filename = options["filename"]
self.filetype = options["filetype"] or "mft"
self.offset = options["offset"] or 0
self.clustersize = options["clustersize"] or 4096
self.mftoffset = False
self.prefix = options["prefix"] or None
self.progress = options["progress"]
else:
self.filename = options.filename
self.filetype = options.filetype
self.offset = options.offset
self.clustersize = options.clustersize
self.mftoffset = False
self.prefix = options.prefix
self.progress = options.progress
# TODO calculate cluster size
def _calculate_mftoffset(self):
with open(self.filename, "rb") as f:
f.seek(self.offset)
f.seek(0x30, 1) # relative
buf = f.read(8)
relmftoffset = struct.unpack_from("<Q", buf, 0)[0]
self.mftoffset = self.offset + relmftoffset * self.clustersize
logging.debug("MFT offset is %s", hex(self.mftoffset))
def record_generator(self, start_at=0):
"""
@type start_at: int
@param start_at: the inode number to start at