Exemple #1
0
  def consume(self, doc, payload):
    """
    Open file pointer as using libewf and pass to strings. See
    ``gransk.plugins.extractors.strings``.

    :param doc: Document object.
    :param payload: File pointer beloning to document.
    :type doc: ``gransk.core.document.Document``
    :type payload: ``file``
    """
    payload.seek(0)
    ewf_handle = pyewf.handle()
    ewf_handle.open_file_objects([payload], "rb")

    for key, value in ewf_handle.get_header_values().items():
      doc.meta[key] = value

    self.buffer_size = ewf_handle.chunk_size

    try:
      super(Subscriber, self).consume(doc, ewf_handle)
    except Exception as err:
      doc.meta['ewf_strings_err'] = six.text_type(err)
      print (err)

    ewf_handle.close()
    payload.seek(0)
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)
Exemple #3
0
    def test___init__discover_parameter_true(self):
        """
        Should initialize member _fs_discoverd with True and call _initialize_partitions.
        :return:
        """
        import pyewf
        from source.ewfimage import EWFImage, EWFImageInfo

        expected_fs_discovered: bool = True
        expected_image_info: EWFImageInfo = EWFImageInfo(
            ewf_handle=pyewf.handle())
        init_mock = MagicMock(return_value=None)
        with patch('source.ewfimage.EWFImage._get_image_information',
                   MagicMock(return_value=expected_image_info)):
            with patch('source.ewfimage.EWFImage._initialize_partitions',
                       init_mock):
                actual_ewf_image = EWFImage(parent=None,
                                            parameters={
                                                'filepath': 'test.e01',
                                                'discover': False
                                            })

        self.assertEqual(expected_fs_discovered,
                         actual_ewf_image._fs_discoverd)
        init_mock.assert_called_once()
Exemple #4
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
Exemple #5
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"))
Exemple #6
0
def mount(iFile):
    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()

    if iFile.lower().endswith(".e01"):
        filenames = pyewf.glob(iFile)
        ewf_handle = pyewf.handle()
        ewf_handle.open(filenames)
        imagehandle = ewf_Img_Info(ewf_handle)

        partitionTable = pytsk3.Volume_Info(imagehandle)

    else:
        imagehandle = pytsk3.Img_Info(iFile)
        partitionTable = pytsk3.Volume_Info(imagehandle)

    return partitionTable, imagehandle
    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))
Exemple #8
0
  def test_read_buffer_at_offset(self):
    """Tests the read_buffer_at_offset function."""
    if not unittest.source:
      return

    ewf_handle = pyewf.handle()

    ewf_handle.open(unittest.source)

    file_size = ewf_handle.get_size()

    # Test normal read.
    data = ewf_handle.read_buffer_at_offset(4096, 0)

    self.assertIsNotNone(data)
    self.assertEqual(len(data), min(file_size, 4096))

    # Test read beyond file size.
    if file_size > 16:
      data = ewf_handle.read_buffer_at_offset(4096, file_size - 16)

      self.assertIsNotNone(data)
      self.assertEqual(len(data), 16)

    with self.assertRaises(ValueError):
      ewf_handle.read_buffer_at_offset(-1, 0)

    with self.assertRaises(ValueError):
      ewf_handle.read_buffer_at_offset(4096, -1)

    ewf_handle.close()

    # Test the read without open.
    with self.assertRaises(IOError):
      ewf_handle.read_buffer_at_offset(4096, 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()
    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)
    def test_open_close(self):
        """Tests the open and close functions."""
        if not unittest.source:
            return

        filenames = pyewf.glob(unittest.source)

        ewf_handle = pyewf.handle()

        # Test open and close.
        ewf_handle.open(filenames)
        ewf_handle.close()

        # Test open and close a second time to validate clean up on close.
        ewf_handle.open(filenames)
        ewf_handle.close()

        if os.path.isfile(unittest.source):
            with open(unittest.source, "rb") as file_object:

                # Test open_file_objects and close.
                ewf_handle.open_file_objects([file_object])
                ewf_handle.close()

                # Test open_file_objects and close a second time to validate clean up on close.
                ewf_handle.open_file_objects([file_object])
                ewf_handle.close()

                # Test open_file_objects and close and dereferencing file_object.
                ewf_handle.open_file_objects([file_object])
                del file_object
                ewf_handle.close()
    def test_open_file_objects(self):
        """Tests the open_file_objects function."""
        if not unittest.source:
            raise unittest.SkipTest("missing source")

        if not os.path.isfile(unittest.source):
            raise unittest.SkipTest("source not a regular file")

        filenames = pyewf.glob(unittest.source)
        file_objects = [open(filename, "rb") for filename in filenames]

        ewf_handle = pyewf.handle()

        ewf_handle.open_file_objects(file_objects)

        # TODO: change IOError into IOError
        with self.assertRaises(MemoryError):
            ewf_handle.open_file_objects(file_objects)

        ewf_handle.close()

        with self.assertRaises(TypeError):
            ewf_handle.open_file_objects(None)

        for file_object in file_objects:
            file_object.close()
Exemple #13
0
  def test_open_close(self):
    """Tests the open and close functions."""
    if not unittest.source:
      return

    ewf_handle = pyewf.handle()

    # Test open and close.
    ewf_handle.open(unittest.source)
    ewf_handle.close()

    # Test open and close a second time to validate clean up on close.
    ewf_handle.open(unittest.source)
    ewf_handle.close()

    file_object = open(unittest.source, "rb")

    # Test open_file_object and close.
    ewf_handle.open_file_object(file_object)
    ewf_handle.close()

    # Test open_file_object and close a second time to validate clean up on close.
    ewf_handle.open_file_object(file_object)
    ewf_handle.close()

    # Test open_file_object and close and dereferencing file_object.
    ewf_handle.open_file_object(file_object)
    del file_object
    ewf_handle.close()
Exemple #14
0
    def test_close(self):
        """Tests the close function."""
        test_source = unittest.source
        if not test_source:
            raise unittest.SkipTest("missing source")

        ewf_handle = pyewf.handle()
Exemple #15
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)
    def test_seek_offset(self):
        """Tests the seek_offset function."""
        if not unittest.source:
            raise unittest.SkipTest("missing source")

        filenames = pyewf.glob(unittest.source)

        ewf_handle = pyewf.handle()

        ewf_handle.open(filenames)

        media_size = ewf_handle.get_media_size()

        ewf_handle.seek_offset(16, os.SEEK_SET)

        offset = ewf_handle.get_offset()
        self.assertEqual(offset, 16)

        ewf_handle.seek_offset(16, os.SEEK_CUR)

        offset = ewf_handle.get_offset()
        self.assertEqual(offset, 32)

        ewf_handle.seek_offset(-16, os.SEEK_CUR)

        offset = ewf_handle.get_offset()
        self.assertEqual(offset, 16)

        if media_size > 16:
            ewf_handle.seek_offset(-16, os.SEEK_END)

            offset = ewf_handle.get_offset()
            self.assertEqual(offset, media_size - 16)

        ewf_handle.seek_offset(16, os.SEEK_END)

        offset = ewf_handle.get_offset()
        self.assertEqual(offset, media_size + 16)

        # TODO: change IOError into ValueError
        with self.assertRaises(IOError):
            ewf_handle.seek_offset(-1, os.SEEK_SET)

        # TODO: change IOError into ValueError
        with self.assertRaises(IOError):
            ewf_handle.seek_offset(-32 - media_size, os.SEEK_CUR)

        # TODO: change IOError into ValueError
        with self.assertRaises(IOError):
            ewf_handle.seek_offset(-32 - media_size, os.SEEK_END)

        # TODO: change IOError into ValueError
        with self.assertRaises(IOError):
            ewf_handle.seek_offset(0, -1)

        ewf_handle.close()

        # Test the seek without open.
        with self.assertRaises(IOError):
            ewf_handle.seek_offset(16, os.SEEK_SET)
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
Exemple #18
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()
def pyewf_test_multi_open_close_file(filename, mode):
  print(
      "Testing multi open close of: {0:s} with access: {1:s}\t".format(
          filename, get_mode_string(mode)), end="")

  result = True
  error_string = None
  try:
    filenames = pyewf.glob(filename)
    ewf_handle = pyewf.handle()

    ewf_handle.open(filenames, mode)
    ewf_handle.close()
    ewf_handle.open(filenames, mode)
    ewf_handle.close()

  except Exception as exception:
    error_string = str(exception)
    result = False

  if not result:
    print("(FAIL)")
  else:
    print("(PASS)")

  if error_string:
    print(error_string)
  return result
def image_handle(imageFile, sha1Hash):
  if (args.imagetype == "e01"):
    filenames = pyewf.glob(imageFile)
    ewf_handle = pyewf.handle()
    ewf_handle.open(filenames)
    imagehandle = ewf_Img_Info(ewf_handle)
  elif (args.imagetype == "raw"):
      print "Raw Type"
      imagehandle = pytsk3.Img_Info(url=imageFile)

  partitionTable = pytsk3.Volume_Info(imagehandle)

  for partition in partitionTable:
    print partition.addr, partition.desc, "%ss(%s)" % (partition.start, partition.start * 512), partition.len
    try:
          filesystemObject = pytsk3.FS_Info(imagehandle, 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

    dic = directoryRecurse(filesystemObject, directoryObject,[], sha1Hash)

  return dic
def pyewf_test_multi_open_close_file_objects(filename, mode):
  print(
      ("Testing multi open close of file-like object of: {0:s} "
       "with access: {1:s}\t").format(filename, get_mode_string(mode)), end="")

  result = True
  error_string = None
  try:
    filenames = pyewf.glob(filename)
    file_objects = []
    for filename in filenames:
      file_object = open(filename, "rb")
      file_objects.append(file_object)

    ewf_handle = pyewf.handle()

    ewf_handle.open_file_objects(file_objects, mode)
    ewf_handle.close()
    ewf_handle.open_file_objects(file_objects, mode)
    ewf_handle.close()

  except Exception as exception:
    error_string = str(exception)
    result = False

  if not result:
    print("(FAIL)")
  else:
    print("(PASS)")

  if error_string:
    print(error_string)
  return result
Exemple #22
0
    def test_open_close(self):
        """Tests the open and close functions."""
        if not unittest.source:
            return

        ewf_handle = pyewf.handle()

        # Test open and close.
        ewf_handle.open(unittest.source)
        ewf_handle.close()

        # Test open and close a second time to validate clean up on close.
        ewf_handle.open(unittest.source)
        ewf_handle.close()

        file_object = open(unittest.source, "rb")

        # Test open_file_object and close.
        ewf_handle.open_file_object(file_object)
        ewf_handle.close()

        # Test open_file_object and close a second time to validate clean up on close.
        ewf_handle.open_file_object(file_object)
        ewf_handle.close()

        # Test open_file_object and close and dereferencing file_object.
        ewf_handle.open_file_object(file_object)
        del file_object
        ewf_handle.close()
Exemple #23
0
    def test_read_buffer_at_offset(self):
        """Tests the read_buffer_at_offset function."""
        if not unittest.source:
            return

        ewf_handle = pyewf.handle()

        ewf_handle.open(unittest.source)

        file_size = ewf_handle.get_size()

        # Test normal read.
        data = ewf_handle.read_buffer_at_offset(4096, 0)

        self.assertIsNotNone(data)
        self.assertEqual(len(data), min(file_size, 4096))

        # Test read beyond file size.
        if file_size > 16:
            data = ewf_handle.read_buffer_at_offset(4096, file_size - 16)

            self.assertIsNotNone(data)
            self.assertEqual(len(data), 16)

        with self.assertRaises(ValueError):
            ewf_handle.read_buffer_at_offset(-1, 0)

        with self.assertRaises(ValueError):
            ewf_handle.read_buffer_at_offset(4096, -1)

        ewf_handle.close()

        # Test the read without open.
        with self.assertRaises(IOError):
            ewf_handle.read_buffer_at_offset(4096, 0)
Exemple #24
0
def bn_getimginfo(image_path):
    logging.debug("bn_getimginfo: Image Info for image %s: ", image_path) 
    filenames = pyewf.glob(image_path)
    ewf_handle = pyewf.handle()
    ewf_handle.open(filenames)

    img = ewf_Img_Info(ewf_handle)
    return img
Exemple #25
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
Exemple #26
0
def pyewf_test_read_file(filename):
  filenames = pyewf.glob(filename)
  ewf_handle = pyewf.handle()

  ewf_handle.open(filenames, "r")
  result = pyewf_test_read(ewf_handle)
  ewf_handle.close()

  return result
Exemple #27
0
    def test_seek_offset(self):
        """Tests the seek_offset function."""
        if not unittest.source:
            return

        ewf_handle = pyewf.handle()

        ewf_handle.open(unittest.source)

        file_size = ewf_handle.get_size()

        ewf_handle.seek_offset(16, os.SEEK_SET)

        offset = ewf_handle.get_offset()
        self.assertEqual(offset, 16)

        ewf_handle.seek_offset(16, os.SEEK_CUR)

        offset = ewf_handle.get_offset()
        self.assertEqual(offset, 32)

        ewf_handle.seek_offset(-16, os.SEEK_CUR)

        offset = ewf_handle.get_offset()
        self.assertEqual(offset, 16)

        ewf_handle.seek_offset(-16, os.SEEK_END)

        offset = ewf_handle.get_offset()
        self.assertEqual(offset, file_size - 16)

        ewf_handle.seek_offset(16, os.SEEK_END)

        offset = ewf_handle.get_offset()
        self.assertEqual(offset, file_size + 16)

        # TODO: change IOError into ValueError
        with self.assertRaises(IOError):
            ewf_handle.seek_offset(-1, os.SEEK_SET)

        # TODO: change IOError into ValueError
        with self.assertRaises(IOError):
            ewf_handle.seek_offset(-32 - file_size, os.SEEK_CUR)

        # TODO: change IOError into ValueError
        with self.assertRaises(IOError):
            ewf_handle.seek_offset(-32 - file_size, os.SEEK_END)

        # TODO: change IOError into ValueError
        with self.assertRaises(IOError):
            ewf_handle.seek_offset(0, -1)

        ewf_handle.close()

        # Test the seek without open.
        with self.assertRaises(IOError):
            ewf_handle.seek_offset(16, os.SEEK_SET)
Exemple #28
0
    def readImageFile(self, imagefile):
        filenames = pyewf.glob(imagefile)
        ewf_handle = pyewf.handle()
        ewf_handle.open(filenames)
        imagehandle = ewf_Img_Info(ewf_handle)

        partitionTable = pytsk3.Volume_Info(imagehandle)

        return partitionTable, imagehandle
Exemple #29
0
  def test_close(self):
    """Tests the close function."""
    if not unittest.source:
      return

    ewf_handle = pyewf.handle()

    with self.assertRaises(IOError):
      ewf_handle.close()
Exemple #30
0
    def test_close(self):
        """Tests the close function."""
        if not unittest.source:
            return

        ewf_handle = pyewf.handle()

        with self.assertRaises(IOError):
            ewf_handle.close()
Exemple #31
0
def pyewf_test_read_file(filename):
    filenames = pyewf.glob(filename)
    ewf_handle = pyewf.handle()

    ewf_handle.open(filenames, "r")
    result = pyewf_test_read(ewf_handle)
    ewf_handle.close()

    return result
Exemple #32
0
  def test_seek_offset(self):
    """Tests the seek_offset function."""
    if not unittest.source:
      return

    ewf_handle = pyewf.handle()

    ewf_handle.open(unittest.source)

    file_size = ewf_handle.get_size()

    ewf_handle.seek_offset(16, os.SEEK_SET)

    offset = ewf_handle.get_offset()
    self.assertEqual(offset, 16)

    ewf_handle.seek_offset(16, os.SEEK_CUR)

    offset = ewf_handle.get_offset()
    self.assertEqual(offset, 32)

    ewf_handle.seek_offset(-16, os.SEEK_CUR)

    offset = ewf_handle.get_offset()
    self.assertEqual(offset, 16)

    ewf_handle.seek_offset(-16, os.SEEK_END)

    offset = ewf_handle.get_offset()
    self.assertEqual(offset, file_size - 16)

    ewf_handle.seek_offset(16, os.SEEK_END)

    offset = ewf_handle.get_offset()
    self.assertEqual(offset, file_size + 16)

    # TODO: change IOError into ValueError
    with self.assertRaises(IOError):
      ewf_handle.seek_offset(-1, os.SEEK_SET)

    # TODO: change IOError into ValueError
    with self.assertRaises(IOError):
      ewf_handle.seek_offset(-32 - file_size, os.SEEK_CUR)

    # TODO: change IOError into ValueError
    with self.assertRaises(IOError):
      ewf_handle.seek_offset(-32 - file_size, os.SEEK_END)

    # TODO: change IOError into ValueError
    with self.assertRaises(IOError):
      ewf_handle.seek_offset(0, -1)

    ewf_handle.close()

    # Test the seek without open.
    with self.assertRaises(IOError):
      ewf_handle.seek_offset(16, os.SEEK_SET)
def pyewf_test_single_open_close_file(filename, mode):
  if not filename:
    filename_string = "None"
  else:
    filename_string = filename

  print(
      "Testing single open close of: {0:s} with access: {1:s}\t".format(
          filename_string, get_mode_string(mode)), end="")

  result = True
  error_string = None
  try:
    filenames = pyewf.glob(filename)
    ewf_handle = pyewf.handle()

    ewf_handle.open(filenames, mode)
    ewf_handle.close()

  except TypeError as exception:
    expected_message = (
        "{0:s}: unsupported string object type.").format(
            "pyewf_glob")

    if not filename and str(exception) == expected_message:
      pass

    else:
      error_string = str(exception)
      result = False

  except ValueError as exception:
    expected_message = (
        "{0:s}: unsupported mode: w.").format(
            "pyewf_handle_open")

    if mode != "w" or str(exception) != expected_message:
      error_string = str(exception)
      result = False

  except Exception as exception:
    error_string = str(exception)
    result = False

  if not result:
    print("(FAIL)")
  else:
    print("(PASS)")

  if error_string:
    print(error_string)
  return result
Exemple #34
0
 def disk_open(path):
     hash_val = calc_hash.get_hash(path, 'before')
     try:
         if pyewf.check_file_signature(path) == True:
             filename = pyewf.glob(path)
             ewf_handle = pyewf.handle()
             ewf_handle.open(filename)
             return disk_analysis.E01Analysis(ewf_handle, path, hash_val)
         else:
             return disk_analysis.DDAnalysis(path, hash_val)
     except:
         print(
             "[Error] input file error by fortools\nPlease check your file")
         return -1
Exemple #35
0
def pyewf_test_read_file_object(filename):
  filenames = pyewf.glob(filename)
  file_objects = []
  for filename in filenames:
    file_object = open(filename, "rb")
    file_objects.append(file_object)

  ewf_handle = pyewf.handle()
  ewf_handle.open_file_objects(file_objects, "r")

  result = pyewf_test_read(ewf_handle)
  ewf_handle.close()

  return result
Exemple #36
0
def pyewf_test_read_file_object(filename):
    filenames = pyewf.glob(filename)
    file_objects = []
    for filename in filenames:
        file_object = open(filename, "rb")
        file_objects.append(file_object)

    ewf_handle = pyewf.handle()
    ewf_handle.open_file_objects(file_objects, "r")

    result = pyewf_test_read(ewf_handle)
    ewf_handle.close()

    return result
    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.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)
    def test_get_offset(self):
        """Tests the get_offset function."""
        if not unittest.source:
            raise unittest.SkipTest("missing source")

        filenames = pyewf.glob(unittest.source)

        ewf_handle = pyewf.handle()

        ewf_handle.open(filenames)

        offset = ewf_handle.get_offset()
        self.assertIsNotNone(offset)

        ewf_handle.close()
Exemple #39
0
    def get_img_object(self):
        logging.info("Opening {}".format(self.evidence_file))
        if self.evidence_type == "ewf":
            try:
                filenames = pyewf.glob(self.evidence_file)
            except IOError:
                _, e, _ = sys.exc_info()
                print("[-] Invalid EWF format:\n {}".format(e))
                sys.exit(2)
            ewf_handle = pyewf.handle()
            ewf_handle.open(filenames)

            img_object = EWFImgInfo(ewf_handle)
        else:
            img_object = pytsk3.Img_Info(self.evidence_file)
        return img_object
Exemple #40
0
  def test_open(self):
    """Tests the open function."""
    if not unittest.source:
      return

    ewf_handle = pyewf.handle()

    ewf_handle.open(unittest.source)

    with self.assertRaises(IOError):
      ewf_handle.open(unittest.source)

    ewf_handle.close()

    with self.assertRaises(TypeError):
      ewf_handle.open(None)

    with self.assertRaises(ValueError):
      ewf_handle.open(unittest.source, mode="w")
Exemple #41
0
def main():
    filenames = pyewf.glob("E:\\YK_F1\\cfreds_2015_data_leakage_pc.E01")    # pyewf에서 연속된 ewf파일을 읽어 들이기 위해 .glob 사용
    ewf_handle = pyewf.handle()
    ewf_handle.open(filenames)      # E01 이미지 파일에 대한 핸들을 오픈한다. (분할된 파일이 하나의 파일 처럼 열림)
    img_info = ewf_Img_Info(ewf_handle)     # ewf_Img_Info을 이용해서 이미지를 오픈한다. 객체의 생성자에서 super를 통해 pytsk 객체로 생성
    vol = pytsk3.Volume_Info(img_info)      # 이미지를 불러들여 볼륨 정보를 얻어온다. 이때 pytsk3 모듈을 사용한다.
    output = open("result.csv", 'wb')
    ext_cnt = open("ext_cnt.txt", 'w')
    for part in vol:
        print part.addr, part.desc, part.start, part.len    # 볼륨 정보를 얻어와서 출력
        if part.len > 2048:
            fs = pytsk3.FS_Info(img_info, offset = part.start*vol.info.block_size)  # 각 볼륨에 대한 파일시스템 정보를 얻어 온다.
            directoryObject = fs.open_dir('/')  # 루트 디렉토리부터 오브젝트를 연다.
            recursive(directoryObject, [], output)  # 디렉터리 탐색 시작
            pass

    cnt = Counter(ext_list)     # 확장자별로 개수를 세기 위한 Counter 이용
    for i in sorted(cnt.items(), key=itemgetter(1), reverse=True):  # 확장자 갯수별로 정렬
        ext_cnt.write(str(i) + '\n')
Exemple #42
0
  def test_read_buffer_file_object(self):
    """Tests the read_buffer function on a file-like object."""
    if not unittest.source:
      return

    file_object = open(unittest.source, "rb")

    ewf_handle = pyewf.handle()

    ewf_handle.open_file_object(file_object)

    file_size = ewf_handle.get_size()

    # Test normal read.
    data = ewf_handle.read_buffer(size=4096)

    self.assertIsNotNone(data)
    self.assertEqual(len(data), min(file_size, 4096))

    ewf_handle.close()
Exemple #43
0
def pyewf_test_seek_file_no_open(filename):
  print("Testing seek of offset without open:\t", end="")

  ewf_handle = pyewf.handle()

  error_string = ""
  result = False
  try:
    ewf_handle.seek(0, os.SEEK_SET)
  except Exception as exception:
    error_string = str(exception)
    result = True

  if not result:
    print("(FAIL)")
  else:
    print("(PASS)")

  if error_string:
    print(error_string)
  return result
Exemple #44
0
def pyewf_test_read_file_no_open(filename):
  print("Testing read of offset without open:\t", end="")

  ewf_handle = pyewf.handle()

  error_string = ""
  result = False
  try:
    ewf_handle.read(size=4096)
  except Exception as exception:
    error_string = str(exception)
    result = True

  if not result:
    print("(FAIL)")
  else:
    print("(PASS)")

  if error_string:
    print(error_string)
  return result
Exemple #45
0
  def _OpenFileObject(self, path_spec):
    """Opens the file-like object defined by path specification.

    Args:
      path_spec: the path specification (instance of path.PathSpec).

    Returns:
      A file-like object or None.

    Raises:
      PathSpecError: if the path specification is invalid.
    """
    if not path_spec.HasParent():
      raise errors.PathSpecError(
          u'Unsupported path specification without parent.')

    parent_path_spec = path_spec.parent

    file_system = resolver.Resolver.OpenFileSystem(
        parent_path_spec, resolver_context=self._resolver_context)

    # Note that we cannot use pyewf's glob function since it does not
    # handle the file system abstraction dfvfs provides.
    segment_file_path_specs = ewf.EWFGlobPathSpec(file_system, path_spec)
    if not segment_file_path_specs:
      return

    if parent_path_spec.IsSystemLevel():
      # Typically the file-like object cache should have room for 127 items.
      self._resolver_context.SetMaximumNumberOfFileObjects(
          len(segment_file_path_specs) + 127)

    for segment_file_path_spec in segment_file_path_specs:
      file_object = resolver.Resolver.OpenFileObject(
          segment_file_path_spec, resolver_context=self._resolver_context)
      self._file_objects.append(file_object)

    ewf_handle = pyewf.handle()
    ewf_handle.open_file_objects(self._file_objects)
    return ewf_handle
Exemple #46
0
  def test_open_file_object(self):
    """Tests the open_file_object function."""
    if not unittest.source:
      return

    file_object = open(unittest.source, "rb")

    ewf_handle = pyewf.handle()

    ewf_handle.open_file_object(file_object)

    with self.assertRaises(IOError):
      ewf_handle.open_file_object(file_object)

    ewf_handle.close()

    # TODO: change IOError into TypeError
    with self.assertRaises(IOError):
      ewf_handle.open_file_object(None)

    with self.assertRaises(ValueError):
      ewf_handle.open_file_object(file_object, mode="w")
def extractFile(imageFile,filenames):
  if (args.imagetype == "e01"):
    filenames = pyewf.glob(imageFile)
    ewf_handle = pyewf.handle()
    ewf_handle.open(filenames)
    imagehandle = ewf_Img_Info(ewf_handle)
  elif (args.imagetype == "raw"):
      print "Raw Type"
      imagehandle = pytsk3.Img_Info(url=imageFile)

  partitionTable = pytsk3.Volume_Info(imagehandle)
  for partition in partitionTable:
    print partition.addr, partition.desc, "%ss(%s)" % (partition.start, partition.start * 512), partition.len
    try:
          filesystemObject = pytsk3.FS_Info(imagehandle, 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'

  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))
    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()


argparser = argparse.ArgumentParser(description="Extract the $MFT from all of the NTFS partitions of an E01")
argparser.add_argument(
    "-i", "--image", dest="imagefile", action="store", type=str, default=None, required=True, help="E01 to extract from"
)
args = argparser.parse_args()
filenames = pyewf.glob(args.imagefile)
ewf_handle = pyewf.handle()
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
    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
Exemple #49
0
  def test_signal_abort(self):
    """Tests the signal_abort function."""
    ewf_handle = pyewf.handle()

    ewf_handle.signal_abort()
 def __init__(self, filename):
   self.ewf_handle = pyewf.handle()
   filenames = pyewf.glob(filename)
   self.ewf_handle.open(filenames)
   super(Ewf_Img_Info, self).__init__()
# ----------------------------------------------------------------------------
# Main
# ----------------------------------------------------------------------------

print "open_close.py " + __version__ + " (libewf " + pyewf.get_version() + ")\n"

argc = len( sys.argv )

if argc < 2:
	print "Usage: open_close.py filename(s)\n"

	sys.exit( 1 )

filenames = sys.argv[ 1: ]

handle = pyewf.handle();

if handle == None:
	print "Missing handle object\n"

	sys.exit( 1 )

try:
	# Open requires a list of filenames
	handle.open(
	 filenames )

except:
	print "Unable to open file(s)\n"
	print sys.exc_info()[ 1 ]