Beispiel #1
0
def get_soft_installdate(softHive):
    # get the windows install timestamp from software hive
    soft = pyregf.file()
    try:
        soft = pyregf.file()
        soft.open(softHive)
        vers_key = soft.get_key_by_path(r'Microsoft\Windows NT\CurrentVersion')
        inst_date = vers_key.get_value_by_name('InstallDate')
        stamp = dt.datetime.utcfromtimestamp(inst_date.get_data_as_integer())
    except (IOError, AttributeError):
        print('Error: InstallDate could not be determined.  Is this a SOFTWARE hive?\n\tFile: {}'.format(softHive))
        sys.exit(0)
    finally:
        soft.close()
    return stamp
def pyregf_test_single_open_close_file_object_with_dereference(
    filename, mode):
  """Tests single file-like object open and close with dereference."""
  description = (
      "Testing single open close of file-like object with dereference of: "
      "{0:s} with access: {1:s}\t").format(
          get_filename_string(filename), get_mode_string(mode))
  print(description, end="")

  error_string = None
  result = True

  try:
    file_object = open(filename, "rb")
    regf_file = pyregf.file()

    regf_file.open_file_object(file_object, mode)
    del file_object
    regf_file.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 #3
0
  def _Open(self, path_spec=None, mode='rb'):
    """Opens the file system object defined by path specification.

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

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

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

    regf_file = pyregf.file()
    regf_file.open_file_object(file_object)
    regf_base_key = self._regf_file.get_root_key()

    self._file_object = file_object
    self._regf_file = regf_file
    self._regf_base_key = regf_base_key
Beispiel #4
0
    def getHostName(self, file_name_fullpath):
        file_object = loadFile(file_name_fullpath)
        regf_file = pyregf.file()
        regf_file.open_file_object(file_object, "r")
        # Get control set number
        tmp_key = regf_file.get_key_by_path(r'Select')
        if tmp_key is not None:
            controlset_number = tmp_key.get_value_by_name(
                'Current').get_data_as_integer()
            # Get host name
            tmp_key = regf_file.get_key_by_path(
                r'ControlSet00' + str(controlset_number) +
                '\Control\ComputerName\ComputerName')
            host_name = tmp_key.get_value_by_name(
                'ComputerName').get_data_as_string()
        else:
            # todo: Close everything down elegantly
            logger.error(
                "Attempting to process non-SYSTEM hive with appcompat_raw_hive plugin: %s"
                % file_name_fullpath)
            raise (Exception(
                'Attempting to process non-SYSTEM hive with appcompat_raw_hive plugin'
            ))

        # Need to close these or the memory will never get freed:
        regf_file.close()
        del regf_file
        file_object.close()
        del file_object
        return host_name
Beispiel #5
0
    def ReadFileObject(self, file_object):
        """Reads a Windows AMCache file-like object.

    Args:
      file_object (file): file-like object.

    Raises:
      ParseError: if the file cannot be read.
    """
        regf_file = pyregf.file()
        regf_file.open_file_object(file_object)

        root_key = regf_file.get_key_by_path('\\Root')
        if root_key:
            file_key = root_key.get_sub_key_by_path('File')
            if file_key:
                self._ReadFileKey(file_key)

            programs_key = root_key.get_sub_key_by_path('Programs')
            if programs_key:
                self._ReadProgramsKey(programs_key)

            inventory_application_key = root_key.get_sub_key_by_path(
                'InventoryApplication')
            if inventory_application_key:
                self._ReadInventoryApplicationKey(inventory_application_key)

            inventory_application_file_key = root_key.get_sub_key_by_path(
                'InventoryApplicationFile')
            if inventory_application_file_key:
                self._ReadInventoryApplicationFileKey(
                    inventory_application_file_key)
Beispiel #6
0
  def test_open_close(self):
    """Tests the open and close functions."""
    if not unittest.source:
      return

    regf_file = pyregf.file()

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

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

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

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

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

    # Test open_file_object and close and dereferencing file_object.
    regf_file.open_file_object(file_object)
    del file_object
    regf_file.close()
Beispiel #7
0
    def test_open_close(self):
        """Tests the open and close functions."""
        test_source = unittest.source
        if not test_source:
            return

        regf_file = pyregf.file()

        # Test open and close.
        regf_file.open(test_source)
        regf_file.close()

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

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

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

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

                # Test open_file_object and close and dereferencing file_object.
                regf_file.open_file_object(file_object)
                del file_object
                regf_file.close()
Beispiel #8
0
def pyregf_test_single_open_close_file_object_with_dereference(
    filename, mode):
  print(
      ("Testing single open close of file-like object with dereference "
       "of: {0:s} with access: {1:s}\t").format(
          filename, get_mode_string(mode)), end="")

  result = True
  try:
    file_object = open(filename, "rb")
    regf_file = pyregf.file()

    regf_file.open_file_object(file_object, mode)
    del file_object
    regf_file.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 calculateID(self, file_name_fullpath):
        instanceID = 0
        file_object = loadFile(file_name_fullpath)
        regf_file = pyregf.file()
        regf_file.open_file_object(file_object, "r")

        # Search for key containing ShimCache entries on all control sets
        # Use last modification time of the last modified one as instanceID
        root = regf_file.get_root_key()
        num_keys = root.get_number_of_sub_keys()
        for i in xrange(0, num_keys):
            tmp_key = root.get_sub_key(i)
            if "controlset" in tmp_key.get_name().lower():
                session_man_key = regf_file.get_key_by_path(
                    "%s\Control\Session Manager" % tmp_key.get_name())
                num_keys = session_man_key.get_number_of_sub_keys()
                for i in xrange(0, num_keys):
                    tmp_key = session_man_key.get_sub_key(i)
                    if "appcompatibility" in tmp_key.get_name().lower(
                    ) or "appcompatcache" in tmp_key.get_name().lower():
                        last_write_time = tmp_key.get_last_written_time_as_integer(
                        )
                        if last_write_time > instanceID:
                            instanceID = last_write_time
                        break

        # Need to close these or the memory will never get freed:
        regf_file.close()
        del regf_file
        file_object.close()
        del file_object
        return instanceID
Beispiel #10
0
def pyregf_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
  try:
    regf_file = pyregf.file()

    regf_file.open(filename, mode)
    regf_file.close()
    regf_file.open(filename, mode)
    regf_file.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 pyregf_test_multi_open_close_file(filename, mode):
  """Tests multiple open and close."""
  description = (
      "Testing multi open close of: {0:s} with access: {1:s}"
      "\t").format(get_filename_string(filename), get_mode_string(mode))
  print(description, end="")

  error_string = None
  result = True

  try:
    regf_file = pyregf.file()

    regf_file.open(filename, mode)
    regf_file.close()
    regf_file.open(filename, mode)
    regf_file.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 test_open_close(self):
        """Tests the open and close functions."""
        if not unittest.source:
            return

        regf_file = pyregf.file()

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

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

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

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

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

        # Test open_file_object and close and dereferencing file_object.
        regf_file.open_file_object(file_object)
        del file_object
        regf_file.close()
Beispiel #13
0
  def test_open_file_object(self):
    """Tests the open_file_object 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")

    regf_file = pyregf.file()

    with open(unittest.source, "rb") as file_object:

      regf_file.open_file_object(file_object)

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

      regf_file.close()

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

      with self.assertRaises(ValueError):
        regf_file.open_file_object(file_object, mode="w")
Beispiel #14
0
    def _Open(self, path_spec=None, mode='rb'):
        """Opens the file system object defined by path specification.

    Args:
      path_spec (Optional[dfvfs.PathSpec]): a path specification.
      mode (Optional[str]): file access mode. The default is 'rb' read-only
          binary.

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

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

        regf_file = pyregf.file()
        regf_file.open_file_object(file_object)
        regf_base_key = self._regf_file.get_root_key()

        self._file_object = file_object
        self._regf_file = regf_file
        self._regf_base_key = regf_base_key
def pyregf_test_single_open_close_file_object(filename, mode):
  """Tests a single file-like object open and close."""
  description = (
      "Testing single open close of file-like object of: {0:s} with access: "
      "{1:s}\t").format(get_filename_string(filename), get_mode_string(mode))
  print(description, end="")

  error_string = None
  result = True

  try:
    file_object = open(filename, "rb")
    regf_file = pyregf.file()

    regf_file.open_file_object(file_object, mode)
    regf_file.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 #16
0
    def ParseFileObject(self, parser_mediator, file_object):
        """Parses an AMCache.hve file-like object for events.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      file_object (dfvfs.FileIO): file-like object.
    """
        regf_file = pyregf.file()
        try:
            regf_file.open_file_object(file_object)
        except IOError:
            # The error is currently ignored -> see TODO above related to the
            # fixing of handling multiple parsers for the same file format.
            return

        root_key = regf_file.get_key_by_path('Root')
        if root_key:
            file_key = root_key.get_sub_key_by_path('File')
            if file_key:
                self._ParseFileKey(parser_mediator, file_key)

            programs_key = root_key.get_sub_key_by_path('Programs')
            if programs_key:
                self._ParseProgramsKey(parser_mediator, programs_key)

        regf_file.close()
Beispiel #17
0
  def __init__(self):
    """Initializes a Windows Registry key object."""
    super(WinPyregfFile, self).__init__()
    self._base_key = None
    self._file_object = None
    self._pyregf_file = pyregf.file()

    self.name = u''
Beispiel #18
0
  def test_close(self):
    """Tests the close function."""
    if not unittest.source:
      raise unittest.SkipTest("missing source")

    regf_file = pyregf.file()

    with self.assertRaises(IOError):
      regf_file.close()
Beispiel #19
0
  def __init__(self, ascii_codepage=u'cp1252'):
    """Initializes the Windows Registry file.

    Args:
      ascii_codepage: optional ASCII string codepage. The default is cp1252
                      (or windows-1252).
    """
    super(RegistryFile, self).__init__()
    self._file_object = None
    self._regf_file = pyregf.file()
    self._regf_file.set_ascii_codepage(ascii_codepage)
Beispiel #20
0
    def __init__(self, ascii_codepage=u'cp1252'):
        """Initializes the Windows Registry file.

    Args:
      ascii_codepage: optional ASCII string codepage. The default is cp1252
                      (or windows-1252).
    """
        super(WinRegistryFileREGF, self).__init__()
        self._file_object = None
        self._regf_file = pyregf.file()
        self._regf_file.set_ascii_codepage(ascii_codepage)
Beispiel #21
0
def main(argv=None):
    fileA, fileB = parseArgs(argv)

    #open the files
    regA = pyregf.file()
    regB = pyregf.file()
    
    regA.open(fileA)
    regB.open(fileB)

    #process the registry
    setA = processRoot(regA.get_root_key())
    setB = processRoot(regB.get_root_key())


    #Print metrics on how many we managed to remove
    if DEBUG:
        report(len(setA),'count-A: ')    
        report(len(setA.difference(setB)),'count-A !B: ')
    
    report(setA.difference(setB), 'UNIQUE-A: {0}'.format(fileA))
Beispiel #22
0
  def __init__(self, ascii_codepage=u'cp1252', key_path_prefix=u''):
    """Initializes the Windows Registry file.

    Args:
      ascii_codepage: optional ASCII string codepage.
      key_path_prefix: optional Windows Registry key path prefix.
    """
    super(REGFWinRegistryFile, self).__init__(
        ascii_codepage=ascii_codepage, key_path_prefix=key_path_prefix)
    self._file_object = None
    self._regf_file = pyregf.file()
    self._regf_file.set_ascii_codepage(ascii_codepage)
Beispiel #23
0
  def __init__(self, ascii_codepage='cp1252', key_path_prefix=''):
    """Initializes the Windows Registry file.

    Args:
      ascii_codepage (Optional[str]): ASCII string codepage.
      key_path_prefix (Optional[str]): Windows Registry key path prefix.
    """
    super(REGFWinRegistryFile, self).__init__(
        ascii_codepage=ascii_codepage, key_path_prefix=key_path_prefix)
    self._file_object = None
    self._regf_file = pyregf.file()
    self._regf_file.set_ascii_codepage(ascii_codepage)
def _processAmCacheFile_StringIO(data):
    regf_file = pyregf.file()
    regf_file.open_file_object(data, "r")

    try:
        ee = parse_execution_entries(regf_file)
    except NotAnAmcacheHive:
        logger.error("doesn't appear to be an Amcache.hve hive")
        return
    finally:
        regf_file.close()

    return ee
Beispiel #25
0
def Main():
    """The main program function.

  Returns:
    A boolean containing True if successful or False if not.
  """
    argument_parser = argparse.ArgumentParser(
        description=(u"Extract the MSIE zone information from a NTUSER.DAT " u"Registry File (REGF).")
    )

    argument_parser.add_argument(
        u"registry_file",
        nargs=u"?",
        action=u"store",
        metavar=u"NTUSER.DAT",
        default=None,
        help=u"path of the NTUSER.DAT Registry file.",
    )

    argument_parser.add_argument(
        u"--codepage",
        dest=u"codepage",
        action=u"store",
        metavar=u"CODEPAGE",
        default=u"cp1252",
        help=u"the codepage of the extended ASCII strings.",
    )

    options = argument_parser.parse_args()

    if not options.registry_file:
        print(u"Registry file missing.")
        print(u"")
        argument_parser.print_help()
        print(u"")
        return False

    logging.basicConfig(level=logging.INFO, format=u"[%(levelname)s] %(message)s")

    regf_file = pyregf.file()
    regf_file.open(options.registry_file)

    # HKCU

    key_path = u"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\UserAssist"
    PrintUserAssistKey(regf_file, key_path, options.codepage)

    regf_file.close()

    return True
Beispiel #26
0
    def __init__(self, ascii_codepage=u"cp1252"):
        """Initializes the Windows Registry file.

    Args:
      ascii_codepage: optional ASCII string codepage. The default is cp1252
                      (or windows-1252).
    """
        super(WinPyregfFile, self).__init__()
        self._ascii_codepage = ascii_codepage
        self._base_key = None
        self._file_object = None
        self._pyregf_file = pyregf.file()

        self.name = u""
Beispiel #27
0
def pyregf_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
  try:
    regf_file = pyregf.file()

    regf_file.open(filename, mode)
    regf_file.close()

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

    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(
            "pyregf_file_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 #28
0
    def __init__(self, ascii_codepage=u'cp1252', key_path_prefix=u''):
        """Initializes the Windows Registry file.

    Args:
      ascii_codepage: optional ASCII string codepage. The default is cp1252
                      (or windows-1252).
      key_path_prefix: optional Windows Registry key path prefix.
    """
        super(REGFWinRegistryFile,
              self).__init__(ascii_codepage=ascii_codepage,
                             key_path_prefix=key_path_prefix)
        self._file_object = None
        self._regf_file = pyregf.file()
        self._regf_file.set_ascii_codepage(ascii_codepage)
Beispiel #29
0
  def test_get_root_key(self):
    """Tests the get_root_key function and root_key property."""
    if not unittest.source:
      raise unittest.SkipTest("missing source")

    regf_file = pyregf.file()

    regf_file.open(unittest.source)

    _ = regf_file.get_root_key()

    _ = regf_file.root_key

    regf_file.close()
def pyregf_test_single_open_close_file(filename, mode):
  """Tests a single open and close."""
  description = (
      "Testing single open close of: {0:s} with access: {1:s}"
      "\t").format(get_filename_string(filename), get_mode_string(mode))
  print(description, end="")

  error_string = None
  result = True

  try:
    regf_file = pyregf.file()

    regf_file.open(filename, mode)
    regf_file.close()

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

    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(
            "pyregf_file_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
def _processAmCacheFile(fileFullPath):
    file_object = open(fileFullPath, "rb")
    regf_file = pyregf.file()
    regf_file.open_file_object(file_object, "r")

    try:
        ee = parse_execution_entries(regf_file)
    except NotAnAmcacheHive:
        logger.error("doesn't appear to be an Amcache.hve hive")
        return
    finally:
        regf_file.close()
        file_object.close()

    return ee
Beispiel #32
0
  def test_get_ascii_codepage(self):
    """Tests the get_ascii_codepage function and ascii_codepage property."""
    if not unittest.source:
      raise unittest.SkipTest("missing source")

    regf_file = pyregf.file()

    regf_file.open(unittest.source)

    ascii_codepage = regf_file.get_ascii_codepage()
    self.assertIsNotNone(ascii_codepage)

    self.assertIsNotNone(regf_file.ascii_codepage)

    regf_file.close()
Beispiel #33
0
  def test_get_type(self):
    """Tests the get_type function and type property."""
    if not unittest.source:
      raise unittest.SkipTest("missing source")

    regf_file = pyregf.file()

    regf_file.open(unittest.source)

    type = regf_file.get_type()
    self.assertIsNotNone(type)

    self.assertIsNotNone(regf_file.type)

    regf_file.close()
Beispiel #34
0
    def calculateID(self, file_name_fullpath):
        instanceID = None
        file_object = loadFile(file_name_fullpath)
        regf_file = pyregf.file()
        regf_file.open_file_object(file_object, "r")
        tmp = regf_file.get_key_by_path(r'Root\File')
        if regf_file.get_key_by_path(r'Root\File') == None:
            logger.warning("Not an AmCache hive! [%s]" % file_name_fullpath)
        else:
            instanceID = regf_file.root_key.last_written_time

        # Need to close these or the memory will never get freed:
        regf_file.close()
        del regf_file
        file_object.close()
        del file_object
        return instanceID
Beispiel #35
0
    def checkMagic(self, file_name_fullpath):
        magic_ok = False
        # Check magic
        magic_id = self.id_filename(file_name_fullpath)
        if 'registry' in magic_id:
            file_object = loadFile(file_name_fullpath)
            regf_file = pyregf.file()
            regf_file.open_file_object(file_object, "r")
            magic_key = regf_file.get_key_by_path(r'Select')
            regf_file.close()
            del regf_file
            if magic_key is not None:
                magic_ok = True

            # Need to close these or the memory will never get freed:
            file_object.close()
            del file_object

        return magic_ok
Beispiel #36
0
  def test_open(self):
    """Tests the open function."""
    if not unittest.source:
      return

    regf_file = pyregf.file()

    regf_file.open(unittest.source)

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

    regf_file.close()

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

    with self.assertRaises(ValueError):
      regf_file.open(unittest.source, mode="w")
    def checkMagic(self, file_name_fullpath):
        magic_ok = False
        # Quick and dirty check
        file_object = loadFile(file_name_fullpath)
        tmp = struct.unpack('4s', file_object.read(4))
        if tmp[0] == "regf":
            # Perform a deeper check using pyregf
            regf_file = pyregf.file()
            regf_file.open_file_object(file_object, "r")
            magic_key = regf_file.get_key_by_path(r'Root\File')
            regf_file.close()
            del regf_file
            if magic_key is not None:
                magic_ok = True

        file_object.close()
        del file_object

        return magic_ok
Beispiel #38
0
    def test_open(self):
        """Tests the open function."""
        if not unittest.source:
            return

        regf_file = pyregf.file()

        regf_file.open(unittest.source)

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

        regf_file.close()

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

        with self.assertRaises(ValueError):
            regf_file.open(unittest.source, mode="w")
    def checkMagic(self, file_name_fullpath):
        magic_ok = False
        # Check magic
        magic_id = self.id_filename(file_name_fullpath)
        if 'registry' in magic_id:
            file_object = loadFile(file_name_fullpath)
            # Perform a deeper check using pyregf
            regf_file = pyregf.file()
            regf_file.open_file_object(file_object, "r")
            magic_key = regf_file.get_key_by_path(r'Root\File')
            regf_file.close()
            del regf_file
            if magic_key is not None:
                magic_ok = True

            file_object.close()
            del file_object

        return magic_ok
Beispiel #40
0
def Main():
  """The main program function.

  Returns:
    A boolean containing True if successful or False if not.
  """
  args_parser = argparse.ArgumentParser(description=(
      u'Extract the MSIE zone information from a NTUSER.DAT '
      u'Registry File (REGF).'))

  args_parser.add_argument(
      u'registry_file', nargs=u'?', action=u'store', metavar=u'NTUSER.DAT',
      default=None, help=u'path of the NTUSER.DAT Registry file.')

  args_parser.add_argument(
      u'--codepage', dest=u'codepage', action=u'store', metavar=u'CODEPAGE',
      default=u'cp1252', help=u'the codepage of the extended ASCII strings.')

  options = args_parser.parse_args()

  if not options.registry_file:
    print u'Registry file missing.'
    print u''
    args_parser.print_help()
    print u''
    return False

  logging.basicConfig(
      level=logging.INFO, format=u'[%(levelname)s] %(message)s')

  regf_file = pyregf.file()
  regf_file.open(options.registry_file)

  # HKCU

  key_path = (
      u'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\UserAssist')
  PrintUserAssistKey(regf_file, key_path, options.codepage)

  regf_file.close()

  return True
Beispiel #41
0
    def test_open(self):
        """Tests the open function."""
        test_source = unittest.source
        if not test_source:
            raise unittest.SkipTest("missing source")

        regf_file = pyregf.file()

        regf_file.open(test_source)

        with self.assertRaises(IOError):
            regf_file.open(test_source)

        regf_file.close()

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

        with self.assertRaises(ValueError):
            regf_file.open(test_source, mode="w")
Beispiel #42
0
    def checkMagic(self, file_name_fullpath):
        magic_ok = False
        # Quick and dirty check
        if pyregf.check_file_signature(file_name_fullpath):
            file_object = loadFile(file_name_fullpath)
            tmp = struct.unpack('4s', file_object.read(4))
            if tmp[0] == "regf":
                regf_file = pyregf.file()
                regf_file.open_file_object(file_object, "r")
                magic_key = regf_file.get_key_by_path(r'Select')
                regf_file.close()
                del regf_file
                if magic_key is not None:
                    magic_ok = True

            # Need to close these or the memory will never get freed:
            file_object.close()
            del file_object

        return magic_ok
Beispiel #43
0
    def ParseFileObject(self, parser_mediator, file_object):
        """Parses an Amcache.hve file for events.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      file_object (dfvfs.FileIO): file-like object.
    """
        regf_file = pyregf.file()  # pylint: disable=no-member
        try:
            regf_file.open_file_object(file_object)
        except IOError:
            # The error is currently ignored -> see TODO above related to the
            # fixing of handling multiple parsers for the same file format.
            return

        root_key = regf_file.get_root_key()
        if root_key is None:
            regf_file.close()
            return

        root_file_key = root_key.get_sub_key_by_path(
            self._AMCACHE_ROOT_FILE_KEY)
        if root_file_key is None:
            regf_file.close()
            return

        for volume_key in root_file_key.sub_keys:
            for am_entry in volume_key.sub_keys:
                self._ProcessAMCacheFileKey(am_entry, parser_mediator)

        root_program_key = root_key.get_sub_key_by_path(
            self._AMCACHE_ROOT_PROGRAM_KEY)
        if root_program_key is None:
            regf_file.close()
            return

        for am_entry in root_program_key.sub_keys:
            self._ProcessAMCacheProgramKey(am_entry, parser_mediator)

        regf_file.close()
Beispiel #44
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.

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

    file_object = resolver.Resolver.OpenFileObject(
        path_spec.parent, resolver_context=self._resolver_context)
    regf_file = pyregf.file()
    regf_file.open_file_object(file_object)
    return regf_file
Beispiel #45
0
    def _OpenFileObject(self, path_spec):
        """Opens the file-like object defined by path specification.

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

    Returns:
      pyregf.file: a Windows Registry file.

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

        file_object = resolver.Resolver.OpenFileObject(
            path_spec.parent, resolver_context=self._resolver_context)
        regf_file = pyregf.file()
        regf_file.open_file_object(file_object)
        return regf_file
Beispiel #46
0
  def test_set_ascii_codepage(self):
    """Tests the set_ascii_codepage function."""
    supported_codepages = (
        "ascii", "cp874", "cp932", "cp936", "cp949", "cp950", "cp1250",
        "cp1251", "cp1252", "cp1253", "cp1254", "cp1255", "cp1256", "cp1257",
        "cp1258")

    regf_file = pyregf.file()

    for codepage in supported_codepages:
      regf_file.set_ascii_codepage(codepage)

    unsupported_codepages = (
        "iso-8859-1", "iso-8859-2", "iso-8859-3", "iso-8859-4", "iso-8859-5",
        "iso-8859-6", "iso-8859-7", "iso-8859-8", "iso-8859-9", "iso-8859-10",
        "iso-8859-11", "iso-8859-13", "iso-8859-14", "iso-8859-15",
        "iso-8859-16", "koi8_r", "koi8_u")

    for codepage in unsupported_codepages:
      with self.assertRaises(RuntimeError):
        regf_file.set_ascii_codepage(codepage)
Beispiel #47
0
def main():
    args = cmdArgParse()

    reg = pyregf.file()
    reg.open(args.fname)

    low_date = dt.datetime.min.date()
    high_date = dt.datetime.max.date()

    if args.use_install:  # parse install date from software hive
        low_date = get_soft_installdate(args.use_install).date()
    elif args.low_filter:  # use the date specified on cli
        low_date = dt.datetime.strptime(args.low_filter, '%Y/%m/%d').date()

    if args.use_lastmodtime:  # parse last mod from hive
        high_date = dt.datetime.utcfromtimestamp(os.path.getmtime(args.fname)).date()
    elif args.high_filter:  # use the date specified on cli
        high_date = dt.datetime.strptime(args.high_filter, '%Y/%m/%d').date()

    summaryText = '#Using date filters:\n#\t{}  -  {}\n'.format(low_date, high_date)
    if args.use_lastwrite:
        summaryText += '#\t[lastwrite] as additional upper filter\n'
    summaryText += '#{}'.format('\t'.join(['keyLastWrite', 'keyName', 'valueName', 'tsType', 'dataOffset', 'ts']))
    print(summaryText)

    for curKey, curPath in get_sub_keys(reg.get_root_key()):  # foreach key in regfile
        lastwrite = curKey.get_last_written_time()  # get the lastwrite time on key
        for i in xrange(curKey.number_of_values):  # foreach value in key
            curValue = curKey.get_value(i)
            vData = curValue.get_data()
            if vData == None:
                continue

            for ts_type, pIdx, result in find_timestamps(vData):  # foreach result we bruteforce
                if args.use_lastwrite and result > lastwrite:
                    continue  # failed lastwrite filter

                if low_date <= result.date() <= high_date:
                    print('\t'.join([str(lastwrite), str(curPath), str(curValue.get_name()), str(ts_type), str(pIdx), str(result)]))
Beispiel #48
0
  def test_open_file_object(self):
    """Tests the open_file_object function."""
    if not unittest.source:
      return

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

    regf_file = pyregf.file()

    regf_file.open_file_object(file_object)

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

    regf_file.close()

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

    with self.assertRaises(ValueError):
      regf_file.open_file_object(file_object, mode="w")
Beispiel #49
0
  def __init__(self, file_entry, codepage='cp1252'):
    """Constructor for the Registry object.

    Args:
      file_entry: A file entry object.
      codepage: The codepage of the Registry hive, used for string
                representation.
    """
    self._pyregf_file = pyregf.file()

    try:
      # TODO: Add a more elegant error handling to this issue. There are some
      # code pages that are not supported by the parent library. However we
      # need to properly set the codepage so the library can properly interpret
      # values in the Registry.
      self._pyregf_file.set_ascii_codepage(codepage)
    except (TypeError, IOError):
      logging.error(
          u'Unable to set the Registry codepage to: {}. Not setting it'.format(
              codepage))

    file_object = file_entry.GetFileObject()
    self._pyregf_file.open_file_object(file_object)
def Main():
  """The main program function.

  Returns:
    A boolean containing True if successful or False if not.
  """
  argument_parser = argparse.ArgumentParser(description=(
      u'Extract the MSIE zone information from a NTUSER.DAT or SYSTEM '
      u'Registry File (REGF).'))

  argument_parser.add_argument(
      u'registry_file', nargs=u'?', action=u'store', metavar=u'SOFTWARE',
      default=None, help=u'path of the SOFTWARE Registry file.')

  options = argument_parser.parse_args()

  if not options.registry_file:
    print(u'Registry file missing.')
    print(u'')
    argument_parser.print_help()
    print(u'')
    return False

  output_mode = 1

  regf_file = pyregf.file()
  regf_file.open(options.registry_file)

  # HKCU

  key_path = (
      u'Software\\Policies\\Microsoft\\Internet Explorer\\Main\\'
      u'FeatureControl\\FEATURE_LOCALMACHINE_LOCKDOWN')
  PrintLockdownKey(regf_file, key_path)

  key_path = (
      u'Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\'
      u'FEATURE_LOCALMACHINE_LOCKDOWN')
  PrintLockdownKey(regf_file, key_path)

  # HKLM

  key_path = (
      u'Policies\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\'
      u'FEATURE_LOCALMACHINE_LOCKDOWN')
  PrintLockdownKey(regf_file, key_path)

  key_path = (
      u'Microsoft\\Internet Explorer\\Main\\FeatureControl\\'
      u'FEATURE_LOCALMACHINE_LOCKDOWN')
  PrintLockdownKey(regf_file, key_path)

  # HKLM Wow64

  key_path = (
      u'Wow6432Node\\Policies\\Microsoft\\Internet Explorer\\Main\\'
      u'FeatureControl\\FEATURE_LOCALMACHINE_LOCKDOWN')
  PrintLockdownKey(regf_file, key_path)

  key_path = (
      u'Wow6432Node\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\'
      u'FEATURE_LOCALMACHINE_LOCKDOWN')
  PrintLockdownKey(regf_file, key_path)

  # TODO: check for value Policies\\Microsoft\\Windows\\CurrentVersion\\
  # Internet Settings\\Security_HKEY_LOCAL_MACHINE_only and its data
  # if not exists or 0, not enabled if 1 only HKLM policy applies

  # HKCU

  key_path = (
      u'Software\\Policies\\Microsoft\\Windows\\CurrentVersion\\'
      u'Internet Settings\\Zones')
  PrintZonesKey(regf_file, key_path, output_mode)

  key_path = (
      u'Software\\Policies\\Microsoft\\Windows\\CurrentVersion\\'
      u'Internet Settings\\Lockdown_Zones')
  PrintZonesKey(regf_file, key_path, output_mode)

  key_path = (
      u'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Zones')
  PrintZonesKey(regf_file, key_path, output_mode)

  key_path = (
      u'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\'
      u'Lockdown_Zones')
  PrintZonesKey(regf_file, key_path, output_mode)

  # HKLM

  key_path = (
      u'Policies\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\'
      u'Zones')
  PrintZonesKey(regf_file, key_path, output_mode)

  key_path = (
      u'Policies\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\'
      u'Lockdown_Zones')
  PrintZonesKey(regf_file, key_path, output_mode)

  key_path = (
      u'Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Zones')
  PrintZonesKey(regf_file, key_path, output_mode)

  key_path = (
      u'Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Lockdown_Zones')
  PrintZonesKey(regf_file, key_path, output_mode)

  # HKLM Wow64

  key_path = (
      u'Wow6432Node\\Policies\\Microsoft\\Windows\\CurrentVersion\\'
      u'Internet Settings\\Zones')
  PrintZonesKey(regf_file, key_path, output_mode)

  key_path = (
      u'Wow6432Node\\Policies\\Microsoft\\Windows\\CurrentVersion\\'
      u'Internet Settings\\Lockdown_Zones')
  PrintZonesKey(regf_file, key_path, output_mode)

  key_path = (
      u'Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\'
      u'Zones')
  PrintZonesKey(regf_file, key_path, output_mode)

  key_path = (
      u'Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\'
      u'Lockdown_Zones'),
  PrintZonesKey(regf_file, key_path, output_mode)

  regf_file.close()

  return True
def parse_registry_file(file_to_parse):

   
   file_object = open(file_to_parse, "rb")
   reg_file = pyregf.file()
   reg_file.open_file_object(file_object)
   #SQLitedb.CreateTempTable(table_name + '_temp', table_columns)
#   key_path = reg_file.get_key_by_path("SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
#   key_path = reg_file.get_key_by_path("SAM\\Domains\\Account\\Users\\Names")
   key_path = reg_file.get_key_by_path("SAM\\Domains\\Account\\Users")
   
   print ("Number of Sub_Keys ==> ", key_path.get_number_of_sub_keys())
   print ("Number of values ==> ", key_path.get_number_of_values())
   
   for i in range (0, key_path.get_number_of_sub_keys() - 1):
      sub_key = key_path.get_sub_key(i)
      user_key = sub_key.get_value_by_name("V")
      if (user_key.get_type() == 3):
          bin_data = user_key.get_data()
          acct_type_number = int(str(struct.unpack_from('<l', bin_data[4:])[0]))
          #print (acct_type_number)
          if acct_type_number in acct_type_dict:
             account_type = acct_type_dict[acct_type_number]
          else:
             account_type = 'Unknown Acct Type'
          pos_1 = int(str(struct.unpack_from('<l', bin_data[4:])[0]))
          pos_3 = int(str(struct.unpack_from('<l', bin_data[12:])[0])) + 204 
          pos_4 = int(str(struct.unpack_from('<l', bin_data[16:])[0]))
          pos_6 = int(str(struct.unpack_from('<l', bin_data[24:])[0])) + 204
          pos_7 = int(str(struct.unpack_from('<l', bin_data[28:])[0]))
          pos_9 = int(str(struct.unpack_from('<l', bin_data[36:])[0])) + 204
          pos_10 = int(str(struct.unpack_from('<l', bin_data[40:])[0]))
          fmt_string_name = ">" + str(pos_4) + "s"		  
          fmt_string_fullname = ">" + str(pos_7) + "s"
          fmt_string_comment = ">" + str(pos_10) + "s"
          user_name = struct.unpack_from(fmt_string_name, bin_data[pos_3:])[0]
          full_name = struct.unpack_from(fmt_string_fullname, bin_data[pos_6:])[0]
          comment = struct.unpack_from(fmt_string_comment, bin_data[pos_9:])[0]
      elif (user_key.get_type() == 1):
          print ("Data of Key ==> ", user_key.get_data_as_string())

      key_path_name = reg_file.get_key_by_path("SAM\\Domains\\Account\\Users\\Names\\" + str(user_name.decode("utf-16")))
      user_name_create_dttm = key_path_name.get_last_written_time()
	  
      user_key = sub_key.get_value_by_name("F")
      if (user_key.get_type() == 3):
          bin_data = user_key.get_data()
          last_login_date = int(str(struct.unpack_from('<q', bin_data[8:])[0])[0:11]) - 11644473600
          pwd_reset_date = int(str(struct.unpack_from('<q', bin_data[24:])[0])[0:11]) - 11644473600
          acct_exp_date = int(str(struct.unpack_from('<q', bin_data[32:])[0])[0:11]) - 11644473600
          pwd_fail_date = int(str(struct.unpack_from('<q', bin_data[40:])[0])[0:11]) - 11644473600
          if last_login_date < 0:
             last_login_date = 0
          if pwd_reset_date < 0:
             pwd_reset_date = 0
          if acct_exp_date < 0:
             acct_exp_date = 0
          if pwd_fail_date < 0:
             pwd_fail_date = 0
          user_rid = struct.unpack_from('<l', bin_data[48:])[0]
          user_acb_flags = int(str(struct.unpack_from('<l', bin_data[56:])[0]))
          user_failed_count = int(str(struct.unpack_from('<h', bin_data[64:])[0]))
          user_login_count = int(str(struct.unpack_from('<h', bin_data[66:])[0]))
      elif (user_key.get_type() == 1):
          print ("Data of Key ==> ", user_key.get_data_as_string())

      user_key = sub_key.get_value_by_name("GivenName")
      if user_key == None:
          given_name = "None"
      else:
          bin_data = user_key.get_data()
          fmt_given_name = ">" + str(len(bin_data)) + "s"		  
          given_name = struct.unpack_from(fmt_given_name, bin_data[0:])[0]

      user_key = sub_key.get_value_by_name("SurName")
      if user_key == None:
         sur_name = "None"
      else:
         bin_data = user_key.get_data()
         fmt_sur_name = ">" + str(len(bin_data)) + "s"		  
         sur_name = struct.unpack_from(fmt_sur_name, bin_data[0:])[0]

      user_key = sub_key.get_value_by_name("InternetUserName")
      if user_key == None:
         internet_name = "None"
      else:
         bin_data = user_key.get_data()
         fmt_internet_name = ">" + str(len(bin_data)) + "s"		  
         internet_name = struct.unpack_from(fmt_internet_name, bin_data[0:])[0]

      user_key = sub_key.get_value_by_name("UserPasswordHint")
      if user_key == None:
         pw_hint = "None"
      else:
         bin_data = user_key.get_data()
         fmt_pw_hint = ">" + str(len(bin_data)) + "s"		  
         pw_hint = struct.unpack_from(fmt_pw_hint, bin_data[0:])[0]

      try:
         # print ("==============================================================")
         # print (" User Name ==> ", str(user_name.decode("utf-16")))
         # print (" Full Name ==> ", str(full_name.decode("utf-16")))
         # print (" Comment ==> ", str(comment.decode("utf-16")))
         # if sur_name == "None" or given_name == "None":
            # print (" Name ==> ", sur_name, " ", given_name)
         # else:
            # print (" Name ==> ", str(sur_name.decode("utf-16")), " ", str(given_name.decode("utf-16")))
         # if internet_name == "None":
            # print (" Internet Username ==> ", internet_name)
         # else:
            # print (" Internet UserName ==> ", str(internet_name.decode("utf-16")))
         # if pw_hint == "None":
            # print (" Password Hint ==> ", pw_hint)
         # else:
            # print (" Password Hint ==> ", str(pw_hint.decode("utf-16")))
         # print (" Account Type ==> ", account_type)
         # print (" Create_dttm ==> ", str(user_name_create_dttm))
         # print (" Last_Login_Date ==> ", datetime.datetime.fromtimestamp(last_login_date).strftime('%Y-%m-%d %H:%M:%S'))
         # print (" Pwd_Reset_Date ==> ", datetime.datetime.fromtimestamp(pwd_reset_date).strftime('%Y-%m-%d %H:%M:%S'))
         # if acct_exp_date == 0 or acct_exp_date == 80589246768:
            # print (" Acct_Exp_Date ==> No Expire Date")
         # else:
            # print (" Acct_Exp_Date ==> ", datetime.datetime.fromtimestamp(acct_exp_date).strftime('%Y-%m-%d %H:%M:%S'))
         # if pwd_fail_date == 0:
            # print (" Pwd_Fail_Date ==> No Fail Date")
         # else:
            # print (" Pwd_Fail_Date ==> ", datetime.datetime.fromtimestamp(pwd_fail_date).strftime('%Y-%m-%d %H:%M:%S'))
         # print (" User_rid ==> ", user_rid)
         # print (" User_ACB_FLAGS ==> ", user_acb_flags)
         # print (" User failed COunt ==> ", user_failed_count)
         # print (" User login count ==> ", user_login_count)
         # for x in acb_flags_dict:
            # if ( x & user_acb_flags):
                # print ("  ----> ", acb_flags_dict[x])
         # print ("==============================================================")
         sql_val_columns = []
         sql_val_columns.append(str(user_name.decode("utf-16")))
         sql_val_columns.append(str(full_name.decode("utf-16")))
         sql_val_columns.append(str(comment.decode("utf-16")))
         if sur_name == "None" or given_name == "None":
            sql_val_columns.append("")
         else:
            sql_val_columns.append(str(sur_name.decode("utf-16")) + " " + str(given_name.decode("utf-16")))
         if internet_name == "None":
            sql_val_columns.append("")
         else:
            sql_val_columns.append(str(internet_name.decode("utf-16")))
         if pw_hint == "None":
            sql_val_columns.append("")
         else:
            sql_val_columns.append(str(pw_hint.decode("utf-16")))
         sql_val_columns.append(account_type)
         sql_val_columns.append(str(user_name_create_dttm))
         sql_val_columns.append(datetime.datetime.fromtimestamp(last_login_date).strftime('%Y-%m-%d %H:%M:%S'))
         sql_val_columns.append(datetime.datetime.fromtimestamp(pwd_reset_date).strftime('%Y-%m-%d %H:%M:%S'))
         if acct_exp_date == 0 or acct_exp_date == 80589246768:
            sql_val_columns.append("")
         else:
            sql_val_columns.append(datetime.datetime.fromtimestamp(acct_exp_date).strftime('%Y-%m-%d %H:%M:%S'))
         if pwd_fail_date == 0:
            sql_val_columns.append("No Fail Date")
         else:
            sql_val_columns.append(datetime.datetime.fromtimestamp(pwd_fail_date).strftime('%Y-%m-%d %H:%M:%S'))
         sql_val_columns.append(user_rid)
         sql_val_columns.append(user_acb_flags)
         sql_val_columns.append(user_failed_count)
         sql_val_columns.append(user_login_count)
         acb_desc = ""
         for x in acb_flags_dict:
            if ( x & user_acb_flags):
                acb_desc = acb_desc + acb_flags_dict[x] + "\n"
         sql_val_columns.append(acb_desc)
         SQLitedb.InsertBindValues(table_name, sql_ins_columns, sql_bind, sql_val_columns)
      except:
         print ("Bad Character")		  
Beispiel #52
0
  def test_close(self):
    """Tests the close function."""
    if not unittest.source:
      return

    regf_file = pyregf.file()
Beispiel #53
0
  def test_signal_abort(self):
    """Tests the signal_abort function."""
    regf_file = pyregf.file()

    regf_file.signal_abort()
def main():
  supported_codepages = [
      "ascii", "cp874", "cp932", "cp936", "cp949", "cp950", "cp1250",
      "cp1251", "cp1252", "cp1253", "cp1254", "cp1255", "cp1256", "cp1257",
      "cp1258"]

  unsupported_codepages = [
      "iso-8859-1", "iso-8859-2", "iso-8859-3", "iso-8859-4", "iso-8859-5",
      "iso-8859-6", "iso-8859-7", "iso-8859-8", "iso-8859-9", "iso-8859-10",
      "iso-8859-11", "iso-8859-13", "iso-8859-14", "iso-8859-15",
      "iso-8859-16", "koi8_r", "koi8_u"]

  regf_file = pyregf.file()

  result = True
  for codepage in supported_codepages:
    print("Testing setting supported ASCII codepage of: {0:s}:\t".format(
        codepage)),
    try:
      regf_file.ascii_codepage = codepage
      result = True
    except:
      result = False

    if not result:
      print("(FAIL)")
      return False
    print("(PASS)")

    print("Testing setting supported ASCII codepage of: {0:s}:\t".format(
        codepage)),
    try:
      regf_file.set_ascii_codepage(codepage)
      result = True
    except:
      result = False

    if not result:
      print("(FAIL)")
      return False
    print("(PASS)")

    for codepage in unsupported_codepages:
      print("Testing setting unsupported ASCII codepage of: {0:s}:\t".format(
          codepage)),

      result = False
      try:
        regf_file.ascii_codepage = codepage
      except RuntimeError as exception:
        expected_message = (
            "{0:s}: unable to determine ASCII codepage.").format(
                "pyregf_file_set_ascii_codepage_from_string")

        if str(exception) == expected_message:
          result = True
      except:
        pass

      if not result:
        print("(FAIL)")
        return False
      print("(PASS)")

      print("Testing setting unsupported ASCII codepage of: {0:s}:\t".format(
          codepage)),

      result = False
      try:
        regf_file.set_ascii_codepage(codepage)
      except RuntimeError as exception:
        expected_message = (
            "{0:s}: unable to determine ASCII codepage.").format(
                "pyregf_file_set_ascii_codepage_from_string")

        if str(exception) == expected_message:
          result = True
      except:
        pass

      if not result:
        print("(FAIL)")
        return False
      print("(PASS)")

  return True