def create_client(self, args):
        created_client = None
        endpoint_filter_kwargs = self._get_endpoint_filter_kwargs(args)

        api_version = args.os_identity_api_version
        if args.no_auth and args.os_auth_url:
            raise Exception(
                'ERROR: argument --os-auth-url/-A: not allowed '
                'with argument --no-auth/-N'
            )

        if args.no_auth:
            if not all([args.endpoint, args.os_tenant_id or
                        args.os_project_id]):
                raise Exception(
                    'ERROR: please specify --endpoint and '
                    '--os-project-id (or --os-tenant-id)')
            created_client = client.Client(
                endpoint=args.endpoint,
                project_id=args.os_tenant_id or args.os_project_id,
                verify=not args.insecure,
                **endpoint_filter_kwargs
            )
        # Token-based authentication
        elif args.os_auth_token:
            if not args.os_auth_url:
                raise Exception('ERROR: please specify --os-auth-url')
            token_kwargs = {
                'auth_url': args.os_auth_url,
                'token': args.os_auth_token
            }
            session = self.create_keystone_session(
                args, api_version, token_kwargs, auth_type='token'
            )
            created_client = client.Client(
                session=session,
                endpoint=args.endpoint,
                **endpoint_filter_kwargs
            )

        # Password-based authentication
        elif args.os_auth_url:
            password_kwargs = {
                'auth_url': args.os_auth_url,
                'password': args.os_password,
                'user_id': args.os_user_id,
                'username': args.os_username
            }
            session = self.create_keystone_session(
                args, api_version, password_kwargs, auth_type='password'
            )
            created_client = client.Client(
                session=session,
                endpoint=args.endpoint,
                **endpoint_filter_kwargs
            )
        else:
            raise Exception('ERROR: please specify authentication credentials')

        return created_client
Exemple #2
0
    def _create_connection(self, ctxt):
        """Creates a connection to the Barbican service.

        :param ctxt: the user context for authentication
        :return: a Barbican Connection object
        :throws NotAuthorized: if the ctxt is None
        """

        # Confirm context is provided, if not raise not authorized
        if not ctxt:
            msg = _("User is not authorized to use key manager.")
            LOG.error(msg)
            raise exception.NotAuthorized(msg)

        try:
            endpoint = CONF.keymgr.encryption_auth_url
            keystone = keystone_client.Client(token=ctxt.auth_token,
                                              endpoint=endpoint)
            keystone_auth = auth.KeystoneAuthV2(keystone=keystone)
            keystone_auth._barbican_url = CONF.keymgr.encryption_api_url
            connection = barbican_client.Client(auth_plugin=keystone_auth)
            return connection
        except Exception as e:
            with excutils.save_and_reraise_exception():
                LOG.error(_("Error creating Barbican client: %s"), (e))
 def _create(self):
     interface = self._get_client_option(CLIENT_NAME, 'endpoint_type')
     client = barbican_client.Client(session=self.context.keystone_session,
                                     service_type=self.KEY_MANAGER,
                                     interface=interface,
                                     region_name=self._get_region_name())
     return client
Exemple #4
0
    def test_client_can_access_server_if_no_session_specified(self):
        barbicanclient = client.Client(
            endpoint=CONF.keymanager.url,
            project_id=CONF.keymanager.project_id,
            auth=self.auth)

        self.assert_client_can_contact_barbican(barbicanclient)
Exemple #5
0
    def _create(self):

        keystone_client = self.clients.client('keystone').client
        auth_plugin = auth.KeystoneAuthV2(keystone=keystone_client)
        client = barbican_client.Client(auth_plugin=auth_plugin)

        return client
Exemple #6
0
    def _get_barbican_client(self, ctxt):
        """Creates a client to connect to the Barbican service.

        :param ctxt: the user context for authentication
        :return: a Barbican Client object
        :raises Forbidden: if the ctxt is None
        """

        # Confirm context is provided, if not raise forbidden
        if not ctxt:
            msg = _("User is not authorized to use key manager.")
            LOG.error(msg)
            raise exception.Forbidden(msg)

        if not hasattr(ctxt, 'project_id') or ctxt.project_id is None:
            msg = _("Unable to create Barbican Client without project_id.")
            LOG.error(msg)
            raise exception.KeyManagerError(msg)

        # If same context, return cached barbican client
        if self._barbican_client and self._current_context == ctxt:
            return self._barbican_client

        try:
            _SESSION = ks_loading.load_session_from_conf_options(
                CONF,
                BARBICAN_OPT_GROUP)

            auth = ctxt.get_auth_plugin()
            service_type, service_name, interface = (CONF.
                                                     barbican.
                                                     catalog_info.
                                                     split(':'))
            region_name = CONF.barbican.os_region_name
            service_parameters = {'service_type': service_type,
                                  'service_name': service_name,
                                  'interface': interface,
                                  'region_name': region_name}

            if CONF.barbican.endpoint_template:
                self._base_url = (CONF.barbican.endpoint_template %
                                  ctxt.to_dict())
            else:
                self._base_url = _SESSION.get_endpoint(
                    auth, **service_parameters)

            # the barbican endpoint can't have the '/v1' on the end
            self._barbican_endpoint = self._base_url.rpartition('/')[0]

            sess = session.Session(auth=auth)
            self._barbican_client = barbican_client.Client(
                session=sess,
                endpoint=self._barbican_endpoint)
            self._current_context = ctxt

        except Exception as e:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE("Error creating Barbican client: %s"), e)

        return self._barbican_client
Exemple #7
0
    def _get_barbican_client(self, ctxt):
        """Creates a client to connect to the Barbican service.

        :param ctxt: the user context for authentication
        :return: a Barbican Client object
        :throws NotAuthorized: if the ctxt is None
        """

        if not self._barbican_client:
            # Confirm context is provided, if not raise not authorized
            if not ctxt:
                msg = _("User is not authorized to use key manager.")
                LOG.error(msg)
                raise exception.NotAuthorized(msg)

            try:
                auth = identity.v3.Token(
                    auth_url=CONF.keymgr.encryption_auth_url,
                    token=ctxt.auth_token)
                sess = session.Session(auth=auth)
                self._barbican_client = barbican_client.Client(
                    session=sess, endpoint=self._barbican_endpoint)
            except Exception as e:
                with excutils.save_and_reraise_exception():
                    LOG.error(_("Error creating Barbican client: %s"), (e))

        return self._barbican_client
Exemple #8
0
    def _migrate_keys(self, volumes):
        LOG.info("Starting migration of ConfKeyManager keys.")

        # Establish a Barbican client session that will be used for the entire
        # key migration process. Use cinder's own service credentials.
        try:
            ks_loading.register_auth_conf_options(self.conf,
                                                  'keystone_authtoken')
            auth = ks_loading.load_auth_from_conf_options(
                self.conf, 'keystone_authtoken')
            sess = ks_session.Session(auth=auth)
            self.barbican = barbican_client.Client(session=sess)
        except Exception as e:
            LOG.error(
                "Aborting encryption key migration due to "
                "error creating Barbican client: %s", e)
            return

        errors = 0
        for volume in volumes:
            try:
                self._migrate_volume_key(volume)
            except Exception as e:
                LOG.error("Error migrating encryption key: %s", e)
                # NOTE(abishop): There really shouldn't be any soft errors, so
                # if an error occurs migrating one key then chances are they
                # will all fail. This avoids filling the log with the same
                # error in situations where there are many keys to migrate.
                errors += 1
                if errors > MAX_KEY_MIGRATION_ERRORS:
                    LOG.error("Aborting encryption key migration "
                              "(too many errors).")
                    break
Exemple #9
0
def create_container(name, cert_payload, key_payload, conf):

    auth = identity.v3.Password(auth_url=conf.os_auth_url,
                                username=conf.os_username,
                                user_domain_name=conf.os_user_domain_name,
                                password=conf.os_password,
                                project_name=conf.os_project_name,
                                project_domain_name=conf.os_project_domain_name)

    # create a Keystone session using the auth plugin we just created
    sess = session.Session(auth=auth)

    # use the session to create a Barbican client
    barbican = client.Client(session=sess)

    # create container
    secret_cert = barbican.secrets.create(name + '.crt', payload=cert_payload)
    secret_key = barbican.secrets.create(name + '.key', payload=key_payload)
    container = barbican.containers.create_certificate(certificate=secret_cert,
                                                       private_key=secret_key)

    # save container in Barbican server
    ref = container.store()

    # test that have valid container reference
    assert ref.startswith("http")

    return ref
Exemple #10
0
def main():
    module = AnsibleModule(
        argument_spec = dict(
            key=dict(required=True, type='str'),
        ),
        supports_check_mode=False
    )

    # Keystone V3 password authentication
    auth = identity.V3Password(auth_url=os.getenv('OS_AUTH_URL'),
			       username=os.getenv('OS_USERNAME'),
			       user_domain_name=os.getenv('OS_USER_DOMAIN_NAME', 'Default'),
			       password=os.getenv('OS_PASSWORD'),
			       project_name=os.getenv('OS_PROJECT_NAME'),
			       project_domain_name=os.getenv('OS_PROJECT_DOMAIN_NAME','Default'))
    sess = session.Session(auth=auth)
    barbican = client.Client(session=sess)
    if not barbican:
        module.fail_json(msg="Unable to initialise Barbican client")

    secret_key = module.params['key']
    secret_list = barbican.secrets.list(name=secret_key)
    if secret_list:
        retrieved_secret = secret_list[0].payload
        module.exit_json(changed=True, secret=retrieved_secret)
    def _get_barbican_client(self, ctxt):
        """Creates a client to connect to the Barbican service.

        :param ctxt: the user context for authentication
        :return: a Barbican Client object
        :throws NotAuthorized: if the ctxt is None
        :throws KeyManagerError: if ctxt is missing project_id
                                 or project_id is None
        """

        if not self._barbican_client:
            # Confirm context is provided, if not raise not authorized
            if not ctxt:
                msg = _("User is not authorized to use key manager.")
                LOG.error(msg)
                raise exception.NotAuthorized(msg)

            if not hasattr(ctxt, 'project_id') or ctxt.project_id is None:
                msg = _("Unable to create Barbican Client without project_id.")
                LOG.error(msg)
                raise exception.KeyManagerError(msg)

            try:
                auth = identity.v3.Token(
                    auth_url=CONF.keymgr.encryption_auth_url,
                    token=ctxt.auth_token,
                    project_id=ctxt.project_id)
                sess = session.Session(auth=auth)
                self._barbican_client = barbican_client.Client(
                    session=sess, endpoint=self._barbican_endpoint)
            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.exception(_LE("Error creating Barbican client."))

        return self._barbican_client
Exemple #12
0
def _get_barbican_secret_payload(ctxt, secret_ref):
    session = keystone.create_keystone_session(ctxt)
    barbican = barbican_client.Client(session=session)
    sec = utils.retry_on_error()(barbican.secrets.get)(secret_ref)
    # NOTE: accessing `payload` leads to another API call being made:
    payload = utils.retry_on_error()(getattr)(sec, "payload")
    return payload
    def test_client_cannot_access_server_if_nonexistent_version_specified(
            self):
        barbicanclient = client.Client(endpoint=CONF.keymanager.url,
                                       project_id=CONF.keymanager.project_id,
                                       auth=self.auth,
                                       version='nonexistent_version')

        self.assert_client_cannot_contact_barbican(barbicanclient)
Exemple #14
0
    def barbican(self):
        if self._barbican:
            return self._barbican

        keystone_client = self.keystone().client
        auth_plugin = auth.KeystoneAuthV2(keystone=keystone_client)
        self._barbican = barbican_client.Client(auth_plugin=auth_plugin)
        return self._barbican
Exemple #15
0
    def test_client_can_access_server_if_no_version_is_specified(self):
        barbicanclient = client.Client(
            project_id=CONF.keymanager.project_id,
            auth=self.auth,
            interface=client._DEFAULT_SERVICE_INTERFACE,
            service_type=client._DEFAULT_SERVICE_TYPE)

        self.assert_client_can_contact_barbican(barbicanclient)
    def test_client_cannot_access_server_if_nonexistent_version_specified(
            self):  # noqa
        barbicanclient_1 = client.Client(
            project_id=CONF.keymanager.project_id,
            auth=self.auth,
            interface=client._DEFAULT_SERVICE_INTERFACE,
            service_type=client._DEFAULT_SERVICE_TYPE,
            version='wrong-version')

        self.assertRaises(TypeError, barbicanclient_1.containers.list)

        barbicanclient_2 = client.Client(endpoint=CONF.keymanager.url,
                                         project_id=CONF.keymanager.project_id,
                                         auth=self.auth,
                                         version='nonexistent_version')

        self.assert_client_cannot_contact_barbican(barbicanclient_2)
Exemple #17
0
 def _barbican_admin_init(self):
     # Import auth_token to have keystone_authtoken settings setup.
     auth = loading.load_auth_from_conf_options(cfg.CONF,
                                                'keystone_authtoken')
     sess = loading.load_session_from_conf_options(cfg.CONF,
                                                   'keystone_authtoken',
                                                   auth=auth)
     return barbicanclient.Client(session=sess)
Exemple #18
0
    def _create(self):
        endpoint_type = self._get_client_option('barbican', 'endpoint_type')
        endpoint = self.url_for(service_type='key-manager',
                                endpoint_type=endpoint_type)
        self._keystone_session.auth = self.context.auth_plugin
        client = barbican_client.Client(
            session=self._keystone_session, endpoint=endpoint)

        return client
Exemple #19
0
    def _create(self):
        endpoint_type = self._get_client_option(CLIENT_NAME, 'endpoint_type')
        endpoint = self.url_for(service_type=self.KEY_MANAGER,
                                endpoint_type=endpoint_type)
        self._keystone_session.auth = self.context.auth_plugin
        client = barbican_client.Client(session=self._keystone_session,
                                        endpoint=endpoint)

        return client
 def _barbican_admin_init(self):
     # Import auth_token to have keystone_authtoken settings setup.
     importutils.import_module('keystonemiddleware.auth_token')
     auth = identity.v2.Password(
         auth_url=cfg.CONF.keystone_authtoken.auth_uri,
         username=cfg.CONF.keystone_authtoken.admin_user,
         password=cfg.CONF.keystone_authtoken.admin_password,
         tenant_name=cfg.CONF.keystone_authtoken.admin_tenant_name)
     sess = session.Session(auth=auth, verify=self.verify)
     return barbicanclient.Client(session=sess)
Exemple #21
0
    def create_client(self, version=None, service_type=None):
        """Return Barbican client."""
        from barbicanclient import client as barbican_client

        version = "v%s" % self.choose_version(version)

        client = barbican_client.Client(version=self.choose_version(version),
                                        session=self.keystone.get_session()[0])

        return client
    def test_client_cannot_access_server_if_endpoint_filter_wrong(self):
        barbicanclient = client.Client(
            project_id=CONF.keymanager.project_id,
            auth=self.auth,
            interface=client._DEFAULT_SERVICE_INTERFACE,
            service_type='wrong-service-type',
            version=client._DEFAULT_API_VERSION,
        )

        self.assert_client_cannot_get_endpoint(barbicanclient)

        barbicanclient = client.Client(
            project_id=CONF.keymanager.project_id,
            auth=self.auth,
            interface='wrong-interface',
            service_type=client._DEFAULT_SERVICE_TYPE,
            version=client._DEFAULT_API_VERSION,
        )

        self.assert_client_cannot_get_endpoint(barbicanclient)

        barbicanclient = client.Client(
            project_id=CONF.keymanager.project_id,
            auth=self.auth,
            interface=client._DEFAULT_SERVICE_INTERFACE,
            service_type=client._DEFAULT_SERVICE_TYPE,
            service_name='wrong-service-name',
            version=client._DEFAULT_API_VERSION,
        )

        self.assert_client_cannot_get_endpoint(barbicanclient)

        barbicanclient = client.Client(
            project_id=CONF.keymanager.project_id,
            auth=self.auth,
            interface=client._DEFAULT_SERVICE_INTERFACE,
            service_type=client._DEFAULT_SERVICE_TYPE,
            region_name='wrong-region-name',
            version=client._DEFAULT_API_VERSION,
        )

        self.assert_client_cannot_get_endpoint(barbicanclient)
Exemple #23
0
    def _create(self):
        keystone_client = self.clients.client('keystone').client
        endpoint_type = self._get_client_option('barbican', 'endpoint_type')
        endpoint = self.url_for(service_type='key-manager',
                                endpoint_type=endpoint_type)
        # Remove version if set
        endpoint = endpoint.rsplit("/", 1)[0]
        client = barbican_client.Client(session=keystone_client.session,
                                        endpoint=endpoint)

        return client
 def get_barbican_client(cls, project_id=None):
     if not cls._barbican_client:
         try:
             cls._barbican_client = barbican_client.Client(
                 session=keystone.get_session(),
                 region_name=CONF.service_auth.region,
                 interface=CONF.service_auth.endpoint_type)
         except Exception:
             with excutils.save_and_reraise_exception():
                 LOG.exception(_LE("Error creating Barbican client"))
     return cls._barbican_client
Exemple #25
0
 def get_barbican_client(cls, project_id=None):
     if not cls._barbican_client:
         try:
             ksession = keystone.KeystoneSession()
             cls._barbican_client = barbican_client.Client(
                 session=ksession.get_session(),
                 region_name=CONF.certificates.region_name,
                 interface=CONF.certificates.endpoint_type)
         except Exception:
             with excutils.save_and_reraise_exception():
                 LOG.exception("Error creating Barbican client")
     return cls._barbican_client
Exemple #26
0
    def get_barbican_client_user_auth(cls, context):
        # get a normal session
        ksession = keystone.KeystoneSession()
        service_auth = ksession.get_auth()

        # make our own auth and swap it in
        user_auth = token.Token(auth_url=service_auth.auth_url,
                                token=context.auth_token,
                                project_id=context.project_id)
        user_session = session.Session(auth=user_auth)

        # create a special barbican client with our user's session
        return barbican_client.Client(session=user_session)
Exemple #27
0
def barbicanclient(request):
    project_id = request.user.project_id
    if keystone.get_version() < 3:
        auth = auth_v2.Token(settings.OPENSTACK_KEYSTONE_URL,
                             request.user.token.id,
                             tenant_id=project_id)
    else:
        domain_id = request.session.get('domain_context')
        auth = auth_v3.Token(settings.OPENSTACK_KEYSTONE_URL,
                             request.user.token.id,
                             project_id=project_id,
                             project_domain_id=domain_id)
    return barbican_client.Client(session=session.Session(auth=auth))
def main():
    session = ksession.Session(auth=v3.Password(**CORIOLIS_CONNECTION_INFO))

    coriolis = coriolis_client.Client(session=session)
    barbican = barbican_client.Client(session=session)

    # fetch and validate options for Azure:
    azure_schema = get_schema_for_plugin('coriolis', 'azure', 'source')
    # NOTE: this parameter validation is also done in any API
    # call involving the Azure source options:
    jsonschema.validate(AZURE_SOURCE_OPTIONS, azure_schema)

    # fetch and validate options schema for OCI:
    oci_schema = get_schema_for_plugin('coriolis', 'oci', 'destination')
    # NOTE: this parameter validation is also done in any API
    # call involving the OCI destination options:
    jsonschema.validate(OCI_DESTINATION_OPTIONS, oci_schema)

    # list all available options on source or target:
    azure_options = coriolis.endpoint_source_options.list(
        AZURE_ENDPOINT_ID, environment=AZURE_SOURCE_OPTIONS)
    print("Avaialble Azure options are: ", json.dumps(azure_options, indent=4))
    oci_options = coriolis.endpoint_destination_options.list(
        OCI_ENDPOINT_ID, environment=OCI_DESTINATION_OPTIONS)
    print("Avaialble OCI options are: ", json.dumps(oci_options, indent=4))

    # check all mapped networks and storage exist:
    check_mapped_networks_exist(
        coriolis,
        OCI_ENDPOINT_ID,
        NETWORK_MAP,
        destination_environment=OCI_DESTINATION_OPTIONS)
    check_mapped_storage_exists(
        coriolis,
        OCI_ENDPOINT_ID,
        NETWORK_MAP,
        destination_environment=OCI_DESTINATION_OPTIONS)

    # get list of Linux VMs off of Azure:
    azure_linux_vms = get_linux_vms_for_endpoint(
        coriolis, AZURE_ENDPOINT_ID, source_options=AZURE_SOURCE_OPTIONS)
    print("Linux VMs currently on Azure: %s" % azure_linux_vms)

    # check network mapping:
    if azure_linux_vms:
        vm_name = azure_linux_vms[0].instance_name
        check_vm_network_mapping(coriolis,
                                 AZURE_ENDPOINT_ID,
                                 vm_name,
                                 NETWORK_MAP,
                                 source_options=AZURE_SOURCE_OPTIONS)
Exemple #29
0
    def barbican(self):
        if self._barbican:
            return self._barbican

        endpoint_type = self._get_client_option('barbican', 'endpoint_type')
        region_name = self._get_client_option('barbican', 'region_name')
        endpoint = self.url_for(service_type='key-manager',
                                endpoint_type=endpoint_type,
                                region_name=region_name)
        session = self.keystone().session
        self._barbican = barbicanclient.Client(session=session,
                                               endpoint=endpoint)

        return self._barbican
    def _setUp(self, entity, entity_id='abcd1234-eabc-5678-9abc-abcdef012345'):
        super(BaseEntityResource, self).setUp()
        self.responses = self.useFixture(fixture.Fixture())
        self.endpoint = 'http://localhost:9311'
        self.project_id = '1234567'

        self.entity = entity
        self.entity_id = entity_id
        self.entity_base = self.endpoint + "/v1/" + self.entity
        self.entity_href = self.entity_base + "/" + self.entity_id
        self.entity_payload_href = self.entity_href + "/payload"

        self.client = client.Client(endpoint=self.endpoint,
                                    project_id=self.project_id)