def main(): args = parse_arguments() # configure our instance of the grafeas api swagger_client.configuration.host = args.target api_instance = swagger_client.GrafeasApi() try: pubkey = util.import_public_keys_from_files_as_dict([args.key]) layout = fetch_layout(args.project_id, api_instance) except Exception as e: print("Exception when fetching the in-toto layout\n{}: {}".format( type(e).__name__, e)) sys.exit(1) # fetch the link metadata for every step for step in layout.signed.steps: for keyid in step.pubkeys: try: fetch_occurrence(args.project_id, step.name, keyid, api_instance) except ApiException as e: raise e pass try: verifylib.in_toto_verify(layout, pubkey) except Exception as e: print("Exception when verifying the supply chain\n{}: {}".format( type(e).__name__, e)) sys.exit(1)
def setUpClass(self): # Create layout with one inspection self.layout = Layout.read({ "_type": "layout", "inspect": [], "steps": [{ "name": "run-command", "expected_command": ["{EDITOR}"], }] }) super(Test_SubstituteOnVerify, self).setUpClass() # Find demo files demo_files = os.path.join(os.path.dirname(os.path.realpath(__file__)), "demo_files") # Copy demo files to temp dir for file in os.listdir(demo_files): shutil.copy(os.path.join(demo_files, file), self.test_dir) # load alice's key self.alice = import_rsa_key_from_file("alice") self.alice_pub_dict = import_public_keys_from_files_as_dict( ["alice.pub"])
def setUpClass(self): # Create layout with one inspection self.layout = Layout.read({ "_type": "layout", "inspect": [], "steps": [{ "name": "run-command", "expected_command": ["{EDITOR}"], }] }) # Backup original cwd self.working_dir = os.getcwd() # Find demo files demo_files = os.path.join(os.path.dirname(os.path.realpath(__file__)), "demo_files") # Create and change into temporary directory self.test_dir = os.path.realpath(tempfile.mkdtemp()) os.chdir(self.test_dir) # Copy demo files to temp dir for file in os.listdir(demo_files): shutil.copy(os.path.join(demo_files, file), self.test_dir) # load alice's key self.alice = import_rsa_key_from_file("alice") self.alice_pub_dict = import_public_keys_from_files_as_dict( ["alice.pub"])
def __verify_in_toto_metadata(self, target_relpath, in_toto_inspection_packet): # Make a temporary directory in a parent directory we control. tempdir = tempfile.mkdtemp(dir=REPOSITORIES_DIR) # Copy files over into temp dir. for rel_path in in_toto_inspection_packet: # Don't confuse Python with any leading path separator. rel_path = rel_path.lstrip('/') abs_path = os.path.join(self.__targets_dir, rel_path) shutil.copy(abs_path, tempdir) # Switch to the temp dir. os.chdir(tempdir) # Load the root layout and public keys. layout = Metablock.load('root.layout') pubkeys = glob.glob('*.pub') layout_key_dict = import_public_keys_from_files_as_dict(pubkeys) # Parameter substitution. params = substitute(target_relpath) try: verifylib.in_toto_verify(layout, layout_key_dict, substitution_parameters=params) except: logger.exception('in-toto failed to verify {}'.format(target_relpath)) raise else: logger.info('in-toto verified {}'.format(target_relpath)) finally: # Switch back to a parent directory we control, so that we can # safely delete temp dir. os.chdir(REPOSITORIES_DIR) # Delete temp dir. shutil.rmtree(tempdir)
def __load_root_layout(self, target_relpath): root_layout = Metablock.load(IN_TOTO_ROOT_LAYOUT) root_layout_pubkeys = glob.glob('*.pub') root_layout_pubkeys = import_public_keys_from_files_as_dict( root_layout_pubkeys) # Parameter substitution. root_layout_params = substitute(target_relpath) return root_layout, root_layout_pubkeys, root_layout_params
def test_import_ed25519_public_keys_from_files_as_dict(self): """Create and import multiple Ed25519 public keys and return KEYDICT. """ name1 = "key4" name2 = "key5" generate_and_write_ed25519_keypair(name1, password=name1) generate_and_write_ed25519_keypair(name2, password=name2) # Succesfully import public keys as keydictionary key_dict = import_public_keys_from_files_as_dict( [name1 + ".pub", name2 + ".pub"], [KEY_TYPE_ED25519] * 2) securesystemslib.formats.KEYDICT_SCHEMA.check_match(key_dict) # Import with wrong number of key types raises an exception with self.assertRaises(securesystemslib.exceptions.Error): import_public_keys_from_files_as_dict( [name1 + ".pub", name2 + ".pub"], [KEY_TYPE_ED25519]) # Import wrongly formatted key raises an exception not_an_ed25519 = "not_an_ed25519" with open(not_an_ed25519, "w") as f: f.write(not_an_ed25519) with self.assertRaises(securesystemslib.exceptions.Error): import_public_keys_from_files_as_dict( [name1 + ".pub", not_an_ed25519], [KEY_TYPE_ED25519] * 2) # Import private key raises an exception with self.assertRaises(securesystemslib.exceptions.Error): import_public_keys_from_files_as_dict([name1, name2], [KEY_TYPE_ED25519] * 2)
def test_import_rsa_public_keys_from_files_as_dict(self): """Create and import multiple rsa public keys and return KEYDICT. """ name1 = "key4" name2 = "key5" generate_and_write_rsa_keypair(name1) generate_and_write_rsa_keypair(name2) # Succefully import public keys as keydictionary key_dict = import_public_keys_from_files_as_dict( [name1 + ".pub", name2 + ".pub"]) securesystemslib.formats.KEYDICT_SCHEMA.check_match(key_dict) # Import wrongly formatted key raises an exception not_an_rsa = "not_an_rsa" open(not_an_rsa, "w").write(not_an_rsa) with self.assertRaises(securesystemslib.exceptions.FormatError): import_public_keys_from_files_as_dict([name1 + ".pub", not_an_rsa]) # Import private key raises an exception with self.assertRaises(securesystemslib.exceptions.FormatError): import_public_keys_from_files_as_dict([name1, name2])
def _verify_metadata(metadata, args): """ <Purpose> Internal method to verify link or layout signatures. <Arguments> metadata: Metablock object (contains Link or Layout object) args: see argparser <Exceptions> SystemExit(0) if verification passes SystemExit(1) if verification fails SystemExit(2) if any exception occurs """ try: # Load pubkeys from disk .... if args.key is not None: pub_key_dict = util.import_public_keys_from_files_as_dict( args.key, args.key_type) # ... or from gpg keyring elif args.gpg is not None: # pragma: no branch pub_key_dict = util.import_gpg_public_keys_from_keyring_as_dict( args.gpg, args.gpg_home) for keyid, verification_key in six.iteritems(pub_key_dict): metadata.verify_signature(verification_key) LOG.info( "Signature verification passed for keyid '{}'".format(keyid)) sys.exit(0) except exceptions.SignatureVerificationError as e: LOG.error("Signature verification failed: {}".format(e)) sys.exit(1) except Exception as e: LOG.error("The following error occurred while verifying signatures: " "{}".format(e)) sys.exit(2)
def __verify_in_toto_metadata(self, target_relpath, in_toto_metadata_relpaths, pubkey_relpaths): # Make a temporary directory. tempdir = tempfile.mkdtemp() prev_cwd = os.getcwd() try: # Copy files over into temp dir. rel_paths = [target_relpath ] + in_toto_metadata_relpaths + pubkey_relpaths for rel_path in rel_paths: # Don't confuse Python with any leading path separator. rel_path = rel_path.lstrip('/') abs_path = os.path.join(self.__targets_dir, rel_path) shutil.copy(abs_path, tempdir) # Switch to the temp dir. os.chdir(tempdir) # Load the root layout and public keys. layout = Metablock.load('root.layout') pubkeys = glob.glob('*.pub') layout_key_dict = import_public_keys_from_files_as_dict(pubkeys) # Verify and inspect. params = substitute(target_relpath) verifylib.in_toto_verify(layout, layout_key_dict, substitution_parameters=params) logger.info('in-toto verified {}'.format(target_relpath)) except: logger.exception( 'in-toto failed to verify {}'.format(target_relpath)) raise finally: os.chdir(prev_cwd) # Delete temp dir. shutil.rmtree(tempdir)