Esempio n. 1
0
def open_fs(vol, img, hashes, hash_type, pbar_total=0):
    # Open FS and Recurse
    print("[+] Recursing through and hashing files")
    pbar = tqdm(desc="Hashing",
                unit=" files",
                unit_scale=True,
                total=pbar_total)
    if vol is not None:
        for part in vol:
            if part.len > 2048 and "Unallocated" not in part.desc and \
                "Extended" not in part.desc and \
                "Primary Table" not in part.desc:
                try:
                    fs = pytsk3.FS_Info(img,
                                        offset=part.start *
                                        vol.info.block_size)
                except IOError:
                    _, e, _ = sys.exc_info()
                    print("[-] Unable to open FS:\n {}".format(e))
        root = fs.open_dir(path="/")
        recurse_files(part.addr, fs, root, [], [""], hashes, hash_type, pbar)
    else:
        try:
            fs = pytsk3.FS_Info(img)
        except IOError:
            _, e, _ = sys.exc_info()
            print("[-] Unable to open FS:\n {}".format(e))
    root = fs.open_dir(path="/")
    recurse_files(1, fs, root, [], [""], hashes, hash_type, pbar)
    pbar.close()
Esempio n. 2
0
def open_fs(vol, img, output):
    print("[+] Recursing through files..")
    recursed_data = []
    # Open FS and Recurse
    if vol is not None:
        for part in vol:
            print(part.desc)
            if part.len > 2048 and b"Unallocated" not in part.desc and \
                    b"Extended" not in part.desc and \
                    b"Primary Table" not in part.desc:
                try:
                    fs = pytsk3.FS_Info(img,
                                        offset=part.start *
                                        vol.info.block_size)
                except IOError:
                    _, e, _ = sys.exc_info()
                    print("[-] Unable to open FS:\n {}".format(e))
                root = fs.open_dir(path="/")
                data = recurse_files(part.addr, fs, root, [], [], [""])
                recursed_data.append(data)

    else:
        try:
            fs = pytsk3.FS_Info(img)
        except IOError:
            _, e, _ = sys.exc_info()
            print("[-] Unable to open FS:\n {}".format(e))
        root = fs.open_dir(path="/")
        data = recurse_files(1, fs, root, [], [], [""])
        recursed_data.append(data)
    write_csv(recursed_data, output)
Esempio n. 3
0
def open_fs(vol, img, ext, output):
    # Open FS and Recurse
    print("[+] Recursing through files and writing file extension matches "
          "to output directory")
    if vol is not None:
        for part in vol:
            if part.len > 2048 and "Unallocated" not in part.desc \
                    and "Extended" not in part.desc \
                    and "Primary Table" not in part.desc:
                try:
                    fs = pytsk3.FS_Info(img,
                                        offset=part.start *
                                        vol.info.block_size)
                except IOError:
                    _, e, _ = sys.exc_info()
                    print("[-] Unable to open FS:\n {}".format(e))
                root = fs.open_dir(path="/")
                recurse_files(part.addr, fs, root, [], [""], ext, output)

    else:
        try:
            fs = pytsk3.FS_Info(img)
        except IOError:
            _, e, _ = sys.exc_info()
            print("[-] Unable to open FS:\n {}".format(e))
        root = fs.open_dir(path="/")
        recurse_files(1, fs, root, [], [""], ext, output)
Esempio n. 4
0
def extractFromDisk(imagehandle,partition,output):
    
    # partitionTable = pytsk3.Volume_Info(imagehandle) #The partition table is returned from the Volume_Info function
    # print partitionTable

    # for partition in partitionTable:
      print partition.addr, partition.desc, "%ss(%s)" % (partition.start, partition.start * 512), partition.len
      if 'Basic data partition' or 'NTFS' in partition.desc:
        try:
            for entry in files:
                path = entry["path"]
                try:
                    
                    filesystemObject = pytsk3.FS_Info(imagehandle, offset=(partition.start*512))

                    fileobject = filesystemObject.open(path)

                    outdir = output+"/"+entry["name"]
                    if not os.path.exists(outdir): os.makedirs(outdir)

                    outFileName = output+"/"+entry["name"]+ "/" +str(partition.addr)+" "+fileobject.info.name.name

                    outfile = open(outFileName, 'w')
                    filedata = fileobject.read_random(0,fileobject.info.meta.size)
                    outfile.write(filedata)
                    outfile.close

                except:

                    pass
           
            for entry in directories:
                directory = entry["path"]

                try:
                    filesystemObject = pytsk3.FS_Info(imagehandle, offset=(partition.start*512))
                    directoryObject = filesystemObject.open_dir(directory)
                    for entryObject in directoryObject:
                        if entryObject.info.name.name in [".", ".."]:
                            continue

                        filepath =(directory+"/"+entryObject.info.name.name)

                        fileobject = filesystemObject.open(filepath)
                        outFileName = output+"/"+entry["name"]+"/"+str(partition.addr)+" "+fileobject.info.name.name
                        outdir = output+"/"+entry["name"]
                        if not os.path.exists(outdir): os.makedirs(outdir)
                        
                        outfile = open(outFileName, 'w')
                        filedata = fileobject.read_random(0,fileobject.info.meta.size)
                        outfile.write(filedata)
                        outfile.close
                except:
                    pass
        except:
            pass
Esempio n. 5
0
def extractFile(imageFile,filenames):


  # vhdi_file = pyvhdi.file()
  # vhdi_file.open(imageFile)
  # img_info = vhdi_Img_Info(vhdi_file)
  # partitionTable = pytsk3.Volume_Info(img_info)

  if "vhd" in imageFile:
    vhdi_file = pyvhdi.file()
    vhdi_file.open(imageFile)
    img_info = vhdi_Img_Info(vhdi_file)
    partitionTable = pytsk3.Volume_Info(img_info)
  else:
    img_info = pytsk3.Img_Info(imageFile)
    partitionTable = pytsk3.Volume_Info(img_info)

  for partition in partitionTable:
    print partition.addr, partition.desc, "%ss(%s)" % (partition.start, partition.start * 512), partition.len
    # try:
    if 'NTFS' in partition.desc:
      filesystemObject = pytsk3.FS_Info(img_info, offset=(partition.start*512))
      print "File System Type Dectected ",filesystemObject.info.ftype
      directoryObject = filesystemObject.open_dir(path=dirPath)
      print "Directory:",dirPath

    elif 'FAT32' in partition.desc:  # Use DFIR tutorial example to deal with other partitions later on.
      filesystemObject = pytsk3.FS_Info(img_info, offset=(partition.start*512))
      print "File System Type Dectected ",filesystemObject.info.ftype
      directoryObject = filesystemObject.open_dir(path=dirPath)
      print "Directory:",dirPath


    outputPath = 'Evidence_Package'

  for filename in filenames:
    if not os.path.exists(outputPath):
      os.makedirs(outputPath)
    if not os.path.isdir(str(filename)):
      try:
        # ex_path = ('%s/%s' % (outputPath, os.path.basename(str(filename)))).replace('//','/') 
        # ex_path = outputPath + os.sep + os.path.basename(str(filename))
        ex_path = ('%s\%s' % (outputPath, os.path.basename(str(filename)))).replace('//','/') 



        extractFile = open(ex_path,'w')

        fileobject = filesystemObject.open(str(filename))
        filedata = fileobject.read_random(0,fileobject.info.meta.size)
        extractFile.write(filedata)
        extractFile.close
      except IOError:
        print('cannot open', str(filename))
Esempio n. 6
0
    def analysis(self, dirPath):

        partitionTable, imagehandle = self.readImageFile(self.imagefile)

        for partition in partitionTable:
            print partition.desc
            if 'NTFS' in partition.desc or 'Basic data partition' in partition.desc or 'Win95 FAT32' in partition.desc:

                if self.extractFromDisk == True:
                    extractFromDisk(imagehandle, partition, self.output()[0])

                if self.getHashList == True:
                    filesystemObject = pytsk3.FS_Info(imagehandle,
                                                      offset=(partition.start *
                                                              512))
                    directoryObject = filesystemObject.open_dir(path=dirPath)
                    print "Directory:", dirPath
                    if not os.path.exists(self.output()[0]):
                        os.makedirs(self.output()[0])
                    outfile = open(self.output()[1], 'wb')
                    outfile.write(
                        '"Inode","Full Path","Creation Time","Modified Time","Accessed Time","Size","MD5 Hash","SHA1 Hash","SHA256 HASH"\n'
                    )
                    hashOutput = csv.writer(outfile, quoting=csv.QUOTE_ALL)
                    self.directoryRecurse(directoryObject, [], hashOutput)
Esempio n. 7
0
def main():
    #TODO move image loading to a method or util class
    imagefile = './forensic_image/AssignmentImage.dmg'
    imagehandle = pytsk3.Img_Info(imagefile)
    partitionTable = pytsk3.Volume_Info(imagehandle)
    print_partition_table(partitionTable)
    filesystemObject = pytsk3.FS_Info(imagehandle, offset=512)
    #print dir(filesystemObject)

    walk_file_system(filesystemObject)
    print 'The lenght of the dictionary is %d' % len(hashMap)
    rev_multidict = {}
    for key, value in hashMap.items():
        rev_multidict.setdefault(value, set()).add(key)

    for v in [
            values for key, values in rev_multidict.items() if len(values) > 1
    ]:
        print list(v)

    print '========'
    fileobject = filesystemObject.open_dir("/")

    for a_file in fileobject:
        if a_file.info.meta.type == pytsk3.TSK_FS_META_TYPE_DIR:
            print ''
Esempio n. 8
0
def justCopy(srcPath, dstPath):
    try:
        driveLetter = srcPath.split("\\")[0]
        imagefile, offset = GetPhysicalDisk(driveLetter)
        imagehandle = pytsk3.Img_Info(imagefile)
        drive = pytsk3.FS_Info(imagehandle, offset=int(offset))

        parsedname = os.path.abspath(srcPath).replace(driveLetter,
                                                      "").replace("\\", "/")
        fileobject = drive.open(parsedname)
        OutFileName = fileobject.info.name.name

        if not os.path.exists(dstPath):
            os.makedirs(dstPath)

        FinalFilePath = os.path.join(dstPath, OutFileName)
        OutFile = open(FinalFilePath, 'wb')
        if fileobject.info.meta.size > 0:
            logging.info("[+] Copying the file \"{}\" ".format(srcPath))
            filedata = fileobject.read_random(0, fileobject.info.meta.size)
            OutFile.write(filedata)
            OutFile.close()
            logging.info(
                "[+] Successfully copied the file '{}' !".format(srcPath))
        else:
            filedata = b""
            logging.warning(
                "[!] Unable to copy the file \"{}\" . The file is Not Found / Empty!"
                .format(srcPath))
    except Exception as e:
        logging.error("[!] Unable to copy the file \"{}\" .".format(srcPath))
        logging.error("[X] Exception : ", exc_info=True)
Esempio n. 9
0
def parseImage(diskPath):

    filenames = pyewf.glob(diskPath)
    ewf_handle = pyewf.handle()
    ewf_handle.open(filenames)

    #call class to parse .EO1 image with pytsk3
    img_Info = ewf_Img_Info(ewf_handle)

    try:
        partitionTable = pytsk3.Volume_Info(img_Info)

    except IOError:
        print "Error!Could not determine partition type ", filenames
        sys.exit(0)

    #find partitions
    for partition in partitionTable:
        print partition.addr, partition.desc, "%s   %s   (%s)" % (
            partition.start, partition.start * 512, partition.len)

        if 'NTFS' in partition.desc:
            fileSystemObject = pytsk3.FS_Info(img_Info,
                                              offset=(partition.start * 512))

            #Extract all files
            directory = fileSystemObject.open_dir(path='/')

            #find all the files of the system
            extraction(directory, [], [])

    ewf_handle.close()
Esempio n. 10
0
def extractFile(imageFile,filenames):


  vhdi_file = pyvhdi.file()
  vhdi_file.open(imageFile)
  img_info = vhdi_Img_Info(vhdi_file)
  partitionTable = pytsk3.Volume_Info(img_info)
  for partition in partitionTable:
    print partition.addr, partition.desc, "%ss(%s)" % (partition.start, partition.start * 512), partition.len
    # try:
    if 'NTFS' in partition.desc:
      filesystemObject = pytsk3.FS_Info(img_info, offset=(partition.start*512))
    # except:
    #         print "Partition has no supported file system"
    #         continue
      print "File System Type Dectected ",filesystemObject.info.ftype
      directoryObject = filesystemObject.open_dir(path=dirPath)
      print "Directory:",dirPath
    outputPath = 'ex_differ_file-test2'

  for filename in filenames:
    if not os.path.exists(outputPath):
      os.makedirs(outputPath)
    if not os.path.isdir(str(filename)):
      try:
        ex_path = ('%s/%s' % (outputPath, os.path.basename(str(filename)))).replace('//','/') 

        extractFile = open(ex_path,'w')

        fileobject = filesystemObject.open(str(filename))
        filedata = fileobject.read_random(0,fileobject.info.meta.size)
        extractFile.write(filedata)
        extractFile.close
      except IOError:
        print('cannot open', str(filename))
Esempio n. 11
0
    def process(self, descriptor, sender_id):
        start = time.time()
        case = json.loads(descriptor.value)

        print 'Processing slice %s' % case['slicenum']
        try:
            img = pytsk3.Img_Info(case['device'])
            fs = pytsk3.FS_Info(img)
            directory = fs.open_dir(path='/')
            self.results = []
            self.list_directory(directory, [], [])

            outfilename = '%s_ads.csv' % case['slicenum']
            out_file = os.path.join(case['casedir'], 'filesystem', outfilename)
            file(out_file, 'w').write('\n'.join(self.results))

            case['ads_results'] = out_file
            desc = Descriptor(outfilename,
                              'ads_results',
                              json.dumps(case),
                              descriptor.domain,
                              agent=self._name_,
                              processing_time=(time.time() - start))
            self.push(desc)
        except:
            print traceback.format_exc()
Esempio n. 12
0
def main(image, img_type, offset):
    try:
        print("[+] Opening {}".format(image))
        if img_type == "ewf":
            print("jammer")
        else:
            img_info = pytsk3.Img_Info(image)

        # Get Filesystem Handle
        try:
            fs = pytsk3.FS_Info(img_info, offset)
        except IOError:
            _, e, _ = sys.exc_info()
            print("[-] Unable to open FS:\n {}".format(e))
            exit()

        root_dir = fs.open_dir(path="/")
        table = [["Name", "Type", "Size", "Create Date", "Modify Date"]]
        for f in root_dir:
            name = f.info.name.name
            if f.info.meta.type == pytsk3.TSK_FS_META_TYPE_DIR:
                f_type = "DIR"
            else:
                f_type = "FILE"
            size = f.info.meta.size
            create = f.info.meta.crtime
            modify = f.info.meta.mtime
            table.append([name, f_type, size, create, modify])
        print(tabulate(table, headers="firstrow"))
    except IOError:
        print("No such file1")
Esempio n. 13
0
def exportHIVE(vol):
    if os.path.isdir('./export') == False:
        os.mkdir('./export')

    img = pytsk3.Img_Info('\\\\.\\' + vol)
    fs_info = pytsk3.FS_Info(img)

    userprofile = os.path.expandvars("%userprofile%")

    ntuser_ = cvtPath(userprofile + "\\NTUSER.DAT")
    usrclass_ = cvtPath(userprofile +
                        "\\AppData\\Local\\Microsoft\\Windows\\UsrClass.dat")
    exportList = []
    exportList.append(ntuser_)
    exportList.append(usrclass_)

    for p in exportList:
        f = fs_info.open(p)
        name = f.info.name.name.decode('utf-8')
        offset = 0
        if f.info.meta == None:
            continue
        size = f.info.meta.size
        BUFF_SIZE = 1024 * 1024
        data = open('./export/' + name, 'wb')
        while offset < size:
            av_to_read = min(BUFF_SIZE, size - offset)
            d = f.read_random(offset, av_to_read)
            if not d: break
            data.write(d)
            offset += len(d)

    print "\nExport Completed\n"
Esempio n. 14
0
def Main():

    args_parser = argparse.ArgumentParser(description=("Lists a file system in a storage media image or device."))
    args_parser.add_argument("images", nargs="+", metavar="IMAGE", action="store", type=str, default=None, help=("Storage media images or devices."))
    options = args_parser.parse_args()


    img = pytsk3.Img_Info(options.images)
    ## Step 2: Open the filesystem
    fs = pytsk3.FS_Info(img)
    ## Step 3: Open the file using the inode
    f = fs.open_meta(inode = 0)

    ## Step 4: Read all the data and print to stdout
    offset = 0
    size = f.info.meta.size

    file_name= "$MFT"
    output_path="./"


    file_2 = open(output_path + file_name,"w")
    while offset < size:
        available_to_read = min(BUFF_SIZE, size - offset)
        data = f.read_random(offset, available_to_read,1)
        if not data: break
        offset += len(data)
        file_2.write(data)
    file_2.close()    
Esempio n. 15
0
    def acquire_files(self, filepath, current, backup):

        # get the image type (raw, encase, split)
        img = self.get_img_info(filepath)

        offsets = self.get_offsets(img)

        # this needs to be expanded if we support dual boot disk images
        # insert the file and the kept the id around
        self.cursor.execute(
            "insert into evidence_sources (filename) values (?)", [filepath])
        self.evidence_id = self.cursor.execute(
            "SELECT last_insert_rowid()").fetchone()[0]

        for (part_num, offset) in offsets:

            self.partition_id = self.new_partition(part_num, offset)

            # FS_INFO
            try:
                fs = pytsk3.FS_Info(img, offset)
            except Exception, e:
                print "FS_Info: unable to get offset %d from filepath %s error: %s" % (
                    offset, filepath, str(e))
                continue

            self.refreshgui()

            if current:
                self.acquire_active_files(fs)

            if backup:
                self.acquire_backup_files(fs)

            self.conn.commit()
Esempio n. 16
0
def main(imgs):
    global FLIST

    fout = open("report.csv",'w')
    fout.write("File Name,MD5 Sum,Meta Data,...,Exif Data,...\n")
    rec = create_dir("./recovered/")
    (con, cur) = open_db()

    for i in imgs:
        if os.path.exists(i):
            print "Processing file - %s" % i
            print "MD5 sum - %s" % hashlib.md5(open(i,'rb').read()).hexdigest()

            img = pytsk3.Img_Info(i)
            fs  = pytsk3.FS_Info(img)
            fs_walk('/', fs)

            for (fname, md5, meta) in FLIST:

                # Write file information out to report.csv
                fout.write(fname+","+md5+","+meta+'\n')

                # Enter file informatino into DB
                cur.execute('''INSERT INTO recovered VALUES (NULL, ?, ?, ?)''', (unicode(fname, errors='replace'), md5, meta))
                con.commit()
            FLIST = [] # Clear the global files listing.

        else:
            print "Unable to find %s" % i
    print "###################################################################"
    print "Completed processing images.  Recovered files saved in ./recovered/"
    print "\tReport written out to report.csv and recovered.db"
    print "###################################################################"
    con.close()
    fout.close()
Esempio n. 17
0
    def __init__(self, address_space, session=None):
        self.session = session
        self.block_size = 512

        # The address space of the entire disk.
        self.address_space = address_space
        self._img_info = AS_Img_Info(address_space)
        try:
            # open as disk image
            tsk_vs = pytsk3.Volume_Info(self._img_info)
            self.volume_system = VolumeSystem(self,
                                              tsk_vs,
                                              session=self.session)
            self.block_size = tsk_vs.info.block_size
            self.partitions = self.volume_system.partitions
        except IOError:
            # open as partition image
            self.volume_system = obj.NoneObject("No Volume")
            self.partitions = []
            try:
                fake_partition = Partition(self,
                                           filesystem=FS(
                                               pytsk3.FS_Info(self._img_info)),
                                           session=self.session)
                self.partitions.append(fake_partition)
            except IOError:
                pass
Esempio n. 18
0
 def __init__(self, volume):
     try:
         self.volume='\\\\.\\'+str(volume)
         self.img=pytsk3.Img_Info(self.volume)
         self.fs=pytsk3.FS_Info(self.img)
     except:
         return "none"
Esempio n. 19
0
def offset_recog():
    partition_offset_list = []


    ewf_handle = pyewf.handle()

    filenames = pyewf.glob("image_sd_pi.E01")

    ewf_handle.open(filenames)

    imagehandle = ewf_Img_Info(ewf_handle)

    partitionTable = pytsk3.Volume_Info(imagehandle)

    for partition in partitionTable:
        print(partition.addr, partition.desc, "%ss(%s)" % (partition.start, partition.start * 512), partition.len)
        partition_offset_list.append(partition.start * 512)


    for x in partition_offset_list:
        print(x)

    filesystemObject = pytsk3.FS_Info(imagehandle, offset=4194304)
    fileobject = filesystemObject.open("/$FAT1")
    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'))
    #outfile = open('DFIRWizard-output', 'w')
    #filedata = fileobject.read_random(0,fileobject.info.meta.size)
    return partition_offset_list
Esempio n. 20
0
 def get_tsk_file_system(self, source_path_spec, configuration):
     file_object = path_spec_resolver.Resolver.OpenFileObject(
         source_path_spec.parent,
         resolver_context=configuration.resolver_context)
     tsk_image_object = tsk_image.TSKFileSystemImage(file_object)
     tsk_file_system = pytsk3.FS_Info(tsk_image_object)
     return tsk_file_system
def get_tsk_inodes(volume, root):
    try:
        # open the extX file system (e.g. /dev/sda1)
        img = pytsk3.Img_Info(volume)
        # FS_Info used as a handle for more detailed file system analysis. Check if file system of volume is of extX
        try:
            fs = pytsk3.FS_Info(img)
        except OSError as e:
            print(e)
            sys.exit(
                "Error: file system of " + volume +
                " is not supported by hidden-inode-detector.py. Only ext2/ext3/ext4 file systems are supported."
            )

        # goes to tsk_walk_path(). root is /
        # first time scan to collect inodes in same (root) dir
        my_inodes, my_inodes_dir = tsk_walk_path(fs=fs, inode=root)
    except (OSError) as e:
        print(e)
        sys.exit("Error: " + volume + " is not a valid mount point")
    # This part tries to go through each dir found the first tsk_walk_path scan, and so on.
    seen = my_inodes_dir.copy()
    active = my_inodes_dir.copy()
    while active:
        next_active = set()
        for current_inode_dir in active:
            test = tsk_walk_path(fs=fs, inode=current_inode_dir)
            for result in test[1]:
                if result not in seen:
                    seen.add(result)
                    next_active.add(result)
        active = next_active

    return my_inodes
Esempio n. 22
0
    def extract_a_file(self, img_path, name, inode):
        ## Now open and read the file specified
        ## Step 1: get an IMG_INFO object (url can be any URL that AFF4 can handle)
        img = pytsk3.Img_Info(img_path)
        ## Step 2: Open the filesystem
        fs = pytsk3.FS_Info(img, offset=self._offset)
        ## Step 3: Open the file using the inode
        f = fs.open_meta(inode=inode)

        ## Step 4: Read all the data and print to stdout
        offset = 0
        size = f.info.meta.size

        if type(name) is None:
            file_name = str(inode)
        else:
            file_name = name

        entry_info = []
        #print(file_name)
        for i in f:
            if (i.info.type == pytsk3.TSK_FS_ATTR_TYPE_NTFS_DATA):
                #print(i.info.name)
                #print(i.info.size)
                if i.info.name is None:
                    entry_info.append([file_name, i.info.size])
        for entry in entry_info:
            file_2 = open(self._output_path + entry[0], "wb")
            while offset < entry[1]:
                available_to_read = min(BUFF_SIZE, entry[1] - offset)
                data = f.read_random(offset, available_to_read, 1)
                if not data: break
                offset += len(data)
                file_2.write(data)
            file_2.close()
Esempio n. 23
0
    def _Open(self, path_spec, mode='rb'):
        """Opens the file system object defined by path specification.

    Args:
      path_spec (PathSpec): path specification.
      mode (Optional[str]): file access mode.

    Raises:
      AccessError: if the access to open the file was denied.
      IOError: if the file system object could not be opened.
      PathSpecError: if the path specification is incorrect.
      ValueError: if the path specification is invalid.
    """
        if not path_spec.HasParent():
            raise errors.PathSpecError(
                'Unsupported path specification without parent.')

        file_object = resolver.Resolver.OpenFileObject(
            path_spec.parent, resolver_context=self._resolver_context)

        try:
            tsk_image_object = tsk_image.TSKFileSystemImage(file_object)
            tsk_file_system = pytsk3.FS_Info(tsk_image_object)
        except:
            file_object.close()
            raise

        self._file_object = file_object
        self._tsk_file_system = tsk_file_system
Esempio n. 24
0
def main(image, img_type, offset):
    print("[+] Opening {}".format(image))
    if img_type == "ewf":
        try:
            filenames = pyewf.glob(image)
        except IOError:
            _, e, _ = sys.exc_info()
            print("[-] Invalid EWF format:\n {}".format(e))
            sys.exit(2)
        ewf_handle = pyewf.handle()
        ewf_handle.open(filenames)
        # Open PYTSK3 handle on EWF Image
        img_info = EWFImgInfo(ewf_handle)
    else:
        img_info = pytsk3.Img_Info(image)
    # Get Filesystem Handle
    try:
        fs = pytsk3.FS_Info(img_info, offset)
    except IOError:
        _, e, _ = sys.exc_info()
        print("[-] Unable to open FS:\n {}".format(e))
        exit()
    root_dir = fs.open_dir(path="/")
    table = [["Name", "Type", "Size", "Create Date", "Modify Date"]]
    for f in root_dir:
        name = f.info.name.name
    if f.info.meta.type == pytsk3.TSK_FS_META_TYPE_DIR:
        f_type = "DIR"
    else:
        f_type = "FILE"
        size = f.info.meta.size
        create = f.info.meta.crtime
        modify = f.info.meta.mtime
        table.append([name, f_type, size, create, modify])
    print(tabulate(table, headers="firstrow"))
Esempio n. 25
0
    def GetVolumes(self, phyDrive="\\\\.\\PhysicalDrive0"):
        list_fs_info = []  # contain the file system object
        block_size = 512  # by default block size is 512

        try:
            img = pytsk3.Img_Info(phyDrive)  # open the physical drive
            volume = pytsk3.Volume_Info(img)  # get volume information
        except OSError as e:
            if "file not found" in str(e):
                raise Exception("PHYSICAL_DRIVE_NOT_FOUND")
            else:
                raise Exception(str(e))

        # for each volume in the drive, check if it is NTFS and open object to handle it
        for part in volume:
            try:
                self.logging(
                    "INFO",
                    "Check partition: desc{0:s}, offset{1:d}, size:{2:d}".
                    format(part.desc.decode('utf-8'), part.start, part.len))
                fs_info = pytsk3.FS_Info(img, offset=part.start * block_size)
                # check if file system is NTFS
                if fs_info.info.ftype in [
                        pytsk3.TSK_FS_TYPE_NTFS, pytsk3.TSK_FS_TYPE_NTFS_DETECT
                ]:
                    list_fs_info.append(fs_info)

            except Exception as e:
                pass

        return list_fs_info
Esempio n. 26
0
  def _Open(self, path_spec=None, mode='rb'):
    """Opens the file system object defined by path specification.

    Args:
      path_spec: optional path specification (instance of path.PathSpec).
                 The default is None.
      mode: optional file access mode. The default is 'rb' read-only binary.

    Raises:
      AccessError: if the access to open the file was denied.
      IOError: if the file system object could not be opened.
      PathSpecError: if the path specification is incorrect.
      ValueError: if the path specification is invalid.
    """
    if not path_spec.HasParent():
      raise errors.PathSpecError(
          u'Unsupported path specification without parent.')

    file_object = resolver.Resolver.OpenFileObject(
        path_spec.parent, resolver_context=self._resolver_context)

    tsk_image_object = tsk_image.TSKFileSystemImage(file_object)
    tsk_file_system = pytsk3.FS_Info(tsk_image_object)

    self._file_object = file_object
    self._tsk_file_system = tsk_file_system
Esempio n. 27
0
    def _update_file_system(self, sector, sector_count, data):

        # update the shadow image
        self.IMG.write(sector, sector_count, data)

        # Reload our filesystem to wipe away caches
        self.FILE_SYSTEM = pytsk3.FS_Info(self.IMG, self.OFFSET_BYTES,
                                          pytsk3.TSK_FS_TYPE_DETECT)
Esempio n. 28
0
def IsHFSPartition(img, partition_start_offset):
    '''Determines if the partition is HFS by mounting it'''
    try:
        fs = pytsk3.FS_Info(img, offset=partition_start_offset)
        fs_info = fs.info  # TSK_FS_INFO
        return fs_info.ftype == pytsk3.TSK_FS_TYPE_HFS_DETECT
    except Exception as ex:
        log.exception("Exception")
    return False
Esempio n. 29
0
    def process(self, descriptor, sender_id):
        start = time.time()
        case = json.loads(descriptor.value)

        print 'Processing %s' % case['file_list']
        img = pytsk3.Img_Info(case['device'])
        fs = pytsk3.FS_Info(img)
        if not os.path.exists(case['file_list']['out_dir']):
            os.makedirs(case['file_list']['out_dir'])
 def open_FS(self):
     # Open FS and Recurse
     if self.vol is not None:
         for partition in self.vol:
             if partition.len > 2048 and "Unallocated" not in partition.desc and "Extended" not in partition.desc and "Primary Table" not in partition.desc:
                 try:
                     self.fs.append(pytsk3.FS_Info(
                         self.image_handle,
                         offset=partition.start * self.vol.info.block_size))
                 except IOError:
                     _, e, _ = sys.exc_info()
                     sys.stderr.write("[-] Unable to open FS:\n {}\n".format(e))
     else:
         try:
             self.fs.append(pytsk3.FS_Info(self.image_handle))
         except IOError:
             _, e, _ = sys.exc_info()
             sys.stderr.write("[-] Unable to open FS:\n {}\n".format(e))