Пример #1
0
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
    """
    if 'all' in list_agents:
        list_agents = None
    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)
Пример #2
0
async def remove_user_role(request,
                           user_id: str,
                           role_ids: list,
                           pretty: bool = False,
                           wait_for_complete: bool = False):
    """Delete a list of roles of one specified user.

    Parameters
    ----------
    request : connexion.request
    user_id : str
        User ID
    role_ids : list
        List of roles ids
    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 role_ids:
        role_ids = None
    f_kwargs = {'user_id': user_id, 'role_ids': role_ids}

    dapi = DistributedAPI(
        f=security.remove_user_role,
        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)
Пример #3
0
async def get_cluster_nodes(request, pretty=False, wait_for_complete=False, offset=0, limit=None, sort=None,
                            search=None, select=None, list_nodes=None):
    """Get information about all nodes in the cluster or a list of them

    :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 select: Select which fields to return (separated by comma)
    :param list_nodes: List of node ids
    """
    # Get type parameter from query
    type_ = request.query.get('type', 'all')

    f_kwargs = {'filter_node': list_nodes,
                'offset': offset,
                'limit': limit,
                'sort': parse_api_param(sort, 'sort'),
                'search': parse_api_param(search, 'search'),
                'select': select,
                'filter_type': type_}

    nodes = await get_system_nodes()
    dapi = DistributedAPI(f=cluster.get_nodes_info,
                          f_kwargs=remove_nones_to_dict(f_kwargs),
                          request_type='local_master',
                          is_async=True,
                          wait_for_complete=wait_for_complete,
                          logger=logger,
                          local_client_arg='lc',
                          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)
Пример #4
0
async def insert_agent(request, pretty=False, wait_for_complete=False):
    """Insert a new agent

    :param pretty: Show results in human-readable format
    :param wait_for_complete: Disable timeout response
    :return: AgentIdKey
    """
    # Get body parameters
    Body.validate_content_type(request,
                               expected_content_type='application/json')
    f_kwargs = await AgentInsertedModel.get_kwargs(request)

    # Get IP if not given
    if not f_kwargs['ip']:
        if configuration.api_conf['behind_proxy_server']:
            try:
                f_kwargs['ip'] = request.headers['X-Forwarded-For']
            except KeyError:
                raise_if_exc(WazuhError(1120))
        else:
            peername = request.transport.get_extra_info('peername')
            if peername is not None:
                f_kwargs['ip'], _ = peername
    f_kwargs['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())
    response = Data(data)

    return web.json_response(data=response,
                             status=200,
                             dumps=prettify if pretty else dumps)
Пример #5
0
async def restart_agents_by_group(request, group_id, pretty=False, wait_for_complete=False):
    """Restart all agents from a group.

    :param pretty: Show results in human-readable format
    :param wait_for_complete: Disable timeout response
    :param group_id: Group ID.
    :return: AllItemsResponseAgents
    """
    f_kwargs = {'group_id': group_id}

    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,
                          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)
Пример #6
0
async def put_file(request, body, filename=None, overwrite=False, pretty=False, wait_for_complete=False):
    """Upload a decoder file.

    Parameters
    ----------
    body : dict
        Body request with the file content to be uploaded.
    filename : str
        Name of the file.
    overwrite : bool
        If set to false, an exception will be raised when updating contents of an already existing file.
    pretty : bool
        Show results in human-readable format.
    wait_for_complete : bool
        Disable timeout response.

    Returns
    -------
    web.json_response
    """
    # 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 = {'filename': filename,
                'overwrite': overwrite,
                'content': parsed_body}

    dapi = DistributedAPI(f=decoder_framework.upload_decoder_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)
Пример #7
0
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 we use the 'all' keyword and the request is distributed_master, agents_list must be '*'
    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)
Пример #8
0
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)
Пример #9
0
async def get_download_file(request, pretty: bool = False, wait_for_complete: bool = False, filename: str = None):
    """Download an specified decoder file.

    :param pretty: Show results in human-readable format
    :param wait_for_complete: Disable timeout response
    :param filename: Filename to download.
    :return: Raw xml file
    """
    f_kwargs = {'filename': filename}

    dapi = DistributedAPI(f=decoder_framework.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())
    response = ConnexionResponse(body=data["message"], mimetype='application/xml')

    return response
Пример #10
0
async def get_stats_remoted(request, pretty=False, wait_for_complete=False):
    """Get manager's or local_node's remoted stats.

    :param pretty: Show results in human-readable format
    :param wait_for_complete: Disable timeout response
    """
    f_kwargs = {'filename': common.remoted_stats}

    dapi = DistributedAPI(
        f=stats.get_daemons_stats,
        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())
    response = Data(data)

    return web.json_response(data=response,
                             status=200,
                             dumps=prettify if pretty else dumps)
Пример #11
0
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)
Пример #12
0
async def get_hotfixes_info(request, pretty=False, wait_for_complete=False, agents_list='*', offset=0, limit=None,
                            sort=None, search=None, select=None, hotfix=None):
    """ Get hotfixes info from all agents or a list of them.

    :param pretty: Show results in human-readable format
    :param wait_for_complete: Disable timeout response
    :param agents_list: List of agent's IDs.
    :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 select: Select which fields to return (separated by comma)
    :param hotfix: Filters by hotfix in Windows agents
    :return:AllItemsResponseSyscollectorHotfixes
    """
    filters = {'hotfix': hotfix}

    f_kwargs = {'agent_list': agents_list,
                'offset': offset,
                'limit': limit,
                'select': select,
                'sort': parse_api_param(sort, 'sort'),
                'search': parse_api_param(search, 'search'),
                'filters': filters,
                'element_type': 'hotfixes'}

    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,
                          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)
Пример #13
0
async def create_user(request):
    """Create a new user.

    Parameters
    ----------
    request : connexion.request

    Returns
    -------
    User data
    """
    f_kwargs = await CreateUserModel.get_kwargs(request)
    dapi = DistributedAPI(
        f=security.create_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'])
    data = raise_if_exc(await dapi.distribute_function())

    return web.json_response(data=data, status=200, dumps=dumps)
Пример #14
0
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)
Пример #15
0
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)
Пример #16
0
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)
Пример #17
0
async def edit_run_as(request,
                      user_id: str,
                      allow_run_as: bool,
                      pretty=False,
                      wait_for_complete=False):
    """Modify the specified user' allow_run_as flag.

    Parameters
    ----------
    request : connexion.request
    user_id : str
        User ID of the user to be updated
    allow_run_as : bool
        Enable or disable authorization context login method for the specified user
    pretty : bool, optional
        Show results in human-readable format
    wait_for_complete : bool, optional
        Disable timeout response

    Returns
    -------
    User data
    """
    f_kwargs = {'user_id': user_id, 'allow_run_as': allow_run_as}

    dapi = DistributedAPI(
        f=security.edit_run_as,
        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)
Пример #18
0
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)
Пример #19
0
async def get_configuration(request, pretty=False, wait_for_complete=False, section=None, field=None):
    """Get manager's or local_node's configuration (ossec.conf)

    :param pretty: Show results in human-readable format
    :param wait_for_complete: Disable timeout response
    :param section: Indicates the wazuh configuration section
    :param field: Indicates a section child, e.g, fields for rule section are include, decoder_dir, etc.
    """
    f_kwargs = {'section': section,
                'field': field}

    dapi = DistributedAPI(f=manager.read_ossec_conf,
                          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)
Пример #20
0
async def get_manager_config_ondemand(request, component, pretty=False, wait_for_complete=False, **kwargs):
    """Get active configuration in manager or local_node for one component [on demand]

    :param pretty: Show results in human-readable format
    :param wait_for_complete: Disable timeout response
    :param component: Specified component.
    """
    f_kwargs = {'component': component,
                'config': kwargs.get('configuration', None)
                }

    dapi = DistributedAPI(f=manager.get_config,
                          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)
Пример #21
0
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 = raise_if_exc(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
                          )
    data = raise_if_exc(await dapi.distribute_function())

    return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)
Пример #22
0
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)
Пример #23
0
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)
Пример #24
0
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)
Пример #25
0
async def revoke_all_tokens(request, pretty: bool = False):
    """Revoke all tokens

    Parameters
    ----------
    pretty : bool, optional
        Show results in human-readable format

    Returns
    -------
    dict
        Status message
    """
    f_kwargs = {}

    nodes = await get_system_nodes()
    if isinstance(nodes, Exception):
        nodes = None

    dapi = DistributedAPI(
        f=security.wrapper_revoke_tokens,
        f_kwargs=remove_nones_to_dict(f_kwargs),
        request_type='distributed_master'
        if nodes is not None else 'local_any',
        is_async=False,
        broadcasting=nodes is not None,
        wait_for_complete=True,
        logger=logger,
        rbac_permissions=request['token_info']['rbac_policies'],
        nodes=nodes)
    data = raise_if_exc(await dapi.distribute_function())
    if type(data) == AffectedItemsWazuhResult and len(
            data.affected_items) == 0:
        raise_if_exc(WazuhPermissionError(4000, data.message))

    return web.json_response(data=data,
                             status=200,
                             dumps=prettify if pretty else dumps)
Пример #26
0
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)
Пример #27
0
async def set_role_rule(request,
                        role_id,
                        rule_ids,
                        pretty=False,
                        wait_for_complete=False):
    """Add a list of rules to one specified role.

    Parameters
    ----------
    role_id : int
        Role ID
    rule_ids : list of int
        List of rule IDs
    pretty : bool
        Show results in human-readable format
    wait_for_complete : bool
        Disable timeout response

    Returns
    -------
    dict
        Role information
    """
    f_kwargs = {'role_id': role_id, 'rule_ids': rule_ids}

    dapi = DistributedAPI(
        f=security.set_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)
Пример #28
0
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 update_configuration(request,
                               node_id,
                               body,
                               pretty=False,
                               wait_for_complete=False):
    """Update Wazuh configuration (ossec.conf) in node node_id.

    Parameters
    ----------
    pretty : bool, optional
        Show results in human-readable format. It only works when `raw` is False (JSON format). Default `True`
    wait_for_complete : bool, optional
        Disable response timeout or not. Default `False`
    """
    # 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 = {'node_id': node_id, 'new_conf': parsed_body}

    nodes = raise_if_exc(await get_system_nodes())
    dapi = DistributedAPI(
        f=manager.update_ossec_conf,
        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)
    data = raise_if_exc(await dapi.distribute_function())

    return web.json_response(data=data,
                             status=200,
                             dumps=prettify if pretty else dumps)
Пример #30
0
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)