-
Notifications
You must be signed in to change notification settings - Fork 34
/
dfxml.py
executable file
·1720 lines (1501 loc) · 67 KB
/
dfxml.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
#!/usr/bin/env python
#
# dfxml.py
# Digital Forensics XML classes
"""Digital Forensics XML classes.
This module contains a number of classes for dealing with dfxml files, both using
the XML DOM model and using the EXPAT model.
The following moduel functions are defined:
isone(x) - returns true if something is equal to 1 (useful for <ALLOC>1</ALLOC>
safeInt(x) - converts something to an int but never raises an exception
The following classes are defined in this module:
byte_run - the class for representing a run on the disk
dftime - represents time. Can be in either Unix timestamp or ISO8601.
Interconverts as necessary.
fileobject - represents a DFXML fileobject.
byte_runs() is function that returns an array of byterun objects.
Each object has the attributes:
file_offset - offset from the beginning of the file
img_offset - offset from the beginning of the image
len - the number of bytes
fs_offset - offset from the beginning of the file system
where encoding, if present, is 0 for raw, 1 for NTFS compressed.
"""
__version__ = "1.0.2"
import sys
import re
from sys import stderr
from subprocess import Popen,PIPE
import base64
import hashlib
import os
import datetime
import logging
_logger = logging.getLogger(os.path.basename(__file__))
tsk_virtual_filenames = set(['$FAT1','$FAT2'])
XMLNS_DC = "http://purl.org/dc/elements/1.1/"
XMLNS_DFXML = "http://www.forensicswiki.org/wiki/Category:Digital_Forensics_XML"
XMLNS_DELTA = "http://www.forensicswiki.org/wiki/Forensic_Disk_Differencing"
def isone(x):
"""Return true if something is one (number or string)"""
try:
return int(x)==1;
except TypeError:
return False
def safeInt(x):
"""Return an integer or False. False is returned, rather than None, because you can
divide False by 3 but you can't divide None by 3.
NOTE: This function could be written as:
def safeInt(x):
return int(x) if x else False
but that doesn't work on older version of Python."""
if x: return int(x)
return False
def timestamp2iso8601(ts):
import time
return time.strftime("%FT%TZ",time.gmtime(ts))
from datetime import tzinfo,timedelta
class GMTMIN(tzinfo):
def __init__(self,minoffset): # DST starts last Sunday in March
self.minoffset = minoffset
def utcoffset(self, dt):
return timedelta(minutes=self.minoffset)
def dst(self, dt):
return timedelta(0)
def tzname(self,dt):
return "GMT+%02d%02d" % (self.minoffset/60,self.minoffset%60)
def parse_iso8601(ts):
Z = ts.find('Z')
if Z>0:
return datetime.datetime.strptime(ts[:Z],"%Y-%m-%dT%H:%M:%S")
raise RuntimeError("parse_iso8601: ISO8601 format {} not recognized".format(ts))
rx_iso8601 = re.compile("(\d\d\d\d)-(\d\d)-(\d\d)[T ](\d\d):(\d\d):(\d\d)(\.\d+)?(Z|[-+]\d\d:?\d\d)?")
def iso8601Tdatetime(s):
"""SLG's conversion of ISO8601 to datetime"""
m = rx_iso8601.search(s)
if not m:
raise ValueError("Cannot parse: "+s)
# Get the microseconds
try:
microseconds = int(float(m.group(7)) * 1000000)
except TypeError:
microseconds = 0
# Figure tz offset
offset = None
minoffset = None
if m.group(8):
if m.group(8)=="Z":
minoffset = 0
elif m.group(8)[0:1] in "-+":
minoffset = int(m.group(8)[0:3]) * 60 + int(m.group(8)[-2:])
z = s.find("Z")
if z>=0:
offset = 0
# Build the response
if minoffset:
return datetime.datetime(int(m.group(1)),int(m.group(2)),int(m.group(3)),
int(m.group(4)),int(m.group(5)),int(m.group(6)),
microseconds,GMTMIN(minoffset))
elif offset:
return datetime.datetime(int(m.group(1)),int(m.group(2)),int(m.group(3)),
int(m.group(4)),int(m.group(5)),int(m.group(6)),
microseconds,GMTMIN(offset))
else:
return datetime.datetime(int(m.group(1)),int(m.group(2)),int(m.group(3)),
int(m.group(4)),int(m.group(5)),int(m.group(6)),
microseconds)
#This format is as specified in RFC 822, section 5.1, and matches the adjustments in RFC 1123, section 5.2.14. It appears in email and HTTP headers.
rx_rfc822datetime = re.compile("(?P<day>\d{1,2}) (?P<month>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (?P<year>\d{4}) (?P<hours>\d\d):(?P<minutes>\d\d):(?P<seconds>\d\d) (?P<timezone>Z|[-+]\d\d:?\d\d)")
three_letter_month_dict = {
"Jan": 1,
"Feb": 2,
"Mar": 3,
"Apr": 4,
"May": 5,
"Jun": 6,
"Jul": 7,
"Aug": 8,
"Sep": 9,
"Oct": 10,
"Nov": 11,
"Dec": 12
}
def rfc822Tdatetime(s):
"""
AJN's conversion of times occurring in RFC 822 data to datetime.
Follows SLG's pattern.
"""
m = rx_rfc822datetime.search(s)
if not m:
raise ValueError("Cannot parse as an RFC 822 timestamp: %r." % s)
mgd = m.groupdict()
# Figure tz offset
offset = None
minoffset = None
match_timezone = mgd.get("timezone")
if match_timezone:
if match_timezone == "Z":
minoffset = 0
elif match_timezone[0] in "-+":
minoffset = int(match_timezone[0:-2]) * 60 + int(match_timezone[-2:])
#TODO Find a reason to use the 'offset' variable? (Hour offset, vs. minute offset?)
if minoffset:
return datetime.datetime(
int(mgd["year"]),
three_letter_month_dict[mgd["month"]],
int(mgd["day"]),
int(mgd["hours"]),
int(mgd["minutes"]),
int(mgd["seconds"]),
0,
GMTMIN(minoffset)
)
else:
return datetime.datetime(
int(mgd["year"]),
three_letter_month_dict[mgd["month"]],
int(mgd["day"]),
int(mgd["hours"]),
int(mgd["minutes"]),
int(mgd["seconds"]),
0
)
################################################################
###
### byte_run class
###
class byte_run:
"""The internal representation for a byte run.
byte_runs have the following attributes:
.img_offset = offset of the byte run from the image start, in bytes
.len = the length of the run, in bytes (prevoiusly called 'bytes')
.sector_size = sector size of the underlying media
Originally this was an array,
which is faster than an attributed object. But this approach is more expandable,
and it's only 70% the speed of an array under Python3.0.
Note that Python 3 removed the __cmp__ class method:
<http://docs.python.org/release/3.0.1/whatsnew/3.0.html#ordering-comparisons>
"""
# declaring slots prevents other attributes from appearing,
# but that prevents the code from working with new XML that has new fields.
# __slots__ = ["file_offset","img_offset","len","fill","sector_size"]
def __init__(self,img_offset=None,len=None,file_offset=None):
self.img_offset = img_offset
self.file_offset = file_offset
self.len = len
self.sector_size = 512 # default
self.hashdigest = dict() #
def __lt__(self,other):
if self.img_offset is not None and other.img_offset is not None:
return self.img_offset < other.img_offset
elif self.file_offset is not None and other.file_offset is not None:
return self.file_offset < other.file_offset
else:
raise ValueError("Byte run objects are incomparable")
def __eq__(self,other):
if self.img_offset is not None and other.img_offset is not None:
return self.img_offset == other.img_offset
elif self.file_offset is not None and other.file_offset is not None:
return self.file_offset == other.file_offset
else:
raise ValueError("Byte run objects are incomparable")
def __str__(self):
try:
return "byte_run[img_offset={0}; file_offset={1} len={2}] ".format(
self.img_offset,self.file_offset,self.len)
except (AttributeError, TypeError):
#Catch attributes that are missing or mis-typed (e.g. NoneType)
pass
try:
return "byte_run[file_offset={0}; fill={1}; len={2}]".format(
self.file_offset,self.fill,self.len)
except AttributeError:
pass
try:
return "byte_run[file_offset={0}; uncompressed_len={1}]".format(
self.file_offset,self.uncompressed_len)
except AttributeError:
return "byte_run"+str(dir(self))
def start_sector(self):
return self.img_offset // self.sector_size
def sector_count(self):
return self.len // self.sector_size
def has_sector(self,s):
if self.sector_size==0:
raise ValueError("%s: sector_size cannot be 0" % (self))
if self.img_offset is None or self.len is None:
# Sparse files don't have data allocated on disk
return False
try:
return self.img_offset <= s * self.sector_size < self.img_offset+self.len
except AttributeError:
# Doesn't have necessary attributes to answer true.
# Usually this happens with runs of a constant value
return False
def extra_len(self):
return self.len % self.sector_size
def decode_xml_attributes(self,attr):
for (key,value) in attr.items():
try:
setattr(self,key,int(value))
except ValueError:
setattr(self,key,value)
def decode_sax_attributes(self,attr):
for (key,value) in attr.items():
if key=='bytes': key=='len' # tag changed name; provide backwards compatiability
try:
setattr(self,key,int(value))
except ValueError:
setattr(self,key,value)
class ComparableMixin(object):
"""
Comparator "Abstract" class. Classes inheriting this must define a _cmpkey() method.
Credit to Lennart Regebro for the total implementation of this class, found equivalently from:
http://regebro.wordpress.com/2010/12/13/python-implementing-rich-comparison-the-correct-way/
http://stackoverflow.com/questions/6907323/comparable-classes-in-python-3/6913420#6913420
"""
def _compare(self, other, method):
try:
return method(self._cmpkey(), other._cmpkey())
except (AttributeError, TypeError):
# _cmpkey not implemented, or return different type,
# so I can't compare with "other".
return NotImplemented
def __lt__(self, other):
return self._compare(other, lambda s, o: s < o)
def __le__(self, other):
return self._compare(other, lambda s, o: s <= o)
def __eq__(self, other):
return self._compare(other, lambda s, o: s == o)
def __ge__(self, other):
return self._compare(other, lambda s, o: s >= o)
def __gt__(self, other):
return self._compare(other, lambda s, o: s > o)
def __ne__(self, other):
return self._compare(other, lambda s, o: s != o)
class dftime(ComparableMixin):
"""Represents a DFXML time. Automatically converts between representations and caches the
results as necessary.."""
UTC = GMTMIN(0)
def ts2datetime(self,ts):
import datetime
return datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=dftime.UTC)
def __init__(self,val):
#'unicode' is not a type in Python 3; 'basestring' is not a type in Python 2.
if sys.version_info >= (3,0):
_basestring = str
else:
_basestring = basestring
if isinstance(val, str) or isinstance(val,_basestring):
#
#Test for ISO 8601 format - "YYYY-MM-DD" should have hyphen at val[4]
if len(val)>5 and val[4]=="-":
self.iso8601_ = val
elif len(val) > 15 and ":" in val[13:15]:
#Maybe the data are instead the timestamp format found in email headers?
#(The check for 13:15 gets the 14th and 15th characters, since the day can be single- or double-digit.)
self.datetime_ = rfc822Tdatetime(val)
else:
#Maybe the data are a string-wrapped int or float?
#If this fails, the string format is completely unexpected, so just raise an error.
self.timestamp_ = float(val)
elif type(val)==int or type(val)==float:
self.timestamp_ = val
elif isinstance(val, datetime.datetime):
self.datetime_ = val
#TODO Unit-test this with a timezone-less datetime
elif val==None:
self.timestamp_ = None
self.iso8601_ = None
elif isinstance(val, dftime):
#If we instead use .timestamp_, we risk having a timezone conversion error
self.iso8601_ = val.iso8601()
else:
raise ValueError("Unknown type '%s' for DFXML time value" % (str(type(val))))
def __str__(self):
return self.iso8601() or ""
def __repr__(self):
return repr(self.iso8601()) or "None"
def __le__(self,b):
if b is None: return None
return self.iso8601().__le__(b.iso8601())
def __gt__(self,b):
if b is None: return None
return self.iso8601().__gt__(b.iso8601())
def _cmpkey(self):
"""Provide a key to use for comparisons; for use with ComparableMixin parent class."""
return self.timestamp()
def __eq__(self,b):
if b == None:
#This will always be False - if self were None, we wouldn't be in this __eq__ method.
return False
return self.timestamp()==b.timestamp()
def iso8601(self):
# Do we have a cached representation?
import time
try:
return self.iso8601_
except AttributeError:
pass
# Do we have a datetime representation?
try:
self.iso8601_ = self.datetime_.isoformat()
return self.iso8601_
except AttributeError:
# We better have a Unix timestamp representation?
self.iso8601_ = time.strftime("%Y-%m-%dT%H:%M:%SZ",time.gmtime(self.timestamp_))
return self.iso8601_
def timestamp(self):
import time
# Do we have a cached representation?
try:
return self.timestamp_
except AttributeError:
pass
# Do we have a datetime_ object?
try:
self.timestamp_ = time.mktime(self.datetime_.timetuple())
return self.timestamp_
except AttributeError:
self.datetime_ = iso8601Tdatetime(self.iso8601_)
self.timestamp_ = time.mktime(self.datetime_.timetuple())
return self.timestamp_
def datetime(self):
import datetime
# return the datetime from parsing either iso8601 or from parsing timestamp
try:
self.datetime_ = self.ts2datetime(self.timestamp_)
# This needs to be in UTC offset. How annoying.
return self.datetime_
except AttributeError:
self.datetime_ = iso8601Tdatetime(self.iso8601_)
return self.datetime_
class registry_object:
def __init__(self):
self.object_index = {}
self._mtime = None
"""Keep handy a handle on the registry object"""
self.registry_handle = self
def mtime(self):
return self._mtime
class registry_cell_object:
def __init__(self):
self._byte_runs = []
"""This is a pointer to a registry_key_object. The root node has no parent key."""
self.parent_key = None
self._name = None
self._full_path = None
"""Keys have two types: "root" (0x2c,0xac) and not-root. Values have several more types."""
self._type = None
"""Keep handy a handle on the registry object"""
self.registry_handle = None
"""Name the cell type, for str() and repr()."""
self._cell_type = "(undefined cell object type)"
"""Only applicable to values."""
self._sha1 = None
def name(self):
"""This is the name of the present key or value."""
return self._name
def full_path(self):
"""
This is the full path from the root of the hive, with keys acting like directories and the value name acting like the basename.
Unlike DFXML, registry paths are delimited with a backslash due to the forward slash being a legal and commonly observed character in cell names.
"""
return self._full_path
def type(self):
"""
This is the data type of the cell. Keys can be root or not-root; values have several types, like UTF-8, binary, etc.
Presently, this exports as a string representation of the type, not the numeric type code.
"""
return self._type
def _myname(self):
"""This function is called by repr and str, due to (vague memories of) the possibility of an infinite loop if __repr__ calls __self__."""
if len(self._byte_runs) > 0:
addr = str(self._byte_runs[0].file_offset)
else:
addr = "(unknown)"
return "".join(["<", self._cell_type, " for hive file offset ", addr, ">"])
def __repr__(self):
return self._myname()
def __str__(self):
return self._myname()
def mtime(self):
raise NotImplementedError("registry_cell_object.mtime() not over-ridden!")
def byte_runs(self):
"""Returns a sorted array of byte_run objects."""
#If this idiom is confusing, see: http://henry.precheur.org/python/copy_list
ret = list(self._byte_runs)
return ret
def sha1(self):
"""
Return None. Meant to be overwritten.
"""
return None
def md5(self):
"""
Return None. Meant to be overwritten.
"""
return None
def sha512(self):
"""
Return None. Meant to be overwritten.
"""
return None
class registry_key_object(registry_cell_object):
def __init__(self):
registry_cell_object.__init__(self)
self._mtime = None
self.values = {}
self.used = True #TODO Add toggling logic for when hivexml (eventually) processes recovered keys
self._cell_type = "registry_key_object"
def mtime(self):
return self._mtime
def root(self):
if self.type() is None:
return None
return self.type() == "root"
class registry_value_object(registry_cell_object):
def __init__(self):
registry_cell_object.__init__(self)
self.value_data = None
self._cell_type = "registry_value_object"
#TODO Replace to be in line with fileobjects: fileobject.hashdigest is a dictionary
self._hashcache = dict()
"""List for the string-list type of value."""
self.strings = None
def mtime(self):
"""Return nothing. Alternatively, we might return mtime of parent key in the future."""
return None
# if self.parent_key:
# return self.parent_key.mtime()
# else:
# return None
def _hash(self, hashfunc):
"""
Return cached hash, populating cache if necessary.
hashfunc expected values: The functions hashlib.sha1, hashlib.sha256, hashlib.md5.
If self.value_data is None, or there are no strings in a "string-list" type, this should return None.
Interpretation: Registry values of type "string-list" are hashed by feeding each element of the list into the hash .update() function. All other Registry values are fed in the same way, as a 1-element list.
For example, a string type value cell with data "a" fed into this function returns md5("a") (if hashlib.md5 were requested). A string-list type value cell with data ["a","b"] returns md5("ab").
This is a simplification to deal with Registry string encodings, and may change in the future.
"""
if self._hashcache.get(repr(hashfunc)) is None:
feed_list = []
if self.type() == "string-list":
feed_list = self.strings
elif not self.value_data is None:
feed_list.append(self.value_data)
#Normalize to hash .update() required type
for (elemindex, elem) in enumerate(feed_list):
if type(elem) == type(""):
#String data take a little extra care:
#"The bytes in your ... file are being automatically decoded to Unicode by Python 3 as you read from the file"
#http://stackoverflow.com/a/7778340/1207160
feed_list[elemindex] = elem.encode("utf-8")
#Hash if there's data to hash
if len(feed_list) > 0:
h = hashfunc()
for elem in feed_list:
h.update(elem)
self._hashcache[repr(hashfunc)] = h.hexdigest()
return self._hashcache.get(repr(hashfunc))
def sha1(self):
return self._hash(hashlib.sha1)
def sha256(self):
return self._hash(hashlib.sha256)
def md5(self):
return self._hash(hashlib.md5)
def sha512(self):
return self._hash(hashlib.sha512)
class fileobject:
"""The base class for file objects created either through XML DOM or EXPAT"""
TIMETAGLIST=['atime','mtime','ctime','dtime','crtime']
def __init__(self,imagefile=None):
self.imagefile = imagefile
self.hashdigest = dict()
def __str__(self):
try:
fn = self.filename()
except KeyError:
fn = "???"
return "fileobject %s byte_runs: %s" % (fn, " ".join([str(x) for x in self.byte_runs()]))
def partition(self):
"""Partion number of the file"""
return self.tag("partition")
def filename(self):
"""Complement name of the file (sometimes called pathname)"""
return self.tag("filename")
def ext(self):
"""Extension, as a lowercase string without the leading '.'"""
import string
(base,ext) = os.path.splitext(self.filename())
if ext == '':
return None
else:
return ext[1:]
def filesize(self):
"""Size of the file, in bytes"""
return safeInt(self.tag("filesize"))
def uid(self):
"""UID of the file"""
return safeInt(self.tag("uid"))
def gid(self):
"""GID of the file"""
return safeInt(self.tag("gid"))
def meta_type(self):
"""Meta-type of the file"""
return safeInt(self.tag("meta_type"))
def mode(self):
"""Mode of the file"""
return safeInt(self.tag("mode"))
def ctime(self):
"""Metadata Change Time (sometimes Creation Time), as number of seconds
since January 1, 1970 (Unix time)"""
t = self.tag("ctime")
if t: return dftime(t)
return None
def atime(self):
"""Access time, as number of seconds since January 1, 1970 (Unix time)"""
t = self.tag("atime")
if t: return dftime(t)
return None
def crtime(self):
"""CR time, as number of seconds since January 1, 1970 (Unix time)"""
t = self.tag("crtime")
if t: return dftime(t)
return None
def mtime(self):
"""Modify time, as number of seconds since January 1, 1970 (Unix time)"""
t = self.tag("mtime")
if t: return dftime(t)
return None
def dtime(self):
"""ext2 dtime"""
t = self.tag("dtime")
if t: return dftime(t)
return None
def times(self):
"""Return a dictionary of all times that the system has"""
ret = {}
for tag in self.TIMETAGLIST:
if self.has_tag(tag):
try:
ret[tag] = dftime(self.tag(tag))
except TypeError:
pass
return ret
def sha1(self):
"""Returns the SHA1 in hex"""
return self.tag("sha1")
def sha256(self):
"""Returns the SHA256 in hex"""
return self.tag("sha256")
def md5(self):
"""Returns the MD5 in hex"""
return self.tag("md5")
def sha512(self):
"""Returns the SHA512 in hex"""
return self.tag("sha512")
def fragments(self):
"""Returns number of file fragments"""
return len(self.byte_runs())
def name_type(self):
"""Return the contents of the name_type tag"""
return self.tag("name_type")
def is_virtual(self):
"""Returns true if the fi entry is a TSK virtual entry"""
return self.filename() in tsk_virtual_filenames
def is_dir(self):
"""Returns true if file is a directory"""
return self.name_type()=='d'
def is_file(self):
"""Returns true if file is a file"""
return self.name_type()=='r' or self.name_type()==None
def inode(self):
"""Inode; may be a number or SleuthKit x-y-z format"""
return self.tag("inode")
def allocated_inode(self):
"""Returns True if the file's inode data structure is allocated, False otherwise. (Does not return None.)"""
return isone(self.tag("alloc_inode"))
def allocated_name(self):
"""Returns True if the file's name data structure is allocated, False otherwise. (Does not return None.)"""
return isone(self.tag("alloc_name"))
def allocated(self):
"""Returns True if the file is allocated, False if it was not
(that is, if it was deleted or is an orphan).
Note that we need to be tolerant of mixed case, as it was changed.
We also need to tolerate the case of the unalloc tag being used.
"""
if self.filename()=="$OrphanFiles": return False
if self.allocated_inode() and self.allocated_name():
return True
else:
return isone(self.tag("alloc")) or isone(self.tag("ALLOC")) or not isone(self.tag("unalloc"))
def compressed(self):
if not self.has_tag("compressed") and not self.has_tag("compressed") : return False
return isone(self.tag("compressed")) or isone(self.tag("COMPRESSED"))
def encrypted(self):
if not self.has_tag("encrypted") and not self.has_tag("encrypted") : return False
return isone(self.tag("encrypted")) or isone(self.tag("ENCRYPTED"))
def file_present(self,imagefile=None):
"""Returns true if the file is present in the disk image"""
if self.filesize()==0:
return False # empty files are never present
if imagefile==None:
imagefile=self.imagefile # use this one
for hashname in ['md5','sha1','sha256', 'sha512']:
oldhash = self.tag(hashname)
if oldhash:
newhash = hashlib.new(hashname,self.contents(imagefile=imagefile)).hexdigest()
return oldhash==newhash
raise ValueError("Cannot process file "+self.filename()+": no hash in "+str(self))
def has_contents(self):
"""True if the file has one or more bytes"""
return len(self.byte_runs())>0
def has_sector(self,s):
"""True if sector s is contained in one of the byte_runs."""
for run in self.byte_runs():
if run.has_sector(s): return True
return False
def libmagic(self):
"""Returns libmagic string if the string is specified
in the xml, or None otherwise"""
return self.tag("libmagic")
def content_for_run(self,run=None,imagefile=None):
""" Returns the content for a specific run. This is a convenience feature
which does not touch the file object if an imagefile is provided."""
if imagefile is None: imagefile=self.imagefile
if run is None: raise ValueError("content_for_run called without a 'run' argument.")
if run.len == -1:
return chr(0) * run.len
elif hasattr(run,'fill'):
return chr(run.fill) * run.len
else:
imagefile.seek(run.img_offset)
return imagefile.read(run.len)
def contents(self,imagefile=None,icat_fallback=True):
""" Returns the contents of all the runs concatenated together. For allocated files
this should be the original file contents. """
if imagefile is None : imagefile=self.imagefile
if imagefile is None : raise ValueError("imagefile is unknown")
if self.encrypted() : raise ValueError("Cannot generate content for encrypted files")
if self.compressed() or imagefile.name.endswith(".aff") or imagefile.name.endswith(".E01"):
if icat_fallback:
#
# For now, compressed files rely on icat rather than python interface
#
offset = safeInt(self.volume.offset)
block_size = safeInt(self.volume.block_size)
if block_size==0: block_size = 512
inode = self.inode()
if inode :
block_size = 512
fstype_flag = ""
fstype = self.volume.ftype_str()
if fstype != None:
fstype_flag = '-f' + fstype
cmd = ['icat',fstype_flag,'-b',str(block_size),'-o',str(offset//block_size),imagefile.name,str(inode)]
else:
cmd = ['icat','-b',str(block_size),'-o',str(offset//block_size),imagefile.name,str(inode)]
(data,err) = Popen(cmd, stdout=PIPE,stderr=PIPE).communicate()
# Check for an error
if len(err) > 0 :
#sys.stderr.write("Debug: type(err) = %r.\n" % type(err))
raise ValueError("icat error (" + str(err).strip() + "): "+" ".join(cmd))
return data
else :
raise ValueError("Inode missing from file in compressed format.")
raise ValueError("Cannot read raw bytes in compressed disk image")
res = []
for run in self.byte_runs():
res.append(self.content_for_run(run=run,imagefile=imagefile))
return "".join(res)
def tempfile(self,calcMD5=False,calcSHA1=False,calcSHA256=False):
"""Return the contents of imagefile in a named temporary file. If
calcMD5, calcSHA1, or calcSHA256 are set TRUE, then the object
returned has a hashlib object as self.md5 or self.sha1 with the
requested hash."""
import tempfile
tf = tempfile.NamedTemporaryFile()
if calcMD5: tf.md5 = hashlib.md5()
if calcSHA1: tf.sha1 = hashlib.sha1()
if calcSHA256: tf.sha256 = hashlib.sha256()
for run in self.byte_runs():
self.imagefile.seek(run.img_offset)
count = run.len
while count>0:
xfer_len = min(count,1024*1024) # transfer up to a megabyte at a time
buf = self.imagefile.read(xfer_len)
if len(buf)==0: break
tf.write(buf)
if calcMD5: tf.md5.update(buf)
if calcSHA1: tf.sha1.update(buf)
if calcSHA256: tf.sha256.update(buf)
count -= xfer_len
tf.flush()
return tf
def savefile(self,filename=None):
"""Saves the file."""
with open(filename,"wb") as f:
for run in self.byte_runs():
self.imagefile.seek(run.img_offset)
count = run.len
while count>0:
xfer_len = min(count,1024*1024) # transfer up to a megabyte at a time
buf = self.imagefile.read(xfer_len)
if len(buf)==0: break
f.write(buf)
count -= xfer_len
def frag_start_sector(self,fragment):
return self.byte_runs()[fragment].img_offset / 512
def name_type(self):
return self.tag("name_type")
class fileobject_dom(fileobject):
"""file objects created through the DOM. Each object has the XML document
stored in the .doc attribute."""
def __init__(self,xmldoc,imagefile=None):
fileobject.__init__(self,imagefile=imagefile)
self.doc = xmldoc
def tag(self,name):
"""Returns the wholeText for any given NAME. Raises KeyError
if the NAME does not exist."""
try:
return self.doc.getElementsByTagName(name)[0].firstChild.wholeText
except IndexError:
# Check for a hash tag with legacy API
if name in ['md5','sha1','sha256']:
for e in self.doc.getElementsByTagName('hashdigest'):
if e.getAttribute('type').lower()==name:
return e.firstChild.wholeText
raise KeyError(name+" not in XML")
def has_tag(self,name) :
try:
temp=self.doc.getElementsByTagName(name)[0].firstChild.wholeText
return True
except IndexError:
# Check for a hash tag with legacy API
if name in ['md5','sha1','sha256', 'sha512']:
for e in self.doc.getElementsByTagName('hashdigest'):
if e.getAttribute('type').lower()==name:
return True
return False
def byte_runs(self):
"""Returns a sorted array of byte_run objects.
"""
ret = []
try:
for run in self.doc.getElementsByTagName("byte_runs")[0].childNodes:
b = byte_run()
if run.nodeType==run.ELEMENT_NODE:
b.decode_xml_attributes(run.attributes)
ret.append(b)
except IndexError:
pass
ret.sort(key=lambda r:r.file_offset)
return ret
class saxobject:
# saxobject is a mix-in that makes it easy to turn XML tags into functions.
# If the sax tag is registered, then a function with the tag's name is created.
# Calling the function returns the value for the tag that is stored in the _tags{}
# dictionary. The _tags{} dictionary is filled by the _end_element() method that is defined.
# For fileobjects all tags are remembered.
def __init__(self):
self._tags = {}
def tag(self,name):
"""Returns the XML text for a given NAME."""
return self._tags.get(name,None)
def has_tag(self,name) : return name in self._tags
def register_sax_tag(tagclass,name):
setattr(tagclass,name,lambda self:self.tag(name))
class fileobject_sax(fileobject,saxobject):
"""file objects created through expat. This class is created with a tags array and a set of byte runs."""
def __init__(self,imagefile=None,xml=None):
fileobject.__init__(self,imagefile=imagefile)
saxobject.__init__(self)
self._byte_runs = []
def byte_runs(self):
"""Returns an array of byte_run objects."""
return self._byte_runs
class volumeobject_sax(saxobject):
"""A class that represents the volume."""
def __init__(self):
if hasattr(saxobject, "__init__"):
saxobject.__init__(self)
self.offset = 0
self.block_size = 0
def __str__(self):
return "volume "+(str(self._tags))
def partition_offset(self):
try:
return self.tag('partition_offset')
except KeyError:
return self.tag('Partition_Offset')
register_sax_tag(volumeobject_sax,'ftype')
register_sax_tag(volumeobject_sax,'ftype_str')
register_sax_tag(volumeobject_sax,'block_count')
register_sax_tag(volumeobject_sax,'first_block')
register_sax_tag(volumeobject_sax,'last_block')
class imageobject_sax(saxobject):
"""A class that represents the disk image"""
register_sax_tag(imageobject_sax,'imagesize')
register_sax_tag(imageobject_sax,'image_filename')
class creatorobject_sax(saxobject):
"""A class that represents the <creator> section of a DFXML file"""
for tag in ['creator','program','version']:
register_sax_tag(creatorobject_sax,tag)
################################################################
################################################################
def safe_b64decode(b64data):
"""
This function takes care of the logistics of base64 decoding XML data in Python 2 and 3.
Recall that Python3 requires b64decode operate on bytes, not a string.