Beispiel #1
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 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 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)
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
Beispiel #5
0
    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 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))
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
Beispiel #8
0
    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)
Beispiel #9
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
Beispiel #10
0
    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()
Beispiel #11
0
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
Beispiel #12
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()
Beispiel #13
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)
Beispiel #14
0
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 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)
Beispiel #16
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"))
Beispiel #17
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
Beispiel #18
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
Beispiel #19
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
Beispiel #20
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
Beispiel #21
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
Beispiel #22
0
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
Beispiel #23
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
Beispiel #24
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
Beispiel #25
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)
Beispiel #27
0
    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()
Beispiel #28
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
Beispiel #29
0
    def test_get_header_codepage(self):
        """Tests the get_header_codepage function and header_codepage property."""
        if not unittest.source:
            raise unittest.SkipTest("missing source")

        filenames = pyewf.glob(unittest.source)

        ewf_handle = pyewf.handle()

        ewf_handle.open(filenames)

        header_codepage = ewf_handle.get_header_codepage()
        self.assertIsNotNone(header_codepage)

        self.assertIsNotNone(ewf_handle.header_codepage)

        ewf_handle.close()
Beispiel #30
0
    def test_get_format(self):
        """Tests the get_format function and format property."""
        if not unittest.source:
            raise unittest.SkipTest("missing source")

        filenames = pyewf.glob(unittest.source)

        ewf_handle = pyewf.handle()

        ewf_handle.open(filenames)

        format = ewf_handle.get_format()
        self.assertIsNotNone(format)

        self.assertIsNotNone(ewf_handle.format)

        ewf_handle.close()
Beispiel #31
0
    def test_get_media_flags(self):
        """Tests the get_media_flags function and media_flags property."""
        if not unittest.source:
            raise unittest.SkipTest("missing source")

        filenames = pyewf.glob(unittest.source)

        ewf_handle = pyewf.handle()

        ewf_handle.open(filenames)

        media_flags = ewf_handle.get_media_flags()
        self.assertIsNotNone(media_flags)

        self.assertIsNotNone(ewf_handle.media_flags)

        ewf_handle.close()
Beispiel #32
0
    def test_get_compression_method(self):
        """Tests the get_compression_method function and compression_method property."""
        if not unittest.source:
            raise unittest.SkipTest("missing source")

        filenames = pyewf.glob(unittest.source)

        ewf_handle = pyewf.handle()

        ewf_handle.open(filenames)

        compression_method = ewf_handle.get_compression_method()
        self.assertIsNotNone(compression_method)

        self.assertIsNotNone(ewf_handle.compression_method)

        ewf_handle.close()
Beispiel #33
0
    def test_get_error_granularity(self):
        """Tests the get_error_granularity function and error_granularity property."""
        if not unittest.source:
            raise unittest.SkipTest("missing source")

        filenames = pyewf.glob(unittest.source)

        ewf_handle = pyewf.handle()

        ewf_handle.open(filenames)

        error_granularity = ewf_handle.get_error_granularity()
        self.assertIsNotNone(error_granularity)

        self.assertIsNotNone(ewf_handle.error_granularity)

        ewf_handle.close()
Beispiel #34
0
    def test_get_chunk_size(self):
        """Tests the get_chunk_size function and chunk_size property."""
        if not unittest.source:
            raise unittest.SkipTest("missing source")

        filenames = pyewf.glob(unittest.source)

        ewf_handle = pyewf.handle()

        ewf_handle.open(filenames)

        chunk_size = ewf_handle.get_chunk_size()
        self.assertIsNotNone(chunk_size)

        self.assertIsNotNone(ewf_handle.chunk_size)

        ewf_handle.close()
Beispiel #35
0
    def test_get_number_of_sectors(self):
        """Tests the get_number_of_sectors function and number_of_sectors property."""
        if not unittest.source:
            raise unittest.SkipTest("missing source")

        filenames = pyewf.glob(unittest.source)

        ewf_handle = pyewf.handle()

        ewf_handle.open(filenames)

        number_of_sectors = ewf_handle.get_number_of_sectors()
        self.assertIsNotNone(number_of_sectors)

        self.assertIsNotNone(ewf_handle.number_of_sectors)

        ewf_handle.close()
Beispiel #36
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')
Beispiel #37
0
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))
Beispiel #38
0
  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()
  
filenames = pyewf.glob("SSFCC-Level5.E01")

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
    file_dict['name_type'] = file_obj.info.name.type

    return file_dict

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Grabs basic system info from EnCase EWF (E01) & RAW DD images.')
    parser.add_argument('-i', '--input', metavar="IMAGE", action='store', help='Path to evidence file (First part of segmented/split image)', required=True)
    parser.add_argument('-s', '--sector_size', metavar="SECTORS", action='store', help='Sector size of image (Default is taken from mmls)', type=int)
    parser.add_argument('-t', '--image_type', metavar="TYPE", action='store', choices=['ewf', 'raw'], help='Image type (Default is raw)', default='raw')
    args = vars(parser.parse_args())

    image_type = args['image_type']

    if image_type == "ewf":
        filenames = pyewf.glob(args['input'])
        ewf_handle = pyewf.handle()
        ewf_handle.open(filenames)
        image_handle = EwfImageInfo(ewf_handle)
    else:
        filenames = args['input']
        if not os.path.isdir(filenames):
        #if len(filenames) == 1:
            #image_handle = pytsk3.Img_Info(filenames[0])
            image_handle = pytsk3.Img_Info(filenames)
        else:
            #image_handle = SplitImage(*filenames)
            print("[!] Currently not supporting Split images")
            sys.exit(1)

    evidence_files = {}
Beispiel #40
0
        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()


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"
        )
 def __init__(self, filename):
   self.ewf_handle = pyewf.handle()
   filenames = pyewf.glob(filename)
   self.ewf_handle.open(filenames)
   super(Ewf_Img_Info, self).__init__()
Beispiel #42
0
# ----------------------------------------------------------------------------
# Main
# ----------------------------------------------------------------------------

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

argc = len( sys.argv )

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

	sys.exit( 1 )

if argc == 2:
	try:
		filenames = pyewf.glob(
		             sys.argv[ 1 ] )

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

		sys.exit( 1 )
else:
	filenames = sys.argv[ 1: ]

handle = pyewf.new_handle();

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

	sys.exit( 1 )