How to use the tuf.roledb function in tuf

To help you get started, we’ve selected a few tuf examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github theupdateframework / tuf / tests / test_slow_retrieval_attack.py View on Github external
def tearDown(self):
    # Modified_TestCase.tearDown() automatically deletes temporary files and
    # directories that may have been created during each test case.
    unittest_toolbox.Modified_TestCase.tearDown(self)
    tuf.roledb.clear_roledb(clear_all=True)
    tuf.keydb.clear_keydb(clear_all=True)
github theupdateframework / tuf / tests / test_sig.py View on Github external
tuf.keydb.add_key(KEYS[1])
    threshold = 2

    roleinfo = tuf.formats.build_dict_conforming_to_schema(
        tuf.formats.ROLE_SCHEMA,
        keyids=[KEYS[0]['keyid'], KEYS[2]['keyid']],
        threshold=threshold)

    tuf.roledb.add_role('Root', roleinfo)

    roleinfo = tuf.formats.build_dict_conforming_to_schema(
        tuf.formats.ROLE_SCHEMA,
        keyids=[KEYS[1]['keyid'], KEYS[2]['keyid']],
        threshold=threshold)

    tuf.roledb.add_role('Release', roleinfo)

    sig_status = tuf.sig.get_signature_status(signable, 'Root')

    self.assertEqual(2, sig_status['threshold'])
    self.assertEqual([KEYS[0]['keyid']], sig_status['good_sigs'])
    self.assertEqual([], sig_status['bad_sigs'])
    self.assertEqual([], sig_status['unknown_sigs'])
    self.assertEqual([KEYS[1]['keyid']], sig_status['untrusted_sigs'])
    self.assertEqual([], sig_status['unknown_signing_schemes'])

    self.assertFalse(tuf.sig.verify(signable, 'Root'))

    self.assertRaises(tuf.exceptions.UnknownRoleError,
                      tuf.sig.get_signature_status, signable, 'unknown_role')

    # Done.  Let's remove the added key(s) from the key database.
github theupdateframework / tuf / tests / test_repository_tool.py View on Github external
# Verify that 'path_hash_prefixes' must exist for hashed bin delegations.

    roleinfo = tuf.roledb.get_roleinfo(self.targets_object.rolename,
        repository_name)

    for delegated_role in roleinfo['delegations']['roles']:
      delegated_role['path_hash_prefixes'] = []

    tuf.roledb.update_roleinfo(self.targets_object.rolename, roleinfo,
        repository_name=repository_name)
    self.assertRaises(securesystemslib.exceptions.Error,
                      self.targets_object.add_target_to_bin, target1_filepath)

    # Verify that an exception is raised if a target does not match with
    # any of the 'path_hash_prefixes'.
    roleinfo = tuf.roledb.get_roleinfo(self.targets_object.rolename,
        repository_name)
    delegated_role = roleinfo['delegations']['roles'][0]
    delegated_role['path_hash_prefixes'] = ['faac']
    delegated_roles = list()
    delegated_roles.append(delegated_role)
    roleinfo['delegations']['roles'] = delegated_roles
    tuf.roledb.update_roleinfo(self.targets_object.rolename, roleinfo,
        repository_name=repository_name)

    self.assertRaises(securesystemslib.exceptions.Error,
                      self.targets_object.add_target_to_bin, target1_filepath)

    # Test for non-existent delegations and hashed bins.
    empty_targets_role = repo_tool.Targets(self.targets_directory, 'empty',
        repository_name=repository_name)
github theupdateframework / tuf / tests / repository_tool.py View on Github external
# types, and that all dict keys are properly named.
    # Raise 'tuf.FormatError' if there is a mismatch.
    tuf.formats.ROLENAME_SCHEMA.check_match(rolename)
    tuf.formats.ANYKEYLIST_SCHEMA.check_match(public_keys)
    tuf.formats.RELPATHS_SCHEMA.check_match(list_of_targets)
    tuf.formats.THRESHOLD_SCHEMA.check_match(threshold)
    tuf.formats.BOOLEAN_SCHEMA.check_match(backtrack)
    
    if restricted_paths is not None:
      tuf.formats.RELPATHS_SCHEMA.check_match(restricted_paths)
    
    if path_hash_prefixes is not None:
      tuf.formats.PATH_HASH_PREFIXES_SCHEMA.check_match(path_hash_prefixes)

    # Check if 'rolename' is not already a delegation.
    if tuf.roledb.role_exists(rolename):
      raise tuf.Error(repr(rolename) + ' already delegated.')

    # Keep track of the valid keyids (added to the new Targets object) and
    # their keydicts (added to this Targets delegations). 
    keyids = [] 
    keydict = {}

    # Add all the keys of 'public_keys' to tuf.keydb.
    for key in public_keys:
      keyid = key['keyid']
      key_metadata_format = tuf.keys.format_keyval_to_metadata(key['keytype'],
                                                               key['keyval'])
      # Update 'keyids' and 'keydict'.
      new_keydict = {keyid: key_metadata_format}
      keydict.update(new_keydict)
      keyids.append(keyid)
github theupdateframework / tuf / tuf / developer_tool.py View on Github external
stored in a libtuf.Repository object.

  
    A tuf.developer_tool.Project object.
  """

  # Does 'repository_directory' have the correct format?
  # Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch.
  securesystemslib.formats.PATH_SCHEMA.check_match(project_directory)
  securesystemslib.formats.NAME_SCHEMA.check_match(repository_name)

  # Do the same for the prefix
  securesystemslib.formats.PATH_SCHEMA.check_match(prefix)

  # Clear the role and key databases since we are loading in a new project.
  tuf.roledb.clear_roledb(clear_all=True)
  tuf.keydb.clear_keydb(clear_all=True)

  # Locate metadata filepaths and targets filepath.
  project_directory = os.path.abspath(project_directory)

  # Load the cfg file and the project.
  config_filename = os.path.join(project_directory, PROJECT_FILENAME)

  project_configuration = securesystemslib.util.load_json_file(config_filename)
  tuf.formats.PROJECT_CFG_SCHEMA.check_match(project_configuration)

  targets_directory = os.path.join(project_directory,
      project_configuration['targets_location'])

  if project_configuration['layout_type'] == 'flat':
    project_directory, junk = os.path.split(project_directory)
github theupdateframework / tuf / tuf / repository_tool.py View on Github external
'keyids': roleinfo['keyids'],
                'threshold': roleinfo['threshold'],
                'terminating': terminating,
                'paths': list(roleinfo['paths'].keys())}

    if paths:
      roleinfo['paths'] = paths

    if path_hash_prefixes:
      roleinfo['path_hash_prefixes'] = path_hash_prefixes
      # A role in a delegations must list either 'path_hash_prefixes'
      # or 'paths'.
      del roleinfo['paths']

    current_roleinfo['delegations']['roles'].append(roleinfo)
    tuf.roledb.update_roleinfo(self.rolename, current_roleinfo,
        repository_name=self._repository_name)

    # Update the public keys of 'new_targets_object'.
    for key in public_keys:
      new_targets_object.add_verification_key(key)

    # Add the new delegation to the top-level 'targets' role object (i.e.,
    # 'repository.targets()').  For example, 'django', which was delegated by
    # repository.target('claimed'), is added to 'repository.targets('django')).

    # Add 'new_targets_object' to the 'targets' role object (this object).
    if self.rolename == 'targets':
      self.add_delegated_role(rolename, new_targets_object)

    else:
      self._parent_targets_object.add_delegated_role(rolename, new_targets_object)
github theupdateframework / tuf / tuf / pushtools / receivetools / receive.py View on Github external
# is needed to authorize the 'targets' metadata file.
  root_metadatapath = os.path.join(metadata_directory, 'root.txt')
  root_signable = tuf.util.load_json_file(root_metadatapath)
  
  # Ensure 'root_signable' is properly formatted.
  try:
    tuf.formats.check_signable_object_format(root_signable)
  except tuf.FormatError, e:
    raise tuf.Error('The repository contains an invalid "root.txt".')
 
  # Extract the metadata object and load the key and role databases.
  # The keys and roles are needed to verify the signatures of the
  # metadata files.
  root_metadata = root_signable['signed']
  tuf.keydb.create_keydb_from_root_metadata(root_metadata)
  tuf.roledb.create_roledb_from_root_metadata(root_metadata)

  # Determine the name of the targets metadata file that was pushed.
  # The required 'info' file should list the metadata file that was
  # pushed by the developer.  Only 'targets.txt' currently supported
  # (i.e., no delegated roles are accepted).
  new_targets_metadata_file = None
  try:
    file_object = open(os.path.join(push_temporary_directory, 'info'), 'r')
  except IOError, e:
    raise tuf.Error('Unable to open push "info" file: '+str(e))
  try:
    # Inspect each line of the 'info' file, searching for the line that
    # specifies the targets metadata file.  Raise an exception if all
    # the lines are processed without finding the 'metadata=' line.
    for line in file_object:
      # Search 'info' for a 'metadata=.../targets.txt' line.
github theupdateframework / tuf / tuf / client / updater.py View on Github external
None.
    """

    # The root metadata role is never deleted without a replacement.
    if metadata_role == 'root':
      return

    # Get rid of the current metadata file.
    self._move_current_to_previous(metadata_role)

    # Remove knowledge of the role.
    if metadata_role in self.metadata['current']:
      del self.metadata['current'][metadata_role]
    tuf.roledb.remove_role(metadata_role, self.repository_name)
github theupdateframework / tuf / tuf / repository_lib.py View on Github external
# This is not a recognized key.  Raise an exception.
        else:
          raise securesystemslib.exceptions.Error('Unsupported keytype:'
          ' ' + key['keytype'])

      # Do we have a duplicate?
      if keyid in keyids:
        raise securesystemslib.exceptions.Error('Same keyid listed twice:'
          ' ' + keyid)

      # Add the loaded keyid for the role being processed.
      keyids.append(keyid)

    # Generate and store the role data belonging to the processed role.
    role_threshold = tuf.roledb.get_role_threshold(rolename, repository_name)
    role_metadata = tuf.formats.make_role_metadata(keyids, role_threshold)
    roledict[rolename] = role_metadata

  # Generate the root metadata object.
  root_metadata = tuf.formats.RootFile.make_metadata(version, expiration_date,
      keydict, roledict, consistent_snapshot)

  return root_metadata
github theupdateframework / tuf / tuf / client / updater.py View on Github external
#   - Usage of this function or a future successor makes sense when the
    #     role of interest is Targets, since we always know exactly how to
    #     validate Targets (We use root.).
    #   - Until it's removed (hopefully soon), we'll try to provide what it has
    #     always provided.  To do this, we fetch and "validate" all delegated
    #     roles listed by snapshot.  For delegated roles only, the order of the
    #     validation impacts the security of the validation -- the most-
    #     recently-validated role delegating to a role you are currently
    #     validating determines the expected keyids and threshold of the role
    #     you are currently validating.  That is NOT GOOD.  Again, please switch
    #     to get_one_valid_targetinfo, which is well-defined and secure.
    if rolename != 'targets':
      self._refresh_targets_metadata(refresh_all_delegated_roles=True)


    if not tuf.roledb.role_exists(rolename, self.repository_name):
      raise tuf.exceptions.UnknownRoleError(rolename)

    return self._targets_of_role(rolename, skip_refresh=True)