Beispiel #1
0
  def test__load_top_level_metadata(self):
    repository_name = 'test_repository'

    temporary_directory = tempfile.mkdtemp(dir=self.temporary_directory)
    repository_directory = os.path.join(temporary_directory, 'repository')
    metadata_directory = os.path.join(repository_directory,
        repo_lib.METADATA_STAGED_DIRECTORY_NAME)
    targets_directory = os.path.join(repository_directory,
        repo_lib.TARGETS_DIRECTORY_NAME)
    shutil.copytree(os.path.join('repository_data', 'repository', 'metadata'),
        metadata_directory)
    shutil.copytree(os.path.join('repository_data', 'repository', 'targets'),
        targets_directory)

    # Add a duplicate signature to the Root file for testing purposes).
    root_file = os.path.join(metadata_directory, 'root.json')
    signable = securesystemslib.util.load_json_file(os.path.join(metadata_directory, 'root.json'))
    signable['signatures'].append(signable['signatures'][0])

    repo_lib.write_metadata_file(signable, root_file, 8, False)

    # Attempt to load a repository that contains a compressed Root file.
    repository = repo_tool.create_new_repository(repository_directory, repository_name)
    filenames = repo_lib.get_metadata_filenames(metadata_directory)
    repo_lib._load_top_level_metadata(repository, filenames, repository_name)

    filenames = repo_lib.get_metadata_filenames(metadata_directory)
    repository = repo_tool.create_new_repository(repository_directory, repository_name)
    repo_lib._load_top_level_metadata(repository, filenames, repository_name)

    # Partially write all top-level roles (we increase the threshold of each
    # top-level role so that they are flagged as partially written.
    repository.root.threshold = repository.root.threshold + 1
    repository.snapshot.threshold = repository.snapshot.threshold + 1
    repository.targets.threshold = repository.targets.threshold + 1
    repository.timestamp.threshold = repository.timestamp.threshold + 1
    repository.write('root', )
    repository.write('snapshot')
    repository.write('targets')
    repository.write('timestamp')

    repo_lib._load_top_level_metadata(repository, filenames, repository_name)

    # Attempt to load a repository with missing top-level metadata.
    for role_file in os.listdir(metadata_directory):
      if role_file.endswith('.json') and not role_file.startswith('root'):
        role_filename = os.path.join(metadata_directory, role_file)
        os.remove(role_filename)
    repo_lib._load_top_level_metadata(repository, filenames, repository_name)

    # Remove the required Root file and verify that an exception is raised.
    os.remove(os.path.join(metadata_directory, 'root.json'))
    self.assertRaises(tuf.exceptions.RepositoryError,
        repo_lib._load_top_level_metadata, repository, filenames,
        repository_name)
Beispiel #2
0
    def build(self, root_pub_path, targets_pub_path, timestamp_pub_path):
        """
        Create or update the repo

        :param root_pub_path: path where the public root key lives
        :type root_pub_path: str
        :param targets_pub_path: path where the public targets key lives
        :type targets_pub_path: str
        :param timestamp_pub_path: path where the public timestamp key lives
        :type timestamp_pub_path: str
        """
        if exists(self._repo_path) and listdir(self._repo_path) != []:
            repository = load_repository(self._repo_path)
        else:
            repository = create_new_repository(self._repo_path)

        pub_root_key = import_rsa_publickey_from_file(root_pub_path)
        repository.root.add_verification_key(pub_root_key)
        repository.root.load_signing_key(self._key)
        repository.root.expiration = (datetime.datetime.now() +
                                      datetime.timedelta(days=EXPIRATION_DAYS))

        pub_target_key = import_rsa_publickey_from_file(targets_pub_path)
        repository.targets.add_verification_key(pub_target_key)
        repository.snapshot.add_verification_key(pub_target_key)
        repository.targets.compressions = ["gz"]
        repository.snapshot.compressions = ["gz"]

        pub_timestamp_key = import_rsa_publickey_from_file(timestamp_pub_path)
        repository.timestamp.add_verification_key(pub_timestamp_key)

        try:
            repository.write_partial()
        except:
            pass
Beispiel #3
0
    def build(self, root_pub_path, targets_pub_path, timestamp_pub_path):
        """
        Create a new repo

        :param root_pub_path: path where the public root key lives
        :type root_pub_path: str
        :param targets_pub_path: path where the public targets key lives
        :type targets_pub_path: str
        :param timestamp_pub_path: path where the public timestamp key lives
        :type timestamp_pub_path: str
        """
        repository = create_new_repository(self._repo_path)

        pub_root_key = import_rsa_publickey_from_file(root_pub_path)
        repository.root.add_verification_key(pub_root_key)
        repository.root.load_signing_key(self._key)

        pub_target_key = import_rsa_publickey_from_file(targets_pub_path)
        repository.targets.add_verification_key(pub_target_key)
        repository.snapshot.add_verification_key(pub_target_key)
        repository.targets.compressions = ["gz"]
        repository.snapshot.compressions = ["gz"]

        pub_timestamp_key = import_rsa_publickey_from_file(timestamp_pub_path)
        repository.timestamp.add_verification_key(pub_timestamp_key)

        repository.write_partial()
Beispiel #4
0
    def create_director_repo_for_vehicle(self, vin):
        """
    Creates a separate repository object for a given vehicle identifier.
    Each uses the same keys.
    Ideally, each would use the same root.json file, but that will have to
    wait until TUF Augmentation Proposal 5 (when the hash of root.json ceases
    to be included in snapshot.json).

    The name of each repository is the VIN string.

    If the repository already exists, it is overwritten.

    Usage:

      d = uptane.services.director.Director(...)
      d.create_director_repo_for_vehicle(vin)
      d.add_target_for_ecu(vin, ecu, target_filepath)

    These repository objects can be manipulated as described in TUF
    documentation; for example, to produce metadata files afterwards for that
    vehicle:
      d.vehicle_repositories[vin].write()


    # TODO: This may be outside of the scope of the reference implementation,
    # and best to put in the demo code. It's not clear what should live in the
    # reference implementation itself for this....

    """

        uptane.formats.VIN_SCHEMA.check_match(vin)

        # Repository Tool expects to use the current directory.
        # Figure out if this is impactful and needs to be changed.
        last_dir = os.getcwd()
        os.chdir(
            self.director_repos_dir)  # TODO: Is messing with cwd a bad idea?

        # Generates absolute path for a subdirectory with name equal to vin,
        # in the current directory, making (relatively) sure that there isn't
        # anything suspect like "../" in the VIN.
        # Then I strip the common prefix back off the absolute path to get a
        # relative path and keep the guarantees.
        # TODO: Clumsy and hacky; fix.
        vin = uptane.common.scrub_filename(vin, self.director_repos_dir)
        vin = os.path.relpath(vin, self.director_repos_dir)

        self.vehicle_repositories[vin] = this_repo = rt.create_new_repository(
            vin, repository_name=vin)

        this_repo.root.add_verification_key(self.key_dirroot_pub)
        this_repo.timestamp.add_verification_key(self.key_dirtime_pub)
        this_repo.snapshot.add_verification_key(self.key_dirsnap_pub)
        this_repo.targets.add_verification_key(self.key_dirtarg_pub)
        this_repo.root.load_signing_key(self.key_dirroot_pri)
        this_repo.timestamp.load_signing_key(self.key_dirtime_pri)
        this_repo.snapshot.load_signing_key(self.key_dirsnap_pri)
        this_repo.targets.load_signing_key(self.key_dirtarg_pri)

        os.chdir(last_dir)
Beispiel #5
0
    def create_metadata(self,
                        root_key_password=None,
                        targets_key_password=None,
                        snapshot_key_password=None,
                        timestamp_key_password=None):
        """
        Create and sign the TUF metadata for the repository.

        You only need to call this once for each repository, and the
        repository's root and metadata private keys must be available.

        :param root_key_password: Password to use for decrypting the TUF root private key. You'll be prompted for one if you don't supply it.
        :type password: str

        :param targets_key_password: Password to use for decrypting the TUF targets private key. You'll be prompted for one if you don't supply it.
        :type password: str

        :param snapshot_key_password: Password to use for decrypting the TUF snapshot private key. You'll be prompted for one if you don't supply it.
        :type password: str

        :param timestamp_key_password: Password to use for decrypting the TUF timestamp private key. You'll be prompted for one if you don't supply it.
        :type password: str
        """
        from tuf.repository_tool import create_new_repository
        # Create repository object and add metadata to it
        self._add_metadata(create_new_repository(self._master_repo_dir),
                           root_key_password,
                           targets_key_password,
                           snapshot_key_password,
                           timestamp_key_password)
Beispiel #6
0
    def __init__(self):
        # Initialize fixtures/ if missing and make it the working directory.
        fixtures_dir = os.path.join(os.path.dirname(
            os.path.realpath(__file__)), 'fixtures')
        if not os.path.exists(fixtures_dir):
            os.mkdir(fixtures_dir)

        self.my_fixtures_dir = os.path.join(fixtures_dir, type(self).__name__)
        print('Building fixtures at {}'.format(self.my_fixtures_dir))

        # Clean up previous fixtures.
        print('Deleting {}'.format(self.my_fixtures_dir))
        if os.path.isdir(self.my_fixtures_dir):
            shutil.rmtree(self.my_fixtures_dir + '/')

        os.mkdir(self.my_fixtures_dir)
        # os.chdir(self.my_fixtures_dir)

        # Create a basic TUF repository.
        self.tufrepo_dir = os.path.join(self.my_fixtures_dir, 'tufrepo')
        print('Initializing repo at {}'.format(self.tufrepo_dir))
        self.repository = rt.create_new_repository(
            self.tufrepo_dir, type(self).__name__)
        self.repository.status()
        self._initialize_basic_roles()
        # self.repository.status()
        print('Initialized repo at {}'.format(self.tufrepo_dir))
Beispiel #7
0
    def create_metadata(self,
                        root_key_password=None,
                        targets_key_password=None,
                        snapshot_key_password=None,
                        timestamp_key_password=None):
        """
        Create and sign the TUF metadata for the repository.

        You only need to call this once for each repository, and the
        repository's root and metadata private keys must be available.

        :param root_key_password: Password to use for decrypting the TUF root private key. You'll be prompted for one if you don't supply it.
        :type password: str

        :param targets_key_password: Password to use for decrypting the TUF targets private key. You'll be prompted for one if you don't supply it.
        :type password: str

        :param snapshot_key_password: Password to use for decrypting the TUF snapshot private key. You'll be prompted for one if you don't supply it.
        :type password: str

        :param timestamp_key_password: Password to use for decrypting the TUF timestamp private key. You'll be prompted for one if you don't supply it.
        :type password: str
        """
        from tuf.repository_tool import create_new_repository
        # Create repository object and add metadata to it
        self._add_metadata(create_new_repository(self._master_repo_dir),
                           root_key_password, targets_key_password,
                           snapshot_key_password, timestamp_key_password)
Beispiel #8
0
def init_repo(parsed_arguments):
    """
  Create a repo at the specified location in --path (the current working
  directory, by default).  Each top-level role has one key, if --bare' is False
  (default).
  """

    repo_path = os.path.join(parsed_arguments.path, REPO_DIR)
    repository = repo_tool.create_new_repository(repo_path)

    if not parsed_arguments.bare:
        set_top_level_keys(repository, parsed_arguments)
        repository.writeall(consistent_snapshot=parsed_arguments.consistent)

    else:
        repository.write('root',
                         consistent_snapshot=parsed_arguments.consistent)
        repository.write('targets',
                         consistent_snapshot=parsed_arguments.consistent)
        repository.write('snapshot',
                         consistent_snapshot=parsed_arguments.consistent)
        repository.write('timestamp',
                         consistent_snapshot=parsed_arguments.consistent)

    write_to_live_repo(parsed_arguments)

    # Create the client files.  The client directory contains the required
    # directory structure and metadata files for clients to successfully perform
    # an update.
    repo_tool.create_tuf_client_directory(
        os.path.join(parsed_arguments.path, REPO_DIR),
        os.path.join(parsed_arguments.path, CLIENT_DIR, REPO_DIR))
Beispiel #9
0
def init_repo(trustdir, repo_name):
    repo_path = trustdir.joinpath(repo_name)
    keystore_dir = create_subdir(repo_path, KEYSTORE_DIR)
    # This is where the repository gets written to by default.
    metadata_staged_dir = create_subdir(repo_path, METADATA_STAGED_DIR)
    metadata_dir = create_subdir(repo_path, METADATA_DIR)

    repo_obj = create_new_repository(str(repo_path))
    create_and_set_keys(keystore_dir, repo_obj)

    write_repo(repo_obj, metadata_staged_dir, metadata_dir)
Beispiel #10
0
    def ready(self):
        settings.REPO=rt.create_new_repository(settings.IMAGE_REPO)

        keys_pri = {}
        keys_pub = {}
        for role in ['root', 'timestamp', 'snapshot']:
            keys_pri[role] = rt.import_ed25519_privatekey_from_file(os.path.join(settings.KEY_PATH, 'director' + role),password='******')
            keys_pub[role] = rt.import_ed25519_publickey_from_file(os.path.join(settings.KEY_PATH, 'director' + role + '.pub'))

        # Because the demo's Director targets key is not named correctly....
        # TODO: Remove this and add 'targets' back to the role list above when
        #       the key is correctly renamed.
        keys_pri['targets'] = rt.import_ed25519_privatekey_from_file(os.path.join(settings.KEY_PATH, 'director'),password='******')
        keys_pub['targets'] = rt.import_ed25519_publickey_from_file(os.path.join(settings.KEY_PATH, 'director.pub'))
        
        settings.REPO.root.add_verification_key(keys_pub['root'])
        settings.REPO.timestamp.add_verification_key(keys_pub['timestamp'])
        settings.REPO.snapshot.add_verification_key(keys_pub['snapshot'])
        settings.REPO.targets.add_verification_key(keys_pub['targets'])
        settings.REPO.root.load_signing_key(keys_pri['root'])
        settings.REPO.timestamp.load_signing_key(keys_pri['timestamp'])
        settings.REPO.snapshot.load_signing_key(keys_pri['snapshot'])
        settings.REPO.targets.load_signing_key(keys_pri['targets'])


        repo_dir=settings.IMAGE_REPO
        targets_json=os.path.join(repo_dir,'metadata','targets.json')
        if os.path.exists(targets_json):
            f=open(targets_json)
            targets_meta=json.loads(f.read())
            f.close()
            targets=targets_meta['signed']['targets']
            for key in targets.keys():
                filepath=os.path.join(repo_dir,'targets',key[1:])
                if os.path.exists(filepath):
                    settings.REPO.targets.add_target(filepath)


        settings.REPO.mark_dirty(['timestamp', 'snapshot'])
        settings.REPO.write() # will be writeall() in most recent TUF branch

        # Move staged metadata (from the write above) to live metadata directory.

        if os.path.exists(os.path.join(settings.IMAGE_REPO, 'metadata')):
            shutil.rmtree(os.path.join(settings.IMAGE_REPO, 'metadata'))

        shutil.copytree(
            os.path.join(settings.IMAGE_REPO, 'metadata.staged'),
            os.path.join(settings.IMAGE_REPO, 'metadata'))
def create_repository(keys):
    repository = rtool.create_new_repository(REPO)

    repository.root.add_verification_key(keys['tuf']['root'])
    repository.root.load_signing_key(keys['tuf']['root'])
    repository.timestamp.add_verification_key(keys['tuf']['timestamp'])
    repository.timestamp.load_signing_key(keys['tuf']['timestamp'])
    repository.snapshot.add_verification_key(keys['tuf']['snapshot'])
    repository.snapshot.load_signing_key(keys['tuf']['snapshot'])
    repository.targets.add_verification_key(keys['tuf']['targets'])
    repository.targets.load_signing_key(keys['tuf']['targets'])

    os.mkdir('repository/targets/layouts')
    repository.targets.delegate('layouts', [keys['tuf']['layouts']], ['layouts/*'])
    repository.targets('layouts').load_signing_key(keys['tuf']['layouts'])

    os.mkdir('repository/targets/packages')
    repository.targets.delegate('packages', [keys['tuf']['packages']], ['packages/*'])
    repository.targets('packages').load_signing_key(keys['tuf']['packages'])
    repository.writeall()
    return repository
Beispiel #12
0
def generate_fixture():
    dir = os.getcwd()

    # Create a basic TUF repository.
    print('Initializing TUF repository in', dir)
    repository = rt.create_new_repository(dir)

    # Import key pairs for all required roles.
    (root_public, root_private) = import_keypair('root')
    (targets_public, targets_private) = import_keypair('targets')
    (snapshot_public, snapshot_private) = import_keypair('snapshot')
    (timestamp_public, timestamp_private) = import_keypair('timestamp')

    # Assign the keys to their roles.
    repository.root.add_verification_key(root_public)
    repository.root.load_signing_key(root_private)
    repository.targets.add_verification_key(targets_public)
    repository.targets.load_signing_key(targets_private)
    repository.snapshot.add_verification_key(snapshot_public)
    repository.snapshot.load_signing_key(snapshot_private)
    repository.timestamp.add_verification_key(timestamp_public)
    repository.timestamp.load_signing_key(timestamp_private)

    repository.mark_dirty(['root', 'snapshot', 'targets', 'timestamp'])

    # Add more targets here as needed.
    repository.targets.add_targets([
        'packages.json', 'files/packages/8/p2/drupal/token.json',
        'drupal/token/1.9.0.0'
    ])

    # Write and publish the repository.
    repository.mark_dirty(['snapshot', 'targets', 'timestamp'])
    repository.status()
    repository.writeall(consistent_snapshot=True)

    staging_dir = path.join(dir, 'metadata.staged')
    live_dir = path.join(dir, 'metadata')
    os.rename(staging_dir, live_dir)
Beispiel #13
0
def create_repo(repo_dir):
    os.mkdir(repo_dir)
    os.chdir(repo_dir)
    (public_root_key, private_root_key) = write_and_import_keypair('root')
    (public_targets_key, private_targets_key) = write_and_import_keypair('targets')
    (public_snapshots_key, private_snapshots_key) = write_and_import_keypair('snapshot')
    (public_timestamps_key, private_timestamps_key) = write_and_import_keypair('timestamp')
    # Bootstrap Repository
    repository = rt.create_new_repository("tufrepo", repo_dir)
    repository.root.add_verification_key(public_root_key)
    repository.root.load_signing_key(private_root_key)
    # Add additional roles
    repository.targets.add_verification_key(public_targets_key)
    repository.targets.load_signing_key(private_targets_key)
    repository.snapshot.add_verification_key(public_snapshots_key)
    repository.snapshot.load_signing_key(private_snapshots_key)
    repository.timestamp.add_verification_key(public_timestamps_key)
    repository.timestamp.load_signing_key(private_timestamps_key)
    repository.status()
    # Make it so (consistently)
    repository.mark_dirty(['root', 'snapshot', 'targets', 'timestamp'])
    repository.writeall(consistent_snapshot=True)
Beispiel #14
0
    def create_director_repo_for_vehicle(self, vin):
        """
    """
        WORKING_DIR = os.getcwd()
        MAIN_REPO_DIR = os.path.join(WORKING_DIR, 'repomain')
        DIRECTOR_REPO_DIR = os.path.join(WORKING_DIR, 'repodirector')
        TARGETS_DIR = os.path.join(MAIN_REPO_DIR, 'targets')
        # DIRECTOR_REPO_HOST = 'http://localhost'
        # DIRECTOR_REPO_PORT = 30301

        vin = inventorydb.scrub_filename(vin, WORKING_DIR)

        self.repositories[vin] = rt.create_new_repository('repodirector_' +
                                                          'vin')

        repodirector.root.add_verification_key(self.key_dirroot_pub)
        repodirector.timestamp.add_verification_key(self.key_dirtime_pub)
        repodirector.snapshot.add_verification_key(self.key_dirsnap_pub)
        repodirector.targets.add_verification_key(self.key_dirtarg_pub)
        repodirector.root.load_signing_key(self.key_dirroot_pri)
        repodirector.timestamp.load_signing_key(self.key_dirtime_pri)
        repodirector.snapshot.load_signing_key(self.key_dirsnap_pri)
        repodirector.targets.load_signing_key(self.key_dirtarg_pri)
  def test_root_role_versioning(self):
    # Test root role versioning
    #
    # 1. Import public and private keys.
    # 2. Add verification keys.
    # 3. Load signing keys.
    # 4. Add target files.
    # 5. Perform delegation.
    # 6. writeall()
    #
    # Copy the target files from 'tuf/tests/repository_data' so that writeall()
    # has target fileinfo to include in metadata.
    temporary_directory = tempfile.mkdtemp(dir=self.temporary_directory)
    targets_directory = os.path.join(temporary_directory, 'repository',
                                     repo_tool.TARGETS_DIRECTORY_NAME)
    original_targets_directory = os.path.join('repository_data',
                                              'repository', 'targets')
    shutil.copytree(original_targets_directory, targets_directory)

    # In this case, create_new_repository() creates the 'repository/'
    # sub-directory in 'temporary_directory' if it does not exist.
    repository_directory = os.path.join(temporary_directory, 'repository')
    metadata_directory = os.path.join(repository_directory,
                                      repo_tool.METADATA_STAGED_DIRECTORY_NAME)
    repository = repo_tool.create_new_repository(repository_directory)




    # (1) Load the public and private keys of the top-level roles, and one
    # delegated role.
    keystore_directory = os.path.join('repository_data', 'keystore')

    # Load the public keys.
    root_pubkey_path = os.path.join(keystore_directory, 'root_key.pub')
    targets_pubkey_path = os.path.join(keystore_directory, 'targets_key.pub')
    snapshot_pubkey_path = os.path.join(keystore_directory, 'snapshot_key.pub')
    timestamp_pubkey_path = os.path.join(keystore_directory, 'timestamp_key.pub')
    role1_pubkey_path = os.path.join(keystore_directory, 'delegation_key.pub')

    root_pubkey = repo_tool.import_rsa_publickey_from_file(root_pubkey_path)
    targets_pubkey = repo_tool.import_ed25519_publickey_from_file(targets_pubkey_path)
    snapshot_pubkey = \
      repo_tool.import_ed25519_publickey_from_file(snapshot_pubkey_path)
    timestamp_pubkey = \
      repo_tool.import_ed25519_publickey_from_file(timestamp_pubkey_path)
    role1_pubkey = repo_tool.import_ed25519_publickey_from_file(role1_pubkey_path)

    # Load the private keys.
    root_privkey_path = os.path.join(keystore_directory, 'root_key')
    targets_privkey_path = os.path.join(keystore_directory, 'targets_key')
    snapshot_privkey_path = os.path.join(keystore_directory, 'snapshot_key')
    timestamp_privkey_path = os.path.join(keystore_directory, 'timestamp_key')
    role1_privkey_path = os.path.join(keystore_directory, 'delegation_key')

    root_privkey = \
      repo_tool.import_rsa_privatekey_from_file(root_privkey_path, 'password')
    targets_privkey = \
      repo_tool.import_ed25519_privatekey_from_file(targets_privkey_path, 'password')
    snapshot_privkey = \
      repo_tool.import_ed25519_privatekey_from_file(snapshot_privkey_path,
                                                'password')
    timestamp_privkey = \
      repo_tool.import_ed25519_privatekey_from_file(timestamp_privkey_path,
                                                'password')
    role1_privkey = \
      repo_tool.import_ed25519_privatekey_from_file(role1_privkey_path,
                                                'password')


    # (2) Add top-level verification keys.
    repository.root.add_verification_key(root_pubkey)
    repository.targets.add_verification_key(targets_pubkey)
    repository.snapshot.add_verification_key(snapshot_pubkey)
    repository.timestamp.add_verification_key(timestamp_pubkey)


    # (3) Load top-level signing keys.
    repository.root.load_signing_key(root_privkey)
    repository.targets.load_signing_key(targets_privkey)
    repository.snapshot.load_signing_key(snapshot_privkey)
    repository.timestamp.load_signing_key(timestamp_privkey)

    # (4) Add target files.
    target1 = 'file1.txt'
    target2 = 'file2.txt'
    target3 = 'file3.txt'
    repository.targets.add_target(target1)
    repository.targets.add_target(target2)


    # (5) Perform delegation.
    repository.targets.delegate('role1', [role1_pubkey], [target3])
    repository.targets('role1').load_signing_key(role1_privkey)

    # (6) Write repository.
    repository.writeall()

    self.assertTrue(os.path.exists(os.path.join(metadata_directory, 'root.json')))
    self.assertTrue(os.path.exists(os.path.join(metadata_directory, '1.root.json')))


    # Verify that the expected metadata is written.
    root_filepath = os.path.join(metadata_directory, 'root.json')
    root_1_filepath = os.path.join(metadata_directory, '1.root.json')
    root_2_filepath = os.path.join(metadata_directory, '2.root.json')
    old_root_signable = securesystemslib.util.load_json_file(root_filepath)
    root_1_signable = securesystemslib.util.load_json_file(root_1_filepath)

    # Make a change to the root keys
    repository.root.add_verification_key(targets_pubkey)
    repository.root.load_signing_key(targets_privkey)
    repository.root.threshold = 2
    repository.writeall()

    new_root_signable = securesystemslib.util.load_json_file(root_filepath)
    root_2_signable = securesystemslib.util.load_json_file(root_2_filepath)

    for role_signable in [old_root_signable, new_root_signable, root_1_signable, root_2_signable]:
      # Raise 'securesystemslib.exceptions.FormatError' if 'role_signable' is an
      # invalid signable.
      tuf.formats.check_signable_object_format(role_signable)

    # Verify contents of versioned roots
    self.assertEqual(old_root_signable, root_1_signable)
    self.assertEqual(new_root_signable, root_2_signable)

    self.assertEqual(root_1_signable['signed']['version'], 1)
    self.assertEqual(root_2_signable['signed']['version'], 2)

    repository.root.remove_verification_key(root_pubkey)
    repository.root.unload_signing_key(root_privkey)
    repository.root.threshold = 2

    # Errors, not enough signing keys to satisfy old threshold
    self.assertRaises(tuf.exceptions.UnsignedMetadataError, repository.writeall)

    # No error, write() ignore's root's threshold and allows it to be written
    # to disk partially signed.
    repository.write('root')
Beispiel #16
0
def clean_slate(use_new_keys=False,
                additional_root_key=False,
                additional_targets_key=False):

    global repo
    global director_service_instance

    # ----------------
    # REPOSITORY SETUP:
    # ----------------

    # Create repo at './repodirector'

    repo = rt.create_new_repository(demo.DIRECTOR_REPO_NAME)

    # Create keys and/or load keys into memory.

    if use_new_keys:
        demo.generate_key('directorroot')
        demo.generate_key('directortimestamp')
        demo.generate_key('directorsnapshot')
        demo.generate_key('director')  # targets
        if additional_root_key:
            demo.generate_key('directorroot2')
        if additional_targets_key:
            demo.generate_key('director2')

    key_dirroot_pub = demo.import_public_key('directorroot')
    key_dirroot_pri = demo.import_private_key('directorroot')
    key_dirtime_pub = demo.import_public_key('directortimestamp')
    key_dirtime_pri = demo.import_private_key('directortimestamp')
    key_dirsnap_pub = demo.import_public_key('directorsnapshot')
    key_dirsnap_pri = demo.import_private_key('directorsnapshot')
    key_dirtarg_pub = demo.import_public_key('director')
    key_dirtarg_pri = demo.import_private_key('director')
    key_dirroot2_pub = None
    key_dirroot2_pri = None
    if additional_root_key:
        key_dirroot2_pub = demo.import_public_key('directorroot2')
        key_dirroot2_pri = demo.import_private_key('directorroot2')
    if additional_targets_key:
        key_dirtarg2_pub = demo.import_public_key('director2')
        key_dirtarg2_pri = demo.import_private_key('director2')

    # Add top level keys to the main repository.

    repo.root.add_verification_key(key_dirroot_pub)
    repo.timestamp.add_verification_key(key_dirtime_pub)
    repo.snapshot.add_verification_key(key_dirsnap_pub)
    repo.targets.add_verification_key(key_dirtarg_pub)
    repo.root.load_signing_key(key_dirroot_pri)
    repo.timestamp.load_signing_key(key_dirtime_pri)
    repo.snapshot.load_signing_key(key_dirsnap_pri)
    repo.targets.load_signing_key(key_dirtarg_pri)
    if additional_targets_key:
        repo.targets.add_verification_key(key_dirtarg2_pub)
        repo.targets.load_signing_key(key_dirtarg2_pri)
    if additional_root_key:
        repo.root.add_verification_key(key_dirroot2_pub)
        repo.root.load_signing_key(key_dirroot2_pri)

    # Add target to director.
    # FOR NOW, we symlink the targets files on the director.
    # In the future, we probably have to have the repository tools add a function
    # like targets.add_target_from_metadata that doesn't require an actual target
    # file to exist, but instead provides metadata on some hypothetical file that
    # the director may not physically hold.
    if os.path.exists(
            os.path.join(demo.DIRECTOR_REPO_TARGETS_DIR,
                         'infotainment_firmware.txt')):
        os.remove(
            os.path.join(demo.DIRECTOR_REPO_TARGETS_DIR,
                         'infotainment_firmware.txt'))

    os.symlink(
        os.path.join(demo.MAIN_REPO_TARGETS_DIR, 'infotainment_firmware.txt'),
        os.path.join(demo.DIRECTOR_REPO_TARGETS_DIR,
                     'infotainment_firmware.txt'))

    fobj = open(
        os.path.join(demo.DIRECTOR_REPO_TARGETS_DIR, 'additional_file.txt'),
        'w')
    fobj.write('Contents of additional_file.txt')
    fobj.close()

    repo.targets.add_target(os.path.join(demo.DIRECTOR_REPO_TARGETS_DIR,
                                         'infotainment_firmware.txt'),
                            custom={"ecu-serial-number": "ecu11111"})

    #repo.targets.add_target(
    #    os.path.join(demo.DIRECTOR_REPO_TARGETS_DIR, 'additional_file.txt'),
    #    custom={"ecu-serial-number": "ecu11111"})

    # --------------
    # SERVICES SETUP:
    # --------------

    # Create the demo Director instance.
    director_service_instance = director.Director(
        key_root=key_dirroot_pri,
        key_timestamp=key_dirtime_pri,
        key_snapshot=key_dirsnap_pri,
        key_targets=key_dirtarg_pri,
        ecu_public_keys=dict())

    # Start with a hard-coded key for a single ECU for now.
    test_ecu_public_key = demo.import_public_key('secondary')
    test_ecu_serial = 'ecu11111'
    director_service_instance.register_ecu_serial(test_ecu_serial,
                                                  test_ecu_public_key)
Beispiel #17
0
def clean_slate(use_new_keys=False):

    global repo

    # Create target files: file1.txt and infotainment_firmware.txt

    if os.path.exists(demo.MAIN_REPO_TARGETS_DIR):
        shutil.rmtree(demo.MAIN_REPO_TARGETS_DIR)

    os.makedirs(demo.MAIN_REPO_TARGETS_DIR)

    fobj = open(os.path.join(demo.MAIN_REPO_TARGETS_DIR, 'file1.txt'), 'w')
    fobj.write('Contents of file1.txt')
    fobj.close()
    fobj = open(
        os.path.join(demo.MAIN_REPO_TARGETS_DIR, 'infotainment_firmware.txt'),
        'w')
    fobj.write('Contents of infotainment_firmware.txt')
    fobj.close()

    # Create repo at './repomain'

    repo = rt.create_new_repository(demo.MAIN_REPO_NAME)

    # Create keys and/or load keys into memory.

    if use_new_keys:
        demo.generate_key('mainroot')
        demo.generate_key('maintimestamp')
        demo.generate_key('mainsnapshot')
        demo.generate_key('maintargets')
        demo.generate_key('mainrole1')

    key_root_pub = demo.import_public_key('mainroot')
    key_root_pri = demo.import_private_key('mainroot')
    key_timestamp_pub = demo.import_public_key('maintimestamp')
    key_timestamp_pri = demo.import_private_key('maintimestamp')
    key_snapshot_pub = demo.import_public_key('mainsnapshot')
    key_snapshot_pri = demo.import_private_key('mainsnapshot')
    key_targets_pub = demo.import_public_key('maintargets')
    key_targets_pri = demo.import_private_key('maintargets')
    key_role1_pub = demo.import_public_key('mainrole1')
    key_role1_pri = demo.import_private_key('mainrole1')

    # Add top level keys to the main repository.

    repo.root.add_verification_key(key_root_pub)
    repo.timestamp.add_verification_key(key_timestamp_pub)
    repo.snapshot.add_verification_key(key_snapshot_pub)
    repo.targets.add_verification_key(key_targets_pub)
    repo.root.load_signing_key(key_root_pri)
    repo.timestamp.load_signing_key(key_timestamp_pri)
    repo.snapshot.load_signing_key(key_snapshot_pri)
    repo.targets.load_signing_key(key_targets_pri)

    # Perform delegation from mainrepo's targets role to mainrepo's role1 role.

    # Delegate to a new Supplier.
    repo.targets.delegate('role1', [key_role1_pub], [
        os.path.join(demo.MAIN_REPO_NAME, 'targets/file1.txt'),
        os.path.join(demo.MAIN_REPO_NAME, 'targets/infotainment_firmware.txt')
    ],
                          threshold=1,
                          backtrack=True,
                          restricted_paths=[
                              os.path.join(demo.MAIN_REPO_TARGETS_DIR, '*')
                          ])

    # Add delegated role keys to repo

    repo.targets('role1').load_signing_key(key_role1_pri)
Beispiel #18
0
def clean_slate(use_new_keys=False):

  global repo

  print(LOG_PREFIX + 'Initializing repository')

  # Create target files: file1.txt and infotainment_firmware.txt

  if os.path.exists(demo.IMAGE_REPO_TARGETS_DIR):
    shutil.rmtree(demo.IMAGE_REPO_TARGETS_DIR)

  os.makedirs(demo.IMAGE_REPO_TARGETS_DIR)

  fobj = open(os.path.join(demo.IMAGE_REPO_TARGETS_DIR, 'file1.txt'), 'w')
  fobj.write('Contents of file1.txt')
  fobj.close()
  fobj = open(os.path.join(demo.IMAGE_REPO_TARGETS_DIR, 'infotainment_firmware.txt'), 'w')
  fobj.write('Contents of infotainment_firmware.txt')
  fobj.close()


  # Create repo at './repomain'

  repo = rt.create_new_repository(demo.IMAGE_REPO_NAME)

  print(LOG_PREFIX + 'Loading all keys')

  # Create keys and/or load keys into memory.

  if use_new_keys:
    demo.generate_key('mainroot')
    demo.generate_key('maintimestamp')
    demo.generate_key('mainsnapshot')
    demo.generate_key('maintargets')
    demo.generate_key('mainrole1')

  key_root_pub = demo.import_public_key('mainroot')
  key_root_pri = demo.import_private_key('mainroot')
  key_timestamp_pub = demo.import_public_key('maintimestamp')
  key_timestamp_pri = demo.import_private_key('maintimestamp')
  key_snapshot_pub = demo.import_public_key('mainsnapshot')
  key_snapshot_pri = demo.import_private_key('mainsnapshot')
  key_targets_pub = demo.import_public_key('maintargets')
  key_targets_pri = demo.import_private_key('maintargets')
  key_role1_pub = demo.import_public_key('mainrole1')
  key_role1_pri = demo.import_private_key('mainrole1')


  # Add top level keys to the main repository.

  repo.root.add_verification_key(key_root_pub)
  repo.timestamp.add_verification_key(key_timestamp_pub)
  repo.snapshot.add_verification_key(key_snapshot_pub)
  repo.targets.add_verification_key(key_targets_pub)
  repo.root.load_signing_key(key_root_pri)
  repo.timestamp.load_signing_key(key_timestamp_pri)
  repo.snapshot.load_signing_key(key_snapshot_pri)
  repo.targets.load_signing_key(key_targets_pri)


  # Perform delegation from Image Repo's targets role to Image Repo's role1
  # role.

  # TODO: <~> Re-enable delegations below. Currently, ASN1 conversion fails
  # when there are delegations. This is, of course, untenable, but for now, it
  # is more important to experiment with ASN1 than to have a sample delegation.
  # Delegate to a new Supplier.
  # repo.targets.delegate('role1', [key_role1_pub],
  #     [os.path.join(demo.IMAGE_REPO_NAME, 'targets/file1.txt'),
  #      os.path.join(demo.IMAGE_REPO_NAME, 'targets/infotainment_firmware.txt')],
  #     threshold=1, backtrack=True,
  #     restricted_paths=[os.path.join(demo.IMAGE_REPO_TARGETS_DIR, '*')])
  # Add delegated role keys to repo
  # repo.targets('role1').load_signing_key(key_role1_pri)


  # Add some starting image files, primarily for use with the web frontend.
  add_target_to_imagerepo('demo/images/INFO1.0.txt', 'INFO1.0.txt')
  add_target_to_imagerepo('demo/images/TCU1.0.txt', 'TCU1.0.txt')
  add_target_to_imagerepo('demo/images/TCU1.1.txt', 'TCU1.1.txt')
  add_target_to_imagerepo('demo/images/TCU1.2.txt', 'TCU1.2.txt')
  add_target_to_imagerepo('demo/images/BCU1.0.txt', 'BCU1.0.txt')
  add_target_to_imagerepo('demo/images/BCU1.1.txt', 'BCU1.1.txt')
  add_target_to_imagerepo('demo/images/BCU1.2.txt', 'BCU1.2.txt')


  print(LOG_PREFIX + 'Signing and hosting initial repository metadata')

  write_to_live()

  host()

  listen()
Beispiel #19
0
def clean_slate(use_new_keys=False):

    global repo

    I_TO_PRINT = TO_PRINT + uptane.YELLOW + '[clean_slate()]: ' + ENDCOLORS
    _print = True
    #TODO: Print to be deleted
    if _print:
        print(
            str('%s %s %s' % (I_TO_PRINT, 'Cleaning slate with use_new_keys:',
                              use_new_keys)))
    #TODO: Until here

    print(LOG_PREFIX + 'Initializing repository')

    # Create target files: file1.txt and infotainment_firmware.txt

    #TODO: Print to be deleted
    if _print: print(I_TO_PRINT + 'Target files: %s' % target_files.keys())
    #TODO: Until here

    if os.path.exists(demo.IMAGE_REPO_TARGETS_DIR):
        #TODO: Print to be deleted
        if _print:
            print(I_TO_PRINT + 'Removing files: ' +
                  demo.IMAGE_REPO_TARGETS_DIR)
        #TODO: Until here

        shutil.rmtree(demo.IMAGE_REPO_TARGETS_DIR)

    #TODO: Print to be deleted
    if _print:
        print(I_TO_PRINT + 'Creating directories: ' +
              demo.IMAGE_REPO_TARGETS_DIR)
    #TODO: Until here

    os.makedirs(demo.IMAGE_REPO_TARGETS_DIR)

    #TODO: Print to be deleted
    if _print:
        print(I_TO_PRINT + 'Writing content for: %s' % target_files.keys())
    #TODO: Until here

    for target in target_files.keys():

        #TODO: Print to be deleted
        if _print: print(I_TO_PRINT + 'Target --> %s' % target)
        #TODO: Until here

        fobj = open(os.path.join(demo.IMAGE_REPO_TARGETS_DIR, target), 'w')
        fobj.write(target_files[target])
        fobj.close()

    # Create repo at './repomain'

    #TODO: Print to be deleted
    if _print:
        print(I_TO_PRINT + 'Creating new repository at: ' +
              demo.IMAGE_REPO_NAME)
    #TODO: Until here

    repo = rt.create_new_repository(demo.IMAGE_REPO_NAME)

    print(LOG_PREFIX + 'Loading all keys')

    # Create keys and/or load keys into memory.
    if use_new_keys:
        demo.generate_key('mainroot')
        demo.generate_key('maintimestamp')
        demo.generate_key('mainsnapshot')
        demo.generate_key('maintargets')
        demo.generate_key('mainrole1')

    #TODO: Print to be deleted
    if _print:
        print(
            I_TO_PRINT +
            'Loading keys for TOP-LEVEL roles: root, timestamp, snapshots, targets, role1'
        )
    #TODO: Until here

    key_root_pub = demo.import_public_key('mainroot')

    #TODO: Print to be deleted
    if _print:
        print(str('%s %s %s' % (I_TO_PRINT, 'key_root_pub:', key_root_pub)))
    #TODO: Until here

    key_root_pri = demo.import_private_key('mainroot')

    #TODO: Print to be deleted
    if _print:
        print(str('%s %s %s' % (I_TO_PRINT, 'key_root_pri:', key_root_pri)))
    #TODO: Until here

    key_timestamp_pub = demo.import_public_key('maintimestamp')

    #TODO: Print to be deleted
    if _print:
        print(
            str('%s %s %s' %
                (I_TO_PRINT, 'key_timestamp_pub:', key_timestamp_pub)))
    #TODO: Until here

    key_timestamp_pri = demo.import_private_key('maintimestamp')

    #TODO: Print to be deleted
    if _print:
        print(
            str('%s %s %s' %
                (I_TO_PRINT, 'key_timestamp_pri:', key_timestamp_pri)))
    #TODO: Until here

    key_snapshot_pub = demo.import_public_key('mainsnapshot')

    #TODO: Print to be deleted
    if _print:
        print(
            str('%s %s %s' %
                (I_TO_PRINT, 'key_snapshot_pub:', key_snapshot_pub)))
    #TODO: Until here

    key_snapshot_pri = demo.import_private_key('mainsnapshot')

    #TODO: Print to be deleted
    if _print:
        print(
            str('%s %s %s' %
                (I_TO_PRINT, 'key_snapshot_pri:', key_snapshot_pri)))
    #TODO: Until here

    key_targets_pub = demo.import_public_key('maintargets')

    #TODO: Print to be deleted
    if _print:
        print(
            str('%s %s %s' %
                (I_TO_PRINT, 'key_targets_pub:', key_targets_pub)))
    #TODO: Until here

    key_targets_pri = demo.import_private_key('maintargets')

    #TODO: Print to be deleted
    if _print:
        print(
            str('%s %s %s' %
                (I_TO_PRINT, 'key_targets_pri:', key_targets_pri)))
    #TODO: Until here

    key_role1_pub = demo.import_public_key('mainrole1')

    #TODO: Print to be deleted
    if _print:
        print(str('%s %s %s' % (I_TO_PRINT, 'key_role1_pub:', key_role1_pub)))
    #TODO: Until here

    key_role1_pri = demo.import_private_key('mainrole1')

    #TODO: Print to be deleted
    if _print:
        print(str('%s %s %s' % (I_TO_PRINT, 'key_role1_pri:', key_role1_pri)))
    #TODO: Until here

    #TODO: Print to be deleted
    if _print:
        print(
            str('\n%s %s' %
                (I_TO_PRINT, 'Adding TOP-LEVEL keys to the main repository')))
    #TODO: Until here

    # Add top level keys to the main repository.

    #TODO: Print to be deleted
    if _print:
        print(str('%s %s' % (I_TO_PRINT, 'Adding verification key_root_pub')))
    #TODO: Until here

    repo.root.add_verification_key(key_root_pub)

    #TODO: Print to be deleted
    if _print:
        print(
            str('%s %s' %
                (I_TO_PRINT, 'Adding verification key_timestamp_pub')))
    #TODO: Until here

    repo.timestamp.add_verification_key(key_timestamp_pub)

    #TODO: Print to be deleted
    if _print:
        print(
            str('%s %s' %
                (I_TO_PRINT, 'Adding verification key_snapshot_pub')))
    #TODO: Until here

    repo.snapshot.add_verification_key(key_snapshot_pub)

    #TODO: Print to be deleted
    if _print:
        print(
            str('%s %s' % (I_TO_PRINT, 'Adding verification key_targets_pub')))
    #TODO: Until here

    repo.targets.add_verification_key(key_targets_pub)

    #TODO: Print to be deleted
    if _print:
        print(str('%s %s' % (I_TO_PRINT, 'Adding signing key_root_pri')))
    #TODO: Until here

    repo.root.load_signing_key(key_root_pri)

    #TODO: Print to be deleted
    if _print:
        print(str('%s %s' % (I_TO_PRINT, 'Adding signing key_timestamp_pri')))
    #TODO: Until here

    repo.timestamp.load_signing_key(key_timestamp_pri)

    #TODO: Print to be deleted
    if _print:
        print(str('%s %s' % (I_TO_PRINT, 'Adding signing key_snapshot_pri')))
    #TODO: Until here

    repo.snapshot.load_signing_key(key_snapshot_pri)

    #TODO: Print to be deleted
    if _print:
        print(str('%s %s' % (I_TO_PRINT, 'Adding signing key_targets_pri')))
    #TODO: Until here

    repo.targets.load_signing_key(key_targets_pri)

    # Perform delegation from Image Repo's targets role to Image Repo's role1
    # role.

    # TODO: <~> Re-enable delegations below. Currently, ASN1 conversion fails
    # when there are delegations. This is, of course, untenable, but for now, it
    # is more important to experiment with ASN1 than to have a sample delegation.
    # Delegate to a new Supplier.
    # repo.targets.delegate('role1', [key_role1_pub],
    #     [os.path.join(demo.IMAGE_REPO_NAME, 'targets/file1.txt'),
    #      os.path.join(demo.IMAGE_REPO_NAME, 'targets/infotainment_firmware.txt')],
    #     threshold=1, backtrack=True,
    #     restricted_paths=[os.path.join(demo.IMAGE_REPO_TARGETS_DIR, '*')])
    # Add delegated role keys to repo
    # repo.targets('role1').load_signing_key(key_role1_pri)

    #TODO: Print to be deleted
    if _print:
        print(I_TO_PRINT + 'Adding some already created targets to imagerepo')
    #TODO: Until here

    # Add some starting image files, primarily for use with the web frontend.
    # add_target_to_imagerepo('demo/images/CommonINFO1.0.txt', 'CommonINFO1.0.txt')
    add_target_to_imagerepo('demo/images/infotainment_firmware.txt',
                            'infotainment_firmware.txt')
    add_target_to_imagerepo('demo/images/URV1.0.txt', 'URV1.0.txt')
    add_target_to_imagerepo('demo/images/URV1.1.txt', 'URV1.1.txt')
    add_target_to_imagerepo('demo/images/URV1.2.txt', 'URV1.2.txt')
    add_target_to_imagerepo('demo/images/UOC1.0.txt', 'UOC1.0.txt')
    add_target_to_imagerepo('demo/images/UOC1.1.txt', 'UOC1.1.txt')
    add_target_to_imagerepo('demo/images/UOC1.2.txt', 'UOC1.2.txt')
    add_target_to_imagerepo('demo/images/UOCMod1_new_firmware.img',
                            'UOCMod1_new_firmware.img')

    print(LOG_PREFIX + 'Signing and hosting initial repository metadata')

    write_to_live()

    host()

    listen()