diff --git a/tests/test_arbitrary_package_attack.py b/tests/test_arbitrary_package_attack.py index 91ba230b..af3b7313 100755 --- a/tests/test_arbitrary_package_attack.py +++ b/tests/test_arbitrary_package_attack.py @@ -54,7 +54,7 @@ import tuf.tufformats import tuf.ssl_crypto.util import tuf.roledb -import tuf.keydb +import tuf.ssl_crypto.keydb import tuf.log import tuf.client.updater as updater import tuf.unittest_toolbox as unittest_toolbox @@ -166,7 +166,7 @@ def tearDown(self): unittest_toolbox.Modified_TestCase.tearDown(self) # updater.Updater() populates the roledb with the name "test_repository" tuf.roledb.clear_roledb(clear_all=True) - tuf.keydb.clear_keydb(clear_all=True) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) def test_without_tuf(self): # Verify that a target file replaced with a malicious version is downloaded diff --git a/tests/test_developer_tool.py b/tests/test_developer_tool.py index e7976511..1b634c32 100755 --- a/tests/test_developer_tool.py +++ b/tests/test_developer_tool.py @@ -27,7 +27,7 @@ import tuf.log import tuf.tufformats import tuf.roledb -import tuf.keydb +import tuf.ssl_crypto.keydb import tuf.developer_tool as developer_tool from tuf.developer_tool import METADATA_DIRECTORY_NAME @@ -56,7 +56,7 @@ def setUp(self): def tearDown(self): # called after every test case tuf.roledb.clear_roledb(clear_all=True) - tuf.keydb.clear_keydb(clear_all=True) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) def test_create_new_project(self): @@ -152,7 +152,7 @@ def test_create_new_project(self): os.chmod(local_tmp, 0o0555) tuf.roledb.clear_roledb() - tuf.keydb.clear_keydb() + tuf.ssl_crypto.keydb.clear_keydb() self.assertRaises(OSError, developer_tool.create_new_project ,project_name, metadata_directory, location_in_repository, targets_directory, project_key) @@ -163,7 +163,7 @@ def test_create_new_project(self): os.chmod(local_tmp, 0o0555) tuf.roledb.clear_roledb() - tuf.keydb.clear_keydb() + tuf.ssl_crypto.keydb.clear_keydb() self.assertRaises(OSError, developer_tool.create_new_project ,project_name, metadata_directory, location_in_repository, targets_directory, project_key) diff --git a/tests/test_endless_data_attack.py b/tests/test_endless_data_attack.py index d5e74bdd..62feb81a 100755 --- a/tests/test_endless_data_attack.py +++ b/tests/test_endless_data_attack.py @@ -60,7 +60,7 @@ import tuf.client.updater as updater import tuf.unittest_toolbox as unittest_toolbox import tuf.roledb -import tuf.keydb +import tuf.ssl_crypto.keydb from simple_settings import settings import six @@ -167,7 +167,7 @@ def tearDown(self): # 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) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) def test_without_tuf(self): diff --git a/tests/test_extraneous_dependencies_attack.py b/tests/test_extraneous_dependencies_attack.py index 483f3b44..1d401eb6 100755 --- a/tests/test_extraneous_dependencies_attack.py +++ b/tests/test_extraneous_dependencies_attack.py @@ -60,7 +60,7 @@ import tuf.log import tuf.client.updater as updater import tuf.roledb -import tuf.keydb +import tuf.ssl_crypto.keydb import tuf.unittest_toolbox as unittest_toolbox from simple_settings import settings import six @@ -172,7 +172,7 @@ def tearDown(self): # 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) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) diff --git a/tests/test_indefinite_freeze_attack.py b/tests/test_indefinite_freeze_attack.py index d89b93aa..cb79995b 100755 --- a/tests/test_indefinite_freeze_attack.py +++ b/tests/test_indefinite_freeze_attack.py @@ -66,7 +66,7 @@ import tuf.repository_tool as repo_tool import tuf.unittest_toolbox as unittest_toolbox import tuf.roledb -import tuf.keydb +import tuf.ssl_crypto.keydb from simple_settings import settings import six @@ -181,7 +181,7 @@ def tearDown(self): # 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) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) def test_without_tuf(self): diff --git a/tests/test_interpose_updater.py b/tests/test_interpose_updater.py index 4f547b1e..07d63320 100755 --- a/tests/test_interpose_updater.py +++ b/tests/test_interpose_updater.py @@ -41,7 +41,7 @@ import tuf.interposition.configuration as configuration import tuf.unittest_toolbox as unittest_toolbox import tuf.roledb -import tuf.keydb +import tuf.ssl_crypto.keydb if sys.version_info >= (2, 7): @@ -196,7 +196,7 @@ def tearDown(self): # We are inheriting from custom class. unittest_toolbox.Modified_TestCase.tearDown(self) tuf.roledb.clear_roledb(clear_all=True) - tuf.keydb.clear_keydb(clear_all=True) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) # Unit Tests @@ -417,7 +417,7 @@ def tearDown(self): # We are inheriting from custom class. unittest_toolbox.Modified_TestCase.tearDown(self) tuf.roledb.clear_roledb('localhost') - tuf.keydb.clear_keydb('localhost') + tuf.ssl_crypto.keydb.clear_keydb('localhost') # Unit Tests diff --git a/tests/test_key_revocation_integration.py b/tests/test_key_revocation_integration.py index 92bb1260..ee034b1a 100755 --- a/tests/test_key_revocation_integration.py +++ b/tests/test_key_revocation_integration.py @@ -55,7 +55,7 @@ import tuf.log from simple_settings import settings import tuf.roledb -import tuf.keydb +import tuf.ssl_crypto.keydb import tuf.repository_tool as repo_tool import tuf.unittest_toolbox as unittest_toolbox import tuf.client.updater as updater @@ -179,7 +179,7 @@ def tearDown(self): # We are inheriting from custom class. unittest_toolbox.Modified_TestCase.tearDown(self) tuf.roledb.clear_roledb(clear_all=True) - tuf.keydb.clear_keydb(clear_all=True) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) diff --git a/tests/test_keydb.py b/tests/test_keydb.py index 4c8c3494..fb251a7c 100755 --- a/tests/test_keydb.py +++ b/tests/test_keydb.py @@ -30,8 +30,8 @@ import tuf import tuf.tufformats -import tuf.keys -import tuf.keydb +import tuf.ssl_crypto.keys +import tuf.ssl_crypto.keydb import tuf.log from simple_settings import settings @@ -41,7 +41,7 @@ # Generate the three keys to use in our test cases. KEYS = [] for junk in range(3): - rsa_key = tuf.keys.generate_rsa_key(2048) + rsa_key = tuf.ssl_crypto.keys.generate_rsa_key(2048) rsa_key['keyid_hash_algorithms'] = settings.REPOSITORY_HASH_ALGORITHMS KEYS.append(rsa_key) @@ -49,12 +49,12 @@ class TestKeydb(unittest.TestCase): def setUp(self): - tuf.keydb.clear_keydb(clear_all=True) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) def tearDown(self): - tuf.keydb.clear_keydb(clear_all=True) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) @@ -63,19 +63,19 @@ def test_create_keydb(self): repository_name = 'example_repository' # The keydb dictionary should contain only the 'default' repository entry. - self.assertTrue('default' in tuf.keydb._keydb_dict) - self.assertEqual(1, len(tuf.keydb._keydb_dict)) + self.assertTrue('default' in tuf.ssl_crypto.keydb._keydb_dict) + self.assertEqual(1, len(tuf.ssl_crypto.keydb._keydb_dict)) - tuf.keydb.create_keydb(repository_name) - self.assertEqual(2, len(tuf.keydb._keydb_dict)) + tuf.ssl_crypto.keydb.create_keydb(repository_name) + self.assertEqual(2, len(tuf.ssl_crypto.keydb._keydb_dict)) # Verify that a keydb cannot be created for a name that already exists. - self.assertRaises(tuf.ssl_commons.exceptions.InvalidNameError, tuf.keydb.create_keydb, repository_name) + self.assertRaises(tuf.ssl_commons.exceptions.InvalidNameError, tuf.ssl_crypto.keydb.create_keydb, repository_name) # Ensure that the key database for 'example_repository' is deleted so that # the key database is returned to its original, default state. - tuf.keydb.remove_keydb(repository_name) + tuf.ssl_crypto.keydb.remove_keydb(repository_name) @@ -85,41 +85,41 @@ def test_remove_keydb(self): keyid = KEYS[0]['keyid'] repository_name = 'example_repository' - self.assertRaises(tuf.ssl_commons.exceptions.InvalidNameError, tuf.keydb.remove_keydb, 'default') + self.assertRaises(tuf.ssl_commons.exceptions.InvalidNameError, tuf.ssl_crypto.keydb.remove_keydb, 'default') - tuf.keydb.create_keydb(repository_name) - tuf.keydb.remove_keydb(repository_name) + tuf.ssl_crypto.keydb.create_keydb(repository_name) + tuf.ssl_crypto.keydb.remove_keydb(repository_name) - # tuf.keydb.remove_keydb() logs a warning if a keydb for a non-existent + # tuf.ssl_crypto.keydb.remove_keydb() logs a warning if a keydb for a non-existent # repository is specified. - tuf.keydb.remove_keydb(repository_name) + tuf.ssl_crypto.keydb.remove_keydb(repository_name) # Test condition for improperly formatted argument, and unexpected argument. - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.remove_keydb, 123) - self.assertRaises(TypeError, tuf.keydb.remove_keydb, rsakey, 123) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.remove_keydb, 123) + self.assertRaises(TypeError, tuf.ssl_crypto.keydb.remove_keydb, rsakey, 123) def test_clear_keydb(self): # Test condition ensuring 'clear_keydb()' clears the keydb database. # Test the length of the keydb before and after adding a key. - self.assertEqual(0, len(tuf.keydb._keydb_dict['default'])) + self.assertEqual(0, len(tuf.ssl_crypto.keydb._keydb_dict['default'])) rsakey = KEYS[0] keyid = KEYS[0]['keyid'] - tuf.keydb._keydb_dict['default'][keyid] = rsakey - self.assertEqual(1, len(tuf.keydb._keydb_dict['default'])) - tuf.keydb.clear_keydb() - self.assertEqual(0, len(tuf.keydb._keydb_dict['default'])) + tuf.ssl_crypto.keydb._keydb_dict['default'][keyid] = rsakey + self.assertEqual(1, len(tuf.ssl_crypto.keydb._keydb_dict['default'])) + tuf.ssl_crypto.keydb.clear_keydb() + self.assertEqual(0, len(tuf.ssl_crypto.keydb._keydb_dict['default'])) # Test condition for unexpected argument. - self.assertRaises(TypeError, tuf.keydb.clear_keydb, 'default', False, 'unexpected_argument') + self.assertRaises(TypeError, tuf.ssl_crypto.keydb.clear_keydb, 'default', False, 'unexpected_argument') # Test condition for improperly formatted arguments. - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.clear_keydb, 0) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.clear_keydb, 'default', 0) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.clear_keydb, 0) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.clear_keydb, 'default', 0) # Test condition for non-existent repository name. - self.assertRaises(tuf.ssl_commons.exceptions.InvalidNameError, tuf.keydb.clear_keydb, 'non-existent') + self.assertRaises(tuf.ssl_commons.exceptions.InvalidNameError, tuf.ssl_crypto.keydb.clear_keydb, 'non-existent') # Test condition for keys added to a non-default key database. Unlike the # test conditions above, this test makes use of the public functions @@ -128,17 +128,17 @@ def test_clear_keydb(self): rsakey = KEYS[0] keyid = KEYS[0]['keyid'] repository_name = 'example_repository' - tuf.keydb.create_keydb(repository_name) - self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.keydb.get_key, keyid, repository_name) - tuf.keydb.add_key(rsakey, keyid, repository_name) - self.assertEqual(rsakey, tuf.keydb.get_key(keyid, repository_name)) + tuf.ssl_crypto.keydb.create_keydb(repository_name) + self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.ssl_crypto.keydb.get_key, keyid, repository_name) + tuf.ssl_crypto.keydb.add_key(rsakey, keyid, repository_name) + self.assertEqual(rsakey, tuf.ssl_crypto.keydb.get_key(keyid, repository_name)) - tuf.keydb.clear_keydb(repository_name) - self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.keydb.get_key, keyid, repository_name) + tuf.ssl_crypto.keydb.clear_keydb(repository_name) + self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.ssl_crypto.keydb.get_key, keyid, repository_name) # Remove 'repository_name' from the key database to revert it back to its # original, default state (i.e., only the 'default' repository exists). - tuf.keydb.remove_keydb(repository_name) + tuf.ssl_crypto.keydb.remove_keydb(repository_name) @@ -146,46 +146,46 @@ def test_get_key(self): # Test conditions using valid 'keyid' arguments. rsakey = KEYS[0] keyid = KEYS[0]['keyid'] - tuf.keydb._keydb_dict['default'][keyid] = rsakey + tuf.ssl_crypto.keydb._keydb_dict['default'][keyid] = rsakey rsakey2 = KEYS[1] keyid2 = KEYS[1]['keyid'] - tuf.keydb._keydb_dict['default'][keyid2] = rsakey2 + tuf.ssl_crypto.keydb._keydb_dict['default'][keyid2] = rsakey2 - self.assertEqual(rsakey, tuf.keydb.get_key(keyid)) - self.assertEqual(rsakey2, tuf.keydb.get_key(keyid2)) - self.assertNotEqual(rsakey2, tuf.keydb.get_key(keyid)) - self.assertNotEqual(rsakey, tuf.keydb.get_key(keyid2)) + self.assertEqual(rsakey, tuf.ssl_crypto.keydb.get_key(keyid)) + self.assertEqual(rsakey2, tuf.ssl_crypto.keydb.get_key(keyid2)) + self.assertNotEqual(rsakey2, tuf.ssl_crypto.keydb.get_key(keyid)) + self.assertNotEqual(rsakey, tuf.ssl_crypto.keydb.get_key(keyid2)) # Test conditions using invalid arguments. - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.get_key, None) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.get_key, 123) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.get_key, ['123']) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.get_key, {'keyid': '123'}) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.get_key, '') - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.get_key, keyid, 123) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.get_key, None) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.get_key, 123) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.get_key, ['123']) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.get_key, {'keyid': '123'}) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.get_key, '') + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.get_key, keyid, 123) # Test condition using a 'keyid' that has not been added yet. keyid3 = KEYS[2]['keyid'] - self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.keydb.get_key, keyid3) + self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.ssl_crypto.keydb.get_key, keyid3) # Test condition for a key added to a non-default repository. repository_name = 'example_repository' rsakey3 = KEYS[2] - tuf.keydb.create_keydb(repository_name) - tuf.keydb.add_key(rsakey3, keyid3, repository_name) + tuf.ssl_crypto.keydb.create_keydb(repository_name) + tuf.ssl_crypto.keydb.add_key(rsakey3, keyid3, repository_name) # Test condition for a key added to a non-existent repository. - self.assertRaises(tuf.ssl_commons.exceptions.InvalidNameError, tuf.keydb.get_key, + self.assertRaises(tuf.ssl_commons.exceptions.InvalidNameError, tuf.ssl_crypto.keydb.get_key, keyid, 'non-existent') # Verify that 'rsakey3' is added to the expected repository name. # If not supplied, the 'default' repository name is searched. - self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.keydb.get_key, keyid3) - self.assertEqual(rsakey3, tuf.keydb.get_key(keyid3, repository_name)) + self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.ssl_crypto.keydb.get_key, keyid3) + self.assertEqual(rsakey3, tuf.ssl_crypto.keydb.get_key(keyid3, repository_name)) # Remove the 'example_repository' so that other test functions have access # to a default state of the keydb. - tuf.keydb.remove_keydb(repository_name) + tuf.ssl_crypto.keydb.remove_keydb(repository_name) @@ -197,55 +197,55 @@ def test_add_key(self): keyid2 = KEYS[1]['keyid'] rsakey3 = KEYS[2] keyid3 = KEYS[2]['keyid'] - self.assertEqual(None, tuf.keydb.add_key(rsakey, keyid)) - self.assertEqual(None, tuf.keydb.add_key(rsakey2, keyid2)) - self.assertEqual(None, tuf.keydb.add_key(rsakey3)) + self.assertEqual(None, tuf.ssl_crypto.keydb.add_key(rsakey, keyid)) + self.assertEqual(None, tuf.ssl_crypto.keydb.add_key(rsakey2, keyid2)) + self.assertEqual(None, tuf.ssl_crypto.keydb.add_key(rsakey3)) - self.assertEqual(rsakey, tuf.keydb.get_key(keyid)) - self.assertEqual(rsakey2, tuf.keydb.get_key(keyid2)) - self.assertEqual(rsakey3, tuf.keydb.get_key(keyid3)) + self.assertEqual(rsakey, tuf.ssl_crypto.keydb.get_key(keyid)) + self.assertEqual(rsakey2, tuf.ssl_crypto.keydb.get_key(keyid2)) + self.assertEqual(rsakey3, tuf.ssl_crypto.keydb.get_key(keyid3)) # Test conditions using arguments with invalid formats. - tuf.keydb.clear_keydb() + tuf.ssl_crypto.keydb.clear_keydb() rsakey3['keytype'] = 'bad_keytype' - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.add_key, None, keyid) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.add_key, '', keyid) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.add_key, ['123'], keyid) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.add_key, {'a': 'b'}, keyid) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.add_key, rsakey, {'keyid': ''}) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.add_key, rsakey, 123) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.add_key, rsakey, False) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.add_key, rsakey, ['keyid']) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.add_key, rsakey3, keyid3) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.add_key, None, keyid) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.add_key, '', keyid) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.add_key, ['123'], keyid) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.add_key, {'a': 'b'}, keyid) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.add_key, rsakey, {'keyid': ''}) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.add_key, rsakey, 123) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.add_key, rsakey, False) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.add_key, rsakey, ['keyid']) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.add_key, rsakey3, keyid3) rsakey3['keytype'] = 'rsa' - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.add_key, rsakey3, keyid3, 123) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.add_key, rsakey3, keyid3, 123) # Test conditions where keyid does not match the rsakey. - self.assertRaises(tuf.ssl_commons.exceptions.Error, tuf.keydb.add_key, rsakey, keyid2) - self.assertRaises(tuf.ssl_commons.exceptions.Error, tuf.keydb.add_key, rsakey2, keyid) + self.assertRaises(tuf.ssl_commons.exceptions.Error, tuf.ssl_crypto.keydb.add_key, rsakey, keyid2) + self.assertRaises(tuf.ssl_commons.exceptions.Error, tuf.ssl_crypto.keydb.add_key, rsakey2, keyid) # Test conditions using keyids that have already been added. - tuf.keydb.add_key(rsakey, keyid) - tuf.keydb.add_key(rsakey2, keyid2) - self.assertRaises(tuf.ssl_commons.exceptions.KeyAlreadyExistsError, tuf.keydb.add_key, rsakey) - self.assertRaises(tuf.ssl_commons.exceptions.KeyAlreadyExistsError, tuf.keydb.add_key, rsakey2) + tuf.ssl_crypto.keydb.add_key(rsakey, keyid) + tuf.ssl_crypto.keydb.add_key(rsakey2, keyid2) + self.assertRaises(tuf.ssl_commons.exceptions.KeyAlreadyExistsError, tuf.ssl_crypto.keydb.add_key, rsakey) + self.assertRaises(tuf.ssl_commons.exceptions.KeyAlreadyExistsError, tuf.ssl_crypto.keydb.add_key, rsakey2) # Test condition for key added to the keydb of a non-default repository. repository_name = 'example_repository' - tuf.keydb.create_keydb(repository_name) - self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.keydb.get_key, keyid3, repository_name) - tuf.keydb.add_key(rsakey3, keyid3, repository_name) - self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.keydb.get_key, keyid3) - self.assertEqual(rsakey3, tuf.keydb.get_key(keyid3, repository_name)) + tuf.ssl_crypto.keydb.create_keydb(repository_name) + self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.ssl_crypto.keydb.get_key, keyid3, repository_name) + tuf.ssl_crypto.keydb.add_key(rsakey3, keyid3, repository_name) + self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.ssl_crypto.keydb.get_key, keyid3) + self.assertEqual(rsakey3, tuf.ssl_crypto.keydb.get_key(keyid3, repository_name)) # Test condition for key added to the keydb of a non-existent repository. - self.assertRaises(tuf.ssl_commons.exceptions.InvalidNameError, tuf.keydb.add_key, + self.assertRaises(tuf.ssl_commons.exceptions.InvalidNameError, tuf.ssl_crypto.keydb.add_key, rsakey3, keyid3, 'non-existent') # Reset the keydb to its original, default state. Other test functions # expect only the 'default' repository to exist. - tuf.keydb.remove_keydb(repository_name) + tuf.ssl_crypto.keydb.remove_keydb(repository_name) @@ -257,43 +257,43 @@ def test_remove_key(self): keyid2 = KEYS[1]['keyid'] rsakey3 = KEYS[2] keyid3 = KEYS[2]['keyid'] - tuf.keydb.add_key(rsakey, keyid) - tuf.keydb.add_key(rsakey2, keyid2) - tuf.keydb.add_key(rsakey3, keyid3) + tuf.ssl_crypto.keydb.add_key(rsakey, keyid) + tuf.ssl_crypto.keydb.add_key(rsakey2, keyid2) + tuf.ssl_crypto.keydb.add_key(rsakey3, keyid3) - self.assertEqual(None, tuf.keydb.remove_key(keyid)) - self.assertEqual(None, tuf.keydb.remove_key(keyid2)) + self.assertEqual(None, tuf.ssl_crypto.keydb.remove_key(keyid)) + self.assertEqual(None, tuf.ssl_crypto.keydb.remove_key(keyid2)) # Ensure the keys were actually removed. - self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.keydb.get_key, keyid) - self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.keydb.get_key, keyid2) + self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.ssl_crypto.keydb.get_key, keyid) + self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.ssl_crypto.keydb.get_key, keyid2) # Test for 'keyid' not in keydb. - self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.keydb.remove_key, keyid) + self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.ssl_crypto.keydb.remove_key, keyid) # Test condition for unknown key argument. - self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.keydb.remove_key, '1') + self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.ssl_crypto.keydb.remove_key, '1') # Test condition for removal of keys from a non-default repository. repository_name = 'example_repository' - tuf.keydb.create_keydb(repository_name) - tuf.keydb.add_key(rsakey, keyid, repository_name) - self.assertRaises(tuf.ssl_commons.exceptions.InvalidNameError, tuf.keydb.remove_key, keyid, 'non-existent') - tuf.keydb.remove_key(keyid, repository_name) - self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.keydb.remove_key, keyid, repository_name) + tuf.ssl_crypto.keydb.create_keydb(repository_name) + tuf.ssl_crypto.keydb.add_key(rsakey, keyid, repository_name) + self.assertRaises(tuf.ssl_commons.exceptions.InvalidNameError, tuf.ssl_crypto.keydb.remove_key, keyid, 'non-existent') + tuf.ssl_crypto.keydb.remove_key(keyid, repository_name) + self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.ssl_crypto.keydb.remove_key, keyid, repository_name) # Reset the keydb so that subsequent tests have access to the original, # default keydb. - tuf.keydb.remove_keydb(repository_name) + tuf.ssl_crypto.keydb.remove_keydb(repository_name) # Test conditions for arguments with invalid formats. - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.remove_key, None) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.remove_key, '') - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.remove_key, 123) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.remove_key, ['123']) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.remove_key, keyid, 123) - self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.keydb.remove_key, {'bad': '123'}) - self.assertRaises(tuf.ssl_commons.exceptions.Error, tuf.keydb.remove_key, rsakey3) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.remove_key, None) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.remove_key, '') + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.remove_key, 123) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.remove_key, ['123']) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.remove_key, keyid, 123) + self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.ssl_crypto.keydb.remove_key, {'bad': '123'}) + self.assertRaises(tuf.ssl_commons.exceptions.Error, tuf.ssl_crypto.keydb.remove_key, rsakey3) @@ -318,44 +318,44 @@ def test_create_keydb_from_root_metadata(self): keydict, roledict, consistent_snapshot, compression_algorithms) - self.assertEqual(None, tuf.keydb.create_keydb_from_root_metadata(root_metadata)) - tuf.keydb.create_keydb_from_root_metadata(root_metadata) + self.assertEqual(None, tuf.ssl_crypto.keydb.create_keydb_from_root_metadata(root_metadata)) + tuf.ssl_crypto.keydb.create_keydb_from_root_metadata(root_metadata) # Ensure 'keyid' and 'keyid2' were added to the keydb database. - self.assertEqual(rsakey, tuf.keydb.get_key(keyid)) - self.assertEqual(rsakey2, tuf.keydb.get_key(keyid2)) + self.assertEqual(rsakey, tuf.ssl_crypto.keydb.get_key(keyid)) + self.assertEqual(rsakey2, tuf.ssl_crypto.keydb.get_key(keyid2)) # Verify that the keydb is populated for a non-default repository. repository_name = 'example_repository' - tuf.keydb.create_keydb_from_root_metadata(root_metadata, repository_name) + tuf.ssl_crypto.keydb.create_keydb_from_root_metadata(root_metadata, repository_name) # Test conditions for arguments with invalid formats. self.assertRaises(tuf.ssl_commons.exceptions.FormatError, - tuf.keydb.create_keydb_from_root_metadata, None) + tuf.ssl_crypto.keydb.create_keydb_from_root_metadata, None) self.assertRaises(tuf.ssl_commons.exceptions.FormatError, - tuf.keydb.create_keydb_from_root_metadata, '') + tuf.ssl_crypto.keydb.create_keydb_from_root_metadata, '') self.assertRaises(tuf.ssl_commons.exceptions.FormatError, - tuf.keydb.create_keydb_from_root_metadata, 123) + tuf.ssl_crypto.keydb.create_keydb_from_root_metadata, 123) self.assertRaises(tuf.ssl_commons.exceptions.FormatError, - tuf.keydb.create_keydb_from_root_metadata, ['123']) + tuf.ssl_crypto.keydb.create_keydb_from_root_metadata, ['123']) self.assertRaises(tuf.ssl_commons.exceptions.FormatError, - tuf.keydb.create_keydb_from_root_metadata, {'bad': '123'}) + tuf.ssl_crypto.keydb.create_keydb_from_root_metadata, {'bad': '123'}) self.assertRaises(tuf.ssl_commons.exceptions.FormatError, - tuf.keydb.create_keydb_from_root_metadata, root_metadata, 123) + tuf.ssl_crypto.keydb.create_keydb_from_root_metadata, root_metadata, 123) # Verify that a keydb cannot be created for a non-existent repository name. - tuf.keydb.create_keydb_from_root_metadata(root_metadata, 'non-existent') + tuf.ssl_crypto.keydb.create_keydb_from_root_metadata(root_metadata, 'non-existent') # Remove the 'non-existent' and 'example_repository' key database so that # subsequent test functions have access to a default keydb. - tuf.keydb.remove_keydb(repository_name) - tuf.keydb.remove_keydb('non-existent') + tuf.ssl_crypto.keydb.remove_keydb(repository_name) + tuf.ssl_crypto.keydb.remove_keydb('non-existent') # Test conditions for correctly formatted 'root_metadata' arguments but # containing incorrect keyids or key types. In these conditions, the keys # should not be added to the keydb database and a warning should be logged. - tuf.keydb.clear_keydb() + tuf.ssl_crypto.keydb.clear_keydb() # 'keyid' does not match 'rsakey2'. keydict[keyid] = rsakey2 @@ -374,13 +374,13 @@ def test_create_keydb_from_root_metadata(self): keydict, roledict, consistent_snapshot, compression_algorithms) - self.assertEqual(None, tuf.keydb.create_keydb_from_root_metadata(root_metadata)) + self.assertEqual(None, tuf.ssl_crypto.keydb.create_keydb_from_root_metadata(root_metadata)) # Ensure only 'keyid2' was added to the keydb database. 'keyid' and # 'keyid3' should not be stored. - self.assertEqual(rsakey2, tuf.keydb.get_key(keyid2)) - self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.keydb.get_key, keyid) - self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.keydb.get_key, keyid3) + self.assertEqual(rsakey2, tuf.ssl_crypto.keydb.get_key(keyid2)) + self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.ssl_crypto.keydb.get_key, keyid) + self.assertRaises(tuf.ssl_commons.exceptions.UnknownKeyError, tuf.ssl_crypto.keydb.get_key, keyid3) rsakey3['keytype'] = 'rsa' diff --git a/tests/test_keys.py b/tests/test_keys.py index 9f5e6e94..4fd5de7e 100755 --- a/tests/test_keys.py +++ b/tests/test_keys.py @@ -33,11 +33,11 @@ import tuf.ssl_crypto.pycrypto_keys import tuf.ssl_crypto.formats import tuf.tufformats -import tuf.keys +import tuf.ssl_crypto.keys logger = logging.getLogger('tuf.test_keys') -KEYS = tuf.keys +KEYS = tuf.ssl_crypto.keys FORMAT_ERROR_MSG = 'tuf.ssl_commons.exceptions.FormatError was raised! Check object\'s format.' DATA = 'SOME DATA REQUIRING AUTHENTICITY.' @@ -262,7 +262,7 @@ def test_verify_signature(self): self.assertRaises(TypeError, KEYS.verify_signature) # Verify that the pure python 'ed25519' base case (triggered if 'pynacl' is - # unavailable) is executed in tuf.keys.verify_signature(). + # unavailable) is executed in tuf.ssl_crypto.keys.verify_signature(). KEYS._ED25519_CRYPTO_LIBRARY = 'invalid' KEYS._available_crypto_libraries = ['invalid'] verified = KEYS.verify_signature(self.ed25519key_dict, ed25519_signature, DATA) diff --git a/tests/test_mix_and_match_attack.py b/tests/test_mix_and_match_attack.py index 6bfd9537..b3c27cf5 100755 --- a/tests/test_mix_and_match_attack.py +++ b/tests/test_mix_and_match_attack.py @@ -59,7 +59,7 @@ import tuf.repository_tool as repo_tool import tuf.unittest_toolbox as unittest_toolbox import tuf.roledb -import tuf.keydb +import tuf.ssl_crypto.keydb from simple_settings import settings import six @@ -175,7 +175,7 @@ def tearDown(self): # 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) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) def test_with_tuf(self): diff --git a/tests/test_replay_attack.py b/tests/test_replay_attack.py index b5a31ca4..2c6310a7 100755 --- a/tests/test_replay_attack.py +++ b/tests/test_replay_attack.py @@ -173,7 +173,7 @@ def tearDown(self): # 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) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) def test_without_tuf(self): diff --git a/tests/test_repository_lib.py b/tests/test_repository_lib.py index 95a74e12..b63bcd42 100755 --- a/tests/test_repository_lib.py +++ b/tests/test_repository_lib.py @@ -47,7 +47,7 @@ import tuf.log import tuf.tufformats import tuf.roledb -import tuf.keydb +import tuf.ssl_crypto.keydb import tuf.ssl_crypto.hash from simple_settings import settings import tuf.repository_lib as repo_lib @@ -91,7 +91,7 @@ def setUp(self): def tearDown(self): tuf.roledb.clear_roledb(clear_all=True) - tuf.keydb.clear_keydb(clear_all=True) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) @@ -273,7 +273,7 @@ def test_import_ed25519_publickey_from_file(self): keytype = imported_ed25519_key['keytype'] keyval = imported_ed25519_key['keyval'] ed25519key_metadata_format = \ - tuf.keys.format_keyval_to_metadata(keytype, keyval, private=False) + tuf.ssl_crypto.keys.format_keyval_to_metadata(keytype, keyval, private=False) ed25519key_metadata_format['keytype'] = 'invalid_keytype' with open(ed25519_keypath + '.pub', 'wb') as file_object: @@ -428,9 +428,9 @@ def test_generate_root_metadata(self): root_signable = tuf.ssl_crypto.util.load_json_file(root_filepath) # generate_root_metadata() expects the top-level roles and keys to be - # available in 'tuf.keydb' and 'tuf.roledb'. + # available in 'tuf.ssl_crypto.keydb' and 'tuf.roledb'. tuf.roledb.create_roledb_from_root_metadata(root_signable['signed']) - tuf.keydb.create_keydb_from_root_metadata(root_signable['signed']) + tuf.ssl_crypto.keydb.create_keydb_from_root_metadata(root_signable['signed']) expires = '1985-10-21T01:22:00Z' root_metadata = repo_lib.generate_root_metadata(1, expires, @@ -438,13 +438,13 @@ def test_generate_root_metadata(self): self.assertTrue(tuf.ssl_crypto.formats.ROOT_SCHEMA.matches(root_metadata)) root_keyids = tuf.roledb.get_role_keyids('root') - tuf.keydb._keydb_dict['default'][root_keyids[0]]['keytype'] = 'bad_keytype' + tuf.ssl_crypto.keydb._keydb_dict['default'][root_keyids[0]]['keytype'] = 'bad_keytype' self.assertRaises(tuf.ssl_commons.exceptions.Error, repo_lib.generate_root_metadata, 1, expires, consistent_snapshot=False) # Reset the root key's keytype, so that we can next verify that a different # tuf.ssl_commons.exceptions.Error exception is raised for duplicate keyids. - tuf.keydb._keydb_dict['default'][root_keyids[0]]['keytype'] = 'rsa' + tuf.ssl_crypto.keydb._keydb_dict['default'][root_keyids[0]]['keytype'] = 'rsa' # Add duplicate keyid to root's roleinfo. tuf.roledb._roledb_dict['default']['root']['keyids'].append(root_keyids[0]) @@ -461,7 +461,7 @@ def test_generate_root_metadata(self): # Test for missing required roles and keys. tuf.roledb.clear_roledb() - tuf.keydb.clear_keydb() + tuf.ssl_crypto.keydb.clear_keydb() self.assertRaises(tuf.ssl_commons.exceptions.Error, repo_lib.generate_root_metadata, 1, expires, False) @@ -681,7 +681,7 @@ def test_sign_metadata(self): targets_filename = os.path.join(metadata_path, 'targets.json') targets_metadata = tuf.ssl_crypto.util.load_json_file(targets_filename)['signed'] - tuf.keydb.create_keydb_from_root_metadata(root_metadata) + tuf.ssl_crypto.keydb.create_keydb_from_root_metadata(root_metadata) tuf.roledb.create_roledb_from_root_metadata(root_metadata) root_keyids = tuf.roledb.get_role_keyids('root') targets_keyids = tuf.roledb.get_role_keyids('targets') @@ -696,13 +696,13 @@ def test_sign_metadata(self): repo_lib.import_ed25519_publickey_from_file(targets_public_keypath) # sign_metadata() expects the private key 'root_metadata' to be in - # 'tuf.keydb'. Remove any public keys that may be loaded before + # 'tuf.ssl_crypto.keydb'. Remove any public keys that may be loaded before # adding private key, otherwise a 'tuf.KeyAlreadyExists' exception is # raised. - tuf.keydb.remove_key(root_private_key['keyid']) - tuf.keydb.add_key(root_private_key) - tuf.keydb.remove_key(targets_public_key['keyid']) - tuf.keydb.add_key(targets_public_key) + tuf.ssl_crypto.keydb.remove_key(root_private_key['keyid']) + tuf.ssl_crypto.keydb.add_key(root_private_key) + tuf.ssl_crypto.keydb.remove_key(targets_public_key['keyid']) + tuf.ssl_crypto.keydb.add_key(targets_public_key) # Verify that a valid root signable is generated. root_signable = repo_lib.sign_metadata(root_metadata, root_keyids, @@ -715,7 +715,7 @@ def test_sign_metadata(self): # Add an invalid keytype to one of the root keys. root_keyid = root_keyids[0] - tuf.keydb._keydb_dict['default'][root_keyid]['keytype'] = 'bad_keytype' + tuf.ssl_crypto.keydb._keydb_dict['default'][root_keyid]['keytype'] = 'bad_keytype' self.assertRaises(tuf.ssl_commons.exceptions.Error, repo_lib.sign_metadata, root_metadata, root_keyids, root_filename) @@ -999,7 +999,7 @@ def test__delete_obsolete_metadata(self): def test__load_top_level_metadata(self): tuf.roledb.clear_roledb(clear_all=True) - tuf.keydb.clear_keydb(clear_all=True) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) temporary_directory = tempfile.mkdtemp(dir=self.temporary_directory) repository_directory = os.path.join(temporary_directory, 'repository') @@ -1067,15 +1067,15 @@ def test__remove_invalid_and_duplicate_signatures(self): root_rsa_key = repo_lib.import_rsa_privatekey_from_file(key_filepath, 'password') - # Add 'root_rsa_key' to tuf.keydb, since + # Add 'root_rsa_key' to tuf.ssl_crypto.keydb, since # _remove_invalid_and_duplicate_signatures() checks for unknown keys in - # tuf.keydb. - tuf.keydb.add_key(root_rsa_key) + # tuf.ssl_crypto.keydb. + tuf.ssl_crypto.keydb.add_key(root_rsa_key) # Append the new valid, but duplicate PSS signature, and test that # duplicates are removed. create_signature() generates a key for the # key type of the first argument (i.e., root_rsa_key). - new_pss_signature = tuf.keys.create_signature(root_rsa_key, + new_pss_signature = tuf.ssl_crypto.keys.create_signature(root_rsa_key, root_signable['signed']) root_signable['signatures'].append(new_pss_signature) diff --git a/tests/test_repository_tool.py b/tests/test_repository_tool.py index 3871e150..73d05103 100755 --- a/tests/test_repository_tool.py +++ b/tests/test_repository_tool.py @@ -45,7 +45,7 @@ import tuf.log import tuf.tufformats import tuf.roledb -import tuf.keydb +import tuf.ssl_crypto.keydb import tuf.ssl_crypto.hash import tuf.repository_tool as repo_tool @@ -88,7 +88,7 @@ def setUp(self): def tearDown(self): tuf.roledb.clear_roledb(clear_all=True) - tuf.keydb.clear_keydb(clear_all=True) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) def test_init(self): @@ -438,7 +438,7 @@ def __init__(self): def tearDown(self): tuf.roledb.clear_roledb() - tuf.keydb.clear_keydb() + tuf.ssl_crypto.keydb.clear_keydb() self.metadata = None @@ -785,7 +785,7 @@ def setUp(self): def tearDown(self): tuf.roledb.clear_roledb() - tuf.keydb.clear_keydb() + tuf.ssl_crypto.keydb.clear_keydb() @@ -807,7 +807,7 @@ def setUp(self): def tearDown(self): tuf.roledb.clear_roledb() - tuf.keydb.clear_keydb() + tuf.ssl_crypto.keydb.clear_keydb() @@ -832,7 +832,7 @@ def setUp(self): def tearDown(self): tuf.roledb.clear_roledb() - tuf.keydb.clear_keydb() + tuf.ssl_crypto.keydb.clear_keydb() @@ -887,7 +887,7 @@ def setUp(self): def tearDown(self): tuf.roledb.clear_roledb() - tuf.keydb.clear_keydb() + tuf.ssl_crypto.keydb.clear_keydb() self.targets_object = None diff --git a/tests/test_roledb.py b/tests/test_roledb.py index 44ca35cf..172f9491 100755 --- a/tests/test_roledb.py +++ b/tests/test_roledb.py @@ -30,7 +30,7 @@ import tuf import tuf.tufformats -import tuf.keys +import tuf.ssl_crypto.keys import tuf.roledb import tuf.log @@ -40,7 +40,7 @@ # Generate the three keys to use in our test cases. KEYS = [] for junk in range(3): - KEYS.append(tuf.keys.generate_rsa_key(2048)) + KEYS.append(tuf.ssl_crypto.keys.generate_rsa_key(2048)) diff --git a/tests/test_root_versioning_integration.py b/tests/test_root_versioning_integration.py index fbe149b5..b80709f5 100755 --- a/tests/test_root_versioning_integration.py +++ b/tests/test_root_versioning_integration.py @@ -38,7 +38,7 @@ import tuf.log import tuf.tufformats import tuf.roledb -import tuf.keydb +import tuf.ssl_crypto.keydb import tuf.ssl_crypto.hash import tuf.repository_tool as repo_tool @@ -59,7 +59,7 @@ def tearDownClass(cls): def tearDown(self): tuf.roledb.clear_roledb() - tuf.keydb.clear_keydb() + tuf.ssl_crypto.keydb.clear_keydb() def test_init(self): # Test normal case. diff --git a/tests/test_sig.py b/tests/test_sig.py index e428f319..d5008043 100755 --- a/tests/test_sig.py +++ b/tests/test_sig.py @@ -32,9 +32,9 @@ import tuf import tuf.log import tuf.tufformats -import tuf.keydb +import tuf.ssl_crypto.keydb import tuf.roledb -import tuf.keys +import tuf.ssl_crypto.keys import tuf.sig logger = logging.getLogger('tuf.test_sig') @@ -42,7 +42,7 @@ # Setup the keys to use in our test cases. KEYS = [] for _ in range(3): - KEYS.append(tuf.keys.generate_rsa_key(2048)) + KEYS.append(tuf.ssl_crypto.keys.generate_rsa_key(2048)) @@ -52,7 +52,7 @@ def setUp(self): def tearDown(self): tuf.roledb.clear_roledb() - tuf.keydb.clear_keydb() + tuf.ssl_crypto.keydb.clear_keydb() def test_get_signature_status_no_role(self): @@ -76,10 +76,10 @@ def test_get_signature_status_no_role(self): # Should verify we are not adding a duplicate signature # when doing the following action. Here we know 'signable' # has only one signature so it's okay. - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[0], signable['signed'])) - tuf.keydb.add_key(KEYS[0]) + tuf.ssl_crypto.keydb.add_key(KEYS[0]) # Improperly formatted role. self.assertRaises(tuf.ssl_commons.exceptions.FormatError, tuf.sig.get_signature_status, @@ -90,17 +90,17 @@ def test_get_signature_status_no_role(self): self.assertRaises(tuf.ssl_commons.exceptions.Error, tuf.sig.verify, *args) # Done. Let's remove the added key(s) from the key database. - tuf.keydb.remove_key(KEYS[0]['keyid']) + tuf.ssl_crypto.keydb.remove_key(KEYS[0]['keyid']) def test_get_signature_status_bad_sig(self): signable = {'signed' : 'test', 'signatures' : []} - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[0], signable['signed'])) signable['signed'] += 'signature no longer matches signed data' - tuf.keydb.add_key(KEYS[0]) + tuf.ssl_crypto.keydb.add_key(KEYS[0]) threshold = 1 roleinfo = tuf.tufformats.make_role_metadata( [KEYS[0]['keyid']], threshold) @@ -118,7 +118,7 @@ def test_get_signature_status_bad_sig(self): self.assertFalse(tuf.sig.verify(signable, 'Root')) # Done. Let's remove the added key(s) from the key database. - tuf.keydb.remove_key(KEYS[0]['keyid']) + tuf.ssl_crypto.keydb.remove_key(KEYS[0]['keyid']) # Remove the role. tuf.roledb.remove_role('Root') @@ -126,11 +126,11 @@ def test_get_signature_status_bad_sig(self): def test_get_signature_status_unknown_method(self): signable = {'signed' : 'test', 'signatures' : []} - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[0], signable['signed'])) signable['signatures'][0]['method'] = 'fake-sig-method' - tuf.keydb.add_key(KEYS[0]) + tuf.ssl_crypto.keydb.add_key(KEYS[0]) threshold = 1 roleinfo = tuf.tufformats.make_role_metadata( [KEYS[0]['keyid']], threshold) @@ -149,7 +149,7 @@ def test_get_signature_status_unknown_method(self): self.assertFalse(tuf.sig.verify(signable, 'Root')) # Done. Let's remove the added key(s) from the key database. - tuf.keydb.remove_key(KEYS[0]['keyid']) + tuf.ssl_crypto.keydb.remove_key(KEYS[0]['keyid']) # Remove the role. tuf.roledb.remove_role('Root') @@ -157,7 +157,7 @@ def test_get_signature_status_unknown_method(self): def test_get_signature_status_single_key(self): signable = {'signed' : 'test', 'signatures' : []} - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[0], signable['signed'])) threshold = 1 @@ -165,7 +165,7 @@ def test_get_signature_status_single_key(self): [KEYS[0]['keyid']], threshold) tuf.roledb.add_role('Root', roleinfo) - tuf.keydb.add_key(KEYS[0]) + tuf.ssl_crypto.keydb.add_key(KEYS[0]) sig_status = tuf.sig.get_signature_status(signable, 'Root') @@ -189,7 +189,7 @@ def test_get_signature_status_single_key(self): self.assertEqual([], sig_status['unknown_method_sigs']) # Done. Let's remove the added key(s) from the key database. - tuf.keydb.remove_key(KEYS[0]['keyid']) + tuf.ssl_crypto.keydb.remove_key(KEYS[0]['keyid']) # Remove the role. tuf.roledb.remove_role('Root') @@ -197,10 +197,10 @@ def test_get_signature_status_single_key(self): def test_get_signature_status_below_threshold(self): signable = {'signed' : 'test', 'signatures' : []} - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[0], signable['signed'])) - tuf.keydb.add_key(KEYS[0]) + tuf.ssl_crypto.keydb.add_key(KEYS[0]) threshold = 2 roleinfo = tuf.tufformats.make_role_metadata( [KEYS[0]['keyid'], @@ -219,7 +219,7 @@ def test_get_signature_status_below_threshold(self): self.assertFalse(tuf.sig.verify(signable, 'Root')) # Done. Let's remove the added key(s) from the key database. - tuf.keydb.remove_key(KEYS[0]['keyid']) + tuf.ssl_crypto.keydb.remove_key(KEYS[0]['keyid']) # Remove the role. tuf.roledb.remove_role('Root') @@ -229,13 +229,13 @@ def test_get_signature_status_below_threshold_unrecognized_sigs(self): signable = {'signed' : 'test', 'signatures' : []} # Two keys sign it, but only one of them will be trusted. - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[0], signable['signed'])) - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[2], signable['signed'])) - tuf.keydb.add_key(KEYS[0]) - tuf.keydb.add_key(KEYS[1]) + tuf.ssl_crypto.keydb.add_key(KEYS[0]) + tuf.ssl_crypto.keydb.add_key(KEYS[1]) threshold = 2 roleinfo = tuf.tufformats.make_role_metadata( [KEYS[0]['keyid'], @@ -254,8 +254,8 @@ def test_get_signature_status_below_threshold_unrecognized_sigs(self): self.assertFalse(tuf.sig.verify(signable, 'Root')) # Done. Let's remove the added key(s) from the key database. - tuf.keydb.remove_key(KEYS[0]['keyid']) - tuf.keydb.remove_key(KEYS[1]['keyid']) + tuf.ssl_crypto.keydb.remove_key(KEYS[0]['keyid']) + tuf.ssl_crypto.keydb.remove_key(KEYS[1]['keyid']) # Remove the role. tuf.roledb.remove_role('Root') @@ -266,13 +266,13 @@ def test_get_signature_status_below_threshold_unauthorized_sigs(self): # Two keys sign it, but one of them is only trusted for a different # role. - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[0], signable['signed'])) - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[1], signable['signed'])) - tuf.keydb.add_key(KEYS[0]) - tuf.keydb.add_key(KEYS[1]) + tuf.ssl_crypto.keydb.add_key(KEYS[0]) + tuf.ssl_crypto.keydb.add_key(KEYS[1]) threshold = 2 roleinfo = tuf.tufformats.make_role_metadata( [KEYS[0]['keyid'], KEYS[2]['keyid']], threshold) @@ -296,8 +296,8 @@ def test_get_signature_status_below_threshold_unauthorized_sigs(self): tuf.sig.get_signature_status, signable, 'unknown_role') # Done. Let's remove the added key(s) from the key database. - tuf.keydb.remove_key(KEYS[0]['keyid']) - tuf.keydb.remove_key(KEYS[1]['keyid']) + tuf.ssl_crypto.keydb.remove_key(KEYS[0]['keyid']) + tuf.ssl_crypto.keydb.remove_key(KEYS[1]['keyid']) # Remove the roles. tuf.roledb.remove_role('Root') @@ -308,10 +308,10 @@ def test_get_signature_status_below_threshold_unauthorized_sigs(self): def test_check_signatures_no_role(self): signable = {'signed' : 'test', 'signatures' : []} - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[0], signable['signed'])) - tuf.keydb.add_key(KEYS[0]) + tuf.ssl_crypto.keydb.add_key(KEYS[0]) # No specific role we're considering. It's invalid to use the # function tuf.sig.verify() without a role specified because @@ -320,16 +320,16 @@ def test_check_signatures_no_role(self): self.assertRaises(tuf.ssl_commons.exceptions.Error, tuf.sig.verify, *args) # Done. Let's remove the added key(s) from the key database. - tuf.keydb.remove_key(KEYS[0]['keyid']) + tuf.ssl_crypto.keydb.remove_key(KEYS[0]['keyid']) def test_verify_single_key(self): signable = {'signed' : 'test', 'signatures' : []} - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[0], signable['signed'])) - tuf.keydb.add_key(KEYS[0]) + tuf.ssl_crypto.keydb.add_key(KEYS[0]) threshold = 1 roleinfo = tuf.tufformats.make_role_metadata( [KEYS[0]['keyid']], threshold) @@ -340,7 +340,7 @@ def test_verify_single_key(self): self.assertTrue(tuf.sig.verify(signable, 'Root')) # Done. Let's remove the added key(s) from the key database. - tuf.keydb.remove_key(KEYS[0]['keyid']) + tuf.ssl_crypto.keydb.remove_key(KEYS[0]['keyid']) # Remove the roles. tuf.roledb.remove_role('Root') @@ -350,13 +350,13 @@ def test_verify_unrecognized_sig(self): signable = {'signed' : 'test', 'signatures' : []} # Two keys sign it, but only one of them will be trusted. - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[0], signable['signed'])) - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[2], signable['signed'])) - tuf.keydb.add_key(KEYS[0]) - tuf.keydb.add_key(KEYS[1]) + tuf.ssl_crypto.keydb.add_key(KEYS[0]) + tuf.ssl_crypto.keydb.add_key(KEYS[1]) threshold = 2 roleinfo = tuf.tufformats.make_role_metadata( [KEYS[0]['keyid'], KEYS[1]['keyid']], threshold) @@ -365,8 +365,8 @@ def test_verify_unrecognized_sig(self): self.assertFalse(tuf.sig.verify(signable, 'Root')) # Done. Let's remove the added key(s) from the key database. - tuf.keydb.remove_key(KEYS[0]['keyid']) - tuf.keydb.remove_key(KEYS[1]['keyid']) + tuf.ssl_crypto.keydb.remove_key(KEYS[0]['keyid']) + tuf.ssl_crypto.keydb.remove_key(KEYS[1]['keyid']) # Remove the roles. tuf.roledb.remove_role('Root') @@ -376,7 +376,7 @@ def test_verify_unrecognized_sig(self): def test_generate_rsa_signature(self): signable = {'signed' : 'test', 'signatures' : []} - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[0], signable['signed'])) self.assertEqual(1, len(signable['signatures'])) @@ -386,7 +386,7 @@ def test_generate_rsa_signature(self): returned_signature = tuf.sig.generate_rsa_signature(signable['signed'], KEYS[0]) self.assertTrue(tuf.ssl_crypto.formats.SIGNATURE_SCHEMA.matches(returned_signature)) - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[1], signable['signed'])) self.assertEqual(2, len(signable['signatures'])) @@ -399,10 +399,10 @@ def test_may_need_new_keys(self): # One untrusted key in 'signable'. signable = {'signed' : 'test', 'signatures' : []} - signable['signatures'].append(tuf.keys.create_signature( + signable['signatures'].append(tuf.ssl_crypto.keys.create_signature( KEYS[0], signable['signed'])) - tuf.keydb.add_key(KEYS[1]) + tuf.ssl_crypto.keydb.add_key(KEYS[1]) threshold = 1 roleinfo = tuf.tufformats.make_role_metadata( [KEYS[1]['keyid']], threshold) @@ -414,7 +414,7 @@ def test_may_need_new_keys(self): # Done. Let's remove the added key(s) from the key database. - tuf.keydb.remove_key(KEYS[1]['keyid']) + tuf.ssl_crypto.keydb.remove_key(KEYS[1]['keyid']) # Remove the roles. tuf.roledb.remove_role('Root') diff --git a/tests/test_slow_retrieval_attack.py b/tests/test_slow_retrieval_attack.py index 52d4dd95..c01738db 100755 --- a/tests/test_slow_retrieval_attack.py +++ b/tests/test_slow_retrieval_attack.py @@ -63,7 +63,7 @@ import tuf.unittest_toolbox as unittest_toolbox import tuf.repository_tool as repo_tool import tuf.roledb -import tuf.keydb +import tuf.ssl_crypto.keydb from simple_settings import settings import six @@ -219,7 +219,7 @@ def tearDown(self): # 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) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) def test_with_tuf_mode_1(self): diff --git a/tests/test_updater.py b/tests/test_updater.py index 62baf908..70fc389c 100755 --- a/tests/test_updater.py +++ b/tests/test_updater.py @@ -69,7 +69,7 @@ from simple_settings import settings import tuf.log import tuf.tufformats -import tuf.keydb +import tuf.ssl_crypto.keydb import tuf.roledb import tuf.repository_tool as repo_tool import tuf.unittest_toolbox as unittest_toolbox @@ -194,7 +194,7 @@ def tearDown(self): # We are inheriting from custom class. unittest_toolbox.Modified_TestCase.tearDown(self) tuf.roledb.clear_roledb(clear_all=True) - tuf.keydb.clear_keydb(clear_all=True) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) @@ -332,8 +332,8 @@ def test_1__rebuild_key_and_role_db(self): # keys multiplied by the number of keyid hash algorithms), to include the # delegated targets key. The delegated roles of 'targets.json' are also # loaded when the repository object is instantiated. - print('\ndifference: ' + repr(list(set(tuf.keydb._keydb_dict[self.repository_name].keys()) - set(root_metadata['keys'].keys())))) - self.assertEqual(number_of_root_keys * 2 + 1, len(tuf.keydb._keydb_dict[self.repository_name])) + print('\ndifference: ' + repr(list(set(tuf.ssl_crypto.keydb._keydb_dict[self.repository_name].keys()) - set(root_metadata['keys'].keys())))) + self.assertEqual(number_of_root_keys * 2 + 1, len(tuf.ssl_crypto.keydb._keydb_dict[self.repository_name])) # Test: normal case. self.repository_updater._rebuild_key_and_role_db() @@ -343,7 +343,7 @@ def test_1__rebuild_key_and_role_db(self): # _rebuild_key_and_role_db() will only rebuild the keys and roles specified # in the 'root.json' file, unlike __init__(). Instantiating an updater # object calls both _rebuild_key_and_role_db() and _import_delegations(). - self.assertEqual(number_of_root_keys * 2, len(tuf.keydb._keydb_dict[self.repository_name])) + self.assertEqual(number_of_root_keys * 2, len(tuf.ssl_crypto.keydb._keydb_dict[self.repository_name])) # Test: properly updated roledb and keydb dicts if the Root role changes. root_metadata = self.repository_updater.metadata['current']['root'] @@ -354,7 +354,7 @@ def test_1__rebuild_key_and_role_db(self): root_roleinfo = tuf.roledb.get_roleinfo('root', self.repository_name) self.assertEqual(root_roleinfo['threshold'], 8) - self.assertEqual(number_of_root_keys * 2 - 2, len(tuf.keydb._keydb_dict[self.repository_name])) + self.assertEqual(number_of_root_keys * 2 - 2, len(tuf.ssl_crypto.keydb._keydb_dict[self.repository_name])) """ @@ -459,20 +459,20 @@ def test_2__import_delegations(self): # there without using '_load_metadata_from_file()' since it calls # '_import_delegations()'. repository_name = self.repository_updater.updater_name - tuf.keydb.clear_keydb(repository_name) + tuf.ssl_crypto.keydb.clear_keydb(repository_name) tuf.roledb.clear_roledb(repository_name) self.assertEqual(len(tuf.roledb._roledb_dict[repository_name]), 0) - self.assertEqual(len(tuf.keydb._keydb_dict[repository_name]), 0) + self.assertEqual(len(tuf.ssl_crypto.keydb._keydb_dict[repository_name]), 0) self.repository_updater._rebuild_key_and_role_db() self.assertEqual(len(tuf.roledb._roledb_dict[repository_name]), 4) # Take into account the number of keyids algorithms supported by default, # which this test condition expects to be two (sha256 and sha512). - print('\nkeydb_dict len: ' + repr(len(tuf.keydb._keydb_dict[repository_name].keys()))) - print('\nkeydb_dict: ' + repr(tuf.keydb._keydb_dict[repository_name].keys())) - self.assertEqual(4 * 2, len(tuf.keydb._keydb_dict[repository_name])) + print('\nkeydb_dict len: ' + repr(len(tuf.ssl_crypto.keydb._keydb_dict[repository_name].keys()))) + print('\nkeydb_dict: ' + repr(tuf.ssl_crypto.keydb._keydb_dict[repository_name].keys())) + self.assertEqual(4 * 2, len(tuf.ssl_crypto.keydb._keydb_dict[repository_name])) # Test: pass a role without delegations. self.repository_updater._import_delegations('root') @@ -482,7 +482,7 @@ def test_2__import_delegations(self): self.assertEqual(len(tuf.roledb._roledb_dict[repository_name]), 4) # Take into account the number of keyid hash algorithms, which this # test condition expects to be two (for sha256 and sha512). - self.assertEqual(len(tuf.keydb._keydb_dict[repository_name]), 4 * 2) + self.assertEqual(len(tuf.ssl_crypto.keydb._keydb_dict[repository_name]), 4 * 2) # Test: normal case, first level delegation. self.repository_updater._import_delegations('targets') @@ -490,7 +490,7 @@ def test_2__import_delegations(self): self.assertEqual(len(tuf.roledb._roledb_dict[repository_name]), 5) # The number of root keys (times the number of key hash algorithms) + # delegation's key. - self.assertEqual(len(tuf.keydb._keydb_dict[repository_name]), 4 * 2 + 1) + self.assertEqual(len(tuf.ssl_crypto.keydb._keydb_dict[repository_name]), 4 * 2 + 1) # Verify that roledb dictionary was added. self.assertTrue('role1' in tuf.roledb._roledb_dict[repository_name]) @@ -504,7 +504,7 @@ def test_2__import_delegations(self): keyids.append(signature['keyid']) for keyid in keyids: - self.assertTrue(keyid in tuf.keydb._keydb_dict[repository_name]) + self.assertTrue(keyid in tuf.ssl_crypto.keydb._keydb_dict[repository_name]) # Verify that _import_delegations() ignores invalid keytypes in the 'keys' # field of parent role's 'delegations'. @@ -520,7 +520,7 @@ def test_2__import_delegations(self): # Verify that _import_delegations() raises an exception if any key in # 'delegations' is improperly formatted (i.e., bad keyid). - tuf.keydb.clear_keydb(repository_name) + tuf.ssl_crypto.keydb.clear_keydb(repository_name) self.repository_updater.metadata['current']['targets']['delegations']\ ['keys'].update({'123': self.repository_updater.metadata['current']\ diff --git a/tests/test_updater_root_rotation_integration.py b/tests/test_updater_root_rotation_integration.py index 7e7f88e6..116c7bce 100755 --- a/tests/test_updater_root_rotation_integration.py +++ b/tests/test_updater_root_rotation_integration.py @@ -60,7 +60,7 @@ from simple_settings import settings import tuf.log import tuf.tufformats -import tuf.keydb +import tuf.ssl_crypto.keydb import tuf.roledb import tuf.repository_tool as repo_tool import tuf.unittest_toolbox as unittest_toolbox @@ -185,7 +185,7 @@ def tearDown(self): # We are inheriting from custom class. unittest_toolbox.Modified_TestCase.tearDown(self) tuf.roledb.clear_roledb(clear_all=True) - tuf.keydb.clear_keydb(clear_all=True) + tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) diff --git a/tuf/client/updater.py b/tuf/client/updater.py index fe3537ae..66175492 100755 --- a/tuf/client/updater.py +++ b/tuf/client/updater.py @@ -120,8 +120,8 @@ import tuf.download import tuf.tufformats import tuf.ssl_crypto.hash -import tuf.keys -import tuf.keydb +import tuf.ssl_crypto.keys +import tuf.ssl_crypto.keydb import tuf.log import tuf.mirrors import tuf.roledb @@ -490,7 +490,7 @@ def _rebuild_key_and_role_db(self): # The metadata files for delegated roles are also not loaded when the # repository is first instantiated. Due to this setup, reloading delegated # roles is not required here. - tuf.keydb.create_keydb_from_root_metadata(self.metadata['current']['root'], + tuf.ssl_crypto.keydb.create_keydb_from_root_metadata(self.metadata['current']['root'], self.updater_name) tuf.roledb.create_roledb_from_root_metadata(self.metadata['current']['root'], self.updater_name) @@ -538,15 +538,15 @@ def _import_delegations(self, parent_role): # Iterate the keys of the delegated roles of 'parent_role' and load them. for keyid, keyinfo in six.iteritems(keys_info): if keyinfo['keytype'] in ['rsa', 'ed25519']: - key, keyids = tuf.keys.format_metadata_to_key(keyinfo) + key, keyids = tuf.ssl_crypto.keys.format_metadata_to_key(keyinfo) # We specify the keyid to ensure that it's the correct keyid # for the key. try: - tuf.keydb.add_key(key, keyid, self.updater_name) + tuf.ssl_crypto.keydb.add_key(key, keyid, self.updater_name) for keyid in keyids: key['keyid'] = keyid - tuf.keydb.add_key(key, keyid=None, repository_name=self.updater_name) + tuf.ssl_crypto.keydb.add_key(key, keyid=None, repository_name=self.updater_name) except tuf.ssl_commons.exceptions.KeyAlreadyExistsError: pass diff --git a/tuf/developer_tool.py b/tuf/developer_tool.py index e433fa07..ad3dc1dd 100755 --- a/tuf/developer_tool.py +++ b/tuf/developer_tool.py @@ -39,9 +39,9 @@ import tuf import tuf.tufformats import tuf.ssl_crypto.util -import tuf.keydb +import tuf.ssl_crypto.keydb import tuf.roledb -import tuf.keys +import tuf.ssl_crypto.keys import tuf.sig import tuf.log from simple_settings import settings @@ -50,8 +50,8 @@ # These imports provide the interface for 'developer_tool.py', since the imports # are made there. -from tuf.keys import format_keyval_to_metadata -from tuf.keys import format_metadata_to_key +from tuf.ssl_crypto.keys import format_keyval_to_metadata +from tuf.ssl_crypto.keys import format_metadata_to_key from tuf.repository_tool import Targets from tuf.repository_lib import get_metadata_fileinfo @@ -249,7 +249,7 @@ def write(self, write_partial=False): # Raise 'tuf.ssl_commons.exceptions.FormatError' if any are improperly formatted. tuf.ssl_crypto.formats.BOOLEAN_SCHEMA.check_match(write_partial) - # At this point the tuf.keydb and tuf.roledb stores must be fully + # At this point the tuf.ssl_crypto.keydb and tuf.roledb stores must be fully # populated, otherwise write() throwns a 'tuf.Repository' exception if # any of the project roles are missing signatures, keys, etc. @@ -310,7 +310,7 @@ def add_verification_key(self, key): tuf.ssl_commons.exceptions.Error, if the project already contains a key. - The role's entries in 'tuf.keydb.py' and 'tuf.roledb.py' are updated. + The role's entries in 'tuf.ssl_crypto.keydb.py' and 'tuf.roledb.py' are updated. None @@ -754,7 +754,7 @@ def _save_project_configuration(metadata_directory, targets_directory, # Build a dictionary containing the actual keys. for key in public_keys: - key_info = tuf.keydb.get_key(key) + key_info = tuf.ssl_crypto.keydb.get_key(key) key_metadata = format_keyval_to_metadata(key_info['keytype'], key_info['keyval']) project_config['public_keys'][key] = key_metadata @@ -807,7 +807,7 @@ def load_project(project_directory, prefix='', new_targets_location=None): # Clear the role and key databases since we are loading in a new project. tuf.roledb.clear_roledb() - tuf.keydb.clear_keydb() + tuf.ssl_crypto.keydb.clear_keydb() # Locate metadata filepaths and targets filepath. project_directory = os.path.abspath(project_directory) @@ -857,7 +857,7 @@ def load_project(project_directory, prefix='', new_targets_location=None): keydict = project_configuration['public_keys'] for keyid in keydict: - key, junk = tuf.keys.format_metadata_to_key(keydict[keyid]) + key, junk = tuf.ssl_crypto.keys.format_metadata_to_key(keydict[keyid]) project.add_verification_key(key) # Load the project's metadata. @@ -890,8 +890,8 @@ def load_project(project_directory, prefix='', new_targets_location=None): for key_metadata in targets_metadata['delegations']['keys'].values(): - key_object, junk = tuf.keys.format_metadata_to_key(key_metadata) - tuf.keydb.add_key(key_object) + key_object, junk = tuf.ssl_crypto.keys.format_metadata_to_key(key_metadata) + tuf.ssl_crypto.keydb.add_key(key_object) for role in targets_metadata['delegations']['roles']: rolename = role['name'] @@ -972,10 +972,10 @@ def load_project(project_directory, prefix='', new_targets_location=None): # Add the keys specified in the delegations field of the Targets role. for key_metadata in metadata_object['delegations']['keys'].values(): - key_object, junk = tuf.keys.format_metadata_to_key(key_metadata) + key_object, junk = tuf.ssl_crypto.keys.format_metadata_to_key(key_metadata) try: - tuf.keydb.add_key(key_object) + tuf.ssl_crypto.keydb.add_key(key_object) except tuf.ssl_commons.exceptions.KeyAlreadyExistsError: pass diff --git a/tuf/keydb.py b/tuf/keydb.py deleted file mode 100755 index 9355d458..00000000 --- a/tuf/keydb.py +++ /dev/null @@ -1,443 +0,0 @@ -""" - - keydb.py - - - Vladimir Diaz - - - March 21, 2012. Based on a previous version of this module by Geremy Condra. - - - See LICENSE for licensing information. - - - Represent a collection of keys and their organization. This module ensures - the layout of the collection remain consistent and easily verifiable. - Provided are functions to add and delete keys from the database, retrieve a - single key, and assemble a collection from keys stored in TUF 'Root' Metadata. - The Update Framework process maintains a set of role info for multiple - repositories. - - RSA keys are currently supported and a collection of keys is organized as a - dictionary indexed by key ID. Key IDs are used as identifiers for keys - (e.g., RSA key). They are the hexadecimal representations of the hash of key - objects (specifically, the key object containing only the public key). See - 'rsa_key.py' and the '_get_keyid()' function to learn precisely how keyids - are generated. One may get the keyid of a key object by simply accessing the - dictionary's 'keyid' key (i.e., rsakey['keyid']). -""" - -# Help with Python 3 compatibility, where the print statement is a function, an -# implicit relative import is invalid, and the '/' operator performs true -# division. Example: print 'hello world' raises a 'SyntaxError' exception. -from __future__ import print_function -from __future__ import absolute_import -from __future__ import division -from __future__ import unicode_literals - -import logging -import copy - -import tuf -import tuf.tufformats -import tuf.keys -import six - -# List of strings representing the key types supported by TUF. -_SUPPORTED_KEY_TYPES = ['rsa', 'ed25519'] - -# See 'log.py' to learn how logging is handled in TUF. -logger = logging.getLogger('tuf.keydb') - -# The key database. -_keydb_dict = {} -_keydb_dict['default'] = {} - - -def create_keydb_from_root_metadata(root_metadata, repository_name='default'): - """ - - Populate the key database with the unique keys found in 'root_metadata'. - The database dictionary will conform to 'tuf.ssl_crypto.formats.KEYDB_SCHEMA' and - have the form: {keyid: key, ...}. - The 'keyid' conforms to 'tuf.ssl_crypto.formats.KEYID_SCHEMA' and 'key' to its - respective type. In the case of RSA keys, this object would match - 'RSAKEY_SCHEMA'. - - - root_metadata: - A dictionary conformant to 'tuf.ssl_crypto.formats.ROOT_SCHEMA'. The keys found - in the 'keys' field of 'root_metadata' are needed by this function. - - repository_name: - The name of the repository to store the key information. If not supplied, - the key database is populated for the 'default' repository. - - - tuf.ssl_commons.exceptions.FormatError, if 'root_metadata' does not have the correct format. - - tuf.ssl_commons.exceptions.InvalidNameError, if 'repository_name' does not exist in the key - database. - - - A function to add the key to the database is called. In the case of RSA - keys, this function is add_key(). - - The old keydb key database is replaced. - - - None. - """ - - # Does 'root_metadata' have the correct format? - # This check will ensure 'root_metadata' has the appropriate number of objects - # and object types, and that all dict keys are properly named. - # Raise 'tuf.ssl_commons.exceptions.FormatError' if the check fails. - tuf.ssl_crypto.formats.ROOT_SCHEMA.check_match(root_metadata) - - # Does 'repository_name' have the correct format? - tuf.ssl_crypto.formats.NAME_SCHEMA.check_match(repository_name) - - # Clear the key database for 'repository_name', or create it if non-existent. - if repository_name in _keydb_dict: - _keydb_dict[repository_name].clear() - - else: - create_keydb(repository_name) - - # Iterate the keys found in 'root_metadata' by converting them to - # 'RSAKEY_SCHEMA' if their type is 'rsa', and then adding them to the - # key database. - for keyid_in_root_metadata, key_metadata in six.iteritems(root_metadata['keys']): - if key_metadata['keytype'] in _SUPPORTED_KEY_TYPES: - # 'key_metadata' is stored in 'KEY_SCHEMA' format. Call - # create_from_metadata_format() to get the key in 'RSAKEY_SCHEMA' - # format, which is the format expected by 'add_key()'. Note: - # The 'keyids' returned by format_metadata_to_key() include keyids in - # addition to the default keyid listed in 'key_dict'. The additional - # keyids are generated according to settings.REPOSITORY_HASH_ALGORITHMS. - key_dict, keyids = tuf.keys.format_metadata_to_key(key_metadata) - - try: - for keyid in keyids: - # Make sure to update key_dict['keyid'] to use one of the other valid - # keyids, otherwise add_key() will have no reference to it. - key_dict['keyid'] = keyid - add_key(key_dict, keyid=None, repository_name=repository_name) - - # Although keyid duplicates should *not* occur (unique dict keys), log a - # warning and continue. Howerver, 'key_dict' may have already been - # adding to the keydb elsewhere. - except tuf.ssl_commons.exceptions.KeyAlreadyExistsError as e: # pragma: no cover - logger.warning(e) - continue - - else: - logger.warning('Root Metadata file contains a key with an invalid keytype.') - - - - - -def create_keydb(repository_name): - """ - - Create a key database for a non-default repository named 'repository_name'. - - - repository_name: - The name of the repository. An empty key database is created, and keys - may be added to via add_key(keyid, repository_name). - - - tuf.ssl_commons.exceptions.FormatError, if 'repository_name' is improperly formatted. - - tuf.ssl_commons.exceptions.InvalidNameError, if 'repository_name' already exists. - - - None. - - - None. - """ - - # Is 'repository_name' properly formatted? Raise 'tuf.ssl_commons.exceptions.FormatError' if not. - tuf.ssl_crypto.formats.NAME_SCHEMA.check_match(repository_name) - - if repository_name in _keydb_dict: - raise tuf.ssl_commons.exceptions.InvalidNameError('Repository name already exists:' - ' ' + repr(repository_name)) - - _keydb_dict[repository_name] = {} - - - - - -def remove_keydb(repository_name): - """ - - Remove a key database for a non-default repository named 'repository_name'. - The 'default' repository cannot be removed. - - - repository_name: - The name of the repository to remove. The 'default' repository should - not be removed, so 'repository_name' cannot be 'default'. - - - tuf.ssl_commons.exceptions.FormatError, if 'repository_name' is improperly formatted. - - tuf.ssl_commons.exceptions.InvalidNameError, if 'repository_name' is 'default'. - - - None. - - - None. - """ - - # Is 'repository_name' properly formatted? Raise 'tuf.ssl_commons.exceptions.FormatError' if not. - tuf.ssl_crypto.formats.NAME_SCHEMA.check_match(repository_name) - - if repository_name not in _keydb_dict: - logger.warn('Repository name does not exist: ' + repr(repository_name)) - return - - if repository_name == 'default': - raise tuf.ssl_commons.exceptions.InvalidNameError('Cannot remove the default repository:' - ' ' + repr(repository_name)) - - del _keydb_dict[repository_name] - - - - -def add_key(key_dict, keyid=None, repository_name='default'): - """ - - Add 'rsakey_dict' to the key database while avoiding duplicates. - If keyid is provided, verify it is the correct keyid for 'rsakey_dict' - and raise an exception if it is not. - - - key_dict: - A dictionary conformant to 'tuf.ssl_crypto.formats.ANYKEY_SCHEMA'. - It has the form: - - {'keytype': 'rsa', - 'keyid': keyid, - 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', - 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} - - keyid: - An object conformant to 'KEYID_SCHEMA'. It is used as an identifier - for RSA keys. - - repository_name: - The name of the repository to add the key. If not supplied, the key is - added to the 'default' repository. - - - tuf.ssl_commons.exceptions.FormatError, if the arguments do not have the correct format. - - tuf.ssl_commons.exceptions.Error, if 'keyid' does not match the keyid for 'rsakey_dict'. - - tuf.ssl_commons.exceptions.KeyAlreadyExistsError, if 'rsakey_dict' is found in the key database. - - tuf.ssl_commons.exceptions.InvalidNameError, if 'repository_name' does not exist in the key - database. - - - The keydb key database is modified. - - - None. - """ - - # Does 'key_dict' have the correct format? - # This check will ensure 'key_dict' has the appropriate number of objects - # and object types, and that all dict keys are properly named. - # Raise 'tuf.ssl_commons.exceptions.FormatError if the check fails. - tuf.ssl_crypto.formats.ANYKEY_SCHEMA.check_match(key_dict) - - # Does 'repository_name' have the correct format? - tuf.ssl_crypto.formats.NAME_SCHEMA.check_match(repository_name) - - # Does 'keyid' have the correct format? - if keyid is not None: - # Raise 'tuf.ssl_commons.exceptions.FormatError' if the check fails. - tuf.ssl_crypto.formats.KEYID_SCHEMA.check_match(keyid) - - # Check if each keyid found in 'key_dict' matches 'keyid'. - if keyid != key_dict['keyid']: - raise tuf.ssl_commons.exceptions.Error('Incorrect keyid. Got ' + key_dict['keyid'] + ' but expected ' + keyid) - - # Ensure 'repository_name' is actually set in the key database. - if repository_name not in _keydb_dict: - raise tuf.ssl_commons.exceptions.InvalidNameError('Repository name does not exist:' - ' ' + repr(repository_name)) - - # Check if the keyid belonging to 'key_dict' is not already - # available in the key database before returning. - keyid = key_dict['keyid'] - if keyid in _keydb_dict[repository_name]: - raise tuf.ssl_commons.exceptions.KeyAlreadyExistsError('Key: ' + keyid) - - _keydb_dict[repository_name][keyid] = copy.deepcopy(key_dict) - - - - - -def get_key(keyid, repository_name='default'): - """ - - Return the key belonging to 'keyid'. - - - keyid: - An object conformant to 'tuf.ssl_crypto.formats.KEYID_SCHEMA'. It is used as an - identifier for keys. - - repository_name: - The name of the repository to get the key. If not supplied, the key is - retrieved from the 'default' repository. - - - tuf.ssl_commons.exceptions.FormatError, if the arguments do not have the correct format. - - tuf.ssl_commons.exceptions.UnknownKeyError, if 'keyid' is not found in the keydb database. - - tuf.ssl_commons.exceptions.InvalidNameError, if 'repository_name' does not exist in the key - database. - - - None. - - - The key matching 'keyid'. In the case of RSA keys, a dictionary conformant - to 'tuf.ssl_crypto.formats.RSAKEY_SCHEMA' is returned. - """ - - # Does 'keyid' have the correct format? - # This check will ensure 'keyid' has the appropriate number of objects - # and object types, and that all dict keys are properly named. - # Raise 'tuf.ssl_commons.exceptions.FormatError' is the match fails. - tuf.ssl_crypto.formats.KEYID_SCHEMA.check_match(keyid) - - # Does 'repository_name' have the correct format? - tuf.ssl_crypto.formats.NAME_SCHEMA.check_match(repository_name) - - if repository_name not in _keydb_dict: - raise tuf.ssl_commons.exceptions.InvalidNameError('Repository name does not exist:' - ' ' + repr(repository_name)) - - # Return the key belonging to 'keyid', if found in the key database. - try: - return copy.deepcopy(_keydb_dict[repository_name][keyid]) - - except KeyError: - raise tuf.ssl_commons.exceptions.UnknownKeyError('Key: ' + keyid) - - - - - -def remove_key(keyid, repository_name='default'): - """ - - Remove the key belonging to 'keyid'. - - - keyid: - An object conformant to 'tuf.ssl_crypto.formats.KEYID_SCHEMA'. It is used as an - identifier for keys. - - repository_name: - The name of the repository to remove the key. If not supplied, the key - is removed from the 'default' repository. - - - tuf.ssl_commons.exceptions.FormatError, if the arguments do not have the correct format. - - tuf.ssl_commons.exceptions.UnknownKeyError, if 'keyid' is not found in key database. - - tuf.ssl_commons.exceptions.InvalidNameError, if 'repository_name' does not exist in the key - database. - - - The key, identified by 'keyid', is deleted from the key database. - - - None. - """ - - # Does 'keyid' have the correct format? - # This check will ensure 'keyid' has the appropriate number of objects - # and object types, and that all dict keys are properly named. - # Raise 'tuf.ssl_commons.exceptions.FormatError' is the match fails. - tuf.ssl_crypto.formats.KEYID_SCHEMA.check_match(keyid) - - # Does 'repository_name' have the correct format? - tuf.ssl_crypto.formats.NAME_SCHEMA.check_match(repository_name) - - if repository_name not in _keydb_dict: - raise tuf.ssl_commons.exceptions.InvalidNameError('Repository name does not exist:' - ' ' + repr(repository_name)) - - # Remove the key belonging to 'keyid' if found in the key database. - if keyid in _keydb_dict[repository_name]: - del _keydb_dict[repository_name][keyid] - - else: - raise tuf.ssl_commons.exceptions.UnknownKeyError('Key: ' + keyid) - - - - - -def clear_keydb(repository_name='default', clear_all=False): - - """ - - Clear the keydb key database. - - - repository_name: - The name of the repository to clear the key database. If not supplied, - the key database is cleared for the 'default' repository. - - clear_all: - Boolean indicating whether to clear the entire keydb. - - - tuf.ssl_commons.exceptions.FormatError, if 'repository_name' is improperly formatted. - - tuf.ssl_commons.exceptions.InvalidNameError, if 'repository_name' does not exist in the key - database. - - - The keydb key database is reset. - - - None. - """ - - # Do the arguments have the correct format? Raise 'tuf.ssl_commons.exceptions.FormatError' if - # 'repository_name' is improperly formatted. - tuf.ssl_crypto.formats.NAME_SCHEMA.check_match(repository_name) - tuf.ssl_crypto.formats.BOOLEAN_SCHEMA.check_match(clear_all) - - global _keydb_dict - - if clear_all: - _keydb_dict = {} - _keydb_dict['default'] = {} - - if repository_name not in _keydb_dict: - raise tuf.ssl_commons.exceptions.InvalidNameError('Repository name does not exist:' - ' ' + repr(repository_name)) - - _keydb_dict[repository_name] = {} diff --git a/tuf/keys.py b/tuf/keys.py deleted file mode 100755 index 7a772ff4..00000000 --- a/tuf/keys.py +++ /dev/null @@ -1,1486 +0,0 @@ -#!/usr/bin/env python - -""" - - keys.py - - - Vladimir Diaz - - - October 4, 2013. - - - See LICENSE for licensing information. - - - The goal of this module is to centralize cryptographic key routines and their - supported operations (e.g., creating and verifying signatures). This module - is designed to support multiple public-key algorithms, such as RSA and - Ed25519, and multiple cryptography libraries. Which cryptography library to - use is determined by the default, or user modified, values set in - 'tuf.settings.py' - - https://en.wikipedia.org/wiki/RSA_(algorithm) - http://ed25519.cr.yp.to/ - - The (RSA and Ed25519)-related functions provided include generate_rsa_key(), - generate_ed25519_key(), create_signature(), and verify_signature(). - The cryptography libraries called by 'tuf.keys.py' generate the actual TUF - keys and the functions listed above can be viewed as the easy-to-use public - interface. - - Additional functions contained here include format_keyval_to_metadata() and - format_metadata_to_key(). These last two functions produce or use TUF keys - compatible with the key structures listed in TUF Metadata files. The key - generation functions return a dictionary containing all the information needed - of TUF keys, such as public & private keys, and a keyID. create_signature() - and verify_signature() are supplemental functions needed for generating - signatures and verifying them. - - - Key IDs are used as identifiers for keys (e.g., RSA key). They are the - hexadecimal representation of the hash of the key object (specifically, the - key object containing only the public key). Review the '_get_keyid()' - function of this module to see precisely how keyids are generated. One may - get the key ID of a key object by simply accessing the dictionary's 'keyid' - key (i.e., rsakey['keyid']). - """ - -# Help with Python 3 compatibility, where the print statement is a function, an -# implicit relative import is invalid, and the '/' operator performs true -# division. Example: print 'hello world' raises a 'SyntaxError' exception. -from __future__ import print_function -from __future__ import absolute_import -from __future__ import division -from __future__ import unicode_literals - -# Required for hexadecimal conversions. Signatures and public/private keys are -# hexlified. -import binascii - -# NOTE: 'warnings' needed to temporarily suppress user warnings raised by -# 'pynacl' (as of version 0.2.3). -# http://docs.python.org/2/library/warnings.html#temporarily-suppressing-warnings -import warnings - -# 'pycrypto' and 'cryptography' are the only currently supported libraries for -# the creation of RSA keys. -# https://github.com/dlitz/pycrypto -# https://github.com/pyca/cryptography -_SUPPORTED_RSA_CRYPTO_LIBRARIES = ['pycrypto', 'pyca-cryptography'] - -# The currently supported libraries for the creation of ed25519 keys and -# signatures. The 'pynacl' library should be installed and used over the slower -# python implementation of ed25519. The python implementation will be used -# if 'pynacl' is unavailable. -_SUPPORTED_ED25519_CRYPTO_LIBRARIES = ['ed25519', 'pynacl'] - -# 'pycrypto' and 'cryptography' are the only currently supported libraries for -# general-purpose cryptography. -# https://github.com/dlitz/pycrypto -# https://github.com/pyca/cryptography -_SUPPORTED_GENERAL_CRYPTO_LIBRARIES = ['pycrypto', 'pyca-cryptography'] - -# Track which libraries are imported and thus available. An optimized version -# of the ed25519 python implementation is provided by TUF and avaialable by -# default. https://github.com/pyca/ed25519 -_available_crypto_libraries = ['ed25519'] - -# Try to import TUF's PyCrypto module (pycrypto_keys.py), which is used here -# for general-purpose cryptography and RSA. -try: - import tuf.ssl_crypto.pycrypto_keys - _available_crypto_libraries.append('pycrypto') - -except ImportError: # pragma: no cover - pass - -# Try to import TUF's pyca/Cryptography module (pyca_crypto_keys.py), which is -# used for general-purpose cryptography and RSA. -try: - import tuf.ssl_crypto.pyca_crypto_keys - _available_crypto_libraries.append('pyca-cryptography') - -except ImportError: # pragma: no cover - pass - -# Import the PyNaCl library, if available. It is recommended this library be -# used over the pure python implementation of ed25519, due to its speedier -# routines and side-channel protections available in the libsodium library. - -# NOTE: Version 0.2.3 of 'pynacl' prints: "UserWarning: reimporting '...' might -# overwrite older definitions." when importing 'nacl.signing' below. Suppress -# user warnings temporarily (at least until this issue is fixed). -with warnings.catch_warnings(): - warnings.simplefilter('ignore') - try: - import nacl - import nacl.signing - _available_crypto_libraries.append('pynacl') - - # PyNaCl's 'cffi' dependency may raise an 'IOError' exception when importing - # 'nacl.signing'. - except (ImportError, IOError): # pragma: no cover - pass - -# The optimized version of the ed25519 library provided by default is imported -# regardless of the availability of PyNaCl. -import tuf.ssl_crypto.ed25519_keys - -# Import the TUF package and TUF-defined exceptions in __init__.py. -import tuf - -# Import the cryptography library settings. -from simple_settings import settings - -# Digest objects needed to generate hashes. -import tuf.ssl_crypto.hash - -# Perform format checks of argument objects. -import tuf.ssl_crypto.pycrypto_keys -import tuf.ssl_crypto.formats -import tuf.tufformats - -# The hash algorithm used in the generation of the key ID for each unique key. -# If multiple hash algorithms is desired for the generation of key IDs, -# 'settings.REPOSITORY_HASH_ALGORITHMS' can be used. -_KEY_ID_HASH_ALGORITHM = settings.DEFAULT_HASH_ALGORITHM - -# Recommended RSA key sizes: -# http://www.emc.com/emc-plus/rsa-labs/historical/twirl-and-rsa-key-size.htm#table1 -# According to the document above, revised May 6, 2003, RSA keys of -# size 3072 provide security through 2031 and beyond. -_DEFAULT_RSA_KEY_BITS = 3072 - -# The crypto libraries to use in 'keys.py', set by default or by the user. -# The following cryptography libraries are currently supported: -# ['pycrypto', 'pynacl', 'ed25519', 'pyca-cryptography'] -_RSA_CRYPTO_LIBRARY = settings.RSA_CRYPTO_LIBRARY -_ED25519_CRYPTO_LIBRARY = settings.ED25519_CRYPTO_LIBRARY -_GENERAL_CRYPTO_LIBRARY = settings.GENERAL_CRYPTO_LIBRARY - - -def generate_rsa_key(bits=_DEFAULT_RSA_KEY_BITS): - """ - - Generate public and private RSA keys, with modulus length 'bits'. In - addition, a keyid identifier for the RSA key is generated. The object - returned conforms to 'tuf.ssl_crypto.formats.RSAKEY_SCHEMA' and has the - form: - - {'keytype': 'rsa', - 'keyid': keyid, - 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', - 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} - - The public and private keys are strings in PEM format. - - Although the PyCrypto and PyCA cryptography libraries do set a minimum key - size (e.g., 1024-bit minimum in PyCrypto), generate() enforces a minimum - key size of 2048 bits. If 'bits' is unspecified, a 3072-bit RSA key is - generated, which is the key size recommended by TUF. These key size - restrictions are only enforced for keys generated within TUF. RSA keys - with sizes lower than what we recommended may still be imported (e.g., with - import_rsakey_from_encrypted_pem(). - - >>> rsa_key = generate_rsa_key(bits=2048) - >>> tuf.ssl_crypto.formats.RSAKEY_SCHEMA.matches(rsa_key) - True - >>> public = rsa_key['keyval']['public'] - >>> private = rsa_key['keyval']['private'] - >>> tuf.ssl_crypto.formats.PEMRSA_SCHEMA.matches(public) - True - >>> tuf.ssl_crypto.formats.PEMRSA_SCHEMA.matches(private) - True - - - bits: - The key size, or key length, of the RSA key. 'bits' must be 2048, or - greater, and a multiple of 256. - - - tuf.ssl_commons.exceptions.FormatError, if 'bits' is improperly or invalid (i.e., not an integer - and not at least 2048). - - tuf.ssl_commons.exceptions.UnsupportedLibraryError, if any of the cryptography libraries specified - in 'tuf.settings.py' are unsupported or unavailable. - - ValueError, if an exception occurs after calling the RSA key generation - routine. 'bits' must be a multiple of 256 if PyCrypto is set via - 'tuf.settings.py'. The 'ValueError' exception is raised by the key generation - function of the cryptography library called. - - - The RSA keys are generated by calling PyCrypto's - Crypto.PublicKey.RSA.generate(). - - - A dictionary containing the RSA keys and other identifying information. - Conforms to 'tuf.ssl_crypto.formats.RSAKEY_SCHEMA'. - """ - - # Does 'bits' have the correct format? - # This check will ensure 'bits' conforms to 'tuf.ssl_crypto.formats.RSAKEYBITS_SCHEMA'. - # 'bits' must be an integer object, with a minimum value of 2048. - # Raise 'tuf.ssl_commons.exceptions.FormatError' if the check fails. - tuf.ssl_crypto.formats.RSAKEYBITS_SCHEMA.check_match(bits) - - # Raise 'tuf.ssl_commons.exceptions.UnsupportedLibraryError' if the following libraries, specified - # in 'settings', are unsupported or unavailable: - # 'settings.RSA_CRYPTO_LIBRARY'. - check_crypto_libraries(['rsa']) - - # Begin building the RSA key dictionary. - rsakey_dict = {} - keytype = 'rsa' - public = None - private = None - - # Generate the public and private RSA keys. The PyCrypto module performs - # the actual key generation. Raise 'ValueError' if 'bits' is less than 1024 - # or not a multiple of 256, although a 2048-bit minimum is enforced by - # tuf.ssl_crypto.formats.RSAKEYBITS_SCHEMA.check_match(). - if _RSA_CRYPTO_LIBRARY == 'pycrypto': - public, private = tuf.ssl_crypto.pycrypto_keys.generate_rsa_public_and_private(bits) - - # Unlike PyCrypto, PyCA Cryptography does not require 'bits' to be a multiple - # 256. - elif _RSA_CRYPTO_LIBRARY == 'pyca-cryptography': - public, private = tuf.ssl_crypto.pyca_crypto_keys.generate_rsa_public_and_private(bits) - - else: # pragma: no cover - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('Invalid crypto' - ' library: ' + repr(_RSA_CRYPTO_LIBRARY) + '.') - - # Generate the keyid of the RSA key. Note: The private key material is - # not included in the generation of the 'keyid' identifier. - key_value = {'public': public, - 'private': ''} - keyid = _get_keyid(keytype, key_value) - - # Build the 'rsakey_dict' dictionary. Update 'key_value' with the RSA - # private key prior to adding 'key_value' to 'rsakey_dict'. - key_value['private'] = private - - rsakey_dict['keytype'] = keytype - rsakey_dict['keyid'] = keyid - rsakey_dict['keyval'] = key_value - - return rsakey_dict - - - - - -def generate_ed25519_key(): - """ - - Generate public and private ED25519 keys, both of length 32-bytes, although - they are hexlified to 64 bytes. - In addition, a keyid identifier generated for the returned ED25519 object. - The object returned conforms to 'tuf.ssl_crypto.formats.ED25519KEY_SCHEMA' and has the - form: - {'keytype': 'ed25519', - 'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', - 'keyval': {'public': '9ccf3f02b17f82febf5dd3bab878b767d8408...', - 'private': 'ab310eae0e229a0eceee3947b6e0205dfab3...'}} - - The public and private keys are strings in PEM format and stored in the - 'keyval' field of the returned dictionary. - - >>> ed25519_key = generate_ed25519_key() - >>> tuf.ssl_crypto.formats.ED25519KEY_SCHEMA.matches(ed25519_key) - True - >>> len(ed25519_key['keyval']['public']) - 64 - >>> len(ed25519_key['keyval']['private']) - 64 - - - None. - - - tuf.ssl_commons.exceptions.UnsupportedLibraryError, if an unsupported or unavailable library is - detected. - - - The ED25519 keys are generated by calling either the optimized pure Python - implementation of ed25519, or the ed25519 routines provided by 'pynacl'. - - - A dictionary containing the ED25519 keys and other identifying information. - Conforms to 'tuf.ssl_crypto.formats.ED25519KEY_SCHEMA'. - """ - - # Raise 'tuf.ssl_commons.exceptions.UnsupportedLibraryError' if the following libraries, specified - # in 'settings', are unsupported or unavailable: - # 'settings.ED25519_CRYPTO_LIBRARY'. - check_crypto_libraries(['ed25519']) - - # Begin building the Ed25519 key dictionary. - ed25519_key = {} - keytype = 'ed25519' - public = None - private = None - - # Generate the public and private Ed25519 key with the 'pynacl' library. - # Unlike in the verification of Ed25519 signatures, do not fall back to the - # optimized, pure python implementation provided by PyCA. Ed25519 should - # always be generated with a backend like libsodium to prevent side-channel - # attacks. - if 'pynacl' in _available_crypto_libraries: - public, private = \ - tuf.ssl_crypto.ed25519_keys.generate_public_and_private() - - else: # pragma: no cover - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('The required PyNaCl library' - ' is unavailable.') - - # Generate the keyid of the Ed25519 key. 'key_value' corresponds to the - # 'keyval' entry of the 'Ed25519KEY_SCHEMA' dictionary. The private key - # information is not included in the generation of the 'keyid' identifier. - key_value = {'public': binascii.hexlify(public).decode(), - 'private': ''} - keyid = _get_keyid(keytype, key_value) - - # Build the 'ed25519_key' dictionary. Update 'key_value' with the Ed25519 - # private key prior to adding 'key_value' to 'ed25519_key'. - key_value['private'] = binascii.hexlify(private).decode() - - ed25519_key['keytype'] = keytype - ed25519_key['keyid'] = keyid - ed25519_key['keyval'] = key_value - - return ed25519_key - - - - - -def format_keyval_to_metadata(keytype, key_value, private=False): - """ - - Return a dictionary conformant to 'tuf.ssl_crypto.formats.KEY_SCHEMA'. - If 'private' is True, include the private key. The dictionary - returned has the form: - - {'keytype': keytype, - 'keyval': {'public': '...', - 'private': '...'}} - - or if 'private' is False: - - {'keytype': keytype, - 'keyval': {'public': '...', - 'private': ''}} - - TUF keys are stored in Metadata files (e.g., root.json) in the format - returned by this function. - - >>> ed25519_key = generate_ed25519_key() - >>> key_val = ed25519_key['keyval'] - >>> keytype = ed25519_key['keytype'] - >>> ed25519_metadata = \ - format_keyval_to_metadata(keytype, key_val, private=True) - >>> tuf.ssl_crypto.formats.KEY_SCHEMA.matches(ed25519_metadata) - True - - - key_type: - The 'rsa' or 'ed25519' strings. - - key_value: - A dictionary containing a private and public keys. - 'key_value' is of the form: - - {'public': '...', - 'private': '...'}}, - - conformant to 'tuf.ssl_crypto.formats.KEYVAL_SCHEMA'. - - private: - Indicates if the private key should be included in the dictionary - returned. - - - tuf.ssl_commons.exceptions.FormatError, if 'key_value' does not conform to - 'tuf.ssl_crypto.formats.KEYVAL_SCHEMA', or if the private key is not present in - 'key_value' if requested by the caller via 'private'. - - - None. - - - A 'tuf.ssl_crypto.formats.KEY_SCHEMA' dictionary. - """ - - # Does 'keytype' have the correct format? - # This check will ensure 'keytype' has the appropriate number - # of objects and object types, and that all dict keys are properly named. - # Raise 'tuf.ssl_commons.exceptions.FormatError' if the check fails. - tuf.ssl_crypto.formats.KEYTYPE_SCHEMA.check_match(keytype) - - # Does 'key_value' have the correct format? - tuf.ssl_crypto.formats.KEYVAL_SCHEMA.check_match(key_value) - - if private is True: - # If the caller requests (via the 'private' argument) to include a private - # key in the returned dictionary, ensure the private key is actually - # present in 'key_val' (a private key is optional for 'KEYVAL_SCHEMA' - # dicts). - if 'private' not in key_value: - raise tuf.ssl_commons.exceptions.FormatError('The required private key is missing' - ' from: ' + repr(key_value)) - - else: - return {'keytype': keytype, 'keyval': key_value} - - else: - public_key_value = {'public': key_value['public']} - - return {'keytype': keytype, - 'keyid_hash_algorithms': settings.REPOSITORY_HASH_ALGORITHMS, - 'keyval': public_key_value} - - - - - -def format_metadata_to_key(key_metadata): - """ - - Construct a TUF key dictionary (e.g., tuf.ssl_crypto.formats.RSAKEY_SCHEMA) - according to the keytype of 'key_metadata'. The dict returned by this - function has the exact format as the dict returned by one of the key - generations functions, like generate_ed25519_key(). The dict returned - has the form: - - {'keytype': keytype, - 'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', - 'keyval': {'public': '...', - 'private': '...'}} - - For example, RSA key dictionaries in RSAKEY_SCHEMA format should be used by - modules storing a collection of keys, such as with keydb.py. RSA keys as - stored in metadata files use a different format, so this function should be - called if an RSA key is extracted from one of these metadata files and need - converting. The key generation functions create an entirely new key and - return it in the format appropriate for 'keydb.py'. - - >>> ed25519_key = generate_ed25519_key() - >>> key_val = ed25519_key['keyval'] - >>> keytype = ed25519_key['keytype'] - >>> ed25519_metadata = \ - format_keyval_to_metadata(keytype, key_val, private=True) - >>> ed25519_key_2, junk = format_metadata_to_key(ed25519_metadata) - >>> tuf.ssl_crypto.formats.ED25519KEY_SCHEMA.matches(ed25519_key_2) - True - >>> ed25519_key == ed25519_key_2 - True - - - key_metadata: - The TUF key dictionary as stored in Metadata files, conforming to - 'tuf.ssl_crypto.formats.KEY_SCHEMA'. It has the form: - - {'keytype': '...', - 'keyval': {'public': '...', - 'private': '...'}} - - - tuf.ssl_commons.exceptions.FormatError, if 'key_metadata' does not conform to - 'tuf.ssl_crypto.formats.KEY_SCHEMA'. - - - None. - - - A tuple containing the key and its keyids. In the case of an RSA key, a - dictionary conformant to 'tuf.ssl_crypto.formats.RSAKEY_SCHEMA'. - """ - - # Does 'key_metadata' have the correct format? - # This check will ensure 'key_metadata' has the appropriate number - # of objects and object types, and that all dict keys are properly named. - # Raise 'tuf.ssl_commons.exceptions.FormatError' if the check fails. - tuf.ssl_crypto.formats.KEY_SCHEMA.check_match(key_metadata) - - # Construct the dictionary to be returned. - key_dict = {} - keytype = key_metadata['keytype'] - key_value = key_metadata['keyval'] - - # Convert 'key_value' to 'tuf.ssl_crypto.formats.KEY_SCHEMA' and generate its hash - # The hash is in hexdigest form. - default_keyid = _get_keyid(keytype, key_value) - keyids = set() - keyids.add(default_keyid) - - for hash_algorithm in settings.REPOSITORY_HASH_ALGORITHMS: - keyid = _get_keyid(keytype, key_value, hash_algorithm) - keyids.add(keyid) - - # All the required key values gathered. Build 'key_dict'. - # 'keyid_hash_algorithms' - key_dict['keytype'] = keytype - key_dict['keyid'] = default_keyid - key_dict['keyid_hash_algorithms'] = settings.REPOSITORY_HASH_ALGORITHMS - key_dict['keyval'] = key_value - - return key_dict, keyids - - - - - -def _get_keyid(keytype, key_value, hash_algorithm=_KEY_ID_HASH_ALGORITHM): - """Return the keyid of 'key_value'.""" - - # 'keyid' will be generated from an object conformant to KEY_SCHEMA, - # which is the format Metadata files (e.g., root.json) store keys. - # 'format_keyval_to_metadata()' returns the object needed by _get_keyid(). - key_meta = format_keyval_to_metadata(keytype, key_value, private=False) - - # Convert the TUF key to JSON Canonical format, suitable for adding - # to digest objects. - key_update_data = tuf.ssl_crypto.formats.encode_canonical(key_meta) - - # Create a digest object and call update(), using the JSON canonical format - # of 'rskey_meta' as the update data. _KEY_ID_HASH_ALGORITHM should be the - # default hash algorithm used to generate the key ID of a unique key. - digest_object = tuf.ssl_crypto.hash.digest(hash_algorithm) - digest_object.update(key_update_data.encode('utf-8')) - - # 'keyid' becomes the hexadecimal representation of the hash. - keyid = digest_object.hexdigest() - - return keyid - - - - - -def check_crypto_libraries(required_libraries): - """ - - Public function that ensures the cryptography libraries specified in - 'settings' are supported and available for each 'required_libraries'. - - - required_libraries: - A list of library strings to validate. One, or multiple, strings from - ['rsa', 'ed25519', 'general'] can be specified. - - - tuf.ssl_commons.exceptions.UnsupportedLibraryError, if the 'required_libraries' and the libraries - specified in 'settings' are not supported or unavailable. - - - Validates the libraries set in 'settings'. - - - None. - """ - - # Does 'required_libraries' have the correct format? - # This check will ensure 'required_libraries' has the appropriate number - # of objects and object types, and that all dict keys are properly named. - # Raise 'tuf.ssl_commons.exceptions.FormatError' if the check fails. - tuf.ssl_crypto.formats.REQUIRED_LIBRARIES_SCHEMA.check_match(required_libraries) - - # The checks below all raise 'tuf.ssl_commons.exceptions.UnsupportedLibraryError' if the general, - # RSA, and Ed25519 crypto libraries specified in 'tuf.settings.py' are not - # supported or unavailable. The appropriate error message is added to the - # exception. The funcions of this module that depend on user-installed - # crypto libraries should call this private function to ensure the called - # routine does not fail with unpredictable exceptions in the event of a - # missing library. The supported and available lists checked are populated - # when 'tuf.keys.py' is imported. - - if 'rsa' in required_libraries and _RSA_CRYPTO_LIBRARY not in \ - _SUPPORTED_RSA_CRYPTO_LIBRARIES: - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('The ' + repr(_RSA_CRYPTO_LIBRARY) + - ' crypto library specified in "settings.RSA_CRYPTO_LIBRARY" is not ' - ' supported.\nSupported crypto libraries: ' + - repr(_SUPPORTED_RSA_CRYPTO_LIBRARIES) + '.') - - if 'ed25519' in required_libraries and _ED25519_CRYPTO_LIBRARY not in \ - _SUPPORTED_ED25519_CRYPTO_LIBRARIES: - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('The ' + repr(_ED25519_CRYPTO_LIBRARY) + - ' crypto library specified in "settings.ED25519_CRYPTO_LIBRARY" is not ' - ' supported.\nSupported crypto libraries: ' + - repr(_SUPPORTED_ED25519_CRYPTO_LIBRARIES) + '.') - - if 'general' in required_libraries and _GENERAL_CRYPTO_LIBRARY not in \ - _SUPPORTED_GENERAL_CRYPTO_LIBRARIES: - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('The ' + repr(_GENERAL_CRYPTO_LIBRARY) + - ' crypto library specified in "settings.GENERAL_CRYPTO_LIBRARY" is not' - ' supported.\nSupported crypto libraries: ' + - repr(_SUPPORTED_GENERAL_CRYPTO_LIBRARIES) + '.') - - if 'rsa' in required_libraries and _RSA_CRYPTO_LIBRARY not in \ - _available_crypto_libraries: - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('The ' + repr(_RSA_CRYPTO_LIBRARY) + - ' crypto library specified in "settings.RSA_CRYPTO_LIBRARY" could not' - ' be imported. Available libraries: ' + repr(_available_crypto_libraries)) - - if 'ed25519' in required_libraries and _ED25519_CRYPTO_LIBRARY not in \ - _available_crypto_libraries: - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('The ' + repr(_ED25519_CRYPTO_LIBRARY) + - ' crypto library specified in "settings.ED25519_CRYPTO_LIBRARY" could' - ' not be imported.') - - if 'general' in required_libraries and _GENERAL_CRYPTO_LIBRARY not in \ - _available_crypto_libraries: - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('The ' + repr(_GENERAL_CRYPTO_LIBRARY) + - ' crypto library specified in "settings.GENERAL_CRYPTO_LIBRARY" could' - ' not be imported.') - - - - - -def create_signature(key_dict, data): - """ - - Return a signature dictionary of the form: - {'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', - 'method': '...', - 'sig': '...'}. - - The signing process will use the private key in - key_dict['keyval']['private'] and 'data' to generate the signature. - - The following signature methods are supported: - - 'RSASSA-PSS' - RFC3447 - RSASSA-PSS - http://www.ietf.org/rfc/rfc3447. - - 'ed25519' - ed25519 - high-speed high security signatures - http://ed25519.cr.yp.to/ - - Which signature to generate is determined by the key type of 'key_dict' - and the available cryptography library specified in 'settings'. - - >>> ed25519_key = generate_ed25519_key() - >>> data = 'The quick brown fox jumps over the lazy dog' - >>> signature = create_signature(ed25519_key, data) - >>> tuf.ssl_crypto.formats.SIGNATURE_SCHEMA.matches(signature) - True - >>> len(signature['sig']) - 128 - >>> rsa_key = generate_rsa_key(2048) - >>> data = 'The quick brown fox jumps over the lazy dog' - >>> signature = create_signature(rsa_key, data) - >>> tuf.ssl_crypto.formats.SIGNATURE_SCHEMA.matches(signature) - True - - - key_dict: - A dictionary containing the TUF keys. An example RSA key dict has the - form: - - {'keytype': 'rsa', - 'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', - 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', - 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} - - The public and private keys are strings in PEM format. - - data: - Data object used by create_signature() to generate the signature. - - - tuf.ssl_commons.exceptions.FormatError, if 'key_dict' is improperly formatted. - - tuf.ssl_commons.exceptions.UnsupportedLibraryError, if an unsupported or unavailable library is - detected. - - TypeError, if 'key_dict' contains an invalid keytype. - - - The cryptography library specified in 'settings' called to perform the - actual signing routine. - - - A signature dictionary conformant to 'tuf.format.SIGNATURE_SCHEMA'. - """ - - # Does 'key_dict' have the correct format? - # This check will ensure 'key_dict' has the appropriate number of objects - # and object types, and that all dict keys are properly named. - # Raise 'tuf.ssl_commons.exceptions.FormatError' if the check fails. - # The key type of 'key_dict' must be either 'rsa' or 'ed25519'. - tuf.ssl_crypto.formats.ANYKEY_SCHEMA.check_match(key_dict) - - # Raise 'tuf.ssl_commons.exceptions.UnsupportedLibraryError' if the following libraries, specified - # in 'settings', are unsupported or unavailable: - # 'settings.RSA_CRYPTO_LIBRARY' or 'settings.ED25519_CRYPTO_LIBRARY'. - check_crypto_libraries([key_dict['keytype']]) - - # Signing the 'data' object requires a private key. - # 'RSASSA-PSS' and 'ed25519' are the only signing methods currently - # supported. RSASSA-PSS keys and signatures can be generated and verified by - # the PyCrypto and 'cryptography' modules, and Ed25519's by PyNaCl and PyCA's - # optimized, pure python implementation of Ed25519. - signature = {} - keytype = key_dict['keytype'] - public = key_dict['keyval']['public'] - private = key_dict['keyval']['private'] - keyid = key_dict['keyid'] - method = None - sig = None - - # Convert 'data' to canonical JSON format so that repeatable signatures are - # generated across different platforms and Python key dictionaries. The - # resulting 'data' is a string encoded in UTF-8 and compatible with the input - # expected by the cryptography functions called below. - data = tuf.ssl_crypto.formats.encode_canonical(data) - - # Call the appropriate cryptography libraries for the supported key types, - # otherwise raise an exception. - if keytype == 'rsa': - if _RSA_CRYPTO_LIBRARY == 'pycrypto': - sig, method = tuf.ssl_crypto.pycrypto_keys.create_rsa_signature(private, data.encode('utf-8')) - - elif _RSA_CRYPTO_LIBRARY == 'pyca-cryptography': - sig, method = tuf.ssl_crypto.pyca_crypto_keys.create_rsa_signature(private, data.encode('utf-8')) - - else: # pragma: no cover - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('Unsupported' - ' "settings.RSA_CRYPTO_LIBRARY": ' + repr(_RSA_CRYPTO_LIBRARY) + '.') - - elif keytype == 'ed25519': - public = binascii.unhexlify(public.encode('utf-8')) - private = binascii.unhexlify(private.encode('utf-8')) - if 'pynacl' in _available_crypto_libraries: - sig, method = tuf.ssl_crypto.ed25519_keys.create_signature(public, private, data.encode('utf-8')) - - else: # pragma: no cover - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('The required PyNaCl library' - ' is unavailable.') - - # 'tuf.ssl_crypto.formats.ANYKEY_SCHEMA' should detect invalid key types. - else: # pragma: no cover - raise TypeError('Invalid key type.') - - # Build the signature dictionary to be returned. - # The hexadecimal representation of 'sig' is stored in the signature. - signature['keyid'] = keyid - signature['method'] = method - signature['sig'] = binascii.hexlify(sig).decode() - - return signature - - - - - -def verify_signature(key_dict, signature, data): - """ - - Determine whether the private key belonging to 'key_dict' produced - 'signature'. verify_signature() will use the public key found in - 'key_dict', the 'method' and 'sig' objects contained in 'signature', - and 'data' to complete the verification. - - >>> ed25519_key = generate_ed25519_key() - >>> data = 'The quick brown fox jumps over the lazy dog' - >>> signature = create_signature(ed25519_key, data) - >>> verify_signature(ed25519_key, signature, data) - True - >>> verify_signature(ed25519_key, signature, 'bad_data') - False - >>> rsa_key = generate_rsa_key() - >>> signature = create_signature(rsa_key, data) - >>> verify_signature(rsa_key, signature, data) - True - >>> verify_signature(rsa_key, signature, 'bad_data') - False - - - key_dict: - A dictionary containing the TUF keys and other identifying information. - If 'key_dict' is an RSA key, it has the form: - - {'keytype': 'rsa', - 'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', - 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', - 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} - - The public and private keys are strings in PEM format. - - signature: - The signature dictionary produced by one of the key generation functions. - 'signature' has the form: - - {'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', - 'method': 'method', - 'sig': sig}. - - Conformant to 'tuf.ssl_crypto.formats.SIGNATURE_SCHEMA'. - - data: - Data object used by tuf.rsa_key.create_signature() to generate - 'signature'. 'data' is needed here to verify the signature. - - - tuf.ssl_commons.exceptions.FormatError, raised if either 'key_dict' or 'signature' are improperly - formatted. - - tuf.ssl_commons.exceptions.UnsupportedLibraryError, if an unsupported or unavailable library is - detected. - - tuf.ssl_commons.exceptions.UnknownMethodError. Raised if the signing method used by - 'signature' is not one supported. - - - The cryptography library specified in 'settings' called to do the actual - verification. - - - Boolean. True if the signature is valid, False otherwise. - """ - - # Does 'key_dict' have the correct format? - # This check will ensure 'key_dict' has the appropriate number - # of objects and object types, and that all dict keys are properly named. - # Raise 'tuf.ssl_commons.exceptions.FormatError' if the check fails. - tuf.ssl_crypto.formats.ANYKEY_SCHEMA.check_match(key_dict) - - # Does 'signature' have the correct format? - tuf.ssl_crypto.formats.SIGNATURE_SCHEMA.check_match(signature) - - # Using the public key belonging to 'key_dict' - # (i.e., rsakey_dict['keyval']['public']), verify whether 'signature' - # was produced by key_dict's corresponding private key - # key_dict['keyval']['private']. - method = signature['method'] - sig = signature['sig'] - sig = binascii.unhexlify(sig.encode('utf-8')) - public = key_dict['keyval']['public'] - keytype = key_dict['keytype'] - valid_signature = False - - # Convert 'data' to canonical JSON format so that repeatable signatures are - # generated across different platforms and Python key dictionaries. The - # resulting 'data' is a string encoded in UTF-8 and compatible with the input - # expected by the cryptography functions called below. - data = tuf.ssl_crypto.formats.encode_canonical(data).encode('utf-8') - - # Call the appropriate cryptography libraries for the supported key types, - # otherwise raise an exception. - if keytype == 'rsa': - if _RSA_CRYPTO_LIBRARY == 'pycrypto': - if 'pycrypto' not in _available_crypto_libraries: # pragma: no cover - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('Metadata downloaded from the remote' - ' repository listed an RSA signature. "pycrypto" was set' - ' (in settings.py) to generate RSA signatures, but the PyCrypto library' - ' is not installed. \n$ pip install PyCrypto, or pip install' - ' tuf[tools], or you can try switching your configuration' - ' (tuf.settings.py) to use pyca-cryptography if that is available instead.') - - else: - valid_signature = tuf.ssl_crypto.pycrypto_keys.verify_rsa_signature(sig, method, - public, data) - elif _RSA_CRYPTO_LIBRARY == 'pyca-cryptography': - if 'pyca-cryptography' not in _available_crypto_libraries: # pragma: no cover - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('Metadata downloaded from the remote' - ' repository listed an RSA signature. "pyca-cryptography" was set' - ' (in settings.py) to generate RSA signatures, but the "cryptography"' - ' library is not installed. \n$ pip install cryptography, or pip' - ' install tuf[tools], or you can try switching your configuration' - ' (tuf/settings.py) to use PyCrypto if that is available instead.') - - else: - valid_signature = tuf.ssl_crypto.pyca_crypto_keys.verify_rsa_signature(sig, method, - public, data) - - else: # pragma: no cover - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('Unsupported' - ' "settings.RSA_CRYPTO_LIBRARY": ' + repr(_RSA_CRYPTO_LIBRARY) + '.') - - elif keytype == 'ed25519': - public = binascii.unhexlify(public.encode('utf-8')) - if _ED25519_CRYPTO_LIBRARY == 'pynacl' or \ - 'pynacl' in _available_crypto_libraries: - valid_signature = tuf.ssl_crypto.ed25519_keys.verify_signature(public, - method, sig, data, - use_pynacl=True) - - # Fall back to the optimized pure python implementation of ed25519. - else: # pragma: no cover - valid_signature = tuf.ssl_crypto.ed25519_keys.verify_signature(public, - method, sig, data, - use_pynacl=False) - - # 'tuf.ssl_crypto.formats.ANYKEY_SCHEMA' should detect invalid key types. - else: # pragma: no cover - raise TypeError('Unsupported key type.') - - return valid_signature - - - - - -def import_rsakey_from_encrypted_pem(encrypted_pem, password): - """ - - Import the public and private RSA keys stored in 'encrypted_pem'. In - addition, a keyid identifier for the RSA key is generated. The object - returned conforms to 'tuf.ssl_crypto.formats.RSAKEY_SCHEMA' and has the - form: - - {'keytype': 'rsa', - 'keyid': keyid, - 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', - 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} - - The public and private keys are strings in PEM format. - - >>> rsa_key = generate_rsa_key() - >>> private = rsa_key['keyval']['private'] - >>> passphrase = 'secret' - >>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase) - >>> rsa_key2 = import_rsakey_from_encrypted_pem(encrypted_pem, passphrase) - >>> tuf.ssl_crypto.formats.RSAKEY_SCHEMA.matches(rsa_key) - True - >>> tuf.ssl_crypto.formats.RSAKEY_SCHEMA.matches(rsa_key2) - True - - - encrypted_pem: - A string in PEM format. - - password: - The password, or passphrase, to decrypt the private part of the RSA - key. 'password' is not used directly as the encryption key, a stronger - encryption key is derived from it. - - - tuf.ssl_commons.exceptions.FormatError, if the arguments are improperly formatted. - - tuf.ssl_commons.exceptions.UnsupportedLibraryError, if any of the cryptography libraries specified - in 'tuf.settings.py' are unsupported or unavailable. - - - None. - - - A dictionary containing the RSA keys and other identifying information. - Conforms to 'tuf.ssl_crypto.formats.RSAKEY_SCHEMA'. - """ - - # Does 'encrypted_pem' have the correct format? - # This check will ensure 'encrypted_pem' conforms to - # 'tuf.ssl_crypto.formats.PEMRSA_SCHEMA'. - tuf.ssl_crypto.formats.PEMRSA_SCHEMA.check_match(encrypted_pem) - - # Does 'password' have the correct format? - tuf.ssl_crypto.formats.PASSWORD_SCHEMA.check_match(password) - - # Raise 'tuf.ssl_commons.exceptions.UnsupportedLibraryError' if the following libraries, specified in - # 'settings', are unsupported or unavailable: - # 'settings.RSA_CRYPTO_LIBRARY' and 'settings.GENERAL_CRYPTO_LIBRARY'. - check_crypto_libraries(['rsa', 'general']) - - # Begin building the RSA key dictionary. - rsakey_dict = {} - keytype = 'rsa' - public = None - private = None - - # Generate the public and private RSA keys. The PyCrypto module performs the - # actual import operation. - if _RSA_CRYPTO_LIBRARY == 'pycrypto': - public, private = \ - tuf.ssl_crypto.pycrypto_keys.create_rsa_public_and_private_from_encrypted_pem(encrypted_pem, - password) - public = format_rsakey_from_pem(public)['keyval']['public'] - private = extract_pem(private, private_pem=True) - - elif _RSA_CRYPTO_LIBRARY == 'pyca-cryptography': - public, private = \ - tuf.ssl_crypto.pyca_crypto_keys.create_rsa_public_and_private_from_encrypted_pem(encrypted_pem, - password) - public = format_rsakey_from_pem(public)['keyval']['public'] - private = extract_pem(private, private_pem=True) - - else: #pragma: no cover - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('Invalid crypto' - ' library: ' + repr(_RSA_CRYPTO_LIBRARY) + '.') - - # Generate the keyid of the RSA key. 'key_value' corresponds to the - # 'keyval' entry of the 'RSAKEY_SCHEMA' dictionary. The private key - # information is not included in the generation of the 'keyid' identifier. - key_value = {'public': public, - 'private': ''} - keyid = _get_keyid(keytype, key_value) - - # Build the 'rsakey_dict' dictionary. Update 'key_value' with the RSA - # private key prior to adding 'key_value' to 'rsakey_dict'. - key_value['private'] = private - - rsakey_dict['keytype'] = keytype - rsakey_dict['keyid'] = keyid - rsakey_dict['keyval'] = key_value - - return rsakey_dict - - - - - -def format_rsakey_from_pem(pem): - """ - - Generate an RSA key object from 'pem'. In addition, a keyid identifier for - the RSA key is generated. The object returned conforms to - 'tuf.ssl_crypto.formats.RSAKEY_SCHEMA' and has the form: - - {'keytype': 'rsa', - 'keyid': keyid, - 'keyval': {'public': '-----BEGIN PUBLIC KEY----- ...', - 'private': ''}} - - The public portion of the RSA key is a string in PEM format. - - >>> rsa_key = generate_rsa_key() - >>> public = rsa_key['keyval']['public'] - >>> rsa_key['keyval']['private'] = '' - >>> rsa_key2 = format_rsakey_from_pem(public) - >>> tuf.ssl_crypto.formats.RSAKEY_SCHEMA.matches(rsa_key) - True - >>> tuf.ssl_crypto.formats.RSAKEY_SCHEMA.matches(rsa_key2) - True - - - pem: - A string in PEM format. - - - tuf.ssl_commons.exceptions.FormatError, if 'pem' is improperly formatted. - - - Only the public portion of the PEM is extracted. Leading or trailing - whitespace is not included in the PEM string stored in the rsakey object - returned. - - - A dictionary containing the RSA keys and other identifying information. - Conforms to 'tuf.ssl_crypto.formats.RSAKEY_SCHEMA'. - """ - - # Does 'pem' have the correct format? - # This check will ensure arguments has the appropriate number - # of objects and object types, and that all dict keys are properly named. - # Raise 'tuf.ssl_commons.exceptions.FormatError' if the check fails. - tuf.ssl_crypto.formats.PEMRSA_SCHEMA.check_match(pem) - - # Ensure the PEM string has a valid header and footer. Although a simple - # validation of 'pem' is performed here, a fully valid PEM string is needed - # later to successfully verify signatures. Performing stricter validation of - # PEMs are left to the external libraries that use 'pem'. - public_pem = extract_pem(pem) - - # Begin building the RSA key dictionary. - rsakey_dict = {} - keytype = 'rsa' - - # Generate the keyid of the RSA key. 'key_value' corresponds to the - # 'keyval' entry of the 'RSAKEY_SCHEMA' dictionary. The private key - # information is not included in the generation of the 'keyid' identifier. - key_value = {'public': public_pem, - 'private': ''} - keyid = _get_keyid(keytype, key_value) - - rsakey_dict['keytype'] = keytype - rsakey_dict['keyid'] = keyid - rsakey_dict['keyval'] = key_value - - return rsakey_dict - - - - - -def extract_pem(pem, private_pem=False): - """ - - Extract only the portion of the pem that includes the header and footer, - with any leading and trailing characters removed. The string returned has - the following form: - - '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----' - - or - - '-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----' - - Note: This function assumes "pem" is a valid pem in the following format: - pem header + key material + key footer. Crypto libraries (e.g., pyca's - cryptography) that parse the pem returned by this function are expected to - fully validate and process the pem. - - - pem: - A string in PEM format. - - private_pem: - Boolean indicating whether 'pem' contains a private key. 'pem' is - expected to begin and end with a private header and footer. - - - tuf.ssl_commons.exceptions.FormatError, if 'pem' is improperly formatted. - - - Only the public and private portion of the PEM is extracted. Leading or - trailing whitespace is not included in the returned PEM string. - - - A PEM string (excluding leading and trailing newline characters). - That is: pem header + key material + pem footer. - - """ - - if private_pem: - pem_header = '-----BEGIN RSA PRIVATE KEY-----' - pem_footer = '-----END RSA PRIVATE KEY-----' - - else: - pem_header = '-----BEGIN PUBLIC KEY-----' - pem_footer = '-----END PUBLIC KEY-----' - - header_start = 0 - footer_start = 0 - - # Raise error message if the expected header or footer is not found in 'pem'. - try: - header_start = pem.index(pem_header) - - except ValueError: - # Be careful not to print private key material in exception message. - if not private_pem: - raise tuf.ssl_commons.exceptions.FormatError('Required PEM header ' + repr(pem_header) + '\n not' - ' found in PEM string: ' + repr(pem)) - - else: - raise tuf.ssl_commons.exceptions.FormatError('Required PEM header ' + repr(pem_header) + '\n not' - ' found in private PEM string.') - - try: - # Search for 'pem_footer' after the PEM header. - footer_start = pem.index(pem_footer, header_start + len(pem_header)) - - except ValueError: - # Be careful not to print private key material in exception message. - if not private_pem: - raise tuf.ssl_commons.exceptions.FormatError('Required PEM footer ' + repr(pem_footer) + '\n not' - ' found in PEM string ' + repr(pem)) - - else: - raise tuf.ssl_commons.exceptions.FormatError('Required PEM footer ' + repr(pem_footer) + '\n not' - ' found in private PEM string.') - - # Extract only the public portion of 'pem'. Leading or trailing whitespace - # is excluded. - pem = pem[header_start:footer_start + len(pem_footer)] - - return pem - - - - - -def encrypt_key(key_object, password): - """ - - Return a string containing 'key_object' in encrypted form. Encrypted strings - may be safely saved to a file. The corresponding decrypt_key() function can - be applied to the encrypted string to restore the original key object. - 'key_object' is a TUF key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA). This - function calls the appropriate cryptography module (e.g., pycrypto_keys.py) - to perform the encryption. - - The currently supported general-purpose crypto module, 'pycrypto_keys.py', - performs the actual cryptographic operation on 'key_object'. Whereas - an encrypted PEM file uses the Triple Data Encryption Algorithm (3DES), the - Cipher-block chaining (CBC) mode of operation, and the Password-Based Key - Derivation Function 1 (PBKDF1) + MD5 to strengthen 'password', encrypted - TUF keys use AES-256-CTR-Mode and passwords strengthened with - PBKDF2-HMAC-SHA256 (100K iterations by default, but may be overriden in - 'settings.PBKDF2_ITERATIONS' by the user). - - http://en.wikipedia.org/wiki/Advanced_Encryption_Standard - http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29 - https://en.wikipedia.org/wiki/PBKDF2 - - >>> ed25519_key = generate_ed25519_key() - >>> password = 'secret' - >>> encrypted_key = encrypt_key(ed25519_key, password).encode('utf-8') - >>> tuf.ssl_crypto.formats.ENCRYPTEDKEY_SCHEMA.matches(encrypted_key) - True - - - key_object: - A TUF key (containing also the private key portion) of the form - 'tuf.ssl_crypto.formats.ANYKEY_SCHEMA' - - password: - The password, or passphrase, to encrypt the private part of the RSA - key. 'password' is not used directly as the encryption key, a stronger - encryption key is derived from it. - - - tuf.ssl_commons.exceptions.FormatError, if the arguments are improperly formatted. - - tuf.ssl_commons.exceptions.CryptoError, if 'key_object' cannot be encrypted. - - tuf.ssl_commons.exceptions.UnsupportedLibraryError, if the general-purpose cryptography library - specified in 'settings.GENERAL_CRYPTO_LIBRARY' is unsupported. - - - Perform crytographic operations using the library specified in - 'tuf.tufformats.GENERAL_CRYPTO_LIBRARY' and 'password'. - - - An encrypted string of the form: 'tuf.ssl_crypto.formats.ENCRYPTEDKEY_SCHEMA'. - """ - - # Does 'key_object' have the correct format? - # This check will ensure 'key_object' has the appropriate number - # of objects and object types, and that all dict keys are properly named. - # Raise 'tuf.ssl_commons.exceptions.FormatError' if the check fails. - tuf.ssl_crypto.formats.ANYKEY_SCHEMA.check_match(key_object) - - # Does 'password' have the correct format? - tuf.ssl_crypto.formats.PASSWORD_SCHEMA.check_match(password) - - # Raise 'tuf.ssl_commons.exceptions.UnsupportedLibraryError' if the following libraries, specified in - # 'settings', are unsupported or unavailable: - # 'settings.GENERAL_CRYPTO_LIBRARY'. - check_crypto_libraries(['general']) - - # Encrypted string of 'key_object'. The encrypted string may be safely saved - # to a file and stored offline. - encrypted_key = None - - # Generate an encrypted string of 'key_object' using AES-256-CTR-Mode, where - # 'password' is strengthened with PBKDF2-HMAC-SHA256. Ensure the general- - # purpose library specified in 'settings.GENERAL_CRYPTO_LIBRARY' is supported. - if _GENERAL_CRYPTO_LIBRARY == 'pycrypto': - encrypted_key = \ - tuf.ssl_crypto.pycrypto_keys.encrypt_key(key_object, password) - - elif _GENERAL_CRYPTO_LIBRARY == 'pyca-cryptography': - encrypted_key = \ - tuf.ssl_crypto.pyca_crypto_keys.encrypt_key(key_object, password) - - # check_crypto_libraries() should have fully verified _GENERAL_CRYPTO_LIBRARY. - else: # pragma: no cover - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('Invalid crypto library:' - ' ' + repr(_GENERAL_CRYPTO_LIBRARY) + '.') - - return encrypted_key - - - - - -def decrypt_key(encrypted_key, passphrase): - """ - - Return a string containing 'encrypted_key' in non-encrypted form. - The decrypt_key() function can be applied to the encrypted string to restore - the original key object, a TUF key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA). - This function calls the appropriate cryptography module (e.g., - pycrypto_keys.py) to perform the decryption. - - The currently supported general-purpose crypto module, 'pycrypto_keys.py', - performs the actual cryptographic operation on 'key_object'. Whereas - an encrypted PEM file uses the Triple Data Encryption Algorithm (3DES), the - Cipher-block chaining (CBC) mode of operation, and the Password-Based Key - Derivation Function 1 (PBKDF1) + MD5 to strengthen 'password', encrypted - TUF keys use AES-256-CTR-Mode and passwords strengthened with - PBKDF2-HMAC-SHA256 (100K iterations be default, but may be overriden in - 'tuf.settings.py' by the user). - - http://en.wikipedia.org/wiki/Advanced_Encryption_Standard - http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29 - https://en.wikipedia.org/wiki/PBKDF2 - - >>> ed25519_key = generate_ed25519_key() - >>> password = 'secret' - >>> encrypted_key = encrypt_key(ed25519_key, password) - >>> decrypted_key = decrypt_key(encrypted_key.encode('utf-8'), password) - >>> tuf.ssl_crypto.formats.ANYKEY_SCHEMA.matches(decrypted_key) - True - >>> decrypted_key == ed25519_key - True - - - encrypted_key: - An encrypted TUF key (additional data is also included, such as salt, - number of password iterations used for the derived encryption key, etc) - of the form 'tuf.ssl_crypto.formats.ENCRYPTEDKEY_SCHEMA'. 'encrypted_key' should - have been generated with encrypted_key(). - - password: - The password, or passphrase, to decrypt 'encrypted_key'. 'password' is - not used directly as the encryption key, a stronger encryption key is - derived from it. The supported general-purpose module takes care of - re-deriving the encryption key. - - - tuf.ssl_commons.exceptions.FormatError, if the arguments are improperly formatted. - - tuf.ssl_commons.exceptions.CryptoError, if 'encrypted_key' cannot be decrypted. - - tuf.ssl_commons.exceptions.UnsupportedLibraryError, if the general-purpose cryptography library - specified in 'settings.GENERAL_CRYPTO_LIBRARY' is unsupported. - - - Perform crytographic operations using the library specified in - 'tuf.tufformats.GENERAL_CRYPTO_LIBRARY' and 'password'. - - - A TUF key object of the form: 'tuf.ssl_crypto.formats.ANYKEY_SCHEMA' (e.g., - RSAKEY_SCHEMA, ED25519KEY_SCHEMA). - """ - - # Does 'encrypted_key' have the correct format? - # This check ensures 'encrypted_key' has the appropriate number - # of objects and object types, and that all dict keys are properly named. - # Raise 'tuf.ssl_commons.exceptions.FormatError' if the check fails. - tuf.ssl_crypto.formats.ENCRYPTEDKEY_SCHEMA.check_match(encrypted_key) - - # Does 'passphrase' have the correct format? - tuf.ssl_crypto.formats.PASSWORD_SCHEMA.check_match(passphrase) - - # Raise 'tuf.ssl_commons.exceptions.UnsupportedLibraryError' if the following libraries, specified in - # 'settings', are unsupported or unavailable: - # 'settings.GENERAL_CRYPTO_LIBRARY'. - check_crypto_libraries(['general']) - - # Store and return the decrypted key object. - key_object = None - - # Decrypt 'encrypted_key' so that the original key object is restored. - # encrypt_key() generates an encrypted string of the TUF key object using - # AES-256-CTR-Mode, where 'password' is strengthened with PBKDF2-HMAC-SHA256. - # Ensure the general-purpose library specified in - # 'settings.GENERAL_CRYPTO_LIBRARY' is supported. - if _GENERAL_CRYPTO_LIBRARY == 'pycrypto': - key_object = \ - tuf.ssl_crypto.pycrypto_keys.decrypt_key(encrypted_key, passphrase) - - elif _GENERAL_CRYPTO_LIBRARY == 'pyca-cryptography': - key_object = \ - tuf.ssl_crypto.pyca_crypto_keys.decrypt_key(encrypted_key, passphrase) - - # check_crypto_libraries() should have fully verified _GENERAL_CRYPTO_LIBRARY. - else: # pragma: no cover - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('Invalid crypto library:' - ' ' + repr(_GENERAL_CRYPTO_LIBRARY) + '.') - - # The corresponding encrypt_key() encrypts and stores key objects in - # non-metadata format (i.e., original format of key object argument to - # encrypt_key()) prior to returning. - - return key_object - - - - - -def create_rsa_encrypted_pem(private_key, passphrase): - """ - - Return a string in PEM format, where the private part of the RSA key is - encrypted. The private part of the RSA key is encrypted by the Triple - Data Encryption Algorithm (3DES) and Cipher-block chaining (CBC) for the - mode of operation. Password-Based Key Derivation Function 1 (PBKDF1) + MD5 - is used to strengthen 'passphrase'. - - https://en.wikipedia.org/wiki/Triple_DES - https://en.wikipedia.org/wiki/PBKDF2 - - >>> rsa_key = generate_rsa_key() - >>> private = rsa_key['keyval']['private'] - >>> passphrase = 'secret' - >>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase) - >>> tuf.ssl_crypto.formats.PEMRSA_SCHEMA.matches(encrypted_pem) - True - - - private_key: - The private key string in PEM format. - - passphrase: - The passphrase, or password, to encrypt the private part of the RSA - key. 'passphrase' is not used directly as the encryption key, a stronger - encryption key is derived from it. - - - tuf.ssl_commons.exceptions.FormatError, if the arguments are improperly formatted. - - tuf.ssl_commons.exceptions.CryptoError, if an RSA key in encrypted PEM format cannot be created. - - TypeError, 'private_key' is unset. - - - PyCrypto's Crypto.PublicKey.RSA.exportKey() called to perform the actual - generation of the PEM-formatted output. - - - A string in PEM format, where the private RSA key is encrypted. - Conforms to 'tuf.ssl_crypto.formats.PEMRSA_SCHEMA'. - """ - - # Does 'private_key' have the correct format? - # This check will ensure 'private_key' has the appropriate number - # of objects and object types, and that all dict keys are properly named. - # Raise 'tuf.ssl_commons.exceptions.FormatError' if the check fails. - tuf.ssl_crypto.formats.PEMRSA_SCHEMA.check_match(private_key) - - # Does 'passphrase' have the correct format? - tuf.ssl_crypto.formats.PASSWORD_SCHEMA.check_match(passphrase) - - # Raise 'tuf.ssl_commons.exceptions.UnsupportedLibraryError' if the following libraries, specified - # in 'settings', are unsupported or unavailable: - # 'settings.GENERAL_CRYPTO_LIBRARY' and 'settings.RSA_CRYPTO_LIBRARY'. - check_crypto_libraries(['rsa', 'general']) - - encrypted_pem = None - - # Generate the public and private RSA keys. The PyCrypto module performs - # the actual key generation. Raise 'ValueError' if 'bits' is less than 1024 - # or not a multiple of 256, although a 2048-bit minimum is enforced by - # tuf.ssl_crypto.formats.RSAKEYBITS_SCHEMA.check_match(). - if _RSA_CRYPTO_LIBRARY == 'pycrypto': - encrypted_pem = \ - tuf.ssl_crypto.pycrypto_keys.create_rsa_encrypted_pem(private_key, passphrase) - - elif _RSA_CRYPTO_LIBRARY == 'pyca-cryptography': - encrypted_pem = \ - tuf.ssl_crypto.pycrypto_keys.create_rsa_encrypted_pem(private_key, passphrase) - - # check_crypto_libraries() should have fully verified _RSA_CRYPTO_LIBRARY. - else: # pragma: no cover - raise tuf.ssl_commons.exceptions.UnsupportedLibraryError('Invalid crypto library:' - ' ' + repr(_RSA_CRYPTO_LIBRARY) + '.') - - return encrypted_pem - - - -if __name__ == '__main__': - # The interactive sessions of the documentation strings can - # be tested by running 'keys.py' as a standalone module: - # $ python keys.py - import doctest - doctest.testmod() diff --git a/tuf/repository_lib.py b/tuf/repository_lib.py index c56f0fee..d9462534 100755 --- a/tuf/repository_lib.py +++ b/tuf/repository_lib.py @@ -45,9 +45,9 @@ import tuf.ssl_crypto.formats import tuf.tufformats import tuf.ssl_crypto.util -import tuf.keydb +import tuf.ssl_crypto.keydb import tuf.roledb -import tuf.keys +import tuf.ssl_crypto.keys import tuf.sig import tuf.log from simple_settings import settings @@ -423,16 +423,16 @@ def _remove_invalid_and_duplicate_signatures(signable): key = None # Remove 'signature' from 'signable' if the listed keyid does not exist - # in 'tuf.keydb'. + # in 'tuf.ssl_crypto.keydb'. try: - key = tuf.keydb.get_key(keyid) + key = tuf.ssl_crypto.keydb.get_key(keyid) except tuf.ssl_commons.exceptions.UnknownKeyError: signable['signatures'].remove(signature) continue # Remove 'signature' from 'signable' if it is an invalid signature. - if not tuf.keys.verify_signature(key, signature, signed): + if not tuf.ssl_crypto.keys.verify_signature(key, signature, signed): logger.debug('Removing invalid signature for ' + repr(keyid)) signable['signatures'].remove(signature) @@ -610,7 +610,7 @@ def _load_top_level_metadata(repository, top_level_filenames): signable = tuf.ssl_crypto.util.load_json_file(root_filename) tuf.tufformats.check_signable_object_format(signable) root_metadata = signable['signed'] - tuf.keydb.create_keydb_from_root_metadata(root_metadata) + tuf.ssl_crypto.keydb.create_keydb_from_root_metadata(root_metadata) tuf.roledb.create_roledb_from_root_metadata(root_metadata) # Load Root's roleinfo and update 'tuf.roledb'. @@ -768,7 +768,7 @@ def _load_top_level_metadata(repository, top_level_filenames): # Add the keys specified in the delegations field of the Targets role. for key_metadata in six.itervalues(targets_metadata['delegations']['keys']): - key_object, keyids = tuf.keys.format_metadata_to_key(key_metadata) + key_object, keyids = tuf.ssl_crypto.keys.format_metadata_to_key(key_metadata) # Add 'key_object' to the list of recognized keys. Keys may be shared, # so do not raise an exception if 'key_object' has already been loaded. @@ -777,10 +777,10 @@ def _load_top_level_metadata(repository, top_level_filenames): # repository maintainer should have also been made aware of the duplicate # key when it was added. try: - tuf.keydb.add_key(key_object) + tuf.ssl_crypto.keydb.add_key(key_object) for keyid in keyids: #pragma: no branch key_object['keyid'] = keyid - tuf.keydb.add_key(key_object, keyid=None) + tuf.ssl_crypto.keydb.add_key(key_object, keyid=None) except tuf.ssl_commons.exceptions.KeyAlreadyExistsError: pass @@ -873,10 +873,10 @@ def generate_and_write_rsa_keypair(filepath, bits=DEFAULT_RSA_KEY_BITS, # Generate public and private RSA keys, encrypted the private portion # and store them in PEM format. - rsa_key = tuf.keys.generate_rsa_key(bits) + rsa_key = tuf.ssl_crypto.keys.generate_rsa_key(bits) public = rsa_key['keyval']['public'] private = rsa_key['keyval']['private'] - encrypted_pem = tuf.keys.create_rsa_encrypted_pem(private, password) + encrypted_pem = tuf.ssl_crypto.keys.create_rsa_encrypted_pem(private, password) # Write public key (i.e., 'public', which is in PEM format) to # '.pub'. If the parent directory of filepath does not exist, @@ -959,7 +959,7 @@ def import_rsa_privatekey_from_file(filepath, password=None): # Convert 'encrypted_pem' to 'tuf.ssl_crypto.formats.RSAKEY_SCHEMA' format. Raise # 'tuf.ssl_commons.exceptions.CryptoError' if 'encrypted_pem' is invalid. - rsa_key = tuf.keys.import_rsakey_from_encrypted_pem(encrypted_pem, password) + rsa_key = tuf.ssl_crypto.keys.import_rsakey_from_encrypted_pem(encrypted_pem, password) return rsa_key @@ -1009,7 +1009,7 @@ def import_rsa_publickey_from_file(filepath): # Convert 'rsa_pubkey_pem' to 'tuf.ssl_crypto.formats.RSAKEY_SCHEMA' format. try: - rsakey_dict = tuf.keys.format_rsakey_from_pem(rsa_pubkey_pem) + rsakey_dict = tuf.ssl_crypto.keys.format_rsakey_from_pem(rsa_pubkey_pem) except tuf.ssl_commons.exceptions.FormatError as e: raise tuf.ssl_commons.exceptions.Error('Cannot import improperly formatted PEM file.' + repr(str(e))) @@ -1076,15 +1076,15 @@ def generate_and_write_ed25519_keypair(filepath, password=None): # used is determined by the user, or by default (set in # 'settings.ED25519_CRYPTO_LIBRARY'). Raise 'tuf.ssl_commons.exceptions.CryptoError' or # 'tuf.ssl_commons.exceptions.UnsupportedLibraryError', if 'ed25519_key' cannot be encrypted. - ed25519_key = tuf.keys.generate_ed25519_key() - encrypted_key = tuf.keys.encrypt_key(ed25519_key, password) + ed25519_key = tuf.ssl_crypto.keys.generate_ed25519_key() + encrypted_key = tuf.ssl_crypto.keys.encrypt_key(ed25519_key, password) # ed25519 public key file contents in metadata format (i.e., does not include # the keyid portion). keytype = ed25519_key['keytype'] keyval = ed25519_key['keyval'] ed25519key_metadata_format = \ - tuf.keys.format_keyval_to_metadata(keytype, keyval, private=False) + tuf.ssl_crypto.keys.format_keyval_to_metadata(keytype, keyval, private=False) # Write the public key, conformant to 'tuf.ssl_crypto.formats.KEY_SCHEMA', to # '.pub'. @@ -1142,10 +1142,10 @@ def import_ed25519_publickey_from_file(filepath): # loaded key object in tuf.ssl_crypto.formats.ED25519KEY_SCHEMA' format that also # includes the keyid. ed25519_key_metadata = tuf.ssl_crypto.util.load_json_file(filepath) - ed25519_key, junk = tuf.keys.format_metadata_to_key(ed25519_key_metadata) + ed25519_key, junk = tuf.ssl_crypto.keys.format_metadata_to_key(ed25519_key_metadata) # Raise an exception if an unexpected key type is imported. - # Redundant validation of 'keytype'. 'tuf.keys.format_metadata_to_key()' + # Redundant validation of 'keytype'. 'tuf.ssl_crypto.keys.format_metadata_to_key()' # should have fully validated 'ed25519_key_metadata'. if ed25519_key['keytype'] != 'ed25519': # pragma: no cover message = 'Invalid key type loaded: ' + repr(ed25519_key['keytype']) @@ -1223,7 +1223,7 @@ def import_ed25519_privatekey_from_file(filepath, password=None): # (i.e., set by the user) and generating the derived encryption key from # 'password'. Raise 'tuf.ssl_commons.exceptions.CryptoError' or 'tuf.ssl_commons.exceptions.UnsupportedLibraryError' if the # decryption fails. - key_object = tuf.keys.decrypt_key(encrypted_key, password) + key_object = tuf.ssl_crypto.keys.decrypt_key(encrypted_key, password) # Raise an exception if an unexpected key type is imported. if key_object['keytype'] != 'ed25519': @@ -1435,7 +1435,7 @@ def generate_root_metadata(version, expiration_date, consistent_snapshot, compression_algorithms=['gz']): """ - Create the root metadata. 'tuf.roledb.py' and 'tuf.keydb.py' are read and + Create the root metadata. 'tuf.roledb.py' and 'tuf.ssl_crypto.keydb.py' are read and the information returned by these modules is used to generate the root metadata object. @@ -1467,7 +1467,7 @@ def generate_root_metadata(version, expiration_date, consistent_snapshot, metadata object (e.g., a required top-level role not found in 'tuf.roledb'.) - The contents of 'tuf.keydb.py' and 'tuf.roledb.py' are read. + The contents of 'tuf.ssl_crypto.keydb.py' and 'tuf.roledb.py' are read. A root metadata object, conformant to 'tuf.ssl_crypto.formats.ROOT_SCHEMA'. @@ -1501,7 +1501,7 @@ def generate_root_metadata(version, expiration_date, consistent_snapshot, # Generate keys for the keyids listed by the role being processed. for keyid in tuf.roledb.get_role_keyids(rolename): - key = tuf.keydb.get_key(keyid) + key = tuf.ssl_crypto.keydb.get_key(keyid) # If 'key' is an RSA key, it would conform to 'tuf.ssl_crypto.formats.RSAKEY_SCHEMA', # and have the form: @@ -1517,7 +1517,7 @@ def generate_root_metadata(version, expiration_date, consistent_snapshot, keytype = key['keytype'] keyval = key['keyval'] keydict[keyid] = \ - tuf.keys.format_keyval_to_metadata(keytype, keyval, private=False) + tuf.ssl_crypto.keys.format_keyval_to_metadata(keytype, keyval, private=False) # This is not a recognized key. Raise an exception. else: @@ -1857,7 +1857,7 @@ def sign_metadata(metadata_object, keyids, filename): Sign a metadata object. If any of the keyids have already signed the file, the old signature is replaced. The keys in 'keyids' must already be - loaded in 'tuf.keydb'. + loaded in 'tuf.ssl_crypto.keydb'. metadata_object: @@ -1904,14 +1904,14 @@ def sign_metadata(metadata_object, keyids, filename): for keyid in keyids: # Load the signing key. - key = tuf.keydb.get_key(keyid) + key = tuf.ssl_crypto.keydb.get_key(keyid) # Generate the signature using the appropriate signing method. if key['keytype'] in SUPPORTED_KEY_TYPES: if 'private' in key['keyval']: signed = signable['signed'] try: - signature = tuf.keys.create_signature(key, signed) + signature = tuf.ssl_crypto.keys.create_signature(key, signed) signable['signatures'].append(signature) except Exception: diff --git a/tuf/repository_tool.py b/tuf/repository_tool.py index e752f35f..67f0776a 100755 --- a/tuf/repository_tool.py +++ b/tuf/repository_tool.py @@ -41,9 +41,9 @@ import tuf import tuf.tufformats import tuf.ssl_crypto.util -import tuf.keydb +import tuf.ssl_crypto.keydb import tuf.roledb -import tuf.keys +import tuf.ssl_crypto.keys import tuf.sig import tuf.log import tuf.repository_lib as repo_lib @@ -100,7 +100,7 @@ TIMESTAMP_EXPIRATION = 86400 try: - tuf.keys.check_crypto_libraries(['rsa', 'ed25519', 'general']) + tuf.ssl_crypto.keys.check_crypto_libraries(['rsa', 'ed25519', 'general']) except tuf.ssl_commons.exceptions.UnsupportedLibraryError: #pragma: no cover logger.warn('Warning: The repository and developer tools require' @@ -217,7 +217,7 @@ def writeall(self, consistent_snapshot=False, compression_algorithms=['gz']): tuf.ssl_crypto.formats.BOOLEAN_SCHEMA.check_match(consistent_snapshot) tuf.ssl_crypto.formats.COMPRESSIONS_SCHEMA.check_match(compression_algorithms) - # At this point, tuf.keydb and tuf.roledb must be fully populated, + # At this point, tuf.ssl_crypto.keydb and tuf.roledb must be fully populated, # otherwise writeall() throws a 'tuf.ssl_commons.exceptions.UnsignedMetadataError' for the # top-level roles. exception if any of the top-level roles are missing # signatures, keys, etc. @@ -595,7 +595,7 @@ def add_verification_key(self, key, expires=None): tuf.ssl_commons.exceptions.Error, if the 'expires' datetime has already expired. - The role's entries in 'tuf.keydb.py' and 'tuf.roledb.py' are updated. + The role's entries in 'tuf.ssl_crypto.keydb.py' and 'tuf.roledb.py' are updated. None. @@ -653,10 +653,10 @@ def add_verification_key(self, key, expires=None): key['expires'] = expires # Ensure 'key', which should contain the public portion, is added to - # 'tuf.keydb.py'. Add 'key' to the list of recognized keys. Keys may be + # 'tuf.ssl_crypto.keydb.py'. Add 'key' to the list of recognized keys. Keys may be # shared, so do not raise an exception if 'key' has already been loaded. try: - tuf.keydb.add_key(key) + tuf.ssl_crypto.keydb.add_key(key) except tuf.ssl_commons.exceptions.KeyAlreadyExistsError: logger.warning('Adding a verification key that has already been used.') @@ -747,7 +747,7 @@ def load_signing_key(self, key): tuf.ssl_commons.exceptions.Error, if the private key is not found in 'key'. - Updates the role's 'tuf.keydb.py' and 'tuf.roledb.py' entries. + Updates the role's 'tuf.ssl_crypto.keydb.py' and 'tuf.roledb.py' entries. None. @@ -767,11 +767,11 @@ def load_signing_key(self, key): # Has the key, with the private portion included, been added to the keydb? # The public version of the key may have been previously added. try: - tuf.keydb.add_key(key) + tuf.ssl_crypto.keydb.add_key(key) except tuf.ssl_commons.exceptions.KeyAlreadyExistsError: - tuf.keydb.remove_key(key['keyid']) - tuf.keydb.add_key(key) + tuf.ssl_crypto.keydb.remove_key(key['keyid']) + tuf.ssl_crypto.keydb.add_key(key) # Update the role's 'signing_keys' field in 'tuf.roledb.py'. roleinfo = tuf.roledb.get_roleinfo(self.rolename) @@ -2180,7 +2180,7 @@ def delegate(self, rolename, public_keys, list_of_targets, threshold=1, A new Target object is created for 'rolename' that is accessible to the - caller (i.e., targets.). The 'tuf.keydb.py' and + caller (i.e., targets.). The 'tuf.ssl_crypto.keydb.py' and 'tuf.roledb.py' stores are updated with 'public_keys'. @@ -2212,10 +2212,10 @@ def delegate(self, rolename, public_keys, list_of_targets, threshold=1, keyids = [] keydict = {} - # Add all the keys in 'public_keys' to tuf.keydb. + # Add all the keys in 'public_keys' to tuf.ssl_crypto.keydb. for key in public_keys: keyid = key['keyid'] - key_metadata_format = tuf.keys.format_keyval_to_metadata(key['keytype'], + key_metadata_format = tuf.ssl_crypto.keys.format_keyval_to_metadata(key['keytype'], key['keyval']) # Update 'keyids' and 'keydict'. new_keydict = {keyid: key_metadata_format} @@ -2869,7 +2869,7 @@ def load_repository(repository_directory): # Load top-level metadata. #tuf.roledb.clear_roledb(clear_all=True) - #tuf.keydb.clear_keydb(clear_all=True) + #tuf.ssl_crypto.keydb.clear_keydb(clear_all=True) repository_directory = os.path.abspath(repository_directory) metadata_directory = os.path.join(repository_directory, @@ -2992,9 +2992,9 @@ def load_repository(repository_directory): # The repository maintainer should have also been made aware of the # duplicate key when it was added. for key_metadata in six.itervalues(metadata_object['delegations']['keys']): - key_object, junk = tuf.keys.format_metadata_to_key(key_metadata) + key_object, junk = tuf.ssl_crypto.keys.format_metadata_to_key(key_metadata) try: - tuf.keydb.add_key(key_object) + tuf.ssl_crypto.keydb.add_key(key_object) except tuf.ssl_commons.exceptions.KeyAlreadyExistsError: pass diff --git a/tuf/sig.py b/tuf/sig.py index 4fae5f9a..a0b7c808 100755 --- a/tuf/sig.py +++ b/tuf/sig.py @@ -47,7 +47,7 @@ import tuf import tuf.tufformats -import tuf.keydb +import tuf.ssl_crypto.keydb import tuf.roledb @@ -66,7 +66,7 @@ def get_signature_status(signable, role=None, repository_name='default', Return a dictionary representing the status of the signatures listed in 'signable'. Given an object conformant to SIGNABLE_SCHEMA, a set of public - keys in 'tuf.keydb', a set of roles in 'tuf.roledb', and a role, the status + keys in 'tuf.ssl_crypto.keydb', a set of roles in 'tuf.roledb', and a role, the status of these signatures can be determined. This method will iterate the signatures in 'signable' and enumerate all the keys that are valid, invalid, unrecognized, unauthorized, or generated using an unknown method. @@ -158,7 +158,7 @@ def get_signature_status(signable, role=None, repository_name='default', # Does the signature use an unrecognized key? try: - key = tuf.keydb.get_key(keyid, repository_name) + key = tuf.ssl_crypto.keydb.get_key(keyid, repository_name) except tuf.ssl_commons.exceptions.UnknownKeyError: unknown_sigs.append(keyid) @@ -166,7 +166,7 @@ def get_signature_status(signable, role=None, repository_name='default', # Does the signature use an unknown key signing method? try: - valid_sig = tuf.keys.verify_signature(key, signature, signed) + valid_sig = tuf.ssl_crypto.keys.verify_signature(key, signature, signed) except tuf.ssl_commons.exceptions.UnknownMethodError: unknown_method_sigs.append(keyid) @@ -354,7 +354,7 @@ def generate_rsa_signature(signed, rsakey_dict): signed: - The data used by 'tuf.keys.create_signature()' to generate signatures. + The data used by 'tuf.ssl_crypto.keys.create_signature()' to generate signatures. It is stored in the 'signed' field of 'signable'. rsakey_dict: @@ -381,6 +381,6 @@ def generate_rsa_signature(signed, rsakey_dict): # Generate the RSA signature. # Raises tuf.ssl_commons.exceptions.FormatError and TypeError. - signature = tuf.keys.create_signature(rsakey_dict, signed) + signature = tuf.ssl_crypto.keys.create_signature(rsakey_dict, signed) return signature