-
Notifications
You must be signed in to change notification settings - Fork 26
/
aff4.py
497 lines (416 loc) · 21.9 KB
/
aff4.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
# Copyright 2018-2019 Schatz Forensic Pty Ltd. All rights reserved.
#
# 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.
# author [email protected]
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from builtins import next
from builtins import str
from builtins import object
import argparse
import sys, os, errno, shutil, uuid
import time
import logging
from pyaff4 import container, version
from pyaff4 import lexicon, logical, escaping
from pyaff4 import rdfvalue, hashes, utils
from pyaff4 import block_hasher, data_store, linear_hasher, zip
from pyaff4 import aff4_map
#logging.basicConfig(level=logging.DEBUG)
VERBOSE = False
TERSE = False
def printImageMetadata(resolver, volume, image):
print("\t%s <%s>" % (image.name(), trimVolume(volume.urn, image.urn)))
with resolver.AFF4FactoryOpen(image.urn) as srcStream:
if type(srcStream) == aff4_map.AFF4Map2:
source_ranges = sorted(srcStream.tree)
for n in source_ranges:
d = n.data
print("\t\t[%x,%x] -> %s[%x,%x]" % (
d.map_offset, d.length, srcStream.targets[d.target_id], d.target_offset, d.length))
def printTurtle(resolver, volume):
metadataURN = volume.urn.Append("information.turtle")
try:
with resolver.AFF4FactoryOpen(metadataURN) as fd:
txt = fd.ReadAll()
print(utils.SmartUnicode(txt))
except:
pass
def meta(file, password):
with container.Container.openURNtoContainer(rdfvalue.URN.FromFileName(file)) as volume:
printTurtle(volume.resolver, volume)
if password != None:
assert not issubclass(volume.__class__, container.PhysicalImageContainer)
volume.setPassword(password[0])
childVolume = volume.getChildContainer()
printTurtle(childVolume.resolver, childVolume)
for image in childVolume.images():
printImageMetadata(childVolume.resolver, childVolume, image)
else:
for image in volume.images():
printImageMetadata(volume.resolver, volume, image)
def list(file, password):
start = time.time()
with container.Container.openURNtoContainer(rdfvalue.URN.FromFileName(file)) as volume:
if password != None:
assert not issubclass(volume.__class__, container.PhysicalImageContainer)
#volume.block_store_stream.DEBUG = True
volume.setPassword(password[0])
childVolume = volume.getChildContainer()
printLogicalImageInfo(file, childVolume)
else:
print("Finished in %d (s)" % int(time.time() - start))
if issubclass(volume.__class__, container.PhysicalImageContainer):
printDiskImageInfo(file, volume)
elif issubclass(volume.__class__, container.LogicalImageContainer):
printLogicalImageInfo(file, volume)
def printLogicalImageInfo(file, volume):
printVolumeInfo(file, volume)
printCaseInfo(volume)
for image in volume.images():
print ("\t%s <%s>" % (image.name(), trimVolume(volume.urn, image.urn)))
def printVolumeInfo(file, volume):
volumeURN = volume.urn
print("AFF4Container: file://%s <%s>" % (file, str(volumeURN)))
def printCaseInfo(volume):
caseDetails = volume.getMetadata("CaseDetails")
if caseDetails == None:
return
print ("\tCase Description: %s" % caseDetails.caseDescription)
print ("\tCase Name: %s" % caseDetails.caseName)
print ("\tExaminer: %s" % caseDetails.examiner)
def printDiskImageInfo(file, volume):
printVolumeInfo(file, volume)
printCaseInfo(volume)
image = volume.getMetadata("DiskImage")
print ("\t%s (DiskImage)" % image.urn)
print ("\t\tSize: %s (bytes)" % image.size)
print ("\t\tSize: %s (bytes)" % image.size)
print ("\t\tSectors: %s" % image.sectorCount)
print ("\t\tBlockMapHash: %s" % image.hash)
# the following property is to test that unknown properties are handled OK
print ("\t\tUnknownproperty: %s" % image.foobar)
computerInfo = volume.getMetadata("ComputeResource")
if computerInfo != None:
print ("\tAcquisition computer details")
print ("\t\tSystem board vendor: %s" % computerInfo.systemboardVendor)
print ("\t\tSystem board serial: %s" % computerInfo.systemboardSerial)
print ("\t\tUnknownproperty: %s" % computerInfo.foobar)
class VerificationListener(object):
def __init__(self):
self.results = []
def onValidBlockHash(self, a):
pass
def onInvalidBlockHash(self, a, b, imageStreamURI, offset):
self.results.append("Invalid block hash comarison for stream %s at offset %d" % (imageStreamURI, offset))
def onValidHash(self, typ, hash, imageStreamURI):
self.results.append("Validation of %s %s succeeded. Hash = %s" % (imageStreamURI, typ, hash))
def onInvalidHash(self, typ, a, b, streamURI):
self.results.append("Invalid %s comarison for stream %s" % (typ, streamURI))
class LinearVerificationListener(object):
def __init__(self):
self.results = []
def onValidHash(self, typ, hash, imageStreamURI):
print ("\t\t%s Verified (%s)" % (typ, hash))
def onInvalidHash(self, typ, hasha, hashb, streamURI):
print ("\t\t%s Hash failure stored = %s calculated = %s)" % (typ, hasha, hashb))
def trimVolume(volume, image):
global TERSE
if TERSE:
volstring = utils.SmartUnicode(volume)
imagestring = utils.SmartUnicode(image)
if imagestring.startswith(volstring):
imagestring = imagestring[len(volstring):]
return imagestring
else:
return image
def verify(file, password):
with container.Container.openURNtoContainer(rdfvalue.URN.FromFileName(file)) as volume:
if password != None:
assert not issubclass(volume.__class__, container.PhysicalImageContainer)
volume.setPassword(password[0])
childVolume = volume.getChildContainer()
printVolumeInfo(file, childVolume)
printCaseInfo(childVolume)
resolver = childVolume.resolver
hasher = linear_hasher.LinearHasher2(resolver, LinearVerificationListener())
for image in childVolume.images():
print("\t%s <%s>" % (image.name(), trimVolume(childVolume.urn, image.urn)))
hasher.hash(image)
else:
printVolumeInfo(file, volume)
printCaseInfo(volume)
resolver = volume.resolver
if type(volume) == container.PhysicalImageContainer:
image = volume.image
listener = VerificationListener()
validator = block_hasher.Validator(listener)
print("Verifying AFF4 File: %s" % file)
validator.validateContainer(rdfvalue.URN.FromFileName(file))
for result in listener.results:
print("\t%s" % result)
elif type(volume) == container.LogicalImageContainer:
#print ("\tLogical Images:")
hasher = linear_hasher.LinearHasher2(resolver, LinearVerificationListener())
for image in volume.images():
print ("\t%s <%s>" % (image.name(), trimVolume(volume.urn, image.urn)))
hasher.hash(image)
def ingestZipfile(container_name, zipfiles, append, check_bytes):
# TODO: check path in exists
start = time.time()
with data_store.MemoryDataStore() as resolver:
container_urn = rdfvalue.URN.FromFileName(container_name)
urn = None
if not os.path.exists(container_name):
volume = container.Container.createURN(resolver, container_urn)
print("Creating AFF4Container: file://%s <%s>" % (container_name, volume.urn))
else:
volume = container.Container.openURNtoContainer(container_urn, mode="+")
print("Appending to AFF4Container: file://%s <%s>" % (container_name, volume.urn))
resolver = volume.resolver
with volume as volume:
for zipfile in zipfiles:
basefilename = os.path.basename(zipfile)
if basefilename.endswith(".bag.zip"):
basefilename = basefilename[0:len(basefilename) - len(".bag.zip")]
filename_arn = rdfvalue.URN.FromFileName(zipfile)
# the following coaxes our ZIP implementation to treat this file
# as a regular old zip
result = zip.BasicZipFile(resolver, urn=None, version=version.basic_zip)
resolver.Set(lexicon.transient_graph, result.urn, lexicon.AFF4_TYPE, rdfvalue.URN("StandardZip"))
resolver.Set(lexicon.transient_graph, result.urn, lexicon.AFF4_STORED, rdfvalue.URN(filename_arn))
with resolver.AFF4FactoryOpen(result.urn, version=version.basic_zip) as zip_file:
for member in zip_file.members:
info = zip_file.members[member]
pathname = basefilename + member.SerializeToString()[len(result.urn.SerializeToString()):]
print(pathname)
with resolver.AFF4FactoryOpen(member, version=version.aff4v10) as src:
hasher = linear_hasher.StreamHasher(src, [lexicon.HASH_SHA1, lexicon.HASH_MD5])
if volume.containsLogicalImage(pathname):
print("\tCollision: this ARN is already present in this volume.")
continue
urn = volume.writeLogicalStreamRabinHashBased(pathname, hasher, info.file_size, check_bytes)
#fsmeta.urn = urn
#fsmeta.store(resolver)
for h in hasher.hashes:
hh = hashes.newImmutableHash(h.hexdigest(), hasher.hashToType[h])
resolver.Add(container_urn, urn, rdfvalue.URN(lexicon.standard.hash), hh)
print ("Finished in %d (s)" % int(time.time() - start))
return urn
def addPathNamesToVolume(resolver, volume, pathnames, recursive, hashbased):
for pathname in pathnames:
if not os.path.exists(pathname):
print("Path %s not found. Skipping." % pathname)
continue
pathname = utils.SmartUnicode(pathname)
print("\tAdding: %s" % pathname)
fsmeta = logical.FSMetadata.create(pathname)
if os.path.isdir(pathname):
image_urn = None
if volume.isAFF4Collision(pathname):
image_urn = rdfvalue.URN("aff4://%s" % uuid.uuid4())
else:
image_urn = volume.urn.Append(escaping.arnPathFragment_from_path(pathname), quote=False)
fsmeta.urn = image_urn
fsmeta.store(resolver)
resolver.Set(volume.urn, image_urn, rdfvalue.URN(lexicon.standard11.pathName), rdfvalue.XSDString(pathname))
resolver.Add(volume.urn, image_urn, rdfvalue.URN(lexicon.AFF4_TYPE),
rdfvalue.URN(lexicon.standard11.FolderImage))
resolver.Add(volume.urn, image_urn, rdfvalue.URN(lexicon.AFF4_TYPE), rdfvalue.URN(lexicon.standard.Image))
if recursive:
for child in os.listdir(pathname):
pathnames.append(os.path.join(pathname, child))
else:
with open(pathname, "rb") as src:
hasher = linear_hasher.StreamHasher(src, [lexicon.HASH_SHA1, lexicon.HASH_MD5])
if hashbased == False:
urn = volume.writeLogicalStream(pathname, hasher, fsmeta.length)
else:
urn = volume.writeLogicalStreamRabinHashBased(pathname, hasher, fsmeta.length)
fsmeta.urn = urn
fsmeta.store(resolver)
for h in hasher.hashes:
hh = hashes.newImmutableHash(h.hexdigest(), hasher.hashToType[h])
resolver.Add(urn, urn, rdfvalue.URN(lexicon.standard.hash), hh)
def addPathNames(container_name, pathnames, recursive, append, hashbased, password):
with data_store.MemoryDataStore() as resolver:
container_urn = rdfvalue.URN.FromFileName(container_name)
urn = None
encryption = False
parentVolume = None
if password != None:
encryption = True
if append == False:
with container.Container.createURN(resolver, container_urn, encryption=encryption) as volume:
print("Creating AFF4Container: file://%s <%s>" % (container_name, volume.urn))
if password != None:
volume.setPassword(password[0])
childVolume = volume.getChildContainer()
addPathNamesToVolume(childVolume.resolver, childVolume, pathnames, recursive, hashbased)
else:
addPathNamesToVolume(resolver, volume, pathnames, recursive, hashbased)
else:
with container.Container.openURNtoContainer(container_urn, mode="+") as volume:
print("Appending to AFF4Container: file://%s <%s>" % (container_name, volume.urn))
if password != None:
volume.setPassword(password[0])
childVolume = volume.getChildContainer()
addPathNamesToVolume(childVolume.resolver, childVolume, pathnames, recursive, hashbased)
else:
addPathNamesToVolume(resolver, volume, pathnames, recursive, hashbased)
return urn
def nextOrNone(iterable):
try:
return next(iterable)
except:
return None
def extractAllFromVolume(container_urn, volume, destFolder):
printVolumeInfo(container_urn.original_filename, volume)
resolver = volume.resolver
for imageUrn in resolver.QueryPredicateObject(volume.urn, lexicon.AFF4_TYPE, lexicon.standard11.FileImage):
imageUrn = utils.SmartUnicode(imageUrn)
pathName = next(resolver.QuerySubjectPredicate(volume.urn, imageUrn, lexicon.standard11.pathName)).value
with resolver.AFF4FactoryOpen(imageUrn) as srcStream:
if destFolder != "-":
drive, pathName = os.path.splitdrive(pathName) # Windows drive letters
destFile = os.path.join(destFolder, drive[:-1], pathName.strip("/\\"))
if not os.path.exists(os.path.dirname(destFile)):
try:
os.makedirs(os.path.dirname(destFile))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(destFile, "wb") as destStream:
shutil.copyfileobj(srcStream, destStream)
print("\tExtracted %s to %s" % (pathName, destFile))
lastWritten = nextOrNone(
resolver.QuerySubjectPredicate(volume.urn, imageUrn, lexicon.standard11.lastWritten))
lastAccessed = nextOrNone(
resolver.QuerySubjectPredicate(volume.urn, imageUrn, lexicon.standard11.lastAccessed))
recordChanged = nextOrNone(
resolver.QuerySubjectPredicate(volume.urn, imageUrn, lexicon.standard11.recordChanged))
birthTime = nextOrNone(
resolver.QuerySubjectPredicate(volume.urn, imageUrn, lexicon.standard11.birthTime))
logical.resetTimestamps(destFile, lastWritten, lastAccessed, recordChanged, birthTime)
else:
shutil.copyfileobj(srcStream, sys.stdout)
def extractAll(container_name, destFolder, password):
container_urn = rdfvalue.URN.FromFileName(container_name)
urn = None
with container.Container.openURNtoContainer(container_urn) as volume:
if password != None:
assert not issubclass(volume.__class__, container.PhysicalImageContainer)
volume.setPassword(password[0])
childVolume = volume.getChildContainer()
extractAllFromVolume(container_urn, childVolume, destFolder)
else:
extractAllFromVolume(container_urn, volume, destFolder)
def extractFromVolume(container_urn, volume, imageURNs, destFolder):
printVolumeInfo(container_urn.original_filename, volume)
resolver = volume.resolver
for imageUrn in imageURNs:
imageUrn = utils.SmartUnicode(imageUrn)
pathName = next(resolver.QuerySubjectPredicate(volume.urn, imageUrn, volume.lexicon.pathName))
with resolver.AFF4FactoryOpen(imageUrn) as srcStream:
if destFolder != "-":
pathName = escaping.arnPathFragment_from_path(pathName.value)
while pathName.startswith("/"):
pathName = pathName[1:]
drive, pathName = os.path.splitdrive(pathName) # Windows drive letters
destFile = os.path.join(destFolder, drive[:-1], pathName.strip("/\\"))
if not os.path.exists(os.path.dirname(destFile)):
try:
os.makedirs(os.path.dirname(destFile))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(destFile, "wb") as destStream:
shutil.copyfileobj(srcStream, destStream, length=32 * 2014)
print("\tExtracted %s to %s" % (pathName, destFile))
else:
shutil.copyfileobj(srcStream, sys.stdout)
def extract(container_name, imageURNs, destFolder, password):
with data_store.MemoryDataStore() as resolver:
container_urn = rdfvalue.URN.FromFileName(container_name)
urn = None
with container.Container.openURNtoContainer(container_urn) as volume:
if password != None:
assert not issubclass(volume.__class__, container.PhysicalImageContainer)
volume.setPassword(password[0])
childVolume = volume.getChildContainer()
extractFromVolume(container_urn, childVolume, imageURNs, destFolder)
else:
extractFromVolume(container_urn, volume, imageURNs, destFolder)
def main(argv):
parser = argparse.ArgumentParser(description='AFF4 command line utility.')
parser.add_argument('-v', "--verify", action="store_true",
help='verify the objects in the container')
parser.add_argument("--verbose", action="store_true",
help='enable verbose output')
parser.add_argument('-t', "--terse", action="store_true",
help='enable terse output')
parser.add_argument('-l', "--list", action="store_true",
help='list the objects in the container')
parser.add_argument('-m', "--meta", action="store_true",
help='dump the AFF4 metadata found in the container')
parser.add_argument('-f', "--folder", nargs=1, action="store", default=os.getcwd(),
help='the destination folder for extraction of logical images')
parser.add_argument('-r', "--recursive", action="store_true",
help='add files and folders recursively')
parser.add_argument('-c', "--create-logical", action="store_true",
help='create an AFF4 logical container containing srcFiles')
parser.add_argument('-x', "--extract", action="store_true",
help='extract objects from the container')
parser.add_argument('-X', "--extract-all", action="store_true",
help='extract ALL objects from the container')
parser.add_argument('-H', "--hash", action="store_true",
help='use hash based imaging for storing content')
parser.add_argument('-p', "--paranoid", action="store_true",
help='do a byte-for-byte comparison when matching hashes are found with hash based imaging')
parser.add_argument('-a', "--append", action="store_true",
help='append to an existing image')
parser.add_argument('-i', "--ingest", action="store_true",
help='ingest a zip file into a hash based image')
parser.add_argument('-e', "--password", nargs=1, action="store",
help='provide a password for encryption. This causes an encrypted container to be used.')
parser.add_argument('aff4container', help='the pathname of the AFF4 container')
parser.add_argument('srcFiles', nargs="*", help='source files and folders to add as logical image')
args = parser.parse_args()
global TERSE
global VERBOSE
VERBOSE = args.verbose
TERSE = args.terse
if args.create_logical == True:
dest = args.aff4container
addPathNames(dest, args.srcFiles, args.recursive, args.append, args.hash, args.password)
elif args.meta == True:
dest = args.aff4container
meta(dest, args.password)
elif args.list == True:
dest = args.aff4container
list(dest, args.password)
elif args.verify == True:
dest = args.aff4container
verify(dest, args.password)
elif args.extract == True:
dest = args.aff4container
extract(dest, args.srcFiles, args.folder[0], args.password)
elif args.extract_all == True:
dest = args.aff4container
extractAll(dest, args.folder[0], args.password)
elif args.ingest == True:
dest = args.aff4container
ingestZipfile(dest, args.srcFiles, False, args.paranoid)
if __name__ == "__main__":
main(sys.argv)