Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
return []
try:
volumes = pytsk3.Volume_Info(baseimage, getattr(pytsk3, 'TSK_VS_TYPE_' + vstype.upper()),
volume_system.parent.offset // volume_system.disk.block_size)
volume_system.volume_source = 'multi'
return volumes
except Exception as e:
# some bug in sleuthkit makes detection sometimes difficult, so we hack around it:
if "(GPT or DOS at 0)" in str(e) and vstype != 'gpt':
volume_system.vstype = 'gpt'
# noinspection PyBroadException
try:
logger.warning("Error in retrieving volume info: TSK couldn't decide between GPT and DOS, "
"choosing GPT for you. Use --vstype=dos to force DOS.", exc_info=True)
volumes = pytsk3.Volume_Info(baseimage, getattr(pytsk3, 'TSK_VS_TYPE_GPT'))
volume_system.volume_source = 'multi'
return volumes
except Exception as e:
logger.exception("Failed retrieving image info (possible empty image).")
raise SubsystemError(e)
else:
logger.exception("Failed retrieving image info (possible empty image).")
raise SubsystemError(e)
finally:
if baseimage:
baseimage.close()
del baseimage
help='Pass this option to extract files found'
)
args = argparser.parse_args()
if not admin.isUserAdmin():
admin.runAsAdmin()
sys.exit()
dirPath = args.path
if not args.search == '.*':
print "Search Term Provided",args.search
outfile = open(args.output,'w')
outfile.write('"Inode","Full Path","Creation Time","Size","MD5 Hash","SHA1 Hash"\n')
wr = csv.writer(outfile, quoting=csv.QUOTE_ALL)
partitionList = psutil.disk_partitions()
for partition in partitionList:
imagehandle = pytsk3.Img_Info('\\\\.\\'+partition.device.strip("\\"))
if 'NTFS' in partition.fstype:
filesystemObject = pytsk3.FS_Info(imagehandle)
directoryObject = filesystemObject.open_dir(path=dirPath)
print "Directory:",dirPath
directoryRecurse(directoryObject,[])
g = globals()
stat_info = os.stat("usbfor.py") #find user's uid to appropriately call cuckoo
luid = stat_info.st_uid
lgid = stat_info.st_gid
cuckoopath = '/home/{0}/.cuckoo/'.format(pwd.getpwuid(luid)[0])
pid = os.fork()
if pid == 0:
try:
if args.d is not None:
for a in args.d:
os.setgid(lgid)
os.setuid(luid) ##statically set uid change to dynamic
print '[+] Carving files from image'
z = a.split('/')[-1]
imghandle = pytsk3.Img_Info(a)
filesystemObject = pytsk3.FS_Info(imghandle)
dirObject = filesystemObject.open_dir(path="/")
recursive_extract(dirObject,[],a,z)
g['acid_{0}'.format(z)] = []
print "[+] Completed carving files from image"
print "[+] Submitting all files found to Cuckoo"
ddpid = subprocess.Popen(['cuckoo','submit','Carved_files_{0}/'.format(z)],stdout=subprocess.PIPE)
stoutdd = ddpid.communicate()
print "[+] Completed submitting files to cuckoo"
for cpid in stoutdd[0].split('\n'):
print cpid
g['acid_{0}'.format(z)].append(cpid.split(' ')[-1].replace("#",""))
g['acid_{0}'.format(z)].pop()
#print analysis information
while True:
img = None
found_osx = False
mac_info = None
time_processing_started = time.time()
try:
if args.input_type.upper() == 'E01':
img = GetImgInfoObjectForE01(args.input_path) # Use this function instead of pytsk3.Img_Info()
mac_info = macinfo.MacInfo(output_params)
elif args.input_type.upper() == 'VMDK':
img = GetImgInfoObjectForVMDK(args.input_path) # Use this function instead of pytsk3.Img_Info()
mac_info = macinfo.MacInfo(output_params)
elif args.input_type.upper() == 'AFF4':
img = GetImgInfoObjectForAff4(args.input_path) # Use this function instead of pytsk3.Img_Info()
mac_info = macinfo.MacInfo(output_params)
elif args.input_type.upper() == 'DD':
img = pytsk3.Img_Info(args.input_path) # Works for split dd images too! Works for DMG too, if no compression/encryption is used!
mac_info = macinfo.MacInfo(output_params)
elif args.input_type.upper() == 'MOUNTED':
if os.path.isdir(args.input_path):
mac_info = macinfo.MountedMacInfo(args.input_path, output_params)
found_osx = FindOsxFiles(mac_info)
else:
Exit("Exiting -> Cannot browse mounted image at " + args.input_path)
log.info("Opened image " + args.input_path)
except Exception as ex:
log.error("Failed to load image. Error Details are: " + str(ex))
Exit()
if args.input_type.upper() != 'MOUNTED':
mac_info.use_native_hfs_parser = True #False if args.use_tsk else True
try:
mac_info.pytsk_image = img
args = argparser.parse_args()
if not admin.isUserAdmin():
admin.runAsAdmin()
sys.exit()
dirPath = args.path
if not args.search == '.*':
print "Search Term Provided",args.search
outfile = open(args.output,'w')
outfile.write('"Inode","Full Path","Creation Time","Size","MD5 Hash","SHA1 Hash"\n')
wr = csv.writer(outfile, quoting=csv.QUOTE_ALL)
partitionList = psutil.disk_partitions()
for partition in partitionList:
imagehandle = pytsk3.Img_Info('\\\\.\\'+partition.device.strip("\\"))
if 'NTFS' in partition.fstype:
filesystemObject = pytsk3.FS_Info(imagehandle)
directoryObject = filesystemObject.open_dir(path=dirPath)
print "Directory:",dirPath
directoryRecurse(directoryObject,[])
#!/usr/bin/python
# Sample program or step 4 in becoming a DFIR Wizard!
# No license as this code is simple and free!
import sys
import pytsk3
import datetime
import admin
if not admin.isUserAdmin():
admin.runAsAdmin()
sys.exit()
imagefile = "\\\\.\\PhysicalDrive0"
imagehandle = pytsk3.Img_Info(imagefile)
partitionTable = pytsk3.Volume_Info(imagehandle)
for partition in partitionTable:
print partition.addr, partition.desc, "%ss(%s)" % (partition.start, partition.start * 512), partition.len
if 'NTFS' in partition.desc:
filesystemObject = pytsk3.FS_Info(imagehandle, offset=(partition.start*512))
fileobject = filesystemObject.open("/$MFT")
print "File Inode:",fileobject.info.meta.addr
print "File Name:",fileobject.info.name.name
print "File Creation Time:",datetime.datetime.fromtimestamp(fileobject.info.meta.crtime).strftime('%Y-%m-%d %H:%M:%S')
outFileName = str(partition.addr)+fileobject.info.name.name
print outFileName
outfile = open(outFileName, 'w')
filedata = fileobject.read_random(0,fileobject.info.meta.size)
outfile.write(filedata)
outfile.close
def tsktest(retstr=None):
# Step 1: get an IMG_INFO object
img = pytsk3.Img_Info("/home/bcadmin/Desktop/jo-work-usb-2009-12-11.E01")
## Step 2: get a Volume_Info object
volume = pytsk3.Volume_Info(img)
## Step 3: Iterate over all the partitions.
retstr = 'PARTITIONS ON THIS DISK:' + '\'
for part in volume:
#print part.addr, part.desc, part.start, part.len
retstr += str(part.addr) + ' ' + str(part.desc) + ' ' + str(part.start) + ' ' + str(part.len) + '<br>'
retstr += '<br>' + 'Contents of the root directory:' + '<br>'
## Now, a hack to recognize the start location. Do NOT use this
## code in production. It's just a demo.
fs = pytsk3.FS_Info(img, offset = 63 * 512)
for directory_entry in fs.open_dir(path="/"):
directory_entry = directory_entry.info.name.name
try:
elif f_type == pytsk3.TSK_FS_META_TYPE_REG and begin.info.meta.size != 0: #if file and size > 1
filedata = begin.read_random(0,begin.info.meta.size)
print "Extracting File : " + str(['/'.join(parentPath)+begin.info.name.name])
#create new folder to extract the file
if not os.path.exists(outputPath):
os.makedirs(outputPath)
#extract the file
extractFile = open(outputPath+begin.info.name.name,'w')
extractFile.write(filedata)
extractFile.close
#if file but file size is 0
elif f_type == pytsk3.TSK_FS_META_TYPE_REG and begin.info.meta.size == 0:
print "Unable to recover : " + str(['/'.join(parentPath)+begin.info.name.name])
except IOError as e:
print e
continue
except KeyboardInterrupt:
sys.exit(1)
def scan_disk(disk_url, scan_file_dir):
"""
Scans a physical disk at disk_url, creates
a scan file and saves it at scan_file_dir
Scan file can be converted into a SemanticDiskEngine object, but only NTFS volumes will have any data at all,
and only metadata.
"""
# make the dir if it doesn't exist
if not os.path.exists(scan_file_dir):
os.makedirs(scan_file_dir)
# open up the image
img = pytsk3.Img_Info(url=disk_url)
# get the volume info
VOL_INFO = pytsk3.Volume_Info(img)
# print out some info about the disk image
logger.debug("--- Volume info ---")
logger.debug("Current: %d" % VOL_INFO.current)
logger.debug("VS Type: %d" % VOL_INFO.info.vstype)
logger.debug("Offset: %d" % VOL_INFO.info.offset)
logger.debug("Block Size: %d" % VOL_INFO.info.block_size)
logger.debug("Endian: %d" % VOL_INFO.info.endian)
logger.debug("Partition List: %s" % VOL_INFO.info.part_list)
logger.debug("Parition Count: %d" % VOL_INFO.info.part_count)
logger.debug("--- Volume info ---")
# Sample program or step 12 in becoming a DFIR Wizard!
# No license as this code is simple and free!
# Goes with blog post http://www.hecfblog.com/2015/05/automating-dfir-how-to-series-on_24.html
import sys
import pytsk3
import datetime
import pyewf
import argparse
import hashlib
import csv
import os
import re
import vss
import pyvshadow
class ewf_Img_Info(pytsk3.Img_Info):
def __init__(self, ewf_handle):
self._ewf_handle = ewf_handle
super(ewf_Img_Info, self).__init__(
url="", type=pytsk3.TSK_IMG_TYPE_EXTERNAL)
def close(self):
self._ewf_handle.close()
def read(self, offset, size):
self._ewf_handle.seek(offset)
return self._ewf_handle.read(size)
def get_size(self):
return self._ewf_handle.get_media_size()
def directoryRecurse(directoryObject, parentPath):