class TestKMIPClientIntegration(TestCase): STARTUP_TIME = 1.0 SHUTDOWN_TIME = 0.1 KMIP_PORT = 9090 CA_CERTS_PATH = os.path.normpath(os.path.join(os.path.dirname( os.path.abspath(__file__)), '../../demos/certs/server.crt')) def setUp(self): super(TestKMIPClientIntegration, self).setUp() self.attr_factory = AttributeFactory() self.cred_factory = CredentialFactory() self.secret_factory = SecretFactory() # Set up the KMIP server process path = os.path.join(os.path.dirname(__file__), os.path.pardir, 'utils', 'server.py') self.server = Popen(['python', '{0}'.format(path), '-p', '{0}'.format(self.KMIP_PORT)], stderr=sys.stdout) time.sleep(self.STARTUP_TIME) if self.server.poll() is not None: raise KMIPServerSuicideError(self.server.pid) # Set up and open the client proxy; shutdown the server if open fails try: self.client = KMIPProxy(port=self.KMIP_PORT, ca_certs=self.CA_CERTS_PATH) self.client.open() except Exception as e: self._shutdown_server() raise e def tearDown(self): super(TestKMIPClientIntegration, self).tearDown() # Close the client proxy and shutdown the server self.client.close() self._shutdown_server() def test_create(self): result = self._create_symmetric_key() self._check_result_status(result.result_status.enum, ResultStatus, ResultStatus.SUCCESS) self._check_object_type(result.object_type.enum, ObjectType, ObjectType.SYMMETRIC_KEY) self._check_uuid(result.uuid.value, str) # Check the template attribute type self._check_template_attribute(result.template_attribute, TemplateAttribute, 2, [[str, 'Cryptographic Length', int, 256], [str, 'Unique Identifier', str, None]]) def test_get(self): credential_type = CredentialType.USERNAME_AND_PASSWORD credential_value = {'Username': '******', 'Password': '******'} credential = self.cred_factory.create_credential(credential_type, credential_value) result = self._create_symmetric_key() uuid = result.uuid.value result = self.client.get(uuid=uuid, credential=credential) self._check_result_status(result.result_status.enum, ResultStatus, ResultStatus.SUCCESS) self._check_object_type(result.object_type.enum, ObjectType, ObjectType.SYMMETRIC_KEY) self._check_uuid(result.uuid.value, str) # Check the secret type secret = result.secret expected = SymmetricKey message = utils.build_er_error(result.__class__, 'type', expected, secret, 'secret') self.assertIsInstance(secret, expected, message) def test_destroy(self): credential_type = CredentialType.USERNAME_AND_PASSWORD credential_value = {'Username': '******', 'Password': '******'} credential = self.cred_factory.create_credential(credential_type, credential_value) result = self._create_symmetric_key() uuid = result.uuid.value # Verify the secret was created result = self.client.get(uuid=uuid, credential=credential) self._check_result_status(result.result_status.enum, ResultStatus, ResultStatus.SUCCESS) self._check_object_type(result.object_type.enum, ObjectType, ObjectType.SYMMETRIC_KEY) self._check_uuid(result.uuid.value, str) secret = result.secret expected = SymmetricKey message = utils.build_er_error(result.__class__, 'type', expected, secret, 'secret') self.assertIsInstance(secret, expected, message) # Destroy the SYMMETRIC_KEY object result = self.client.destroy(uuid, credential) self._check_result_status(result.result_status.enum, ResultStatus, ResultStatus.SUCCESS) self._check_uuid(result.uuid.value, str) # Verify the secret was destroyed result = self.client.get(uuid=uuid, credential=credential) self._check_result_status(result.result_status.enum, ResultStatus, ResultStatus.OPERATION_FAILED) expected = ResultReason observed = type(result.result_reason.enum) message = utils.build_er_error(result.result_reason.__class__, 'type', expected, observed) self.assertEqual(expected, observed, message) expected = ResultReason.ITEM_NOT_FOUND observed = result.result_reason.enum message = utils.build_er_error(result.result_reason.__class__, 'value', expected, observed) self.assertEqual(expected, observed, message) def test_register(self): credential_type = CredentialType.USERNAME_AND_PASSWORD credential_value = {'Username': '******', 'Password': '******'} credential = self.cred_factory.create_credential(credential_type, credential_value) object_type = ObjectType.SYMMETRIC_KEY algorithm_value = CryptoAlgorithmEnum.AES mask_flags = [CryptographicUsageMask.ENCRYPT, CryptographicUsageMask.DECRYPT] attribute_type = AttributeType.CRYPTOGRAPHIC_USAGE_MASK usage_mask = self.attr_factory.create_attribute(attribute_type, mask_flags) attributes = [usage_mask] template_attribute = TemplateAttribute(attributes=attributes) key_format_type = KeyFormatType(KeyFormatTypeEnum.RAW) key_data = ( b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00') key_material = KeyMaterial(key_data) key_value = KeyValue(key_material) cryptographic_algorithm = CryptographicAlgorithm(algorithm_value) cryptographic_length = CryptographicLength(128) key_block = KeyBlock( key_format_type=key_format_type, key_compression_type=None, key_value=key_value, cryptographic_algorithm=cryptographic_algorithm, cryptographic_length=cryptographic_length, key_wrapping_data=None) secret = SymmetricKey(key_block) result = self.client.register(object_type, template_attribute, secret, credential) self._check_result_status(result.result_status.enum, ResultStatus, ResultStatus.SUCCESS) self._check_uuid(result.uuid.value, str) # Check the template attribute type self._check_template_attribute(result.template_attribute, TemplateAttribute, 1, [[str, 'Unique Identifier', str, None]]) # Check that the returned key bytes match what was provided uuid = result.uuid.value result = self.client.get(uuid=uuid, credential=credential) self._check_result_status(result.result_status.enum, ResultStatus, ResultStatus.SUCCESS) self._check_object_type(result.object_type.enum, ObjectType, ObjectType.SYMMETRIC_KEY) self._check_uuid(result.uuid.value, str) # Check the secret type secret = result.secret expected = SymmetricKey message = utils.build_er_error(result.__class__, 'type', expected, secret, 'secret') self.assertIsInstance(secret, expected, message) key_block = result.secret.key_block key_value = key_block.key_value key_material = key_value.key_material expected = key_data observed = key_material.value message = utils.build_er_error(key_material.__class__, 'value', expected, observed, 'value') self.assertEqual(expected, observed, message) def _shutdown_server(self): if self.server.poll() is not None: return else: # Terminate the server process. If it resists, kill it. pid = self.server.pid self.server.terminate() time.sleep(self.SHUTDOWN_TIME) if self.server.poll() is None: raise KMIPServerZombieError(pid) def _create_symmetric_key(self): credential_type = CredentialType.USERNAME_AND_PASSWORD credential_value = {'Username': '******', 'Password': '******'} credential = self.cred_factory.create_credential(credential_type, credential_value) object_type = ObjectType.SYMMETRIC_KEY attribute_type = AttributeType.CRYPTOGRAPHIC_ALGORITHM algorithm = self.attr_factory.create_attribute( attribute_type, CryptoAlgorithmEnum.AES) mask_flags = [CryptographicUsageMask.ENCRYPT, CryptographicUsageMask.DECRYPT] attribute_type = AttributeType.CRYPTOGRAPHIC_USAGE_MASK usage_mask = self.attr_factory.create_attribute(attribute_type, mask_flags) attributes = [algorithm, usage_mask] template_attribute = TemplateAttribute(attributes=attributes) return self.client.create(object_type, template_attribute, credential) def _check_result_status(self, result_status, result_status_type, result_status_value): # Error check the result status type and value expected = result_status_type message = utils.build_er_error(result_status_type, 'type', expected, result_status) self.assertIsInstance(result_status, expected, message) expected = result_status_value message = utils.build_er_error(result_status_type, 'value', expected, result_status) self.assertEqual(expected, result_status, message) def _check_uuid(self, uuid, uuid_type): # Error check the UUID type and value not_expected = None message = utils.build_er_error(uuid_type, 'type', 'not {0}'.format(not_expected), uuid) self.assertNotEqual(not_expected, uuid, message) expected = uuid_type message = utils.build_er_error(uuid_type, 'type', expected, uuid) self.assertEqual(expected, type(uuid), message) def _check_object_type(self, object_type, object_type_type, object_type_value): # Error check the object type type and value expected = object_type_type message = utils.build_er_error(object_type_type, 'type', expected, object_type) self.assertIsInstance(object_type, expected, message) expected = object_type_value message = utils.build_er_error(object_type_type, 'value', expected, object_type) self.assertEqual(expected, object_type, message) def _check_template_attribute(self, template_attribute, template_attribute_type, num_attributes, attribute_features): # Error check the template attribute type expected = template_attribute_type message = utils.build_er_error(template_attribute.__class__, 'type', expected, template_attribute) self.assertIsInstance(template_attribute, expected, message) attributes = template_attribute.attributes expected = num_attributes observed = len(attributes) message = utils.build_er_error(TemplateAttribute.__class__, 'number', expected, observed, 'attributes') for i in range(num_attributes): features = attribute_features[i] self._check_attribute(attributes[i], features[0], features[1], features[2], features[3]) def _check_attribute(self, attribute, attribute_name_type, attribute_name_value, attribute_value_type, attribute_value_value): # Error check the attribute name and value type and value attribute_name = attribute.attribute_name attribute_value = attribute.attribute_value self._check_attribute_name(attribute_name, attribute_name_type, attribute_name_value) if attribute_name_value == 'Unique Identifier': self._check_uuid(attribute_value.value, attribute_value_type) else: self._check_attribute_value(attribute_value, attribute_value_type, attribute_value_value) def _check_attribute_name(self, attribute_name, attribute_name_type, attribute_name_value): # Error check the attribute name type and value expected = attribute_name_type observed = type(attribute_name.value) message = utils.build_er_error(attribute_name_type, 'type', expected, observed) self.assertEqual(expected, observed, message) expected = attribute_name_value observed = attribute_name.value message = utils.build_er_error(attribute_name_type, 'value', expected, observed) self.assertEqual(expected, observed, message) def _check_attribute_value(self, attribute_value, attribute_value_type, attribute_value_value): expected = attribute_value_type observed = type(attribute_value.value) message = utils.build_er_error(Attribute, 'type', expected, observed, 'attribute_value') self.assertEqual(expected, observed, message) expected = attribute_value_value observed = attribute_value.value message = utils.build_er_error(Attribute, 'value', expected, observed, 'attribute_value') self.assertEqual(expected, observed, message)
CryptographicAlgorithm.AES) mask_flags = [CryptographicUsageMask.ENCRYPT, CryptographicUsageMask.DECRYPT] attribute_type = AttributeType.CRYPTOGRAPHIC_USAGE_MASK usage_mask = attribute_factory.create_attribute(attribute_type, mask_flags) name = Attribute.AttributeName('Name') name_value = Name.NameValue('FOOBAR') name_type = Name.NameType(NameType.UNINTERPRETED_TEXT_STRING) value = Name(name_value=name_value, name_type=name_type) nameattr = Attribute(attribute_name=name, attribute_value=value) attributes = [algorithm, usage_mask, nameattr] template_attribute = TemplateAttribute(attributes=attributes) result = client.create(object_type, template_attribute, credential) attrs = [nameattr] result = client.locate(attributes=attrs, credential=credential) client.close() logger.debug('locate() result status: {}'. format(result.result_status.enum)) if result.result_status.enum == ResultStatus.SUCCESS: logger.debug('retrieved object type: {}'. format(result.object_type.enum)) logger.debug('Located UUIDs: {}'.format(','.join([u.value for u in result.uuids])))
class ProxyKmipClient(api.KmipClient): """ A simplified KMIP client for conducting KMIP operations. The ProxyKmipClient is a simpler KMIP client supporting various KMIP operations. It wraps the original KMIPProxy, reducing the boilerplate needed to deploy PyKMIP in client applications. The underlying proxy client is responsible for setting up the underlying socket connection and for writing/reading data to/from the socket. Like the KMIPProxy, the ProxyKmipClient is not thread-safe. """ def __init__(self, hostname=None, port=None, cert=None, key=None, ca=None, ssl_version=None, username=None, password=None, config='client'): """ Construct a ProxyKmipClient. Args: hostname (string): The host or IP address of a KMIP appliance. Optional, defaults to None. port (int): The port number used to establish a connection to a KMIP appliance. Usually 5696 for KMIP applications. Optional, defaults to None. cert (string): The path to the client's certificate. Optional, defaults to None. key (string): The path to the key for the client's certificate. Optional, defaults to None. ca (string): The path to the CA certificate used to verify the server's certificate. Optional, defaults to None. ssl_version (string): The name of the ssl version to use for the connection. Example: 'PROTOCOL_SSLv23'. Optional, defaults to None. username (string): The username of the KMIP appliance account to use for operations. Optional, defaults to None. password (string): The password of the KMIP appliance account to use for operations. Optional, defaults to None. config (string): The name of a section in the PyKMIP configuration file. Use to load a specific set of configuration settings from the configuration file, instead of specifying them manually. Optional, defaults to the default client section, 'client'. """ self.logger = logging.getLogger() self.attribute_factory = attributes.AttributeFactory() self.object_factory = factory.ObjectFactory() # TODO (peter-hamilton) Consider adding validation checks for inputs. self.proxy = KMIPProxy(host=hostname, port=port, certfile=cert, keyfile=key, ca_certs=ca, ssl_version=ssl_version, username=username, password=password, config=config) # TODO (peter-hamilton) Add a multiprocessing lock for synchronization. self._is_open = False def open(self): """ Open the client connection. Raises: ClientConnectionFailure: if the client connection is already open Exception: if an error occurs while trying to open the connection """ if self._is_open: raise exceptions.ClientConnectionFailure( "client connection already open") else: try: self.proxy.open() self._is_open = True except Exception as e: self.logger.exception("could not open client connection", e) raise e def close(self): """ Close the client connection. Raises: ClientConnectionNotOpen: if the client connection is not open Exception: if an error occurs while trying to close the connection """ if not self._is_open: raise exceptions.ClientConnectionNotOpen() else: try: self.proxy.close() self._is_open = False except Exception as e: self.logger.exception("could not close client connection", e) raise e def create(self, algorithm, length, operation_policy_name=None, name=None): """ Create a symmetric key on a KMIP appliance. Args: algorithm (CryptographicAlgorithm): An enumeration defining the algorithm to use to generate the symmetric key. length (int): The length in bits for the symmetric key. operation_policy_name (string): The name of the operation policy to use for the new symmetric key. Optional, defaults to None name (string): The name to give the key. Optional, defaults to None Returns: string: The uid of the newly created symmetric key. Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input arguments are invalid """ # Check inputs if not isinstance(algorithm, enums.CryptographicAlgorithm): raise TypeError( "algorithm must be a CryptographicAlgorithm enumeration") elif not isinstance(length, six.integer_types) or length <= 0: raise TypeError("length must be a positive integer") # Verify that operations can be given at this time if not self._is_open: raise exceptions.ClientConnectionNotOpen() # Create the template containing the attributes common_attributes = self._build_common_attributes( operation_policy_name) key_attributes = self._build_key_attributes(algorithm, length) key_attributes.extend(common_attributes) if name: key_attributes.extend(self._build_name_attribute(name)) template = cobjects.TemplateAttribute(attributes=key_attributes) # Create the symmetric key and handle the results result = self.proxy.create(enums.ObjectType.SYMMETRIC_KEY, template) status = result.result_status.value if status == enums.ResultStatus.SUCCESS: uid = result.uuid.value return uid else: reason = result.result_reason.value message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message) def create_key_pair(self, algorithm, length, operation_policy_name=None, public_name=None, private_name=None): """ Create an asymmetric key pair on a KMIP appliance. Args: algorithm (CryptographicAlgorithm): An enumeration defining the algorithm to use to generate the key pair. length (int): The length in bits for the key pair. operation_policy_name (string): The name of the operation policy to use for the new key pair. Optional, defaults to None. public_name (string): The name to give the public key. Optional, defaults to None. private_name (string): The name to give the public key. Optional, defaults to None. Returns: string: The uid of the newly created public key. string: The uid of the newly created private key. Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input arguments are invalid """ # Check inputs if not isinstance(algorithm, enums.CryptographicAlgorithm): raise TypeError( "algorithm must be a CryptographicAlgorithm enumeration") elif not isinstance(length, six.integer_types) or length <= 0: raise TypeError("length must be a positive integer") # Verify that operations can be given at this time if not self._is_open: raise exceptions.ClientConnectionNotOpen() # Create the common attributes that are shared common_attributes = self._build_common_attributes( operation_policy_name) key_attributes = self._build_key_attributes(algorithm, length) key_attributes.extend(common_attributes) template = cobjects.CommonTemplateAttribute(attributes=key_attributes) # Create public / private specific attributes public_template = None if public_name: name_attr = self._build_name_attribute(name=public_name) public_template = cobjects.PublicKeyTemplateAttribute( names=name_attr) private_template = None if private_name: name_attr = self._build_name_attribute(name=private_name) private_template = cobjects.PrivateKeyTemplateAttribute( names=name_attr) # Create the asymmetric key pair and handle the results result = self.proxy.create_key_pair( common_template_attribute=template, private_key_template_attribute=private_template, public_key_template_attribute=public_template) status = result.result_status.value if status == enums.ResultStatus.SUCCESS: public_uid = result.public_key_uuid.value private_uid = result.private_key_uuid.value return public_uid, private_uid else: reason = result.result_reason.value message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message) def register(self, managed_object): """ Register a managed object with a KMIP appliance. Args: managed_object (ManagedObject): A managed object to register. An instantiatable subclass of ManagedObject from the Pie API. Returns: string: The uid of the newly registered managed object. Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input argument is invalid """ # Check input if not isinstance(managed_object, pobjects.ManagedObject): raise TypeError("managed object must be a Pie ManagedObject") # Verify that operations can be given at this time if not self._is_open: raise exceptions.ClientConnectionNotOpen() # Extract and create attributes object_attributes = list() if hasattr(managed_object, 'cryptographic_usage_masks'): if managed_object.cryptographic_usage_masks is not None: mask_attribute = self.attribute_factory.create_attribute( enums.AttributeType.CRYPTOGRAPHIC_USAGE_MASK, managed_object.cryptographic_usage_masks) object_attributes.append(mask_attribute) if hasattr(managed_object, 'operation_policy_name'): if managed_object.operation_policy_name is not None: opn_attribute = self.attribute_factory.create_attribute( enums.AttributeType.OPERATION_POLICY_NAME, managed_object.operation_policy_name) object_attributes.append(opn_attribute) template = cobjects.TemplateAttribute(attributes=object_attributes) object_type = managed_object.object_type # Register the managed object and handle the results secret = self.object_factory.convert(managed_object) result = self.proxy.register(object_type, template, secret) status = result.result_status.value if status == enums.ResultStatus.SUCCESS: uid = result.uuid.value return uid else: reason = result.result_reason.value message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message) def get(self, uid): """ Get a managed object from a KMIP appliance. Args: uid (string): The unique ID of the managed object to retrieve. Returns: ManagedObject: The retrieved managed object object. Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input argument is invalid """ # Check input if not isinstance(uid, six.string_types): raise TypeError("uid must be a string") # Verify that operations can be given at this time if not self._is_open: raise exceptions.ClientConnectionNotOpen() # Get the managed object and handle the results result = self.proxy.get(uid) status = result.result_status.value if status == enums.ResultStatus.SUCCESS: managed_object = self.object_factory.convert(result.secret) return managed_object else: reason = result.result_reason.value message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message) def get_attributes(self, uid=None, attribute_names=None): """ Get the attributes associated with a managed object. If the uid is not specified, the appliance will use the ID placeholder by default. If the attribute_names list is not specified, the appliance will return all viable attributes for the managed object. Args: uid (string): The unique ID of the managed object with which the retrieved attributes should be associated. Optional, defaults to None. attribute_names (list): A list of string attribute names indicating which attributes should be retrieved. Optional, defaults to None. """ # Check input if uid is not None: if not isinstance(uid, six.string_types): raise TypeError("uid must be a string") if attribute_names is not None: if not isinstance(attribute_names, list): raise TypeError("attribute_names must be a list of strings") else: for attribute_name in attribute_names: if not isinstance(attribute_name, six.string_types): raise TypeError( "attribute_names must be a list of strings") # Verify that operations can be given at this time if not self._is_open: raise exceptions.ClientConnectionNotOpen() # Get the list of attributes for a managed object result = self.proxy.get_attributes(uid, attribute_names) status = result.result_status.value if status == enums.ResultStatus.SUCCESS: return result.uuid, result.attributes else: reason = result.result_reason.value message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message) def get_attribute_list(self, uid=None): """ Get the names of the attributes associated with a managed object. If the uid is not specified, the appliance will use the ID placeholder by default. Args: uid (string): The unique ID of the managed object with which the retrieved attribute names should be associated. Optional, defaults to None. """ # Check input if uid is not None: if not isinstance(uid, six.string_types): raise TypeError("uid must be a string") # Verify that operations can be given at this time if not self._is_open: raise exceptions.ClientConnectionNotOpen() # Get the list of attribute names for a managed object. result = self.proxy.get_attribute_list(uid) status = result.result_status.value if status == enums.ResultStatus.SUCCESS: attribute_names = sorted(result.names) return attribute_names else: reason = result.result_reason.value message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message) def destroy(self, uid): """ Destroy a managed object stored by a KMIP appliance. Args: uid (string): The unique ID of the managed object to destroy. Returns: None Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input argument is invalid """ # Check input if not isinstance(uid, six.string_types): raise TypeError("uid must be a string") # Verify that operations can be given at this time if not self._is_open: raise exceptions.ClientConnectionNotOpen() # Destroy the managed object and handle the results result = self.proxy.destroy(uid) status = result.result_status.value if status == enums.ResultStatus.SUCCESS: return else: reason = result.result_reason.value message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message) def _build_key_attributes(self, algorithm, length): # Build a list of core key attributes. 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 ]) return [algorithm_attribute, length_attribute, mask_attribute] def _build_common_attributes(self, operation_policy_name=None): ''' Build a list of common attributes that are shared across symmetric as well as asymmetric objects ''' common_attributes = [] if operation_policy_name: common_attributes.append( self.attribute_factory.create_attribute( enums.AttributeType.OPERATION_POLICY_NAME, operation_policy_name)) return common_attributes def _build_name_attribute(self, name=None): ''' Build a name attribute, returned in a list for ease of use in the caller ''' name_list = [] if name: name_list.append( self.attribute_factory.create_attribute( enums.AttributeType.NAME, name)) return name_list def __enter__(self): self.open() return self def __exit__(self, exc_type, exc_value, traceback): self.close()
class ProxyKmipClient(api.KmipClient): """ A simplified KMIP client for conducting KMIP operations. The ProxyKmipClient is a simpler KMIP client supporting various KMIP operations. It wraps the original KMIPProxy, reducing the boilerplate needed to deploy PyKMIP in client applications. The underlying proxy client is responsible for setting up the underlying socket connection and for writing/reading data to/from the socket. Like the KMIPProxy, the ProxyKmipClient is not thread-safe. """ def __init__(self, hostname=None, port=None, cert=None, key=None, ca=None, ssl_version=None, username=None, password=None, config='client'): """ Construct a ProxyKmipClient. Args: hostname (string): The host or IP address of a KMIP appliance. Optional, defaults to None. port (int): The port number used to establish a connection to a KMIP appliance. Usually 5696 for KMIP applications. Optional, defaults to None. cert (string): The path to the client's certificate. Optional, defaults to None. key (string): The path to the key for the client's certificate. Optional, defaults to None. ca (string): The path to the CA certificate used to verify the server's certificate. Optional, defaults to None. ssl_version (string): The name of the ssl version to use for the connection. Example: 'PROTOCOL_SSLv23'. Optional, defaults to None. username (string): The username of the KMIP appliance account to use for operations. Optional, defaults to None. password (string): The password of the KMIP appliance account to use for operations. Optional, defaults to None. config (string): The name of a section in the PyKMIP configuration file. Use to load a specific set of configuration settings from the configuration file, instead of specifying them manually. Optional, defaults to the default client section, 'client'. """ self.logger = logging.getLogger() self.attribute_factory = attributes.AttributeFactory() self.object_factory = factory.ObjectFactory() # TODO (peter-hamilton) Consider adding validation checks for inputs. self.proxy = KMIPProxy( host=hostname, port=port, certfile=cert, keyfile=key, ca_certs=ca, ssl_version=ssl_version, username=username, password=password, config=config) # TODO (peter-hamilton) Add a multiprocessing lock for synchronization. self._is_open = False def open(self): """ Open the client connection. Raises: ClientConnectionFailure: if the client connection is already open Exception: if an error occurs while trying to open the connection """ if self._is_open: raise exceptions.ClientConnectionFailure( "client connection already open") else: try: self.proxy.open() self._is_open = True except Exception as e: self.logger.exception("could not open client connection", e) raise e def close(self): """ Close the client connection. Raises: ClientConnectionNotOpen: if the client connection is not open Exception: if an error occurs while trying to close the connection """ if not self._is_open: raise exceptions.ClientConnectionNotOpen() else: try: self.proxy.close() self._is_open = False except Exception as e: self.logger.exception("could not close client connection", e) raise e def create(self, algorithm, length): """ Create a symmetric key on a KMIP appliance. Args: algorithm (CryptographicAlgorithm): An enumeration defining the algorithm to use to generate the symmetric key. length (int): The length in bits for the symmetric key. Returns: string: The uid of the newly created symmetric key. Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input arguments are invalid """ # Check inputs if not isinstance(algorithm, enums.CryptographicAlgorithm): raise TypeError( "algorithm must be a CryptographicAlgorithm enumeration") elif not isinstance(length, six.integer_types) or length <= 0: raise TypeError("length must be a positive integer") # Verify that operations can be given at this time if not self._is_open: raise exceptions.ClientConnectionNotOpen() # Create the template containing the attributes attributes = self._build_key_attributes(algorithm, length) template = cobjects.TemplateAttribute(attributes=attributes) # Create the symmetric key and handle the results result = self.proxy.create(enums.ObjectType.SYMMETRIC_KEY, template) status = result.result_status.enum if status == enums.ResultStatus.SUCCESS: uid = result.uuid.value return uid else: reason = result.result_reason.enum message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message) def create_key_pair(self, algorithm, length): """ Create an asymmetric key pair on a KMIP appliance. Args: algorithm (CryptographicAlgorithm): An enumeration defining the algorithm to use to generate the key pair. length (int): The length in bits for the key pair. Returns: string: The uid of the newly created public key. string: The uid of the newly created private key. Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input arguments are invalid """ # Check inputs if not isinstance(algorithm, enums.CryptographicAlgorithm): raise TypeError( "algorithm must be a CryptographicAlgorithm enumeration") elif not isinstance(length, six.integer_types) or length <= 0: raise TypeError("length must be a positive integer") # Verify that operations can be given at this time if not self._is_open: raise exceptions.ClientConnectionNotOpen() # Create the template containing the attributes attributes = self._build_key_attributes(algorithm, length) template = cobjects.CommonTemplateAttribute(attributes=attributes) # Create the asymmetric key pair and handle the results result = self.proxy.create_key_pair(common_template_attribute=template) status = result.result_status.enum if status == enums.ResultStatus.SUCCESS: public_uid = result.public_key_uuid.value private_uid = result.private_key_uuid.value return public_uid, private_uid else: reason = result.result_reason.enum message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message) def register(self, managed_object): """ Register a managed object with a KMIP appliance. Args: managed_object (ManagedObject): A managed object to register. An instantiatable subclass of ManagedObject from the Pie API. Returns: string: The uid of the newly registered managed object. Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input argument is invalid """ # Check input if not isinstance(managed_object, pobjects.ManagedObject): raise TypeError("managed object must be a Pie ManagedObject") # Verify that operations can be given at this time if not self._is_open: raise exceptions.ClientConnectionNotOpen() # Extract and create attributes attributes = list() if hasattr(managed_object, 'cryptographic_usage_masks'): mask_attribute = self.attribute_factory.create_attribute( enums.AttributeType.CRYPTOGRAPHIC_USAGE_MASK, managed_object.cryptographic_usage_masks) attributes.append(mask_attribute) template = cobjects.TemplateAttribute(attributes=attributes) object_type = managed_object.object_type # Register the managed object and handle the results secret = self.object_factory.convert(managed_object) result = self.proxy.register(object_type, template, secret) status = result.result_status.enum if status == enums.ResultStatus.SUCCESS: uid = result.uuid.value return uid else: reason = result.result_reason.enum message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message) def get(self, uid): """ Get a managed object from a KMIP appliance. Args: uid (string): The unique ID of the managed object to retrieve. Returns: ManagedObject: The retrieved managed object object. Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input argument is invalid """ # Check input if not isinstance(uid, six.string_types): raise TypeError("uid must be a string") # Verify that operations can be given at this time if not self._is_open: raise exceptions.ClientConnectionNotOpen() # Get the managed object and handle the results result = self.proxy.get(uid) status = result.result_status.enum if status == enums.ResultStatus.SUCCESS: managed_object = self.object_factory.convert(result.secret) return managed_object else: reason = result.result_reason.enum message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message) def get_attribute_list(self, uid=None): """ Get the names of the attributes associated with a managed object. If the uid is not specified, the appliance will use the ID placeholder by default. Args: uid (string): The unique ID of the managed object with which the retrieved attribute names should be associated. Optional, defaults to None. """ # Check input if uid is not None: if not isinstance(uid, six.string_types): raise TypeError("uid must be a string") # Verify that operations can be given at this time if not self._is_open: raise exceptions.ClientConnectionNotOpen() # Get the list of attribute names for a managed object. result = self.proxy.get_attribute_list(uid) status = result.result_status.enum if status == enums.ResultStatus.SUCCESS: attribute_names = sorted(result.names) return attribute_names else: reason = result.result_reason.enum message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message) def destroy(self, uid): """ Destroy a managed object stored by a KMIP appliance. Args: uid (string): The unique ID of the managed object to destroy. Returns: None Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input argument is invalid """ # Check input if not isinstance(uid, six.string_types): raise TypeError("uid must be a string") # Verify that operations can be given at this time if not self._is_open: raise exceptions.ClientConnectionNotOpen() # Destroy the managed object and handle the results result = self.proxy.destroy(uid) status = result.result_status.enum if status == enums.ResultStatus.SUCCESS: return else: reason = result.result_reason.enum message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message) def _build_key_attributes(self, algorithm, length): # Build a list of core key attributes. 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]) return [algorithm_attribute, length_attribute, mask_attribute] def __enter__(self): self.open() return self def __exit__(self, exc_type, exc_value, traceback): self.close()
name_type = Name.NameType(NameType.UNINTERPRETED_TEXT_STRING) value = Name(name_value=name_value, name_type=name_type) name = Attribute(attribute_name=name, attribute_value=value) attributes = [algorithm_obj, usage_mask, length_obj, name] if opts.operation_policy_name is not None: opn = attribute_factory.create_attribute( enums.AttributeType.OPERATION_POLICY_NAME, opts.operation_policy_name) attributes.append(opn) template_attribute = TemplateAttribute(attributes=attributes) # Create the SYMMETRIC_KEY object result = client.create(object_type, template_attribute, credential) client.close() # Display operation results logger.info('create() result status: {0}'.format( result.result_status.value)) if result.result_status.value == ResultStatus.SUCCESS: logger.info('created object type: {0}'.format( result.object_type.value)) logger.info('created UUID: {0}'.format(result.uuid.value)) logger.info('created template attribute: {0}'.format( result.template_attribute)) else: logger.info('create() result reason: {0}'.format( result.result_reason.value))
class TestKMIPClientIntegration(TestCase): STARTUP_TIME = 1.0 SHUTDOWN_TIME = 0.1 KMIP_PORT = 9090 CA_CERTS_PATH = os.path.normpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), '../utils/certs/server.crt')) def setUp(self): super(TestKMIPClientIntegration, self).setUp() self.attr_factory = AttributeFactory() self.cred_factory = CredentialFactory() self.secret_factory = SecretFactory() # Set up the KMIP server process path = os.path.join(os.path.dirname(__file__), os.path.pardir, 'utils', 'server.py') self.server = Popen( ['python', '{0}'.format(path), '-p', '{0}'.format(self.KMIP_PORT)], stderr=sys.stdout) time.sleep(self.STARTUP_TIME) if self.server.poll() is not None: raise KMIPServerSuicideError(self.server.pid) # Set up and open the client proxy; shutdown the server if open fails try: self.client = KMIPProxy(port=self.KMIP_PORT, ca_certs=self.CA_CERTS_PATH) self.client.open() except Exception as e: self._shutdown_server() raise e def tearDown(self): super(TestKMIPClientIntegration, self).tearDown() # Close the client proxy and shutdown the server self.client.close() self._shutdown_server() def test_create(self): result = self._create_symmetric_key() self._check_result_status(result.result_status.value, ResultStatus, ResultStatus.SUCCESS) self._check_object_type(result.object_type.value, ObjectType, ObjectType.SYMMETRIC_KEY) self._check_uuid(result.uuid.value, str) # Check the template attribute type self._check_template_attribute( result.template_attribute, TemplateAttribute, 2, [[str, 'Cryptographic Length', int, 256], [str, 'Unique Identifier', str, None]]) def test_get(self): credential_type = CredentialType.USERNAME_AND_PASSWORD credential_value = {'Username': '******', 'Password': '******'} credential = self.cred_factory.create_credential( credential_type, credential_value) result = self._create_symmetric_key() uuid = result.uuid.value result = self.client.get(uuid=uuid, credential=credential) self._check_result_status(result.result_status.value, ResultStatus, ResultStatus.SUCCESS) self._check_object_type(result.object_type.value, ObjectType, ObjectType.SYMMETRIC_KEY) self._check_uuid(result.uuid.value, str) # Check the secret type secret = result.secret expected = SymmetricKey message = utils.build_er_error(result.__class__, 'type', expected, secret, 'secret') self.assertIsInstance(secret, expected, message) def test_destroy(self): credential_type = CredentialType.USERNAME_AND_PASSWORD credential_value = {'Username': '******', 'Password': '******'} credential = self.cred_factory.create_credential( credential_type, credential_value) result = self._create_symmetric_key() uuid = result.uuid.value # Verify the secret was created result = self.client.get(uuid=uuid, credential=credential) self._check_result_status(result.result_status.value, ResultStatus, ResultStatus.SUCCESS) self._check_object_type(result.object_type.value, ObjectType, ObjectType.SYMMETRIC_KEY) self._check_uuid(result.uuid.value, str) secret = result.secret expected = SymmetricKey message = utils.build_er_error(result.__class__, 'type', expected, secret, 'secret') self.assertIsInstance(secret, expected, message) # Destroy the SYMMETRIC_KEY object result = self.client.destroy(uuid, credential) self._check_result_status(result.result_status.value, ResultStatus, ResultStatus.SUCCESS) self._check_uuid(result.uuid.value, str) # Verify the secret was destroyed result = self.client.get(uuid=uuid, credential=credential) self._check_result_status(result.result_status.value, ResultStatus, ResultStatus.OPERATION_FAILED) expected = ResultReason observed = type(result.result_reason.value) message = utils.build_er_error(result.result_reason.__class__, 'type', expected, observed) self.assertEqual(expected, observed, message) expected = ResultReason.ITEM_NOT_FOUND observed = result.result_reason.value message = utils.build_er_error(result.result_reason.__class__, 'value', expected, observed) self.assertEqual(expected, observed, message) def test_register(self): credential_type = CredentialType.USERNAME_AND_PASSWORD credential_value = {'Username': '******', 'Password': '******'} credential = self.cred_factory.create_credential( credential_type, credential_value) object_type = ObjectType.SYMMETRIC_KEY algorithm_value = CryptoAlgorithmEnum.AES mask_flags = [ CryptographicUsageMask.ENCRYPT, CryptographicUsageMask.DECRYPT ] attribute_type = AttributeType.CRYPTOGRAPHIC_USAGE_MASK usage_mask = self.attr_factory.create_attribute( attribute_type, mask_flags) attributes = [usage_mask] template_attribute = TemplateAttribute(attributes=attributes) key_format_type = KeyFormatType(KeyFormatTypeEnum.RAW) key_data = ( b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00') key_material = KeyMaterial(key_data) key_value = KeyValue(key_material) cryptographic_algorithm = CryptographicAlgorithm(algorithm_value) cryptographic_length = CryptographicLength(128) key_block = KeyBlock(key_format_type=key_format_type, key_compression_type=None, key_value=key_value, cryptographic_algorithm=cryptographic_algorithm, cryptographic_length=cryptographic_length, key_wrapping_data=None) secret = SymmetricKey(key_block) result = self.client.register(object_type, template_attribute, secret, credential) self._check_result_status(result.result_status.value, ResultStatus, ResultStatus.SUCCESS) self._check_uuid(result.uuid.value, str) # Check the template attribute type self._check_template_attribute(result.template_attribute, TemplateAttribute, 1, [[str, 'Unique Identifier', str, None]]) # Check that the returned key bytes match what was provided uuid = result.uuid.value result = self.client.get(uuid=uuid, credential=credential) self._check_result_status(result.result_status.value, ResultStatus, ResultStatus.SUCCESS) self._check_object_type(result.object_type.value, ObjectType, ObjectType.SYMMETRIC_KEY) self._check_uuid(result.uuid.value, str) # Check the secret type secret = result.secret expected = SymmetricKey message = utils.build_er_error(result.__class__, 'type', expected, secret, 'secret') self.assertIsInstance(secret, expected, message) key_block = result.secret.key_block key_value = key_block.key_value key_material = key_value.key_material expected = key_data observed = key_material.value message = utils.build_er_error(key_material.__class__, 'value', expected, observed, 'value') self.assertEqual(expected, observed, message) def _shutdown_server(self): if self.server.poll() is not None: return else: # Terminate the server process. If it resists, kill it. pid = self.server.pid self.server.terminate() time.sleep(self.SHUTDOWN_TIME) if self.server.poll() is None: raise KMIPServerZombieError(pid) def _create_symmetric_key(self): credential_type = CredentialType.USERNAME_AND_PASSWORD credential_value = {'Username': '******', 'Password': '******'} credential = self.cred_factory.create_credential( credential_type, credential_value) object_type = ObjectType.SYMMETRIC_KEY attribute_type = AttributeType.CRYPTOGRAPHIC_ALGORITHM algorithm = self.attr_factory.create_attribute(attribute_type, CryptoAlgorithmEnum.AES) mask_flags = [ CryptographicUsageMask.ENCRYPT, CryptographicUsageMask.DECRYPT ] attribute_type = AttributeType.CRYPTOGRAPHIC_USAGE_MASK usage_mask = self.attr_factory.create_attribute( attribute_type, mask_flags) attributes = [algorithm, usage_mask] template_attribute = TemplateAttribute(attributes=attributes) return self.client.create(object_type, template_attribute, credential) def _check_result_status(self, result_status, result_status_type, result_status_value): # Error check the result status type and value expected = result_status_type message = utils.build_er_error(result_status_type, 'type', expected, result_status) self.assertIsInstance(result_status, expected, message) expected = result_status_value message = utils.build_er_error(result_status_type, 'value', expected, result_status) self.assertEqual(expected, result_status, message) def _check_uuid(self, uuid, uuid_type): # Error check the UUID type and value not_expected = None message = utils.build_er_error(uuid_type, 'type', 'not {0}'.format(not_expected), uuid) self.assertNotEqual(not_expected, uuid, message) expected = uuid_type message = utils.build_er_error(uuid_type, 'type', expected, uuid) self.assertEqual(expected, type(uuid), message) def _check_object_type(self, object_type, object_type_type, object_type_value): # Error check the object type type and value expected = object_type_type message = utils.build_er_error(object_type_type, 'type', expected, object_type) self.assertIsInstance(object_type, expected, message) expected = object_type_value message = utils.build_er_error(object_type_type, 'value', expected, object_type) self.assertEqual(expected, object_type, message) def _check_template_attribute(self, template_attribute, template_attribute_type, num_attributes, attribute_features): # Error check the template attribute type expected = template_attribute_type message = utils.build_er_error(template_attribute.__class__, 'type', expected, template_attribute) self.assertIsInstance(template_attribute, expected, message) attributes = template_attribute.attributes expected = num_attributes observed = len(attributes) message = utils.build_er_error(TemplateAttribute.__class__, 'number', expected, observed, 'attributes') for i in range(num_attributes): features = attribute_features[i] self._check_attribute(attributes[i], features[0], features[1], features[2], features[3]) def _check_attribute(self, attribute, attribute_name_type, attribute_name_value, attribute_value_type, attribute_value_value): # Error check the attribute name and value type and value attribute_name = attribute.attribute_name attribute_value = attribute.attribute_value self._check_attribute_name(attribute_name, attribute_name_type, attribute_name_value) if attribute_name_value == 'Unique Identifier': self._check_uuid(attribute_value.value, attribute_value_type) else: self._check_attribute_value(attribute_value, attribute_value_type, attribute_value_value) def _check_attribute_name(self, attribute_name, attribute_name_type, attribute_name_value): # Error check the attribute name type and value expected = attribute_name_type observed = type(attribute_name.value) message = utils.build_er_error(attribute_name_type, 'type', expected, observed) self.assertEqual(expected, observed, message) expected = attribute_name_value observed = attribute_name.value message = utils.build_er_error(attribute_name_type, 'value', expected, observed) self.assertEqual(expected, observed, message) def _check_attribute_value(self, attribute_value, attribute_value_type, attribute_value_value): expected = attribute_value_type observed = type(attribute_value.value) message = utils.build_er_error(Attribute, 'type', expected, observed, 'attribute_value') self.assertEqual(expected, observed, message) expected = attribute_value_value observed = attribute_value.value message = utils.build_er_error(Attribute, 'value', expected, observed, 'attribute_value') self.assertEqual(expected, observed, message)