Exemplo n.º 1
0
def EnumerateFilesystemsFromClient(args):
  """List all local filesystems mounted on this system."""
  del args  # Unused.
  for fs_struct in client_utils_osx.GetFileSystems():
    yield rdf_client_fs.Filesystem(
        device=fs_struct.f_mntfromname,
        mount_point=fs_struct.f_mntonname,
        type=fs_struct.f_fstypename)

  drive_re = re.compile("r?disk[0-9].*")
  for drive in os.listdir("/dev"):
    if not drive_re.match(drive):
      continue

    path = os.path.join("/dev", drive)
    try:
      img_inf = pytsk3.Img_Info(path)
      # This is a volume or a partition - we send back a TSK device.
      yield rdf_client_fs.Filesystem(device=path)

      vol_inf = pytsk3.Volume_Info(img_inf)

      for volume in vol_inf:
        if volume.flags == pytsk3.TSK_VS_PART_FLAG_ALLOC:
          offset = volume.start * vol_inf.info.block_size
          yield rdf_client_fs.Filesystem(
              device="{path}:{offset}".format(path=path, offset=offset),
              type="partition")

    except (IOError, RuntimeError):
      continue
Exemplo n.º 2
0
    def __init__(self, url):
        # parse out the different volumes

        self.url = url
        self.img = pytsk3.Img_Info(url=self.url)
        self.VOL_INFO = pytsk3.Volume_Info(self.img)

        self.vol_to_se = {}
        self.VOLUMES = []
        self.VOLUME_BOUNDARIES = []

        # print out some info about the disk image
        logger.debug("--- Volume info ---")
        logger.debug("Current: %d" % self.VOL_INFO.current)
        logger.debug("VS Type: %d" % self.VOL_INFO.info.vstype)
        logger.debug("Offset: %d" % self.VOL_INFO.info.offset)
        logger.debug("Block Size: %d" % self.VOL_INFO.info.block_size)
        logger.debug("Endian: %d" % self.VOL_INFO.info.endian)
        logger.debug("Partition List: %s" % self.VOL_INFO.info.part_list)
        logger.debug("Parition Count: %d" % self.VOL_INFO.info.part_count)
        logger.debug("--- Volume info ---")

        # Add each volume
        for vol in self.VOL_INFO:
            #print part.addr, part.desc, part.start, part.len
            self.add_volume(vol)
Exemplo n.º 3
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"
Exemplo n.º 4
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")
    def iterate_image(self, image, img_type, output, part_type):
        volume = None
        print("[+] Opening {}".format(image))
        if img_type == "ewf":
            try:
                #image = image.split('/')
                #image = image[len(image) - 1]
                image = image.replace('/', '\\')
                print(image)
                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)
            print(filenames)
            # Open PYTSK3 handle on EWF Image
            img_info = EWFImgInfo(ewf_handle)
        else:
            img_info = pytsk3.Img_Info(image)
            print(img_info)

        try:
            if part_type is not None:
                attr_id = getattr(pytsk3, "TSK_VS_TYPE_" + part_type)
                volume = pytsk3.Volume_Info(img_info, attr_id)
                print(volume)
            else:
                volume = pytsk3.Volume_Info(img_info)
                print(volume)
        except IOError:
            _, e, _ = sys.exc_info()
            print("[-] Unable to read partition table:\n {}".format(e))
        image_stored_list.open_fs(self, volume, img_info, output)
Exemplo n.º 6
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 ''
Exemplo n.º 7
0
 def __init__(self, file, hash_val):
     self.__file = file
     self.img = pytsk3.Img_Info(self.__file)
     self.__partition_list = list()
     self.__vol = pytsk3.Volume_Info(self.img)
     self.__hash_val = [hash_val]
     self.__cal_hash()
Exemplo n.º 8
0
def initialise_block_db(image_path, image_hash, case):
    """Creates a new image database.

  Args:
    image_path: Path to image file
    image_hash: MD5 of the image
    case: Case ID

  Returns:
    Boolean value to indicate whether the image has already been processed
  """
    img = pytsk3.Img_Info(image_path)

    block_db = PostgresqlDataStore(autocommit=True)
    image_exists = check_tracking_database(block_db, image_path, image_hash,
                                           case)

    if not image_exists:
        db_name = ''.join(('fs', image_hash))
        block_db.execute('CREATE DATABASE {0:s}'.format(db_name))

        block_db.switch_database(db_name=db_name)

        populate_block_db(img, block_db, batch_size=1500)

    return image_exists
Exemplo n.º 9
0
def main(image, img_type, hashes, part_type=None, pbar_total=0):
    hash_list, hash_type = read_hashes(hashes)
    volume = None
    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)
        try:
            if part_type is not None:
                attr_id = getattr(pytsk3, "TSK_VS_TYPE_" + part_type)
                volume = pytsk3.Volume_Info(img_info, attr_id)
            else:
                volume = pytsk3.Volume_Info(img_info)
        except IOError:
            _, e, _ = sys.exc_info()
            print("[-] Unable to read partition table:\n {}".format(e))
            open_fs(volume, img_info, hash_list, hash_type, pbar_total)
Exemplo n.º 10
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()    
Exemplo n.º 11
0
    def open_vol(self):
        sys.stderr.write("[+] Opening {}\n".format(self.evidence))
        # Handle EWF/Raw Images
        if self.image_type == "ewf":
            try:
                filenames = pyewf.glob(self.evidence)
            except IOError:
                _, e, _ = sys.exc_info()
                sys.stderr.write("[-] Invalid EWF format:\n {}\n".format(e))
                raise IOError

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

            # Open PYTSK3 handle on EWF Image
            self.image_handle = EWFImgInfo(ewf_handle)
        else:
            self.image_handle = pytsk3.Img_Info(self.evidence)

        # Open volume from image
        try:
            self.vol = pytsk3.Volume_Info(self.image_handle)
        except IOError:
            _, e, _ = sys.exc_info()
            sys.stderr.write("[-] Unable to read partition table. Possible logical image:\n {}\n".format(e))
Exemplo n.º 12
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"))
Exemplo n.º 13
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()
Exemplo n.º 14
0
def main():
    args = parser.parse_args()
    image = args.image
    partition_starts = []

    # Check if the user provided image format is ewf. If so, use the libewf developer's provided class to extend
    # the capabilities of pytsk3 to include the ewf format. If the image format is not ewf then pytsk3 can handle the image natively.
    try:
        if args.format == "ewf":
            files = pyewf.glob(args.image)
            ewf_handle = pyewf.handle()
            ewf_handle.open(files)
            image_handle = ewf_Img_Info(ewf_handle)
        else:
            image_handle = pytsk3.Img_Info(url=image)

        # Once a handle to the image has been established print all of the detected partitions to the user and allow them to pick the partition of
        # interest to be scanned.
        print "Which partition should be scanned?"

        volume = pytsk3.Volume_Info(image_handle)
        for partition in volume:
            print partition.addr, partition.desc, "%s(%s)" % (
                partition.start, partition.start * 512), partition.len
            partition_starts.append(int(partition.start))

    except IOError, error:
        print error
Exemplo n.º 15
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
Exemplo n.º 16
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"
Exemplo n.º 17
0
Arquivo: osx.py Projeto: tanner-g/grr
    def Run(self, unused_args):
        """List all local filesystems mounted on this system."""
        for fs_struct in client_utils_osx.GetFileSystems():
            self.SendReply(
                rdf_client.Filesystem(device=fs_struct.f_mntfromname,
                                      mount_point=fs_struct.f_mntonname,
                                      type=fs_struct.f_fstypename))

        drive_re = re.compile("r?disk[0-9].*")
        for drive in os.listdir("/dev"):
            if not drive_re.match(drive):
                continue

            path = os.path.join("/dev", drive)
            try:
                img_inf = pytsk3.Img_Info(path)
                # This is a volume or a partition - we send back a TSK device.
                self.SendReply(rdf_client.Filesystem(device=path))

                vol_inf = pytsk3.Volume_Info(img_inf)

                for volume in vol_inf:
                    if volume.flags == pytsk3.TSK_VS_PART_FLAG_ALLOC:
                        offset = volume.start * vol_inf.info.block_size
                        self.SendReply(
                            rdf_client.Filesystem(device=path + ":" +
                                                  str(offset),
                                                  type="partition"))

            except (IOError, RuntimeError):
                continue
def image_read(image, img_type, part_type):
    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)
        e01_metadata(ewf_handle)
        # Open PYTSK3 handle on EWF Image
        img_info = EWFImgInfo(ewf_handle)
    else:
        img_info = pytsk3.Img_Info(image)

    try:
        if part_type is not None:
            attr_id = getattr(pytsk3, "TSK_VS_TYPE_" + part_type)
            volume = pytsk3.Volume_Info(img_info, attr_id)
        else:
            volume = pytsk3.Volume_Info(img_info)
    except IOError:
        _, e, _ = sys.exc_info()
        print("[-] Unable to read partition table:\n {}".format(e))
        sys.exit(3)
    part_metadata(volume)
Exemplo n.º 19
0
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
Exemplo n.º 20
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()
Exemplo n.º 21
0
    def __init__(self, url):
        # parse out the different volumes
        logger.info("Initializing Semantic Engine")
        self.url = url
        self.img = pytsk3.Img_Info(url=self.url)
        self.VOL_INFO = pytsk3.Volume_Info(self.img)

        self.vol_to_se = {}
        self.VOLUMES = []
        self.VOLUME_BOUNDARIES = []

        # print out some info about the disk image
        '''
        print("--- Volume info ---")
        print("Current: %d" % self.VOL_INFO.current)
        print("VS Type: %d" % self.VOL_INFO.info.vstype)
        print("Offset: %d" % self.VOL_INFO.info.offset)
        print("Block Size: %d" % self.VOL_INFO.info.block_size)
        print("Endian: %d" % self.VOL_INFO.info.endian)
        print("Partition List: %s" % self.VOL_INFO.info.part_list)
        print("Parition Count: %d" % self.VOL_INFO.info.part_count)
        print("--- Volume info ---")
        '''
        # Add each volume
        for vol in self.VOL_INFO:
            self.add_volume(vol)
Exemplo n.º 22
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)
Exemplo n.º 23
0
    def _find_volumes(self, volume_system, vstype='detect'):
        """Finds all volumes based on the pytsk3 library."""

        try:
            # noinspection PyUnresolvedReferences
            import pytsk3
        except ImportError:
            logger.error("pytsk3 not installed, could not detect volumes")
            raise ModuleNotFoundError("pytsk3")

        baseimage = None
        try:
            # ewf raw image is now available on base mountpoint
            # either as ewf1 file or as .dd file
            raw_path = volume_system.parent.get_raw_path()
            # noinspection PyBroadException
            try:
                baseimage = pytsk3.Img_Info(raw_path)
            except Exception:
                logger.error(
                    "Failed retrieving image info (possible empty image).",
                    exc_info=True)
                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
Exemplo n.º 24
0
def main(image,
         img_type,
         offset,
         hashListFile,
         evidence_Dir,
         part_Type,
         pbar_total=0):
    matched_Hash_Files = {}
    hash_List, type_of_Hash = get_Hash_Type(hashListFile)
    volume = None
    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)

    # The above code is taken from the "Combining pyewf with pytsk3" section of
    # the python development page for pyewf

    try:
        if part_Type is not None:
            attr_ID = getattr(pytsk3, "TSK_VS_TYPE_" + part_Type)
            volume = pytsk3.Volume_Info(img_info, attr_ID)
        else:
            volume = pytsk3.Volume_Info(img_info)
    except IOError:
        _, e, _ = sys.exc_info()
        print("[-] Unable to read partition table:\n {}".format(e))
        exit()

    finished_fileDict = open_FS(volume, img_info, hash_List, type_of_Hash,
                                matched_Hash_Files, evidence_Dir, pbar_total)

    for hash_Value in hash_List:
        if hash_Value in finished_fileDict:
            print("value for %r in finished_fileDict: %r" %
                  (hash_Value, finished_fileDict[hash_Value]))
        else:
            continue

    finished_evidenceDict = os_Hash_Check(evidence_Dir, hash_List,
                                          type_of_Hash)

    for hash_Value in hash_List:
        if hash_Value in finished_fileDict:
            print("value for %r in finished_evidenceDict: %r" %
                  (hash_Value, finished_evidenceDict[hash_Value]))
        else:
            continue
Exemplo n.º 25
0
def main(imgpath):
    img = pytsk3.Img_Info(imgpath)
    vol = pytsk3.Volume_Info(img)
    bs = vol.info.block_size
    for part in vol:
        try:
            mount(imgpath, part, bs)
        except Exception as e:
            print(e)
Exemplo n.º 26
0
def main(imgs):

    for i in imgs:
        if os.path.exists(i):
            img = pytsk3.Img_Info(i)
            fs = pytsk3.FS_Info(img)
            fs_walk("/", fs)

        else:
            print "Unable to find %s" % i
Exemplo n.º 27
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))
def parse_logical(options):
    tsk_img = pytsk3.Img_Info(
        options.source
    )
    processor = VolumeProcessor(
        tsk_img, description=options.source,
        temp_location=options.temp_dir,
        output_template=options.output_template,
        dump_db=options.dump_db
    )
    processor.process()
Exemplo n.º 29
0
    def get_partitions(self):
        partitions = []

        with open(self.file_path) as imageFile:
            image_handle = pytsk3.Img_Info(imageFile.name)

        partition_table = pytsk3.Volume_Info(image_handle)

        for partition in partition_table:
            #print partition.addr, partition.desc, "%ss(%s)" % (partition.start, partition.start * 512), partition.len
            partitions.add(Partition(partition.addr, partition.desc, partition.start, partition.len))
Exemplo n.º 30
0
def SelectImage(img_type, files):
    if img_type == "raw":
        if len(files) == 1:
            # For a single file this is faster.
            return pytsk3.Img_Info(files[0])
        else:
            return SplitImage(*files)

    elif img_type == "ewf":
        # Instantiate our special image object
        return EWFImgInfo(*files)