def test_mac_on_invalid_inputs(self): """ Test that a TypeError exception is raised when wrong type of arguments are given to mac operation. """ uuid = 'aaaaaaaa-1111-2222-3333-ffffffffffff' uuid_invalid = int(123) algorithm = enums.CryptographicAlgorithm.HMAC_SHA256 algorithm_invalid = enums.CryptographicUsageMask.MAC_GENERATE data = (b'\x00\x01\x02\x03\x04') data_invalid = int(123) result = results.MACResult(contents.ResultStatus( enums.ResultStatus.SUCCESS), uuid=attr.UniqueIdentifier(uuid), mac_data=obj.MACData(data)) args = [uuid_invalid, algorithm, data] with ProxyKmipClient() as client: client.proxy.mac.return_value = result self.assertRaises(TypeError, client.mac, *args) args = [uuid, algorithm_invalid, data] with ProxyKmipClient() as client: client.proxy.mac.return_value = result self.assertRaises(TypeError, client.mac, *args) args = [uuid, algorithm, data_invalid] with ProxyKmipClient() as client: client.proxy.mac.return_value = result self.assertRaises(TypeError, client.mac, *args)
def test_mac_on_operation_failure(self): """ Test that a KmipOperationFailure exception is raised when the backend fails to generate MAC. """ uuid = 'aaaaaaaa-1111-2222-3333-ffffffffffff' algorithm = enums.CryptographicAlgorithm.HMAC_SHA256 data = (b'\x00\x01\x02\x03\x04') status = enums.ResultStatus.OPERATION_FAILED reason = enums.ResultReason.GENERAL_FAILURE message = "Test failure message" result = results.OperationResult(contents.ResultStatus(status), contents.ResultReason(reason), contents.ResultMessage(message)) error_msg = str(KmipOperationFailure(status, reason, message)) client = ProxyKmipClient() client.open() client.proxy.mac.return_value = result args = [uuid, algorithm, data] self.assertRaisesRegexp(KmipOperationFailure, error_msg, client.mac, *args)
def test_get(self): """ Test that a secret can be retrieved with proper input. """ # Key encoding obtained from Section 14.2 of the KMIP 1.1 test # documentation. secret = objects.SymmetricKey( enums.CryptographicAlgorithm.AES, 128, (b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E' b'\x0F')) fact = factory.ObjectFactory() result = results.GetResult(contents.ResultStatus( enums.ResultStatus.SUCCESS), uuid=attr.PublicKeyUniqueIdentifier( 'aaaaaaaa-1111-2222-3333-ffffffffffff'), secret=fact.convert(secret)) with ProxyKmipClient() as client: client.proxy.get.return_value = result result = client.get('aaaaaaaa-1111-2222-3333-ffffffffffff') client.proxy.get.assert_called_with( 'aaaaaaaa-1111-2222-3333-ffffffffffff') self.assertIsInstance(result, objects.SymmetricKey) self.assertEqual(result, secret)
def AsymmetricKeyRSA(): c = ProxyKmipClient(hostname=KMIP_IP,port=SERVER_PORT,cert=CERT_PATH,key=KEY_PATH,ca=CA_PATH) print("Asymmetric Key Creation") with c: key_id = c.create_key_pair( enums.CryptographicAlgorithm.RSA, KEY_BITS, public_usage_mask=[ enums.CryptographicUsageMask.ENCRYPT ], private_usage_mask=[ enums.CryptographicUsageMask.DECRYPT ] ) print("Private Key ID : " +key_id[1]) current_directory = os.getcwd() temp_directory = os.path.join(current_directory,TEMP_DIRECTORY) if not os.path.exists(temp_directory): os.makedirs(temp_directory) orig_stdout = sys.stdout f = open(KEY_HEX_OUTPUT, 'w') sys.stdout = f print(c.get(key_id[1])) sys.stdout = orig_stdout f.close()
def test_get_attributes(self): """ Test that a secret's attributes can be retrieved with proper input. """ result = results.GetAttributesResult( contents.ResultStatus(enums.ResultStatus.SUCCESS), uuid='aaaaaaaa-1111-2222-3333-ffffffffffff', attributes=[ obj.Attribute( attribute_name=obj.Attribute.AttributeName('Name'), attribute_index=obj.Attribute.AttributeIndex(0), attribute_value=attr.Name( name_value=attr.Name.NameValue('Test Name'), name_type=attr.Name.NameType( enums.NameType.UNINTERPRETED_TEXT_STRING))), obj.Attribute( attribute_name=obj.Attribute.AttributeName('Object Type'), attribute_value=attr.ObjectType( enums.ObjectType.SYMMETRIC_KEY)) ]) with ProxyKmipClient() as client: client.proxy.get_attributes.return_value = result result = client.get_attributes( 'aaaaaaaa-1111-2222-3333-ffffffffffff', ['Name', 'Object Type']) client.proxy.get_attributes.assert_called_with( 'aaaaaaaa-1111-2222-3333-ffffffffffff', ['Name', 'Object Type']) self.assertIsInstance(result[0], six.string_types) self.assertIsInstance(result[1], list) for r in result[1]: self.assertIsInstance(r, obj.Attribute)
def test_create(self): """ Test that a symmetric key can be created with proper inputs and that its UID is returned properly. """ # Create the template to test the create call algorithm = enums.CryptographicAlgorithm.AES length = 256 algorithm_attribute = self.attribute_factory.create_attribute( enums.AttributeType.CRYPTOGRAPHIC_ALGORITHM, algorithm) length_attribute = self.attribute_factory.create_attribute( enums.AttributeType.CRYPTOGRAPHIC_LENGTH, length) mask_attribute = self.attribute_factory.create_attribute( enums.AttributeType.CRYPTOGRAPHIC_USAGE_MASK, [ enums.CryptographicUsageMask.ENCRYPT, enums.CryptographicUsageMask.DECRYPT ]) attributes = [algorithm_attribute, length_attribute, mask_attribute] template = obj.TemplateAttribute(attributes=attributes) key_id = 'aaaaaaaa-1111-2222-3333-ffffffffffff' status = enums.ResultStatus.SUCCESS result = results.CreateResult(contents.ResultStatus(status), uuid=attr.UniqueIdentifier(key_id)) with ProxyKmipClient() as client: client.proxy.create.return_value = result uid = client.create(algorithm, length) client.proxy.create.assert_called_with( enums.ObjectType.SYMMETRIC_KEY, template) self.assertIsInstance(uid, six.string_types) self.assertEqual(uid, key_id)
def test_close_on_close(self): """ Test that a ClientConnectionNotOpen exception is raised when trying to close a closed client connection. """ client = ProxyKmipClient() self.assertRaises(ClientConnectionNotOpen, client.close)
def test_open(self): """ Test that the client can open a connection. """ client = ProxyKmipClient() client.open() client.proxy.open.assert_called_with()
def test_register_on_operation_failure(self): """ Test that a KmipOperationFailure exception is raised when the backend fails to register a key. """ status = enums.ResultStatus.OPERATION_FAILED reason = enums.ResultReason.GENERAL_FAILURE message = "Test failure message" result = results.OperationResult(contents.ResultStatus(status), contents.ResultReason(reason), contents.ResultMessage(message)) error_msg = str(KmipOperationFailure(status, reason, message)) # Key encoding obtained from Section 14.2 of the KMIP 1.1 test # documentation. key_value = ( b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E' b'\x0F') key = objects.SymmetricKey(enums.CryptographicAlgorithm.AES, 128, key_value) client = ProxyKmipClient() client.open() client.proxy.register.return_value = result args = [key] self.assertRaisesRegexp(KmipOperationFailure, error_msg, client.register, *args)
def _get_root_secret(self, conf): if self.keymaster_config_path: section = self.keymaster_conf_section else: section = conf['__name__'] if os.path.isdir(conf['__file__']): raise ValueError( 'KmipKeyMaster config cannot be read from conf dir %s. Use ' 'keymaster_config_path option in the proxy server config to ' 'specify a config file.') key_id = conf.get('key_id') if not key_id: raise ValueError('key_id option is required') kmip_logger = logging.getLogger('kmip') for handler in self.logger.logger.handlers: kmip_logger.addHandler(handler) with ProxyKmipClient(config=section, config_file=conf['__file__']) as client: secret = client.get(key_id) if (secret.cryptographic_algorithm.name, secret.cryptographic_length) != ('AES', 256): raise ValueError('Expected an AES-256 key, not %s-%d' % (secret.cryptographic_algorithm.name, secret.cryptographic_length)) return secret.value
def test_create_on_closed(self): """ Test that a ClientConnectionNotOpen exception is raised when trying to create a symmetric key on an unopened client connection. """ client = ProxyKmipClient() args = [enums.CryptographicAlgorithm.AES, 256] self.assertRaises(ClientConnectionNotOpen, client.create, *args)
def test_close(self): """ Test that the client can close an open connection. """ client = ProxyKmipClient() client.open() client.close() client.proxy.close.assert_called_with()
def test_destroy_on_invalid_uid(self): """ Test that a TypeError exception is raised when trying to destroy a secret with an invalid ID. """ args = [0] with ProxyKmipClient() as client: self.assertRaises(TypeError, client.destroy, *args)
def test_open_on_open(self): """ Test that a ClientConnectionFailure exception is raised when trying to open an opened client connection. """ client = ProxyKmipClient() client.open() self.assertRaises(ClientConnectionFailure, client.open)
def test_open_on_proxy_failure(self): """ Test that an Exception is raised when an error occurs while opening the client proxy connection. """ client = ProxyKmipClient() client.proxy.open.side_effect = Exception self.assertRaises(Exception, client.open)
def test_destroy_on_closed(self): """ Test that a ClientConnectionNotOpen exception is raised when trying to destroy a secret on an unopened client connection. """ client = ProxyKmipClient() args = ['aaaaaaaa-1111-2222-3333-ffffffffffff'] self.assertRaises(ClientConnectionNotOpen, client.destroy, *args)
def test_register_on_invalid_uid(self): """ Test that a TypeError exception is raised when trying to register a key with an invalid key object. """ args = ['invalid'] with ProxyKmipClient() as client: self.assertRaises(TypeError, client.register, *args)
def _connection(self, data=None): data = data or {} mapping = {'hostname': 'server', 'port': 'port', 'cert': 'cert', 'key': 'cert_key', 'ca': 'ca'} try: with ProxyKmipClient(**{k: data[v] for k, v in mapping.items() if data.get(v)}) as conn: yield conn except (ClientConnectionFailure, ClientConnectionNotOpen, socket.timeout) as e: raise CallError(f'Failed to connect to KMIP Server: {e}')
def test_create_key_pair_on_invalid_length(self): """ Test that a TypeError exception is raised when trying to create an asymmetric key pair with an invalid length. """ args = [enums.CryptographicAlgorithm.AES, 'invalid'] with ProxyKmipClient() as client: self.assertRaises(TypeError, client.create_key_pair, *args)
def test_create_key_pair_on_invalid_algorithm(self): """ Test that a TypeError exception is raised when trying to create an asymmetric key pair with an invalid algorithm. """ args = ['invalid', 256] with ProxyKmipClient() as client: self.assertRaises(TypeError, client.create_key_pair, *args)
def test_get_attribute_list_on_invalid_uid(self): """ Test that a TypeError exception is raised when trying to retrieve the attribute names of a managed object with an invalid ID. """ args = [0] with ProxyKmipClient() as client: self.assertRaises(TypeError, client.get_attribute_list, *args)
def test_get_attributes_on_invalid_uid(self): """ Test that a TypeError exception is raised when trying to retrieve a secret's attributes with an invalid ID. """ args = [0] with ProxyKmipClient() as client: self.assertRaisesRegexp(TypeError, "uid must be a string", client.get_attributes, *args)
def test_create_key_pair_with_key_names(self): """ Test that an asymmetric key pair can be created with proper inputs, specifically testing that the private / public names are correctly sent with the request """ # Create the template to test the create key pair call algorithm = enums.CryptographicAlgorithm.RSA length = 2048 algorithm_attribute = self.attribute_factory.create_attribute( enums.AttributeType.CRYPTOGRAPHIC_ALGORITHM, algorithm) length_attribute = self.attribute_factory.create_attribute( enums.AttributeType.CRYPTOGRAPHIC_LENGTH, length) mask_attribute = self.attribute_factory.create_attribute( enums.AttributeType.CRYPTOGRAPHIC_USAGE_MASK, [ enums.CryptographicUsageMask.ENCRYPT, enums.CryptographicUsageMask.DECRYPT ]) private_name_attribute = self.attribute_factory.create_attribute( enums.AttributeType.NAME, "private") public_name_attribute = self.attribute_factory.create_attribute( enums.AttributeType.NAME, "public") pair_attributes = [ algorithm_attribute, length_attribute, mask_attribute ] template = obj.CommonTemplateAttribute(attributes=pair_attributes) private_template = obj.PrivateKeyTemplateAttribute( names=[private_name_attribute]) public_template = obj.PublicKeyTemplateAttribute( names=[public_name_attribute]) status = enums.ResultStatus.SUCCESS result = results.CreateKeyPairResult( contents.ResultStatus(status), public_key_uuid=attr.PublicKeyUniqueIdentifier( 'aaaaaaaa-1111-2222-3333-ffffffffffff'), private_key_uuid=attr.PrivateKeyUniqueIdentifier( 'ffffffff-3333-2222-1111-aaaaaaaaaaaa')) with ProxyKmipClient() as client: client.proxy.create_key_pair.return_value = result public_uid, private_uid = client.create_key_pair( enums.CryptographicAlgorithm.RSA, 2048, public_name="public", private_name="private") kwargs = { 'common_template_attribute': template, 'private_key_template_attribute': private_template, 'public_key_template_attribute': public_template } client.proxy.create_key_pair.assert_called_with(**kwargs)
def test_close_on_proxy_failure(self): """ Test that an Exception is raised when an error occurs while closing the client proxy connection. """ client = ProxyKmipClient() client._is_open = True client.proxy.close.side_effect = Exception self.assertRaises(Exception, client.close)
def test_context_manager(self): """ Test that the KmipClient can be used by the with-statement as a context manager. """ with ProxyKmipClient() as client: self.assertTrue(client._is_open) client.proxy.open.assert_called_with() self.assertFalse(client._is_open) client.proxy.close.assert_called_with()
def test_get_attributes_on_invalid_attribute_name(self): """ Test that a TypeError exception is raised when trying to retrieve a secret's attributes with an invalid attribute name. """ args = [None, [0]] with ProxyKmipClient() as client: self.assertRaisesRegexp( TypeError, "attribute_names must be a list of strings", client.get_attributes, *args)
def test_get_attribute_list_on_closed(self): """ Test that a ClientConnectionNotOpen exception is raised when trying to retrieve the attribute names of a managed object on an unopened client connection. """ client = ProxyKmipClient() args = ['aaaaaaaa-1111-2222-3333-ffffffffffff'] self.assertRaises(ClientConnectionNotOpen, client.get_attribute_list, *args)
def test_exit(self): """ Test the result and effect of the exit method for the context manager. """ client = ProxyKmipClient() client.__enter__() self.assertTrue(client._is_open) client.__exit__(None, None, None) self.assertFalse(client._is_open)
def test_enter(self): """ Test the result and effect of the enter method for the context manager. """ client = ProxyKmipClient() self.assertFalse(client._is_open) result = client.__enter__() self.assertEqual(result, client) self.assertTrue(client._is_open)
def test_get_attributes_on_closed(self): """ Test that a ClientConnectionNotOpen exception is raised when trying to retrieve a secret's attributes on an unopened client connection. """ client = ProxyKmipClient() args = [ 'aaaaaaaa-1111-2222-3333-ffffffffffff', ['Name', 'Object Type'] ] self.assertRaises(ClientConnectionNotOpen, client.get_attributes, *args)