def remote_token_add_signing_key_new_member(ss_api_config, security_server,
                                                client):
        new_member_class = client[
            ConfKeysSecServerClients.CONF_KEY_SS_CLIENT_MEMBER_CLASS]
        new_member_code = client[
            ConfKeysSecServerClients.CONF_KEY_SS_CLIENT_MEMBER_CODE]
        new_member_name = client[
            ConfKeysSecServerClients.CONF_KEY_SS_CLIENT_MEMBER_NAME]

        token_id = security_server[
            ConfKeysSecurityServer.CONF_KEY_SOFT_TOKEN_ID]
        ss_code = security_server[ConfKeysSecurityServer.CONF_KEY_SERVER_CODE]
        dn_country = security_server[ConfKeysSecurityServer.CONF_KEY_DN_C]

        sign_key_label = default_member_sign_key_label(security_server, client)
        ssi = remote_get_security_server_instance(ss_api_config)
        token = remote_get_token(ss_api_config, security_server)
        sign_ca = remote_get_sign_certificate_authority(ss_api_config)

        token_key_labels = list(map(lambda key: key.label, token.keys))
        has_sign_key = sign_key_label in token_key_labels

        sign_cert_subject = {
            'C': dn_country,
            'O': new_member_name,
            'CN': new_member_code,
            'serialNumber':
            '/'.join([ssi.instance_id, ss_code, new_member_class])
        }

        sign_key_req_param = KeyLabelWithCsrGenerate(
            key_label=sign_key_label,
            csr_generate_request=CsrGenerate(
                key_usage_type=KeyUsageType.SIGNING,
                ca_name=sign_ca.name,
                csr_format=CsrFormat.
                DER,  # Test CA setup at least only works with DER
                member_id=':'.join(
                    [ssi.instance_id, new_member_class,
                     str(new_member_code)]),
                subject_field_values=sign_cert_subject))
        token_api = TokensApi(ApiClient(ss_api_config))
        if not has_sign_key:
            try:
                BaseController.log_info(
                    TokenLabels.generate_key(token_id, sign_key_label, 'SIGN'))
                response = token_api.add_key_and_csr(token_id,
                                                     body=sign_key_req_param)
                BaseController.log_info("Created " + str(response.key.usage) +
                                        " CSR '" + response.csr_id +
                                        "' for key '" + response.key.id +
                                        "' as '" + response.key.label + "'")
            except ApiException as err:
                BaseController.log_api_error(TokenLabels.error(), err)
        else:
            BaseController.log_info(
                "Skipping KEY and CSR creation, key for member " + '/'.join([
                    ssi.instance_id, ss_code, new_member_class,
                    str(new_member_code)
                ]) + "already exists")
    def remote_add_endpoint(ss_api_config, service_description,
                            service_description_conf, endpoint_conf):
        endpoint = Endpoint(
            id=None,
            service_code=service_description_conf["rest_service_code"],
            method=endpoint_conf["method"],
            path=endpoint_conf["path"],
            generated=None)

        try:
            services_api = ServicesApi(ApiClient(ss_api_config))
            response = services_api.add_endpoint(
                id=service_description.services[0].id, body=endpoint)
            if response:
                BaseController.log_info("Added service endpoint '" +
                                        endpoint.method + " " + endpoint.path +
                                        "'" + EndpointController.FOR_SERVICE +
                                        "'" +
                                        service_description.services[0].id +
                                        "'")
        except ApiException as err:
            if err.status == 409:
                BaseController.log_info("Service endpoint '" +
                                        endpoint.method + " " + endpoint.path +
                                        "'" + EndpointController.FOR_SERVICE +
                                        "'" +
                                        service_description.services[0].id +
                                        "' already added")
            else:
                BaseController.log_api_error('ServicesApi->add_endpoint', err)
Example #3
0
 def remote_add_service_description(ss_api_config, security_server_conf, client_conf, service_description_conf):
     code = service_description_conf['rest_service_code'] if service_description_conf['rest_service_code'] else None
     description_add = ServiceDescriptionAdd(url=service_description_conf['url'],
                                             rest_service_code=code,
                                             ignore_warnings=True,
                                             type=service_description_conf['type'])
     clients_api = ClientsApi(ApiClient(ss_api_config))
     try:
         client_controller = ClientController()
         client = client_controller.find_client(clients_api, security_server_conf, client_conf)
         if client:
             try:
                 response = clients_api.add_client_service_description(client.id, body=description_add)
                 if response:
                     BaseController.log_info("Added service description with type '" + response.type + "' and url '" + response.url +
                                             "' (got full id " + response.id + ")")
             except ApiException as err:
                 if err.status == 409:
                     BaseController.log_info(ServiceController.SERVICE_DESCRIPTION_FOR + "'" + client_controller.partial_client_id(client_conf) +
                                             "' with url '" + description_add.url +
                                             "' and type '" + description_add.type + "' already exists.")
                 else:
                     BaseController.log_api_error('ClientsApi->add_client_service_description', err)
     except ApiException as find_err:
         BaseController.log_api_error(ClientController.CLIENTS_API_FIND_CLIENTS, find_err)
Example #4
0
    def remote_update_service_parameter(ss_api_config, service_description_conf, service):
        try:
            services_api = ServicesApi(ApiClient(ss_api_config))
            for configurable_service in service_description_conf["services"]:
                response = None
                if service.service_code == configurable_service["service_code"]:
                    timeout = int(configurable_service["timeout"])
                    timeout_all = bool(service_description_conf["timeout_all"])
                    ssl_auth = bool(configurable_service["ssl_auth"])
                    ssl_auth_all = bool(service_description_conf["ssl_auth_all"])
                    url = configurable_service["url"]
                    url_all = bool(service_description_conf["url_all"])

                    service_update = ServiceUpdate(url=url,
                                                   timeout=timeout,
                                                   ssl_auth=ssl_auth,
                                                   url_all=url_all,
                                                   timeout_all=timeout_all,
                                                   ssl_auth_all=ssl_auth_all)
                    response = services_api.update_service(service.id, body=service_update)
            if response:
                BaseController.log_info("Updated service parameters for service '" + service.id +
                                        "' (got full id " + response.id + ")")
        except ApiException as err:
            BaseController.log_api_error('ServicesApi->update_service', err)
Example #5
0
    def remote_add_access_rights_for_service(self,
                                             ss_api_config,
                                             service_description_conf,
                                             client_controller,
                                             clients_api,
                                             client,
                                             service):
        try:
            services_api = ServicesApi(ApiClient(ss_api_config))
            access_list = service_description_conf["access"] if service_description_conf["access"] else []
            configurable_services = service_description_conf["services"] if service_description_conf["services"] else []
            for configurable_service in configurable_services:
                if service.service_code == configurable_service["service_code"]:
                    access_list = configurable_service["access"] if configurable_service["access"] else []

                    self.remote_add_access_from_access_list(client_controller,
                                                            clients_api,
                                                            services_api,
                                                            client,
                                                            service,
                                                            access_list)
                else:
                    BaseController.log_info("Access rights are not defined for service ")
        except ApiException as err:
            if err.status == 409:
                BaseController.log_info("Access rights for client '" + client.id + "' using service '" + service.id + "' already added")
            else:
                BaseController.log_api_error('ServicesApi->add_service_service_clients', err)
 def remote_import_certificates(ss_api_config, security_server):
     token_cert_api = TokenCertificatesApi(ApiClient(ss_api_config))
     for cert in security_server["certificates"]:
         location = cement.utils.fs.join_exists(cert)
         if not location[1]:
             BaseController.log_info("Certificate '" + location[0] +
                                     "' does not exist")
         else:
             cert_file_loc = location[0]
             try:
                 cert_file = open(cert_file_loc, "rb")
                 cert_data = cert_file.read()
                 cert_file.close()
                 token_cert_api.import_certificate(body=cert_data)
                 BaseController.log_info("Imported certificate '" +
                                         cert_file_loc + "'")
             except ApiException as err:
                 if err.status == 409 and err.body.count(
                         "certificate_already_exists"):
                     BaseController.log_info("Certificate '" +
                                             cert_file_loc +
                                             "' already imported.")
                 else:
                     BaseController.log_api_error(
                         'TokenCertificatesApi->import_certificate', err)
 def remote_add_service_endpoints(self, ss_api_config, security_server_conf,
                                  client_conf, service_description_conf,
                                  endpoint_conf):
     try:
         clients_api = ClientsApi(ApiClient(ss_api_config))
         client_controller = ClientController()
         client = client_controller.find_client(clients_api,
                                                security_server_conf,
                                                client_conf)
         if client:
             try:
                 service_description = ServiceController(
                 ).get_client_service_description(clients_api, client,
                                                  service_description_conf)
                 if service_description:
                     if service_description.type == ServiceType().WSDL:
                         BaseController.log_info(
                             "Wrong service description, endpoints for WSDL services are not"
                             " allowed, skipped endpoint creation " +
                             EndpointController.FOR_SERVICE + "'" +
                             service_description.url + "'")
                     else:
                         self.remote_add_endpoint(ss_api_config,
                                                  service_description,
                                                  service_description_conf,
                                                  endpoint_conf)
             except ApiException as find_err:
                 BaseController.log_api_error(
                     ClientController.
                     CLIENTS_API_GET_CLIENT_SERVICE_DESCRIPTION, find_err)
     except ApiException as find_err:
         BaseController.log_api_error(
             ClientController.CLIENTS_API_FIND_CLIENTS, find_err)
 def remote_add_endpoints_access(self, ss_api_config, security_server_conf,
                                 client_conf, service_description_conf):
     try:
         client_controller = ClientController()
         clients_api = ClientsApi(ApiClient(ss_api_config))
         client = client_controller.find_client(clients_api,
                                                security_server_conf,
                                                client_conf)
         if client:
             service_clients_candidates = client_controller.get_clients_service_client_candidates(
                 clients_api, client.id, [])
             try:
                 service_controller = ServiceController()
                 clients_api = ClientsApi(ApiClient(ss_api_config))
                 service_description = service_controller.get_client_service_description(
                     clients_api, client, service_description_conf)
                 if service_description.type != ServiceType().WSDL:
                     self.remote_add_endpoint_access(
                         ss_api_config, service_description,
                         service_description_conf,
                         service_clients_candidates)
             except ApiException as find_err:
                 BaseController.log_api_error(
                     ClientController.
                     CLIENTS_API_GET_CLIENT_SERVICE_DESCRIPTION, find_err)
     except ApiException as find_err:
         BaseController.log_api_error(
             ClientController.CLIENTS_API_FIND_CLIENTS, find_err)
Example #9
0
    def get_clients_service_client_candidates(clients_api, client_id, candidates_ids):
        try:
            candidates = clients_api.find_service_client_candidates(client_id)

            if candidates_ids is None or len(candidates_ids) == 0:
                return candidates
            else:
                return [x for x in candidates if x.id in candidates_ids]

        except ApiException as find_err:
            BaseController.log_api_error('ClientsApi->find_service_client_candidates', find_err)
Example #10
0
 def remote_update_service_parameters(self, ss_api_config, security_server_conf, client_conf, service_description_conf):
     clients_api = ClientsApi(ApiClient(ss_api_config))
     try:
         client_controller = ClientController()
         client = client_controller.find_client(clients_api, security_server_conf, client_conf)
         if client:
             try:
                 service_description = self.get_client_service_description(clients_api, client, service_description_conf)
                 if service_description:
                     for service in service_description.services:
                         self.remote_update_service_parameter(ss_api_config, service_description_conf, service)
             except ApiException as find_err:
                 BaseController.log_api_error(ClientController.CLIENTS_API_GET_CLIENT_SERVICE_DESCRIPTION, find_err)
     except ApiException as find_err:
         BaseController.log_api_error(ClientController.CLIENTS_API_FIND_CLIENTS, find_err)
 def remote_add_endpoint_access(self, ss_api_config, service_description,
                                service_description_conf,
                                service_clients_candidates):
     for endpoint_conf in service_description_conf["endpoints"]:
         try:
             access_list = endpoint_conf["access"] if endpoint_conf[
                 "access"] else []
             if len(access_list) > 0:
                 self.add_access_from_list(ss_api_config,
                                           service_description,
                                           service_clients_candidates,
                                           endpoint_conf, access_list)
         except ApiException as find_err:
             BaseController.log_api_error(
                 ClientController.
                 CLIENTS_API_GET_CLIENT_SERVICE_DESCRIPTION, find_err)
Example #12
0
    def remote_register_client(self, ss_api_config, security_server_conf, client_conf):
        clients_api = ClientsApi(ApiClient(ss_api_config))
        try:
            client = self.find_client(clients_api, security_server_conf, client_conf)
            if client:
                if ClientStatus.SAVED != client.status:
                    BaseController.log_info(
                        security_server_conf['name'] + ": " + self.partial_client_id(client_conf) + " already registered."
                    )
                    return

                try:
                    clients_api.register_client(id=client.id)
                    BaseController.log_info("Registered client " + self.partial_client_id(client_conf))
                except ApiException as reg_err:
                    BaseController.log_api_error('ClientsApi->register_client', reg_err)
        except ApiException as find_err:
            BaseController.log_api_error(ClientController.CLIENTS_API_FIND_CLIENTS, find_err)
 def remote_token_login(ss_api_config, security_server):
     token_id = security_server['software_token_id']
     token_pin = security_server['software_token_pin']
     try:
         BaseController.log_info('Performing software token ' +
                                 str(token_id) + ' login: '******'" +
                                 security_server['name'] + "' token " +
                                 str(token_id) + " logged in.")
     except ApiException as err:
         if err.status == 409:
             BaseController.log_info("Token " + str(token_id) +
                                     " already logged in for '" +
                                     security_server['name'] + "'.")
         else:
             BaseController.log_api_error('TokensApi->login_token', err)
    def remote_register_certificate(ss_api_config, security_server):
        registrable_cert = CertController.find_actionable_auth_certificate(
            ss_api_config, security_server, 'REGISTER')
        if not registrable_cert:
            return None

        token_cert_api = TokenCertificatesApi(ApiClient(ss_api_config))
        ss_address = SecurityServerAddress(
            BaseController.security_server_address(security_server))
        try:
            response = token_cert_api.register_certificate(
                registrable_cert.certificate_details.hash, body=ss_address)
            BaseController.log_info("Registered certificate " +
                                    registrable_cert.certificate_details.hash +
                                    " for address '" + str(ss_address) + "'")
            return response
        except ApiException as err:
            BaseController.log_api_error(
                'TokenCertificatesApi->import_certificate', err)
Example #15
0
    def remote_update_client(self, ss_api_config, security_server_conf, client_conf):
        clients_api = ClientsApi(ApiClient(ss_api_config))
        try:
            client = self.find_client(clients_api, security_server_conf, client_conf)
            if client:
                if client.status not in [ClientStatus.SAVED, ClientStatus.REGISTERED, ClientStatus.REGISTRATION_IN_PROGRESS]:
                    BaseController.log_info(
                        security_server_conf['name'] + ": " + self.partial_client_id(client_conf) + " not added/registered yet."
                    )
                    return

                try:
                    client.connection_type = convert_swagger_enum(ConnectionType, client_conf['connection_type'])
                    response = clients_api.update_client(client.id, body=client)
                    BaseController.log_info("Updated client " + self.partial_client_id(client_conf) + " connection type")
                    return response
                except ApiException as reg_err:
                    BaseController.log_api_error('ClientsApi->update_client', reg_err)
        except ApiException as find_err:
            BaseController.log_api_error(ClientController.CLIENTS_API_FIND_CLIENTS, find_err)
    def remote_download_internal_tsl(self, ss_api_config, security_server):
        system_api = SystemApi(ApiClient(ss_api_config))
        downloaded_internal = []

        # Impossible to get valid byte array via generated client API conversion, resort to HTTP response.
        try:
            with cement.utils.fs.Tmp(prefix=security_server["name"] +
                                     "_certs_",
                                     suffix='.tar.gz',
                                     cleanup=False) as tmp:
                http_response = system_api.download_system_certificate(
                    _preload_content=False)
                if 200 == http_response.status:
                    with open(tmp.file, 'wb') as file:
                        file.write(http_response.data)
                        downloaded_internal.append(
                            DownloadedTLS(security_server["name"], file.name))
                else:
                    BaseController.log_info(
                        "Failed to download TSL internal certifucate for security server '"
                        + security_server["name"] + "' (HTTP " +
                        http_response.status + ", " + http_response.reason +
                        ")")

                # Remove empty folder that fs.Tmp creates and that would remain with auto-clean off
                os.rmdir(tmp.dir)
        except ApiException as err:
            BaseController.log_api_error(
                "Failed to download the TSL internal cert", err)

        render_data = []
        if self.is_output_tabulated():
            render_data = [DownloadedTSLListMapper.headers()]
            render_data.extend(
                map(DownloadedTSLListMapper.as_list, downloaded_internal))
        else:
            render_data.extend(
                map(DownloadedTSLListMapper.as_object, downloaded_internal))

        self.render(render_data)
        return downloaded_internal
Example #17
0
    def remote_add_client(self, ss_api_config, client_conf):
        conn_type = convert_swagger_enum(ConnectionType, client_conf['connection_type'])
        client = Client(member_class=client_conf['member_class'],
                        member_code=client_conf['member_code'],
                        connection_type=conn_type,
                        member_name=client_conf['member_name'],
                        subsystem_code=client_conf['subsystem_code'] if 'subsystem_code' in client_conf else None,
                        owner=False,
                        has_valid_local_sign_cert=False)

        client_add = ClientAdd(client=client, ignore_warnings=True)
        clients_api = ClientsApi(ApiClient(ss_api_config))
        try:
            response = clients_api.add_client(body=client_add)
            BaseController.log_info("Added client subsystem " + self.partial_client_id(client_conf) + " (got full id " + response.id + ")")
            return response
        except ApiException as err:
            if err.status == 409:
                BaseController.log_info("Client for '" + self.partial_client_id(client_conf) + "' already exists.")
            else:
                BaseController.log_api_error('ClientsApi->add_client', err)
 def add_access_based_on_service_client_candidate(ss_api_config,
                                                  service_description,
                                                  endpoint_conf, access,
                                                  candidate):
     endpoint = [
         e for e in service_description.services[0].endpoints
         if e.method == endpoint_conf["method"]
         and e.path == endpoint_conf["path"]
     ]
     if len(endpoint) == 0:
         BaseController.log_info("Error adding client access rights '" +
                                 access + "' for the endpoint '" +
                                 endpoint_conf["method"] + " " +
                                 endpoint_conf["path"] + "'" +
                                 EndpointController.FOR_SERVICE + "'" +
                                 service_description.id +
                                 "', endpoint not found")
     else:
         try:
             endpoints_api = EndpointsApi(ApiClient(ss_api_config))
             response = endpoints_api.add_endpoint_service_clients(
                 endpoint[0].id, body=ServiceClients(items=candidate))
             if response:
                 BaseController.log_info(
                     "Added client access rights: '" + candidate[0].id +
                     "'for endpoint '" + endpoint[0].method + "' '" +
                     endpoint[0].path + "' in service '" +
                     service_description.services[0].id + "'")
         except ApiException as err:
             if err.status == 409:
                 BaseController.log_info(
                     "Added client access rights: '" + candidate[0].id +
                     "'for endpoint '" + endpoint[0].method + "' '" +
                     endpoint[0].path + "' in service '" +
                     service_description.services[0].id + "' already added")
             else:
                 BaseController.log_api_error(
                     'EndpointsApi->add_endpoint_service_clients', err)
Example #19
0
 def remote_enable_service_description(self, ss_api_config, security_server_conf, client_conf, service_description_conf):
     clients_api = ClientsApi(ApiClient(ss_api_config))
     service_descriptions_api = ServiceDescriptionsApi(ApiClient(ss_api_config))
     try:
         client_controller = ClientController()
         client = client_controller.find_client(clients_api, security_server_conf, client_conf)
         if client:
             try:
                 service_description = self.get_client_service_description(clients_api, client, service_description_conf)
                 if service_description:
                     try:
                         service_descriptions_api.enable_service_description(service_description.id)
                         BaseController.log_info(ServiceController.SERVICE_DESCRIPTION_FOR + "'" + client_controller.partial_client_id(client_conf) +
                                                 "' with id: '" + service_description.id + "' enabled successfully.")
                     except ApiException as err:
                         if err.status == 409:
                             BaseController.log_info(ServiceController.SERVICE_DESCRIPTION_FOR + "'" + client_controller.partial_client_id(client_conf) +
                                                     "' with id: '" + service_description.id + "' already enabled.")
                         else:
                             BaseController.log_api_error('ServiceDescriptionsApi->enable_service_description', err)
             except ApiException as find_err:
                 BaseController.log_api_error(ClientController.CLIENTS_API_GET_CLIENT_SERVICE_DESCRIPTION, find_err)
     except ApiException as find_err:
         BaseController.log_api_error(ClientController.CLIENTS_API_FIND_CLIENTS, find_err)
    def remote_token_add_keys_with_csrs(ss_api_config, security_server):
        def log_creations(results):
            for result in results:
                BaseController.log_info("Created " + str(result.key.usage) +
                                        " CSR '" + result.csr_id +
                                        "' for key '" + result.key.id +
                                        "' as '" + result.key.label + "'")

        responses = []

        token_id = security_server[
            ConfKeysSecurityServer.CONF_KEY_SOFT_TOKEN_ID]
        ss_code = security_server[ConfKeysSecurityServer.CONF_KEY_SERVER_CODE]
        member_class = security_server[
            ConfKeysSecurityServer.CONF_KEY_MEMBER_CLASS]
        dn_country = security_server[ConfKeysSecurityServer.CONF_KEY_DN_C]
        dn_common_name = security_server[
            ConfKeysSecurityServer.CONF_KEY_MEMBER_CODE]
        dn_org = security_server[ConfKeysSecurityServer.CONF_KEY_DN_ORG]
        fqdn = security_server[ConfKeysSecurityServer.CONF_KEY_FQDN]

        auth_key_label = default_auth_key_label(security_server)
        sign_key_label = default_sign_key_label(security_server)

        try:
            ssi = remote_get_security_server_instance(ss_api_config)
            token = remote_get_token(ss_api_config, security_server)
            auth_ca = remote_get_auth_certificate_authority(ss_api_config)
            sign_ca = remote_get_sign_certificate_authority(ss_api_config)

            token_key_labels = list(map(lambda key: key.label, token.keys))
            has_auth_key = auth_key_label in token_key_labels
            has_sign_key = sign_key_label in token_key_labels

            sign_cert_subject = {
                'C': dn_country,
                'O': dn_org,
                'CN': dn_common_name,
                'serialNumber':
                '/'.join([ssi.member_class, ss_code, member_class])
            }

            auth_cert_subject = copy.deepcopy(sign_cert_subject)
            auth_cert_subject['CN'] = fqdn

            auth_key_req_param = KeyLabelWithCsrGenerate(
                key_label=auth_key_label,
                csr_generate_request=CsrGenerate(
                    key_usage_type=KeyUsageType.AUTHENTICATION,
                    ca_name=auth_ca.name,
                    csr_format=CsrFormat.
                    DER,  # Test CA setup at least only works with DER
                    member_id=':'.join(
                        [ssi.instance_id, ssi.member_class, ssi.member_code]),
                    subject_field_values=auth_cert_subject))

            sign_key_req_param = KeyLabelWithCsrGenerate(
                key_label=sign_key_label,
                csr_generate_request=CsrGenerate(
                    key_usage_type=KeyUsageType.SIGNING,
                    ca_name=sign_ca.name,
                    csr_format=CsrFormat.
                    DER,  # Test CA setup at least only works with DER
                    member_id=':'.join(
                        [ssi.instance_id, ssi.member_class, ssi.member_code]),
                    subject_field_values=sign_cert_subject))

            if has_sign_key and has_auth_key:
                BaseController.log_info("No key initialization needed.")
                return

            token_api = TokensApi(ApiClient(ss_api_config))
            if not has_auth_key:
                try:
                    BaseController.log_info(
                        TokenLabels.generate_key(token_id, sign_key_label,
                                                 'AUTH'))
                    response = token_api.add_key_and_csr(
                        token_id, body=auth_key_req_param)
                    responses.append(response)
                except ApiException as err:
                    BaseController.log_api_error(TokenLabels.error(), err)
                    log_creations(responses)

            if not has_sign_key:
                try:
                    BaseController.log_info(
                        TokenLabels.generate_key(token_id, sign_key_label,
                                                 'SIGN'))
                    response = token_api.add_key_and_csr(
                        token_id, body=sign_key_req_param)
                    responses.append(response)
                except ApiException as err:
                    BaseController.log_api_error(TokenLabels.error(), err)
                    log_creations(responses)
        except Exception as exc:
            log_creations(responses)
            raise exc

        log_creations(responses)