async def update_policy(request, policy_id: int, pretty: bool = False, wait_for_complete: bool = False): """Update the information of one specified policy. Parameters ---------- request : connexion.request policy_id : int Specific policy id in the system to be updated pretty : bool, optional Show results in human-readable format wait_for_complete : bool, optional Disable timeout response Returns ------- Policy information updated """ # Get body parameters Body.validate_content_type(request, expected_content_type='application/json') f_kwargs = await PolicyModel.get_kwargs( request, additional_kwargs={'policy_id': policy_id}) dapi = DistributedAPI( f=security.update_policy, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies']) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def get_agent_summary_os(request, pretty=False, wait_for_complete=False): """Get agents OS summary. :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :return: ListMetadata """ f_kwargs = {} dapi = DistributedAPI( f=agent.get_agents_summary_os, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies']) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def remove_role_rule(request, role_id: int, rule_ids: list, pretty: bool = False, wait_for_complete: bool = False): """Delete a list of rules of one specified role. Parameters ---------- request : request.connexion role_id : int rule_ids : list List of rule ids pretty : bool, optional Show results in human-readable format wait_for_complete : bool, optional Disable timeout response Returns ------- Role information """ if 'all' in rule_ids: rule_ids = None f_kwargs = {'role_id': role_id, 'rule_ids': rule_ids} dapi = DistributedAPI( f=security.remove_role_rule, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies']) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def delete_syscheck_agent(request, agent_id='*', pretty=False, wait_for_complete=False): """ :param pretty: Show results in human-readable format :type pretty: bool :param wait_for_complete: Disable timeout response :type wait_for_complete: bool :param agent_id: Agent ID :type agent_id: str """ f_kwargs = {'agent_list': [agent_id]} dapi = DistributedAPI(f=clear, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='distributed_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies'] ) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def get_files(request, pretty=False, wait_for_complete=False, path=None): """Get file contents in manager or local_node. :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :param path: Filepath to return. """ f_kwargs = {'path': path} dapi = DistributedAPI( f=manager.get_file, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_any', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies']) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def restart_agents(request, pretty=False, wait_for_complete=False, agents_list='*'): """ Restarts all agents :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :param agents_list: List of agent's IDs. :return: AllItemsResponseAgentIDs """ f_kwargs = {'agent_list': agents_list} dapi = DistributedAPI(f=agent.restart_agents, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='distributed_master', is_async=False, wait_for_complete=wait_for_complete, rbac_permissions=request['token_info']['rbac_policies'], broadcasting=agents_list == '*', logger=logger ) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def delete_users(request, user_ids: list = None, pretty=False, wait_for_complete=False): """Delete an existent list of users. Parameters ---------- request : connexion.request user_ids : list, optional IDs of the users to be removed pretty : bool, optional Show results in human-readable format wait_for_complete : bool, optional Disable timeout response Returns ------- Result of the operation """ if 'all' in user_ids: user_ids = None f_kwargs = {'user_ids': user_ids} dapi = DistributedAPI( f=security.remove_users, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, logger=logger, current_user=request['token_info']['sub'], rbac_permissions=request['token_info']['rbac_policies'], wait_for_complete=wait_for_complete) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def delete_security_config(request, pretty=False, wait_for_complete=False): """Restore default security configuration Parameters ---------- request pretty : bool Show results in human-readable format wait_for_complete : bool Disable timeout response Returns ------- dict: Status message """ f_kwargs = { "updated_config": await SecurityConfigurationModel.get_kwargs(default_security_configuration) } dapi = DistributedAPI( f=security.update_security_config, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies']) data = raise_if_exc(await dapi.distribute_function()) await security_revoke_tokens() return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def put_group_config(request, body, group_id, pretty=False, wait_for_complete=False): """Update group configuration. Update an specified group's configuration. This API call expects a full valid XML file with the shared configuration tags/syntax. :param body: Body parameters :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :param group_id: Group ID. :return: ApiResponse """ # Parse body to utf-8 Body.validate_content_type(request, expected_content_type='application/xml') parsed_body = Body.decode_body(body, unicode_error=2006, attribute_error=2007) f_kwargs = {'group_list': [group_id], 'file_data': parsed_body} dapi = DistributedAPI( f=agent.upload_group_file, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies']) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def delete_agents(request, pretty=False, wait_for_complete=False, list_agents=None, purge=False, status='all', older_than="7d"): """Delete all agents or a list of them with optional criteria based on the status or time of the last connection. :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :param list_agents: List of agent's IDs. :param purge: Delete an agent from the key store :param status: Filters by agent status. Use commas to enter multiple statuses. :param older_than: Filters out disconnected agents for longer than specified. Time in seconds, ‘[n_days]d’, ‘[n_hours]h’, ‘[n_minutes]m’ or ‘[n_seconds]s’. For never_connected agents, uses the register date. :return: AllItemsResponseAgentIDs """ f_kwargs = { 'agent_list': list_agents, 'purge': purge, 'status': status, 'older_than': older_than, 'use_only_authd': configuration.api_conf['use_only_authd'] } dapi = DistributedAPI( f=agent.delete_agents, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies']) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def clear_rootcheck_database(request, pretty=False, wait_for_complete=False, agents_list=None): """Clear the rootcheck database for all agents or a list of them. Parameters ---------- pretty : bool Show results in human-readable format. wait_for_complete : bool Disable timeout response. agents_list : list List of agent's IDs. Returns ------- web.Response """ if 'all' in agents_list: agents_list = '*' f_kwargs = {'agent_list': agents_list} dapi = DistributedAPI( f=rootcheck.clear, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='distributed_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, broadcasting=agents_list == '*', rbac_permissions=request['token_info']['rbac_policies']) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def update_user(request, user_id: str, pretty=False, wait_for_complete=False): """Modify an existent user. Parameters ---------- request : connexion.request user_id : str User ID of the user to be updated pretty : bool, optional Show results in human-readable format wait_for_complete : bool, optional Disable timeout response Returns ------- User data """ Body.validate_content_type(request, expected_content_type='application/json') f_kwargs = await UpdateUserModel.get_kwargs( request, additional_kwargs={'user_id': user_id}) dapi = DistributedAPI( f=security.update_user, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, logger=logger, rbac_permissions=request['token_info']['rbac_policies'], wait_for_complete=wait_for_complete) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def get_agent_fields(request, pretty=False, wait_for_complete=False, fields=None, offset=0, limit=database_limit, select=None, sort=None, search=None, q=None): """Get distinct fields in agents. Returns all the different combinations that agents have for the selected fields. It also indicates the total number of agents that have each combination. :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :param fields: List of fields affecting the operation. :param offset: First element to return in the collection :param limit: Maximum number of elements to return :param select: Select which fields to return (separated by comma) :param sort: Sorts the collection by a field or fields (separated by comma). Use +/- at the beginning to list in ascending or descending order. :param search: Looks for elements with the specified string :param q: Query to filter results by. For example q="status=active" :return: ListMetadata """ f_kwargs = {'offset': offset, 'limit': limit, 'select': select, 'sort': parse_api_param(sort, 'sort'), 'search': parse_api_param(search, 'search'), 'fields': fields, 'q': q} dapi = DistributedAPI(f=agent.get_distinct_agents, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies'] ) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def get_agent_config(request, pretty=False, wait_for_complete=False, agent_id=None, component=None, **kwargs): """Get active configuration Returns the active configuration the agent is currently using. This can be different from the configuration present in the configuration file, if it has been modified and the agent has not been restarted yet. :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :param agent_id: Agent ID. All posible values since 000 onwards. :param component: Selected agent's component. :return: AgentConfiguration """ f_kwargs = { 'agent_list': [agent_id], 'component': component, 'config': kwargs.get('configuration', None) } dapi = DistributedAPI( f=agent.get_agent_config, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='distributed_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies']) data = raise_if_exc(await dapi.distribute_function()) response = Data(data) return web.json_response(data=response, status=200, dumps=prettify if pretty else dumps)
async def get_attack(request, pretty=False, wait_for_complete=False, offset=0, limit=database_limit, phase_name=None, platform_name=None, q=None, search=None, select=None, sort=None): """Get information from MITRE ATT&CK database :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :param phase_name: Filters by phase :param platform_name: Filters by platform :param search: Search if the string is contained in the db :param offset: First item to return :param limit: Maximum number of items to return :param sort: Sort the items. Format: {'fields': ['field1', 'field2'], 'order': 'asc|desc'} :param select: Select fields to return. Format: {"fields":["field1","field2"]}. :param q: Query to filter by :return: Data """ f_kwargs = {'id_': request.query.get('id', None), 'phase_name': phase_name, 'platform_name': platform_name, 'select': select, 'search': parse_api_param(search, 'search'), 'offset': offset, 'limit': limit, 'sort': parse_api_param(sort, 'sort'), 'q': q } dapi = DistributedAPI(f=mitre.get_attack, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies'] ) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def put_syscheck(request, list_agents='*', pretty=False, wait_for_complete=False): """Run a syscheck scan over the agent_ids :type list_agents: List of agent ids :param pretty: Show results in human-readable format :type pretty: bool :param wait_for_complete: Disable timeout response :type wait_for_complete: bool """ f_kwargs = {'agent_list': list_agents} dapi = DistributedAPI(f=run, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='distributed_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, broadcasting=list_agents == '*', rbac_permissions=request['token_info']['rbac_policies'] ) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def post_group(request, group_id, pretty=False, wait_for_complete=False): """Create a new group. :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :param group_id: Group ID. :return: ApiResponse """ f_kwargs = {'group_id': group_id} dapi = DistributedAPI( f=agent.create_group, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies']) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def get_log_summary_node(request, node_id, pretty=False, wait_for_complete=False): """Get a summary of a specified node's wazuh logs. :param node_id: Cluster node name. :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response """ f_kwargs = {'node_id': node_id} nodes = await get_system_nodes() dapi = DistributedAPI(f=manager.ossec_log_summary, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='distributed_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies'], nodes=nodes, cluster_required=True ) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def post_new_agent(request, agent_name, pretty=False, wait_for_complete=False): """Add agent (quick method) Adds a new agent with name `agent_name`. This agent will use `any` as IP.' :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :param agent_name: Agent name used when the agent was registered. :return: AgentIdKeyData """ f_kwargs = {'name': agent_name, 'use_only_authd': configuration.api_conf['use_only_authd']} dapi = DistributedAPI(f=agent.add_agent, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies'] ) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
def test_DistributedAPI_local_request(mock_local_request): """Test `local_request` method from class DistributedAPI and check the behaviour when an error raise.""" dapi_kwargs = {'f': manager.status, 'logger': logger} raise_if_exc_routine(dapi_kwargs=dapi_kwargs) dapi_kwargs = {'f': cluster.get_nodes_info, 'logger': logger, 'local_client_arg': 'lc'} raise_if_exc_routine(dapi_kwargs=dapi_kwargs) dapi_kwargs['is_async'] = True raise_if_exc_routine(dapi_kwargs=dapi_kwargs) with patch('asyncio.wait_for', new=AsyncMock(side_effect=TimeoutError('Testing'))): dapi = DistributedAPI(f=manager.status, logger=logger) try: raise_if_exc(loop.run_until_complete(dapi.distribute_function())) except ProblemException as e: assert e.ext['dapi_errors'][list(e.ext['dapi_errors'].keys())[0]]['error'] == \ 'Timeout executing API request' with patch('asyncio.wait_for', new=AsyncMock(side_effect=WazuhError(1001))): dapi_kwargs = {'f': manager.status, 'logger': logger} raise_if_exc_routine(dapi_kwargs=dapi_kwargs, expected_error=1001) dapi_kwargs['debug'] = True raise_if_exc_routine(dapi_kwargs=dapi_kwargs, expected_error=1001) with patch('asyncio.wait_for', new=AsyncMock(side_effect=WazuhInternalError(1001))): dapi_kwargs = {'f': manager.status, 'logger': logger} raise_if_exc_routine(dapi_kwargs=dapi_kwargs, expected_error=1001) dapi = DistributedAPI(f=manager.status, logger=logger, debug=True) try: raise_if_exc(loop.run_until_complete(dapi.distribute_function())) except WazuhInternalError as e: assert e.code == 1001 with patch('asyncio.wait_for', new=AsyncMock(side_effect=KeyError('Testing'))): dapi_kwargs = {'f': manager.status, 'logger': logger} raise_if_exc_routine(dapi_kwargs=dapi_kwargs, expected_error=1000) dapi = DistributedAPI(f=manager.status, logger=logger, debug=True) try: raise_if_exc(loop.run_until_complete(dapi.distribute_function())) except Exception as e: assert type(e) == KeyError
async def get_hardware_info(request, agent_id, pretty=False, wait_for_complete=False, select=None): """ Get hardware info of an agent :param agent_id: Agent ID :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :param select: Select which fields to return (separated by comma) :return: Data """ f_kwargs = {'agent_list': [agent_id], 'select': select, 'element_type': 'hardware'} dapi = DistributedAPI(f=syscollector.get_item_agent, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='distributed_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies'] ) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def delete_groups(request, groups_list=None, pretty=False, wait_for_complete=False): """Delete all groups or a list of them. :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :param groups_list: Array of group's IDs. :return: AllItemsResponseGroupIDs + AgentGroupDeleted """ if 'all' in groups_list: groups_list = None f_kwargs = {'group_list': groups_list} dapi = DistributedAPI(f=agent.delete_groups, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies'] ) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def put_security_config(request, pretty=False, wait_for_complete=False): """Update current security configuration with the given one. :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response """ f_kwargs = { 'updated_config': await SecurityConfigurationModel.get_kwargs(request) } dapi = DistributedAPI( f=security.update_security_config, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies']) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def put_files(request, body, overwrite=False, pretty=False, wait_for_complete=False, path=None): """Upload file in manager or local_node. :param body: Body request with the content of the file to be uploaded :param overwrite: If set to false, an exception will be raised when updating contents of an already existing filename. :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :param path: Filepath to return. """ # Parse body to utf-8 Body.validate_content_type( request, expected_content_type='application/octet-stream') parsed_body = Body.decode_body(body, unicode_error=1911, attribute_error=1912) f_kwargs = {'path': path, 'overwrite': overwrite, 'content': parsed_body} dapi = DistributedAPI( f=manager.upload_file, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_any', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies']) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def remove_policies(request, policy_ids: list = None, pretty: bool = False, wait_for_complete: bool = False): """Removes a list of roles in the system. Parameters ---------- request : connexion.request policy_ids : list, optional List of policies ids to be deleted pretty : bool, optional Show results in human-readable format wait_for_complete : bool, optional Disable timeout response Returns ------- Two list with deleted roles and not deleted roles """ if 'all' in policy_ids: policy_ids = None f_kwargs = {'policy_ids': policy_ids} dapi = DistributedAPI( f=security.remove_policies, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies']) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def get_rules_files(request, pretty=False, wait_for_complete=False, offset=0, limit=None, sort=None, search=None, status=None, filename=None, relative_dirname=None): """Get all files which defines rules :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :param offset: First element to return in the collection :param limit: Maximum number of elements to return :param sort: Sorts the collection by a field or fields (separated by comma). Use +/- at the beginning to list in ascending or descending order. :param search: Looks for elements with the specified string :param status: Filters by rules status. :param filename: List of filenames to filter by.. :param relative_dirname: Filters by relative dirname. :return: Data object """ f_kwargs = {'offset': offset, 'limit': limit, 'sort_by': parse_api_param(sort, 'sort')['fields'] if sort is not None else ['filename'], 'sort_ascending': True if sort is None or parse_api_param(sort, 'sort')['order'] == 'asc' else False, 'search_text': parse_api_param(search, 'search')['value'] if search is not None else None, 'complementary_search': parse_api_param(search, 'search')['negation'] if search is not None else None, 'status': status, 'filename': filename, 'relative_dirname': relative_dirname} dapi = DistributedAPI(f=rule_framework.get_rules_files, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_any', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies'] ) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def put_upgrade_custom_agents(request, agents_list=None, pretty=False, wait_for_complete=False, file_path=None, installer=None): """Upgrade agents using a local WPK file. Parameters ---------- pretty : bool Show results in human-readable format. wait_for_complete : bool Disable timeout response. agents_list : list List of agent IDs. All possible values from 000 onwards. file_path : str Path to the WPK file. The file must be on a folder on the Wazuh's installation directory (by default, <code>/var/ossec</code>). installer : str Installation file. Returns ------- ApiResponse Upgrade message after trying to upgrade the agents. """ f_kwargs = {'agent_list': agents_list, 'file_path': file_path, 'installer': installer} dapi = DistributedAPI(f=agent.upgrade_agents, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='distributed_master', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies'] ) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
def generate_token(user_id=None, data=None, run_as=False): """Generate an encoded jwt token. This method should be called once a user is properly logged on. Parameters ---------- user_id : str Unique username data : dict Roles permissions for the user run_as : bool Indicate if the user has logged in with run_as or not Returns ------- JWT encode token """ dapi = DistributedAPI(f=get_security_conf, request_type='local_master', is_async=False, wait_for_complete=False, logger=logging.getLogger('wazuh-api')) result = raise_if_exc( pool.submit(asyncio.run, dapi.distribute_function()).result()).dikt timestamp = int(time()) payload = { "iss": JWT_ISSUER, "aud": "Wazuh API REST", "nbf": int(timestamp), "exp": int(timestamp + result['auth_token_exp_timeout']), "sub": str(user_id), "run_as": run_as, "rbac_roles": data['roles'], "rbac_mode": result['rbac_mode'] } return jwt.encode(payload, generate_keypair()[0], algorithm=JWT_ALGORITHM)
async def get_decoders_parents(request, pretty: bool = False, wait_for_complete: bool = False, offset: int = 0, limit: int = None, select : list = None, sort: str = None, search: str = None): """Get decoders by parents Returns information about all parent decoders. A parent decoder is a decoder used as base of other decoders :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response :param offset: First element to return in the collection :param limit: Maximum number of elements to return :param select: List of selected fields to return :param sort: Sorts the collection by a field or fields (separated by comma). Use +/- at the beginning to list in ascending or descending order. :param search: Looks for elements with the specified string :return: Data object """ f_kwargs = {'offset': offset, 'limit': limit, 'select': select, 'sort_by': parse_api_param(sort, 'sort')['fields'] if sort is not None else ['filename', 'position'], 'sort_ascending': True if sort is None or parse_api_param(sort, 'sort')['order'] == 'asc' else False, 'search_text': parse_api_param(search, 'search')['value'] if search is not None else None, 'complementary_search': parse_api_param(search, 'search')['negation'] if search is not None else None, 'parents': True} dapi = DistributedAPI(f=decoder_framework.get_decoders, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_any', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies'] ) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
async def get_stats_weekly(request, pretty=False, wait_for_complete=False): """Get manager's or local_node's stats by week. Returns Wazuh statistical information per week. Each number in the averages field represents the average of alerts per hour for that specific day. :param pretty: Show results in human-readable format :param wait_for_complete: Disable timeout response """ f_kwargs = {} dapi = DistributedAPI( f=stats.weekly, f_kwargs=remove_nones_to_dict(f_kwargs), request_type='local_any', is_async=False, wait_for_complete=wait_for_complete, logger=logger, rbac_permissions=request['token_info']['rbac_policies']) data = raise_if_exc(await dapi.distribute_function()) return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)