Beispiel #1
0
async def get_tasks_status(request,
                           pretty=False,
                           wait_for_complete=False,
                           offset=0,
                           limit=database_limit,
                           tasks_list=None,
                           agents_list=None,
                           command=None,
                           node=None,
                           module=None,
                           status=None,
                           q=None,
                           search=None,
                           select=None,
                           sort=None):
    """Check the status of the specified tasks

    Parameters
    ----------
    tasks_list : list
        List of task's IDs
    pretty : bool, optional
        Show results in human-readable format
    wait_for_complete : bool, optional
        Disable timeout response

    Returns
    -------
    Tasks's status
    """
    f_kwargs = {
        'select': select,
        'search': parse_api_param(search, 'search'),
        'offset': offset,
        'limit': limit,
        'filters': {
            'task_list': tasks_list,
            'agent_list': agents_list,
            'status': status,
            'module': module,
            'command': command,
            'node': node
        },
        'sort': parse_api_param(sort, 'sort'),
        'q': q
    }

    dapi = DistributedAPI(
        f=get_task_status,
        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)
Beispiel #2
0
async def get_group_files(request, group_id, pretty=False, wait_for_complete=False, offset=0, limit=None, sort=None,
                          search=None):
    """Get the files placed under the group directory

    :param pretty: Show results in human-readable format
    :param wait_for_complete: Disable timeout response
    :param group_id: Group ID.
    :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
    :return: GroupFile
    """
    hash_ = request.query.get('hash', 'md5')  # Select algorithm to generate the returned checksums.
    f_kwargs = {'group_list': [group_id],
                '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,
                'hash_algorithm': hash_}

    dapi = DistributedAPI(f=agent.get_group_files,
                          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)
Beispiel #3
0
async def get_agent_outdated(request, pretty=False, wait_for_complete=False, offset=0, limit=database_limit, sort=None,
                             search=None, q=None):
    """Get outdated agents.

    :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 q: Query to filter results by. For example q="status=active"
    :return: AllItemsResponseAgentsSimple
    """
    f_kwargs = {'offset': offset,
                'limit': limit,
                'sort': parse_api_param(sort, 'sort'),
                'search': parse_api_param(search, 'search'),
                'q': q}

    dapi = DistributedAPI(f=agent.get_outdated_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)
Beispiel #4
0
async def get_list_group(request, pretty=False, wait_for_complete=False, groups_list=None, offset=0, limit=None,
                         sort=None, search=None):
    """Get groups.

    Returns a list containing basic information about each agent group such as number of agents belonging to the group
    and the checksums of the configuration and shared files.

    :param pretty: Show results in human-readable format
    :param wait_for_complete: Disable timeout response
    :param groups_list: Array of group'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
    :return: AllItemsResponseGroups
    """
    hash_ = request.query.get('hash', 'md5')  # Select algorithm to generate the returned checksums.
    f_kwargs = {'offset': offset,
                'limit': limit,
                'group_list': groups_list,
                'sort': parse_api_param(sort, 'sort'),
                'search': parse_api_param(search, 'search'),
                'hash_algorithm': hash_}
    dapi = DistributedAPI(f=agent.get_agent_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)
Beispiel #5
0
async def get_rules_groups(request, pretty=False, wait_for_complete=False, offset=0, limit=None, sort=None,
                           search=None):
    """Get all rule groups names.

    :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
    :return: Data object
    """
    f_kwargs = {'offset': offset,
                'limit': limit,
                'sort_by': parse_api_param(sort, 'sort')['fields'] if sort is not None else [''],
                '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,
                }

    dapi = DistributedAPI(f=rule_framework.get_groups,
                          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)
Beispiel #6
0
async def get_syscheck_agent(request, agent_id, pretty=False, wait_for_complete=False, offset=0,
                             limit=None, select=None, sort=None, search=None, distinct=False,
                             summary=False, md5=None, sha1=None, sha256=None, q=None):

    """
    :param agent_id: Agent ID
    :type agent_id: str
    :param pretty: Show results in human-readable format 
    :type pretty: bool
    :param wait_for_complete: Disable timeout response 
    :type wait_for_complete: bool
    :param offset: First element to return in the collection
    :type offset: int
    :param limit: Maximum number of elements to return
    :type limit: int
    :param select: Select which fields to return (separated by comma)
    :type select: List[str]
    :param sort: Sorts the collection by a field or fields (separated by comma). Use +/- at the beginning to list in ascending or descending order. 
    :type sort: str
    :param search: Looks for elements with the specified string
    :type search: str
    :param summary: Returns a summary grouping by filename.
    :type summary: bool
    :param md5: Filters files with the specified MD5 checksum.
    :type md5: str
    :param sha1: Filters files with the specified SHA1 checksum.
    :type sha1: str
    :param sha256: Filters files with the specified SHA256 checksum.
    :type sha256: str
    :param distinct: Look for distinct values.
    :type distinct: bool
    :param q: Query to filter results by.
    :type q: str
    """

    # get type parameter from query
    type_ = request.query.get('type', None)
    # get hash parameter from query
    hash_ = request.query.get('hash', None)
    # get file parameter from query
    file_ = request.query.get('file', None)

    filters = {'type': type_, 'md5': md5, 'sha1': sha1,
               'sha256': sha256, 'hash': hash_, 'file': file_}

    f_kwargs = {'agent_list': [agent_id], 'offset': offset, 'limit': limit,
                'select': select, 'sort': parse_api_param(sort, 'sort'), 'search': parse_api_param(search, 'search'),
                'summary': summary, 'filters': filters, 'distinct': distinct, 'q': q}

    dapi = DistributedAPI(f=files,
                          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)
Beispiel #7
0
async def get_network_protocol_info(request,
                                    agent_id,
                                    pretty=False,
                                    wait_for_complete=False,
                                    offset=0,
                                    limit=None,
                                    select=None,
                                    sort=None,
                                    search=None,
                                    iface=None,
                                    gateway=None,
                                    dhcp=None):
    """ Get network protocol 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 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 iface: Filters by iface
    :param gateway: Filters by gateway
    :param dhcp: Filters by dhcp
    :return: Data
    """
    filters = {
        'iface': iface,
        'type': request.query.get('type', None),
        'gateway': gateway,
        'dhcp': dhcp
    }

    f_kwargs = {
        'agent_list': [agent_id],
        'offset': offset,
        'limit': limit,
        'select': select,
        'sort': parse_api_param(sort, 'sort'),
        'search': parse_api_param(search, 'search'),
        'filters': filters,
        'element_type': 'netproto'
    }

    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 get_sca_agent(request,
                        agent_id=None,
                        pretty=False,
                        wait_for_complete=False,
                        name=None,
                        description=None,
                        references=None,
                        offset=0,
                        limit=database_limit,
                        sort=None,
                        search=None,
                        q=None):
    """Get security configuration assessment (SCA) database of an agent

    :param agent_id: Agent ID. All possible values since 000 onwards.
    :param pretty: Show results in human-readable format
    :param wait_for_complete: Disable timeout response
    :param name: Filters by policy name
    :param description: Filters by policy description
    :param references: Filters by references
    :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 q: Query to filter results by. This is specially useful to filter by total checks passed, failed or total
    score (fields pass, fail, score)
    :return: AllItemsResponseSCADatabase
    """
    filters = {
        'name': name,
        'description': description,
        'references': references
    }

    f_kwargs = {
        'agent_list': [agent_id],
        'offset': offset,
        'limit': limit,
        'sort': parse_api_param(sort, 'sort'),
        'search': parse_api_param(search, 'search'),
        'q': q,
        'filters': filters
    }

    dapi = DistributedAPI(
        f=sca.get_sca_list,
        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)
Beispiel #9
0
async def get_rules(request, rule_ids=None, pretty=False, wait_for_complete=False, offset=0, select=None,
                    limit=None, sort=None, search=None, q=None, status=None, group=None, level=None, filename=None,
                    relative_dirname=None, pci_dss=None, gdpr=None, gpg13=None, hipaa=None, tsc=None, mitre=None):
    """Get information about all Wazuh rules.

    :param rule_ids: Filters by rule ID
    :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 select: List of selected fields to return
    :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 q: Query to filter results by. For example q="status=active"
    :param status: Filters by rules status.
    :param group: Filters by rule group.
    :param level: Filters by rule level. Can be a single level (4) or an interval (2-4)
    :param filename: List of filenames to filter by.
    :param relative_dirname: Filters by relative dirname.
    :param pci_dss: Filters by PCI_DSS requirement name.
    :param gdpr: Filters by GDPR requirement.
    :param gpg13: Filters by GPG13 requirement.
    :param hipaa: Filters by HIPAA requirement.
    :param tsc: Filters by TSC requirement.
    :param mitre: Filters by mitre attack ID.
    :return: Data object
    """
    f_kwargs = {'rule_ids': rule_ids, 'offset': offset, 'limit': limit, 'select': select,
                'sort_by': parse_api_param(sort, 'sort')['fields'] if sort is not None else ['id'],
                '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,
                'q': q,
                'status': status,
                'group': group,
                'level': level,
                'filename': filename,
                'relative_dirname': relative_dirname,
                'pci_dss': pci_dss,
                'gdpr': gdpr,
                'gpg13': gpg13,
                'hipaa': hipaa,
                'nist_800_53': request.query.get('nist-800-53', None),
                'tsc': tsc,
                'mitre': mitre}

    dapi = DistributedAPI(f=rule_framework.get_rules,
                          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)
Beispiel #10
0
async def get_log(request,
                  pretty=False,
                  wait_for_complete=False,
                  offset=0,
                  limit=None,
                  sort=None,
                  search=None,
                  category=None,
                  type_log=None):
    """Get manager's or local_node's last 2000 wazuh log entries.

    :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 category: Filter by category of log.
    :param type_log: Filters by log level.
    """
    f_kwargs = {
        'offset':
        offset,
        'limit':
        limit,
        'sort_by':
        parse_api_param(sort, 'sort')['fields']
        if sort is not None else ['timestamp'],
        'sort_ascending':
        False if sort is None
        or parse_api_param(sort, 'sort')['order'] == 'desc' else True,
        '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,
        'category':
        category,
        'type_log':
        type_log
    }

    dapi = DistributedAPI(
        f=manager.ossec_log,
        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)
Beispiel #11
0
async def get_agents_ciscat_results(request, agent_id: str, pretty: bool = False, wait_for_complete: bool = False,
                                    offset: int = 0, limit: int = None, select: List[str] = None, sort: str = None,
                                    search: str = None, benchmark: str = None, profile: str = None, fail: int = None,
                                    error: int = None, notchecked: int = None, unknown: int = None, score: int = None):
    """Get CIS-CAT results from an agent

    Returns the agent's ciscat results info.

    :param agent_id: Agent ID. All posible values since 000 onwards.
    :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: 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 benchmark: Filters by benchmark type.
    :param profile: Filters by evaluated profile.
    :param fail: Filters by failed checks
    :param error: Filters by encountered errors
    :param notchecked: Filters by not checked
    :param unknown: Filters by unknown results.
    :param score: Filters by final score
    :return: Data
    """
    f_kwargs = {
        'agent_list': [agent_id],
        'offset': offset,
        'limit': limit,
        'sort': parse_api_param(sort, 'sort'),
        'search': parse_api_param(search, 'search'),
        'select': select,
        'filters': {
            'benchmark': benchmark,
            'profile': profile,
            'pass': request.query.get('pass', None),
            'fail': fail,
            'error': error,
            'notchecked': notchecked,
            'unknown': unknown,
            'score': score
                }
            }

    dapi = DistributedAPI(f=ciscat.get_ciscat_results,
                          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']
                          )
    response = raise_if_exc(await dapi.distribute_function())

    return web.json_response(data=response, status=200, dumps=prettify if pretty else dumps)
Beispiel #12
0
async def get_ports_info(request, pretty=False, wait_for_complete=False, agents_list='*', offset=0, limit=None,
                         select=None, sort=None, search=None, pid=None, protocol=None, tx_queue=None, state=None,
                         process=None):
    """ Get ports 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 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 pid: Filters by pid
    :param protocol: Filters by protocol
    :param tx_queue: Filters by tx_queue
    :param state: Filters by state
    :param process: Filters by process
    :return: AllItemsResponseSyscollectorPorts
    """
    filters = {
        'pid': pid,
        'protocol': protocol,
        'tx_queue': tx_queue,
        'state': state,
        'process': process
    }
    # Add nested fields to kwargs filters
    nested = ['local.ip', 'local.port', 'remote.ip']
    for field in nested:
        filters[field] = request.query.get(field, None)

    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': 'ports'
                }

    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)
async def get_hotfix_info(request,
                          agent_id,
                          pretty=False,
                          wait_for_complete=False,
                          offset=0,
                          limit=None,
                          sort=None,
                          search=None,
                          select=None,
                          hotfix=None,
                          q=None):
    """ Get info about an agent's hotfixes

    :param agent_id: Agent ID
    :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 hotfix: Filters by hotfix in Windows agents
    :param q: Query to filter results by.
    :return:
    """

    filters = {'hotfix': hotfix}

    f_kwargs = {
        'agent_list': [agent_id],
        'offset': offset,
        'limit': limit,
        'select': select,
        'sort': parse_api_param(sort, 'sort'),
        'search': parse_api_param(search, 'search'),
        'filters': filters,
        'element_type': 'hotfixes',
        'q': q
    }

    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 get_hardware_info(request,
                            pretty=False,
                            wait_for_complete=False,
                            list_agents='*',
                            offset=0,
                            limit=None,
                            select=None,
                            sort=None,
                            search=None,
                            board_serial=None):
    """ Get hardware 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 list_agents: List of agent's IDs.
    :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 board_serial: Filters by board_serial
    :return: AllItemsResponseSyscollectorHardware
    """
    filters = {'board_serial': board_serial}
    # Add nested fields to kwargs filters
    nested = ['ram.free', 'ram.total', 'cpu.cores', 'cpu.mhz', 'cpu.name']
    for field in nested:
        filters[field] = request.query.get(field, None)
    f_kwargs = {
        'agent_list': list_agents,
        'offset': offset,
        'limit': limit,
        'select': select,
        'sort': parse_api_param(sort, 'sort'),
        'search': parse_api_param(search, 'search'),
        'filters': filters,
        '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,
        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)
Beispiel #15
0
async def get_cis_cat_results(request, pretty=False, wait_for_complete=False, agents_list='*', offset=0, limit=None,
                              select=None, sort=None, search=None, benchmark=None, profile=None, fail=None, error=None,
                              notchecked=None, unknown=None, score=None):
    """ Get ciscat results 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 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 benchmark: Filters by benchmark
    :param profile: Filters by evaluated profile
    :param fail: Filters by failed checks
    :param error: Filters by encountered errors
    :param notchecked: Filters by not checked
    :param unknown: Filters by unknown results.
    :param score: Filters by final score
    :return: AllItemsResponseCiscatResult
    """
    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': {
                    'benchmark': benchmark,
                    'profile': profile,
                    'fail': fail,
                    'error': error,
                    'notchecked': notchecked,
                    'unknown': unknown,
                    'score': score,
                    'pass': request.query.get('pass', None)
                }
                }

    dapi = DistributedAPI(f=ciscat.get_ciscat_results,
                          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)
Beispiel #16
0
async def get_cluster_nodes(request,
                            pretty=False,
                            wait_for_complete=False,
                            offset=0,
                            limit=None,
                            sort=None,
                            search=None,
                            select=None,
                            nodes_list=None,
                            q=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 nodes_list: List of node ids
    :param q: Query to filter results by.
    """
    # Get type parameter from query
    type_ = request.query.get('type', 'all')

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

    nodes = raise_if_exc(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)
    data = raise_if_exc(await dapi.distribute_function())

    return web.json_response(data=data,
                             status=200,
                             dumps=prettify if pretty else dumps)
Beispiel #17
0
async def get_network_interface_info(request, pretty=False, wait_for_complete=False, agents_list='*', offset=0,
                                     limit=None, select=None, sort=None, search=None, adapter=None, state=None,
                                     mtu=None):
    """ Get all network interfaces 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 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 adapter: Filters by adapter
    :param state: Filters by state
    :param mtu: Filters by mtu
    :return: AllItemsResponseSyscollectorInterface
    """
    filters = {
        'adapter': adapter,
        'type': request.query.get('type', None),
        'state': state,
        'mtu': mtu
    }
    # Add nested fields to kwargs filters
    nested = ['tx.packets', 'rx.packets', 'tx.bytes', 'rx.bytes', 'tx.errors', 'rx.errors', 'tx.dropped', 'rx.dropped']
    for field in nested:
        filters[field] = request.query.get(field, None)

    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': 'netiface'
                }

    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)
Beispiel #18
0
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)
Beispiel #19
0
async def get_os_info(request, pretty=False, wait_for_complete=False, agents_list='*', offset=0, limit=None,
                      select=None, sort=None, search=None, os_name=None, architecture=None, os_version=None,
                      version=None, release=None):
    """ Get OS 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 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 os_name: Filters by os_name
    :param architecture: Filters by architecture
    :param os_version: Filters by os_version
    :param version: Filters by version
    :param release: Filters by release
    :return: AllItemsResponseSyscollectorOS
    """
    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': {
                    'os_name': os_name,
                    'architecture': architecture,
                    'os_version': os_version,
                    'version': version,
                    'release': release
                },
                'element_type': 'os'
                }

    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)
Beispiel #20
0
async def get_network_address_info(request, pretty=False, wait_for_complete=False, agents_list='*', offset=0,
                                   limit=None, select=None, sort=None, search=None, iface_name=None, proto=None,
                                   address=None, broadcast=None, netmask=None):
    """ Get the IPv4 and IPv6 addresses associated to all network interfaces

    :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 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 iface_name: Filters by interface name
    :param proto: Filters by IP protocol
    :param address: IP address associated with the network interface
    :param broadcast: Filters by broadcast direction
    :param netmask: Filters by netmask
    :return: AllItemsResponseSyscollectorNetwork
    """
    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': {
                    'iface_name': iface_name,
                    'proto': proto,
                    'address': address,
                    'broadcast': broadcast,
                    'netmask': netmask
                },
                'element_type': 'netaddr'
                }

    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)
Beispiel #21
0
        def wrapper(request):
            def coerce_dict(md):
                """ MultiDict -> dict of lists
                """
                try:
                    return md.to_dict(flat=False)
                except AttributeError:
                    return dict(md.items())

            # Raise exception if semicolon is used in q parameter
            if 'q' in request.query.keys():
                q = parse_api_param(request.url, 'q')
                if q:
                    if ';' in q:
                        raise_if_exc(APIError(code=2009))

            query = coerce_dict(request.query)
            path_params = coerce_dict(request.path_params)
            form = coerce_dict(request.form)

            request.query = self.resolve_query(query)
            request.path_params = self.resolve_path(path_params)
            request.form = self.resolve_form(form)
            response = function(request)
            return response
Beispiel #22
0
        def wrapper(request):
            def coerce_dict(md):
                """ MultiDict -> dict of lists
                """
                try:
                    return md.to_dict(flat=False)
                except AttributeError:
                    return dict(md.items())

            # Raise exception if semicolon is used in q parameter
            if 'q' in request.query.keys():
                q = parse_api_param(request.url, 'q')
                if q:
                    if ';' in q:
                        raise_if_exc(APIError(code=2009))

            # Transform to lowercase the values for query parameter's spec.yaml enums
            lower_fields = ['component', 'configuration', 'hash', 'requirement', 'status', 'type', 'section', 'tag',
                            'level', 'resource']
            request.query.update(
                {k.lower(): [list_item.lower() for list_item in v] if isinstance(v, list) else v.lower()
                 for k, v in request.query.items() if k in lower_fields})

            query = coerce_dict(request.query)
            path_params = coerce_dict(request.path_params)
            form = coerce_dict(request.form)

            request.query = self.resolve_query(query)
            request.path_params = self.resolve_path(path_params)
            request.form = self.resolve_form(form)
            response = function(request)
            return response
Beispiel #23
0
async def get_decoders(request, decoder_names: list = None, pretty: bool = False, wait_for_complete: bool = False,
                       offset: int = 0, limit: int = None, select: list = None, sort: str = None, search: str = None,
                       q: str = None, filename: str = None, relative_dirname: str = None, status: str = None):
    """Get all decoders

    Returns information about all decoders included in ossec.conf. This information include decoder's route,
    decoder's name, decoder's file among others

    :param decoder_names: Filters by decoder name.
    :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
    :param q: Query to filter results by. For example q="status=active"
    :param filename: List of filenames to filter by.
    :param relative_dirname: Filters by relative dirname.
    :param status: Filters by list status.
    :return: Data object
    """
    f_kwargs = {'names': decoder_names,
                '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,
                'q': q,
                'filename': filename,
                'status': status,
                'relative_dirname': relative_dirname}

    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)
Beispiel #24
0
async def get_policies(request, policy_ids: list = None, pretty: bool = False, wait_for_complete: bool = False,
                       offset: int = 0, limit: int = None, search: str = None, select: str = None, sort: str = None):
    """Returns information from all system policies.

    Parameters
    ----------
    request : connexion.request
    policy_ids : list, optional
        List of policies
    pretty : bool, optional
        Show results in human-readable format
    wait_for_complete : bool, optional
        Disable timeout response
    offset : int, optional
        First item to return
    limit : int, optional
        Maximum number of items to return
    search : str, optional
        Looks for elements with the specified string
    select : str
        Select which fields to return (separated by comma)
    sort : str, optional
        Sorts the collection by a field or fields (separated by comma). Use +/- at the beginning to list in
        ascending or descending order

    Returns
    -------
    Policies information
    """
    f_kwargs = {'policy_ids': policy_ids, 'offset': offset, 'limit': limit, 'select': select,
                'sort_by': parse_api_param(sort, 'sort')['fields'] if sort is not None else ['id'],
                '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
                }

    dapi = DistributedAPI(f=security.get_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)
Beispiel #25
0
async def get_log_node(request, node_id, pretty=False, wait_for_complete=False, offset=0, limit=None, sort=None,
                       search=None, tag=None, level=None, q=None):
    """Get a specified node's wazuh logs.

    Returns the last 2000 wazuh log entries in node {node_id}.

    :param node_id: Cluster node name.
    :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 tag: Filter by category/tag of log.
    :param level: Filters by log level.
    :param q: Query to filter results by.
    """
    f_kwargs = {'node_id': node_id,
                'offset': offset,
                'limit': limit,
                'sort_by': parse_api_param(sort, 'sort')['fields'] if sort is not None else ['timestamp'],
                'sort_ascending': False if sort is None or parse_api_param(sort, 'sort')['order'] == 'desc' else True,
                '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,
                'tag': tag,
                'level': level,
                'q': q}

    nodes = raise_if_exc(await get_system_nodes())
    dapi = DistributedAPI(f=manager.ossec_log,
                          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)
Beispiel #26
0
async def get_lists(request, pretty: bool = False, wait_for_complete: bool = False, offset: int = 0, limit: int = None,
                    select: list = None, sort: str = None, search: str = None, filename: str = None,
                    relative_dirname: str = None):
    """ Get all CDB lists

    :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.
    :param filename: List of filenames to filter by.
    :param relative_dirname: Filters by relative dirname
    :return: Data object
    """
    path = [os.path.join(relative_dirname, item) for item in filename] if filename and relative_dirname else None
    f_kwargs = {'offset': offset,
                'select': select,
                'limit': limit,
                'sort_by': parse_api_param(sort, 'sort')['fields'] if sort is not None else ['relative_dirname',
                                                                                             '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,
                'filename': filename,
                'relative_dirname': relative_dirname,
                'path': path
                }

    dapi = DistributedAPI(f=cdb_list.get_lists,
                          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)
Beispiel #27
0
def test_get_ciscat_results_search(agents_info_mock, socket_mock, search,
                                   total_expected_items):
    """Check if the number of items returned is as expected when using the search parameter.

    Parameters
    ----------
    search : str
        String to be searched in the database.
    total_expected_items : int
        Number of expected items to be returned.
    """
    with patch('wazuh.core.utils.WazuhDBConnection') as mock_wdb:
        mock_wdb.return_value = InitWDBSocketMock(sql_schema_file=db_file)
        result = get_ciscat_results(agent_list=['001'],
                                    search=parse_api_param(
                                        search, 'search')).render()['data']
        assert result['total_affected_items'] == total_expected_items
Beispiel #28
0
def test_get_ciscat_results_sort(agents_info_mock, socket_mock, sort,
                                 first_item):
    """Check if the the first item returned is expected when using sort parameter

    Parameters
    ----------
    sort : str
        Field and order to sort by
    first_item : int
        Expected string to be contained in the log of the first returned element.
    """
    with patch('wazuh.core.utils.WazuhDBConnection') as mock_wdb:
        mock_wdb.return_value = InitWDBSocketMock(sql_schema_file=db_file)
        result = get_ciscat_results(agent_list=['001'],
                                    sort=parse_api_param(
                                        sort, 'sort')).render()['data']
        assert result['affected_items'][0]['scan']['id'] == first_item
def test_get_rootcheck_agent_search(mock_connect, mock_send, mock_info, search,
                                    total_expected_items):
    """Checks if the number of items returned is as expected when using the search parameter.

    Parameters
    ----------
    search : str
        String to be searched in the database.
    total_expected_items : int
        Number of expected items to be returned.
    """
    result = rootcheck.get_rootcheck_agent(agent_list=['001'],
                                           search=parse_api_param(
                                               search, 'search'),
                                           filters={
                                               'status': 'all'
                                           }).render()['data']
    assert result['total_affected_items'] == total_expected_items
def test_get_rootcheck_agent_sort(mock_connect, mock_send, mock_info, sort,
                                  first_item):
    """Checks if the the first item returned is expected when using sort parameter

    Parameters
    ----------
    sort : str
        Field and order to sort by
    first_item : int
        Expected string to be contained in the log of the first returned element.
    """
    result = rootcheck.get_rootcheck_agent(agent_list=['001'],
                                           sort=parse_api_param(sort, 'sort'),
                                           filters={
                                               'status': 'all'
                                           }).render()['data']

    assert first_item in result['affected_items'][0]['log']