def status_server_initialization(api_config): initialization_api = InitializationApi(ApiClient(api_config)) security_servers_api = SecurityServersApi(ApiClient(api_config)) init_response = initialization_api.get_initialization_status() ssi = StatusServerInitialization( has_anchor=init_response.is_anchor_imported, has_server_code=init_response.is_server_code_initialized, has_server_owner=init_response.is_server_owner_initialized, token_init_status=init_response.software_token_init_status # Later conditional fill for: server_code, server_owner, token_init_status ) if init_response.is_anchor_imported: ss_api_response = security_servers_api.get_security_servers( current_server=True) sec_server_details = ss_api_response.pop() ssi.server_code = sec_server_details.server_code if init_response.is_server_code_initialized else None ssi.server_owner = sec_server_details.member_code if init_response.is_server_owner_initialized else None ssi.id_ = sec_server_details.id if init_response.is_server_owner_initialized and init_response.is_server_code_initialized else None ssi.token_init_status = init_response.software_token_init_status return ssi
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)
def status_anchor(api_config): initialization_api = InitializationApi(ApiClient(api_config)) system_api = SystemApi(ApiClient(api_config)) init_response = initialization_api.get_initialization_status() if not init_response.is_anchor_imported: return StatusAnchor(has_anchor=False) anchor = system_api.get_anchor() return StatusAnchor(has_anchor=True, hash_=anchor.hash, created_at=anchor.created_at)
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_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)
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)
def check_init_status(self, ss_api_config): try: initialization_api = InitializationApi(ApiClient(ss_api_config)) response = initialization_api.get_initialization_status() return response except ApiException as err: self.log_api_error('InitializationApi->get_initialization_status', err)
def remote_get_tokens(ss_api_config): try: token_api = TokensApi(ApiClient(ss_api_config)) token_list_response = token_api.get_tokens() return token_list_response except ApiException as err: print("Exception when calling TokensApi->get_tokens: %s\n" % 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_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)
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 status_roles(api_config): user_api = UserApi(ApiClient(api_config)) try: user = user_api.get_user() except ApiException as aex: if aex.status == 401 or aex.status == 403: return StatusRoles(permitted=False, roles=[]) return StatusRoles(permitted=True, roles=user.roles)
def remote_get_configured(ss_api_config): try: system_api = SystemApi(ApiClient(ss_api_config)) ts_list_response = system_api.get_configured_timestamping_services( ) return ts_list_response except ApiException as e: print("Exception when listing timestamping services: %s\n", e)
def status_global(api_config): diagnostics_api = DiagnosticsApi(ApiClient(api_config)) glob_conf_diag = diagnostics_api.get_global_conf_diagnostics() glob_status = StatusGlobal(class_=glob_conf_diag.status_class, code=glob_conf_diag.status_code, updated=glob_conf_diag.prev_update_at, refresh=glob_conf_diag.next_update_at) return glob_status
def remote_download_csrs(self, ss_api_config, security_server): key_labels = self.get_key_labels(security_server) token = remote_get_token(ss_api_config, security_server) auth_keys = list( filter(lambda key: key.label in key_labels['auth'], token.keys)) sign_keys = list( filter(lambda key: key.label in key_labels['sign'], token.keys)) if not (auth_keys or sign_keys): return [] keys_api = KeysApi(ApiClient(ss_api_config)) downloaded_csrs = [] for keytype in [(sign_keys, 'sign'), (auth_keys, 'auth')]: for key in keytype[0]: for csr in key.certificate_signing_requests: with cement.utils.fs.Tmp(prefix=csr_file_prefix( keytype[1], key, csr), suffix='.der', cleanup=False) as tmp: # Impossible to get valid byte array via generated client API conversion, resort to HTTP response. http_response = keys_api.download_csr( key.id, csr.id, csr_format=CsrFormat.DER, _preload_content=False) if 200 == http_response.status: with open(tmp.file, 'wb') as file: file.write(http_response.data) downloaded_csrs.append( DownloadedCsr(csr.id, key.id, keytype[1].upper(), file.name)) else: BaseController.log_info( "Failed to download key '" + key.id + "' CSR '" + csr.id + "' (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) render_data = [] if self.is_output_tabulated(): render_data = [DownloadedCsrListMapper.headers()] render_data.extend( map(DownloadedCsrListMapper.as_list, downloaded_csrs)) else: render_data.extend( map(DownloadedCsrListMapper.as_object, downloaded_csrs)) self.render(render_data) return downloaded_csrs
def upload_anchor(self, ss_api_config, security_server): try: self.log_info('Uploading configuration anchor for security server: ' + security_server['name']) system_api = SystemApi(ApiClient(ss_api_config)) anchor = open(security_server["configuration_anchor"], "r") response = system_api.upload_initial_anchor(body=anchor.read()) self.log_info('Upload of configuration anchor from \"' + security_server["configuration_anchor"] + '\" successful') return response except ApiException as err: self.log_api_error('SystemApi->upload_initial_anchor', err)
def init_security_server(self, ss_api_config, security_server): try: self.log_info('Initializing security server: ' + security_server['name']) initialization_api = InitializationApi(ApiClient(ss_api_config)) response = initialization_api.init_security_server(body=InitialServerConf( owner_member_class=security_server["owner_member_class"], owner_member_code=security_server["owner_member_code"], security_server_code=security_server["security_server_code"], software_token_pin=security_server["software_token_pin"], ignore_warnings=True)) self.log_info('Security server \"' + security_server["name"] + '\" initialized') return response except ApiException as err: self.log_api_error('InitializationApi->init_security_server', err)
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_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_list(self, ss_api_config): try: token_api = TokensApi(ApiClient(ss_api_config)) token_list_response = token_api.get_tokens() render_data = [] if self.is_output_tabulated(): render_data = [TokenListMapper.headers()] render_data.extend( map(TokenListMapper.as_list, token_list_response)) else: render_data.extend( map(TokenListMapper.as_object, token_list_response)) self.render(render_data) except ApiException as err: print("Exception when calling TokensApi->get_tokens: %s\n" % err)
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_activate_certificate(ss_api_config, security_server): activatable_cert = CertController.find_actionable_auth_certificate( ss_api_config, security_server, 'ACTIVATE') if not activatable_cert: return None token_cert_api = TokenCertificatesApi(ApiClient(ss_api_config)) token_cert_api.activate_certificate( activatable_cert.certificate_details.hash) # responseless PUT cert_actions = token_cert_api.get_possible_actions_for_certificate( activatable_cert.certificate_details.hash) if 'ACTIVATE' not in cert_actions: BaseController.log_info("Activated certificate " + activatable_cert.certificate_details.hash) else: BaseController.log_info("Could not activate certificate " + activatable_cert.certificate_details.hash) return cert_actions
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)
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
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 remote_timestamp_service_init(self, ss_api_config, security_server): try: approved_ts = self.get_approved_timestamping_services( ss_api_config) if approved_ts: system_api = SystemApi(ApiClient(ss_api_config)) ts_init_response = system_api.add_configured_timestamping_service( body=TimestampingService(name=approved_ts[0].name, url=approved_ts[0].url)) if ts_init_response: # single timestamping service added is also returned print(security_server['name']) self.render_timestamping_services([ts_init_response]) except ApiException as excn: if 409 == excn.status: print(security_server['name'], "Timestamping service already configured.") else: tsiferr_msg = "Timestamping service initialization configuration failure" print(security_server['name'], tsiferr_msg, excn) logging.error(security_server['name'] + ' ' + tsiferr_msg, excn)
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)