Example #1
0
def remove_user_role(user_id, role_ids):
    """Create a relationship between a user and a role

    :param user_id: User id
    :param role_ids: List of role ids
    :return User-Roles information
    """
    username = get_username(user_id=user_id)
    result = AffectedItemsWazuhResult(
        none_msg=f'No role was unlinked from user {username}',
        some_msg=f'Some roles were not unlinked from user {username}',
        all_msg=f'All roles were unlinked from user {username}')
    success = False
    with UserRolesManager() as urm:
        for role_id in role_ids:
            user_role = urm.remove_role_in_user(user_id=int(user_id[0]),
                                                role_id=role_id)
            if user_role == SecurityError.INVALID:
                result.add_failed_item(id_=int(role_id),
                                       error=WazuhError(4016))
            elif user_role == SecurityError.ROLE_NOT_EXIST:
                result.add_failed_item(id_=int(role_id),
                                       error=WazuhError(4002))
            elif user_role == SecurityError.USER_NOT_EXIST:
                result.add_failed_item(id_=int(user_id[0]),
                                       error=WazuhError(5001))
                break
            elif user_role == SecurityError.ADMIN_RESOURCES:
                result.add_failed_item(id_=int(user_id[0]),
                                       error=WazuhError(4008))
            else:
                success = True
                result.total_affected_items += 1
        if success:
            with AuthenticationManager() as auth:
                result.affected_items.append(auth.get_user_id(int(user_id[0])))
            result.affected_items.sort(key=str)
            invalid_users_tokens(users=user_id)

    return result
Example #2
0
def clear(agent_list=None):
    """Clear the rootcheck database for a list of agents.

    Parameters
    ----------
    agent_list : list
        List of agent ids.

    Returns
    -------
    result : AffectedItemsWazuhResult
        JSON containing the affected agents.
    """
    result = AffectedItemsWazuhResult(
        all_msg='Rootcheck database was cleared on returned agents',
        some_msg='Rootcheck database was not cleared on some agents',
        none_msg="No rootcheck database was cleared")

    wdb_conn = WazuhDBConnection()
    system_agents = get_agents_info()
    agent_list = set(agent_list)
    not_found_agents = agent_list - system_agents
    # Add non existent agents to failed_items
    [
        result.add_failed_item(id_=agent_id, error=WazuhResourceNotFound(1701))
        for agent_id in not_found_agents
    ]

    eligible_agents = agent_list - not_found_agents
    for agent_id in eligible_agents:
        try:
            wdb_conn.execute(f"agent {agent_id} rootcheck delete", delete=True)
            result.affected_items.append(agent_id)
        except WazuhError as e:
            result.add_failed_item(id_=agent_id, error=e)

    result.affected_items.sort(key=int)
    result.total_affected_items = len(result.affected_items)

    return result
Example #3
0
def test_DistributedAPI_tmp_file_cluster_error(mock_cluster_status):
    """Test the behaviour when an error raises with temporal files function."""
    open('/tmp/dapi_file.txt', 'a').close()
    with patch('wazuh.core.cluster.cluster.get_node',
               return_value={
                   'type': 'master',
                   'node': 'unknown'
               }):
        with patch('wazuh.core.cluster.dapi.dapi.get_node_wrapper',
                   return_value=AffectedItemsWazuhResult(
                       affected_items=[{
                           'type': 'master',
                           'node': 'unknown'
                       }])):
            with patch('wazuh.core.cluster.local_client.LocalClient.execute',
                       new=AsyncMock(side_effect=WazuhClusterError(3022))):
                dapi_kwargs = {
                    'f': manager.status,
                    'logger': logger,
                    'request_type': 'distributed_master',
                    'f_kwargs': {
                        'tmp_file': '/tmp/dapi_file.txt'
                    }
                }
                raise_if_exc_routine(dapi_kwargs=dapi_kwargs,
                                     expected_error=3022)

            open('/tmp/dapi_file.txt', 'a').close()
            with patch('wazuh.core.cluster.local_client.LocalClient.execute',
                       new=AsyncMock(side_effect=WazuhClusterError(1000))):
                dapi_kwargs = {
                    'f': manager.status,
                    'logger': logger,
                    'request_type': 'distributed_master',
                    'f_kwargs': {
                        'tmp_file': '/tmp/dapi_file.txt'
                    }
                }
                raise_if_exc_routine(dapi_kwargs=dapi_kwargs,
                                     expected_error=1000)
Example #4
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_list': [group_id], 'select': ['id']}

    dapi = DistributedAPI(f=agent.get_agents_in_group,
                          f_kwargs=remove_nones_to_dict(f_kwargs),
                          request_type='local_master',
                          is_async=False,
                          wait_for_complete=wait_for_complete,
                          logger=logger,
                          rbac_permissions=request['token_info']['rbac_policies']
                          )

    agents = raise_if_exc(await dapi.distribute_function())
    agent_list = [a['id'] for a in agents.affected_items]

    if not agent_list:
        data = AffectedItemsWazuhResult(none_msg='Restart command was not sent to any agent')
        return web.json_response(data=data, status=200, dumps=prettify if pretty else dumps)

    f_kwargs = {'agent_list': agent_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,
                          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)
Example #5
0
def remove_users(user_ids):
    """Remove a specified list of users

    Parameters
    ----------
    user_ids : list
        List of IDs

    Returns
    -------
    Status message
    """
    result = AffectedItemsWazuhResult(
        none_msg='No user was deleted',
        some_msg='Some users were not deleted',
        all_msg='Users were successfully deleted')
    with AuthenticationManager() as auth:
        for user_id in user_ids:
            user_id = int(user_id)
            current_user = auth.get_user(common.current_user.get())
            if not isinstance(current_user, bool) and user_id == int(
                    current_user['id']) and user_id > max_id_reserved:
                result.add_failed_item(id_=user_id, error=WazuhError(5008))
                continue
            user = auth.get_user_id(user_id)
            query = auth.delete_user(user_id)
            if not query:
                result.add_failed_item(id_=user_id, error=WazuhError(5001))
            elif query == SecurityError.ADMIN_RESOURCES:
                result.add_failed_item(id_=user_id, error=WazuhError(5004))
            elif query == SecurityError.RELATIONSHIP_ERROR:
                result.add_failed_item(id_=user_id, error=WazuhError(4025))
            elif user:
                with TokenManager() as tm:
                    tm.add_user_roles_rules(users={user_id})
                result.affected_items.append(user)
                result.total_affected_items += 1

        result.affected_items.sort(key=str)
    return result
Example #6
0
def read_ossec_conf(section=None, field=None):
    """ Wrapper for get_ossec_conf

    :param section: Filters by section (i.e. rules).
    :param field: Filters by field in section (i.e. included).
    :return: AffectedItemsWazuhResult.
    """
    result = AffectedItemsWazuhResult(
        all_msg=f"Configuration was successfully read"
        f"{' in specified node' if node_id != 'manager' else ''}",
        some_msg='Could not read configuration in some nodes',
        none_msg=f"Could not read configuration"
        f"{' in specified node' if node_id != 'manager' else ''}")

    try:
        result.affected_items.append(
            get_ossec_conf(section=section, field=field))
    except WazuhError as e:
        result.add_failed_item(id_=node_id, error=e)
    result.total_affected_items = len(result.affected_items)

    return result
Example #7
0
def get_agents_sync_group(agent_list=None):
    """Get agents configuration sync status.

    :param agent_list: List of agents ID's.
    :return AffectedItemsWazuhResult.
    """
    result = AffectedItemsWazuhResult(all_msg='Sync info was returned for all selected agents',
                                      some_msg='Sync info was not returned for some selected agents',
                                      none_msg='No sync info was returned',
                                      )

    system_agents = get_agents_info()
    for agent_id in agent_list:
        try:
            if agent_id == "000":
                raise WazuhError(1703)
            if agent_id not in system_agents:
                raise WazuhResourceNotFound(1701)
            else:
                # Check if agent exists and it is active
                agent_info = Agent(agent_id).get_basic_information()
                # Check if it has a multigroup
                if len(agent_info['group']) > 1:
                    multi_group = ','.join(agent_info['group'])
                    multi_group = hashlib.sha256(multi_group.encode()).hexdigest()[:8]
                    group_merged_path = path.join(common.multi_groups_path, multi_group, "merged.mg")
                else:
                    group_merged_path = path.join(common.shared_path, agent_info['group'][0], "merged.mg")
                result.affected_items.append({'id': agent_id,
                                              'synced': md5(group_merged_path) == agent_info['mergedSum']})
        except (IOError, KeyError):
            # The file couldn't be opened and therefore the group has not been synced
            result.affected_items.append({'id': agent_id, 'synced': False})
        except WazuhException as e:
            result.add_failed_item(id_=agent_id, error=e)

    result.total_affected_items = len(result.affected_items)

    return result
Example #8
0
def totals(date):
    """Retrieve statistical information for the current or specified date.

    Parameters
    ----------
    date: date
        Date object with the date value of the stats.

    Returns
    -------
    AffectedItemsWazuhResult
        Array of dictionaries. Each dictionary represents an hour.
    """
    result = AffectedItemsWazuhResult(
        all_msg='Statistical information for each node was successfully read',
        some_msg='Could not read statistical information for some nodes',
        none_msg='Could not read statistical information for any node')
    affected = totals_(date)
    result.affected_items = affected
    result.total_affected_items = len(result.affected_items)

    return result
Example #9
0
def files(agent_list=None, offset=0, limit=common.database_limit, sort=None, search=None, select=None, filters=None,
          q='', summary=False, distinct=False):
    """Return a list of files from the database that match the filters

    :param agent_list: Agent ID.
    :param filters: Fields to filter by
    :param summary: Returns a summary grouping by filename.
    :param offset: First item to return.
    :param limit: Maximum number of items to return.
    :param sort: Sorts the items. Format: {"fields":["field1","field2"],"order":"asc|desc"}.
    :param search: Looks for items with the specified string.
    :param select: Select fields to return. Format: ["field1","field2"].
    :param q: Query to filter by
    :param distinct: Look for distinct values
    :return: AffectedItemsWazuhResult.
    """
    if filters is None:
        filters = {}
    parameters = {"date": "date", "mtime": "mtime", "file": "file", "size": "size", "perm": "perm", "uname": "uname",
                  "gname": "gname", "md5": "md5", "sha1": "sha1", "sha256": "sha256", "inode": "inode", "gid": "gid",
                  "uid": "uid", "type": "type", "changes": "changes", "attributes": "attributes"}
    summary_parameters = {"date": "date", "mtime": "mtime", "file": "file"}
    result = AffectedItemsWazuhResult(all_msg='FIM findings of the agent were returned',
                                      none_msg='No FIM information was returned')

    if 'hash' in filters:
        q = f'(md5={filters["hash"]},sha1={filters["hash"]},sha256={filters["hash"]})' + ('' if not q else ';' + q)
        del filters['hash']

    db_query = WazuhDBQuerySyscheck(agent_id=agent_list[0], offset=offset, limit=limit, sort=sort, search=search,
                                    filters=filters, query=q, select=select, table='fim_entry', distinct=distinct,
                                    fields=summary_parameters if summary else parameters)

    db_query = db_query.run()

    result.affected_items = db_query['items']
    result.total_affected_items = db_query['totalItems']

    return result
Example #10
0
def add_policy(name=None, policy=None):
    """Creates a policy in the system

    :param name: The new policy name
    :param policy: The new policy
    :return Policy information
    """
    result = AffectedItemsWazuhResult(
        none_msg='Policy was not created',
        all_msg='Policy was successfully created')
    sanitize_rbac_policy(policy)
    with PoliciesManager() as pm:
        status = pm.add_policy(name=name, policy=policy)
        if status == SecurityError.ALREADY_EXIST:
            result.add_failed_item(id_=name, error=WazuhError(4009))
        elif status == SecurityError.INVALID:
            result.add_failed_item(id_=name, error=WazuhError(4006))
        else:
            result.affected_items.append(pm.get_policy(name=name))
            result.total_affected_items += 1

    return result
Example #11
0
def remove_role_policy(role_id, policy_ids):
    """Removes a relationship between a role and a policy

    :param role_id: The new role_id
    :param policy_ids: List of policies ids
    :return Result of operation
    """
    result = AffectedItemsWazuhResult(
        none_msg=f'No policy was unlinked from role {role_id[0]}',
        some_msg=f'Some policies were not unlinked from role {role_id[0]}',
        all_msg=f'All policies were unlinked from role {role_id[0]}')
    success = False
    with RolesPoliciesManager() as rpm:
        for policy_id in policy_ids:
            policy_id = int(policy_id)
            role_policy = rpm.remove_policy_in_role(role_id=role_id[0],
                                                    policy_id=policy_id)
            if role_policy == SecurityError.INVALID:
                result.add_failed_item(id_=policy_id, error=WazuhError(4010))
            elif role_policy == SecurityError.ROLE_NOT_EXIST:
                result.add_failed_item(id_=int(role_id[0]),
                                       error=WazuhError(4002))
            elif role_policy == SecurityError.POLICY_NOT_EXIST:
                result.add_failed_item(id_=policy_id, error=WazuhError(4007))
            elif role_policy == SecurityError.ADMIN_RESOURCES:
                result.add_failed_item(id_=int(role_id[0]),
                                       error=WazuhError(4008))
            else:
                success = True
                result.total_affected_items += 1
        if success:
            with RolesManager() as rm:
                result.affected_items.append(
                    rm.get_role_id(role_id=role_id[0]))
                role = rm.get_role_id(role_id=role_id[0])
                invalid_roles_tokens(roles=[role['id']])
            result.affected_items.sort(key=str)

    return result
Example #12
0
def remove_agent_from_groups(agent_list=None, group_list=None):
    """Removes an agent assigment from a list of groups.

    :param agent_list: List of agents ID's.
    :param group_list: List of Group names.
    :return: AffectedItemsWazuhResult.
    """
    agent_id = agent_list[0]
    result = AffectedItemsWazuhResult(all_msg='Specified agent was removed from returned groups',
                                      some_msg='Specified agent was not removed from some groups',
                                      none_msg='Specified agent was not removed from any group'
                                      )

    # Check if agent exists and it is not 000
    if agent_id == '000':
        raise WazuhError(1703)
    if agent_id not in get_agents_info():
        raise WazuhResourceNotFound(1701)

    # We move default group to last position in case it is contained in group_list. When an agent is removed from all
    # groups it is reverted to 'default'. We try default last to avoid removing it and then adding again.
    try:
        group_list.append(group_list.pop(group_list.index('default')))
    except ValueError:
        pass

    system_groups = get_groups()
    for group_id in group_list:
        try:
            if group_id not in system_groups:
                raise WazuhResourceNotFound(1710)
            Agent.unset_single_group_agent(agent_id=agent_id, group_id=group_id, force=True)
            result.affected_items.append(group_id)
        except WazuhException as e:
            result.add_failed_item(id_=group_id, error=e)
    result.total_affected_items = len(result.affected_items)
    result.affected_items.sort()

    return result
Example #13
0
def get_config(component=None, config=None):
    """ Wrapper for get_active_configuration

    :param component: Selected component.
    :param config: Configuration to get, written on disk.
    :return: AffectedItemsWazuhResult.
    """
    result = AffectedItemsWazuhResult(all_msg=f"Active configuration read successfully"
                                              f"{' in specified node' if node_id != 'manager' else ''}",
                                      some_msg='Could not read active configuration in some nodes',
                                      none_msg=f"Could not read active configuration"
                                               f"{' in specified node' if node_id != 'manager' else ''}"
                                      )

    try:
        data = configuration.get_active_configuration(agent_id='000', component=component, configuration=config)
        len(data.keys()) > 0 and result.affected_items.append(data)
    except WazuhError as e:
        result.add_failed_item(id_=node_id, error=e)
    result.total_affected_items = len(result.affected_items)

    return result
Example #14
0
def remove_role_rule(role_id, rule_ids):
    """Remove a relationship between a role and one or more rules.

    :param role_id: The new role_id
    :param rule_ids: List of rule ids
    :return Result of operation
    """
    result = AffectedItemsWazuhResult(
        none_msg=f'No security rule was unlinked from role {role_id[0]}',
        some_msg=
        f'Some security rules were not unlinked from role {role_id[0]}',
        all_msg=f'All security rules were unlinked from role {role_id[0]}')
    success = False
    with RolesRulesManager() as rrm:
        for rule_id in rule_ids:
            role_rule = rrm.remove_rule_in_role(role_id=int(role_id[0]),
                                                rule_id=int(rule_id))
            if role_rule == SecurityError.INVALID:
                result.add_failed_item(id_=rule_id, error=WazuhError(4024))
            elif role_rule == SecurityError.ROLE_NOT_EXIST:
                result.add_failed_item(id_=int(role_id[0]),
                                       error=WazuhError(4002))
            elif role_rule == SecurityError.RULE_NOT_EXIST:
                result.add_failed_item(id_=rule_id, error=WazuhError(4022))
            elif role_rule == SecurityError.ADMIN_RESOURCES:
                result.add_failed_item(id_=int(role_id[0]),
                                       error=WazuhError(4008))
            else:
                success = True
                result.total_affected_items += 1
        if success:
            with RolesManager() as rm:
                result.affected_items.append(
                    rm.get_role_id(role_id=role_id[0]))
                # Invalidate users with auth_context
                invalid_run_as_tokens()
            result.affected_items.sort(key=str)

    return result
Example #15
0
def create_user(username: str = None,
                password: str = None,
                allow_run_as: bool = False):
    """Create a new user

    Parameters
    ----------
    username : str
        Name for the new user
    password : str
        Password for the new user
    allow_run_as : bool
        Enable authorization context login method for the new user

    Returns
    -------
    result : AffectedItemsWazuhResult
        Status message
    """
    if len(password) > 64 or len(password) < 8:
        raise WazuhError(5009)
    elif not _user_password.match(password):
        raise WazuhError(5007)

    result = AffectedItemsWazuhResult(none_msg='User could not be created',
                                      all_msg='User was successfully created')
    with AuthenticationManager() as auth:
        if auth.add_user(username, password, allow_run_as=allow_run_as):
            operation = auth.get_user(username)
            if operation:
                result.affected_items.append(operation)
                result.total_affected_items = 1
            else:
                result.add_failed_item(id_=username, error=WazuhError(5000))
        else:
            result.add_failed_item(id_=username, error=WazuhError(5000))

    return result
Example #16
0
def run(agent_list=None):
    """Run a syscheck scan in the specified agents.

    Parameters
    ----------
    agent_list : str
        List of the agents IDs to run the scan for.

    Returns
    -------
    result : AffectedItemsWazuhResult
        Confirmation/Error message.
    """
    result = AffectedItemsWazuhResult(
        all_msg='Syscheck scan was restarted on returned agents',
        some_msg='Syscheck scan was not restarted on some agents',
        none_msg='No syscheck scan was restarted')
    for agent_id in agent_list:
        try:
            agent_info = Agent(agent_id).get_basic_information()
            agent_status = agent_info.get('status', 'N/A')
            if agent_status.lower() != 'active':
                result.add_failed_item(
                    id_=agent_id,
                    error=WazuhError(
                        1601,
                        extra_message='Status - {}'.format(agent_status)))
            else:
                wq = WazuhQueue(common.ARQUEUE)
                wq.send_msg_to_agent(WazuhQueue.HC_SK_RESTART, agent_id)
                result.affected_items.append(agent_id)
                wq.close()
        except WazuhError as e:
            result.add_failed_item(id_=agent_id, error=e)
    result.affected_items = sorted(result.affected_items, key=int)
    result.total_affected_items = len(result.affected_items)

    return result
Example #17
0
def run(agent_list=None):
    """Run rootcheck scan.

    Parameters
    ----------
    agent_list : list
         Run rootcheck in a list of agents.

    Returns
    -------
    result : AffectedItemsWazuhResult
        JSON containing the affected agents.
    """
    result = AffectedItemsWazuhResult(
        all_msg='Rootcheck scan was restarted on returned agents',
        some_msg='Rootcheck scan was not restarted on some agents',
        none_msg='No rootcheck scan was restarted')
    for agent_id in agent_list:
        try:
            agent_info = Agent(agent_id).get_basic_information()
            agent_status = agent_info.get('status', 'N/A')
            if agent_status.lower() != 'active':
                result.add_failed_item(
                    id_=agent_id,
                    error=WazuhError(
                        1601,
                        extra_message='Status - {}'.format(agent_status)))
            else:
                oq = OssecQueue(common.ARQUEUE)
                oq.send_msg_to_agent(OssecQueue.HC_SK_RESTART, agent_id)
                result.affected_items.append(agent_id)
                oq.close()
        except WazuhError as e:
            result.add_failed_item(id_=agent_id, error=e)
    result.affected_items = sorted(result.affected_items, key=int)
    result.total_affected_items = len(result.affected_items)

    return result
Example #18
0
def delete_groups(group_list=None):
    """Delete a list of groups and remove it from every agent assignments.

    :param group_list: List of Group names.
    :return: AffectedItemsWazuhResult.
    """
    result = AffectedItemsWazuhResult(all_msg='All selected groups were deleted',
                                      some_msg='Some groups were not deleted',
                                      none_msg='No group was deleted')

    affected_agents = set()
    system_groups = get_groups()
    for group_id in group_list:
        try:
            # Check if group exists
            if group_id not in system_groups:
                raise WazuhResourceNotFound(1710)
            if group_id == 'default':
                raise WazuhError(1712)
            agent_list = list(map(operator.itemgetter('id'),
                                  WazuhDBQueryMultigroups(group_id=group_id, limit=None).run()['items']))
            try:
                affected_agents_result = remove_agents_from_group(agent_list=agent_list, group_list=[group_id])
                if affected_agents_result.total_failed_items != 0:
                    raise WazuhError(4015)
            except WazuhError:
                raise WazuhError(4015)
            Agent.delete_single_group(group_id)
            result.affected_items.append(group_id)
            affected_agents.update(affected_agents_result.affected_items)
        except WazuhException as e:
            result.add_failed_item(id_=group_id, error=e)

    result['affected_agents'] = sorted(affected_agents, key=int)
    result.affected_items.sort()
    result.total_affected_items = len(result.affected_items)

    return result
Example #19
0
def hourly():
    """
    Returns the hourly averages.
    :return: Dictionary: averages and interactions.
    """

    averages = []
    interactions = 0

    # What's the 24 for?
    for i in range(25):
        try:
            hfile = open(common.stats_path + '/hourly-average/' + str(i))
            data = hfile.read()

            if i == 24:
                interactions = int(data)
            else:
                averages.append(int(data))

            hfile.close()
        except IOError:
            if i < 24:
                averages.append(0)

    result = AffectedItemsWazuhResult(
        all_msg=
        'Statistical information per hour for each node was successfully read',
        some_msg=
        'Could not read statistical information per hour for some nodes',
        none_msg='Could not read statistical information per hour for any node'
    )
    result.affected_items.append({
        'averages': averages,
        'interactions': interactions
    })
    result.total_affected_items = len(result.affected_items)
    return result
Example #20
0
def get_agents(agent_list=None, offset=0, limit=common.database_limit, sort=None, search=None, select=None,
               filters=None, q=None):
    """Gets a list of available agents with basic attributes.

    :param agent_list: List of agents ID's.
    :param offset: First item to return.
    :param limit: Maximum number of items to return.
    :param sort: Sorts the items. Format: {"fields":["field1","field2"],"order":"asc|desc"}.
    :param select: Select fields to return. Format: {"fields":["field1","field2"]}.
    :param search: Looks for items with the specified string. Format: {"fields": ["field1","field2"]}
    :param filters: Defines required field filters. Format: {"field1":"value1", "field2":["value2","value3"]}
    :param q: Defines query to filter in DB.
    :return: AffectedItemsWazuhResult.
    """
    result = AffectedItemsWazuhResult(all_msg='All selected agents information was returned',
                                      some_msg='Some agents information was not returned',
                                      none_msg='No agent information was returned'
                                      )
    if agent_list:
        if filters is None:
            filters = dict()

        system_agents = get_agents_info()

        for agent_id in agent_list:
            if agent_id not in system_agents:
                result.add_failed_item(id_=agent_id, error=WazuhResourceNotFound(1701))

        rbac_filters = get_rbac_filters(system_resources=system_agents, permitted_resources=agent_list, filters=filters)

        db_query = WazuhDBQueryAgents(offset=offset, limit=limit, sort=sort, search=search, select=select,
                                      query=q, **rbac_filters)
        data = db_query.run()
        result.affected_items.extend(data['items'])
        result.total_affected_items = data['totalItems']

    return result
Example #21
0
def update_user(user_id: str = None,
                password: str = None,
                allow_run_as: bool = None):
    """Update a specified user

    Parameters
    ----------
    user_id : list
        User ID
    password : str
        Password for the new user
    allow_run_as : bool
        Enable authorization context login method for the new user

    Returns
    -------
    Status message
    """
    if password is None and allow_run_as is None:
        raise WazuhError(4001)
    if password:
        if len(password) > 64 or len(password) < 8:
            raise WazuhError(5009)
        elif not _user_password.match(password):
            raise WazuhError(5007)
    result = AffectedItemsWazuhResult(all_msg='User was successfully updated',
                                      none_msg='User could not be updated')
    with AuthenticationManager() as auth:
        query = auth.update_user(int(user_id[0]), password, allow_run_as)
        if query is False:
            result.add_failed_item(id_=int(user_id[0]), error=WazuhError(5001))
        else:
            result.affected_items.append(auth.get_user_id(int(user_id[0])))
            result.total_affected_items += 1
            invalid_users_tokens(users=user_id)

    return result
Example #22
0
def update_policy(policy_id=None, name=None, policy=None):
    """Updates a policy in the system

    :param policy_id: Policy id to be update
    :param name: The new policy name
    :param policy: The new policy
    :return Policy information
    """
    if name is None and policy is None:
        raise WazuhError(4001)
    result = AffectedItemsWazuhResult(
        none_msg='Policy was not updated',
        all_msg='Policy was successfully updated')
    policy is not None and sanitize_rbac_policy(policy)
    with PoliciesManager() as pm:
        status = pm.update_policy(policy_id=policy_id[0],
                                  name=name,
                                  policy=policy)
        if status == SecurityError.ALREADY_EXIST:
            result.add_failed_item(id_=int(policy_id[0]),
                                   error=WazuhError(4013))
        elif status == SecurityError.INVALID:
            result.add_failed_item(id_=int(policy_id[0]),
                                   error=WazuhError(4006))
        elif status == SecurityError.POLICY_NOT_EXIST:
            result.add_failed_item(id_=int(policy_id[0]),
                                   error=WazuhError(4007))
        elif status == SecurityError.ADMIN_RESOURCES:
            result.add_failed_item(id_=int(policy_id[0]),
                                   error=WazuhError(4008))
        else:
            updated = pm.get_policy_id(int(policy_id[0]))
            result.affected_items.append(updated)
            result.total_affected_items += 1
            invalid_roles_tokens(roles=updated['roles'])

    return result
Example #23
0
def ossec_log(level=None, tag=None, offset=0, limit=common.database_limit, sort_by=None,
              sort_ascending=True, search_text=None, complementary_search=False, search_in_fields=None, q=''):
    """Gets logs from ossec.log.

    :param level: Filters by log level: all, error or info.
    :param tag: Filters by log category/tag (i.e. wazuh-remoted).
    :param offset: First item to return.
    :param limit: Maximum number of items to return.
    :param sort_by: Fields to sort the items by
    :param sort_ascending: Sort in ascending (true) or descending (false) order
    :param search_text: Text to search
    :param complementary_search: Find items without the text to search
    :param search_in_fields: Fields to search in
    :param q: Defines query to filter.
    :return: AffectedItemsWazuhResult
    """
    result = AffectedItemsWazuhResult(all_msg=f"Logs were successfully read"
                                              f"{' in specified node' if node_id != 'manager' else ''}",
                                      some_msg='Could not read logs in some nodes',
                                      none_msg=f"Could not read logs"
                                               f"{' in specified node' if node_id != 'manager' else ''}"
                                      )
    logs = get_ossec_logs()

    query = []
    level and query.append(f'level={level}')
    tag and query.append(f'tag={tag}')
    q and query.append(q)
    query = ';'.join(query)

    data = process_array(logs, search_text=search_text, search_in_fields=search_in_fields,
                         complementary_search=complementary_search, sort_by=sort_by,
                         sort_ascending=sort_ascending, offset=offset, limit=limit, q=query)
    result.affected_items.extend(data['items'])
    result.total_affected_items = data['totalItems']

    return result
Example #24
0
def clear(agent_list=None):
    """Clear the syscheck database for a list of agents.

    :param agent_list: List of agent ids
    :return: AffectedItemsWazuhResult.
    """
    result = AffectedItemsWazuhResult(
        all_msg='Syscheck database was cleared on returned agents',
        some_msg='Syscheck database was not cleared on some agents',
        none_msg="No syscheck database was cleared")
    wdb_conn = WazuhDBConnection()
    for agent in agent_list:
        if agent not in get_agents_info():
            result.add_failed_item(id_=agent,
                                   error=WazuhResourceNotFound(1701))
        else:
            try:
                wdb_conn.execute(
                    "agent {} sql delete from fim_entry".format(agent),
                    delete=True)
                # Update key fields which contains keys to value 000
                wdb_conn.execute(
                    "agent {} sql update metadata set value = '000' "
                    "where key like 'fim_db%'".format(agent),
                    update=True)
                wdb_conn.execute(
                    "agent {} sql update metadata set value = '000' "
                    "where key = 'syscheck-db-completed'".format(agent),
                    update=True)
                result.affected_items.append(agent)
            except WazuhError as e:
                result.add_failed_item(id_=agent, error=e)

    result.affected_items.sort(key=int)
    result.total_affected_items = len(result.affected_items)

    return result
Example #25
0
def get_agents_keys(agent_list=None):
    """Get the key of existing agents.

    :param agent_list: List of agents ID's.
    :return: AffectedItemsWazuhResult.
    """
    result = AffectedItemsWazuhResult(
        all_msg='Obtained keys for all selected agents',
        some_msg='Some agent keys were not obtained',
        none_msg='No agent keys were obtained')
    system_agents = get_agents_info()
    for agent_id in agent_list:
        try:
            if agent_id not in system_agents:
                raise WazuhResourceNotFound(1701)
            result.affected_items.append({
                'id': agent_id,
                'key': Agent(agent_id).get_key()
            })
        except WazuhException as e:
            result.add_failed_item(id_=agent_id, error=e)
    result.total_affected_items = len(result.affected_items)

    return result
Example #26
0
def reconnect_agents(
        agent_list: Union[list, str] = None) -> AffectedItemsWazuhResult:
    """Force reconnect a list of agents.

    Parameters
    ----------
    agent_list : Union[list, str]
        List of agent IDs. All possible values from 000 onwards. Default `*`

    Returns
    -------
    AffectedItemsWazuhResult
    """
    result = AffectedItemsWazuhResult(
        all_msg='Force reconnect command was sent to all agents',
        some_msg='Force reconnect command was not sent to some agents',
        none_msg='Force reconnect command was not sent to any agent')

    system_agents = get_agents_info()
    wq = WazuhQueue(common.ARQUEUE)
    for agent_id in agent_list:
        try:
            if agent_id not in system_agents:
                raise WazuhResourceNotFound(1701)
            if agent_id == "000":
                raise WazuhError(1703)
            Agent(agent_id).reconnect(wq)
            result.affected_items.append(agent_id)
        except WazuhException as e:
            result.add_failed_item(id_=agent_id, error=e)
    wq.close()

    result.total_affected_items = len(result.affected_items)
    result.affected_items.sort(key=int)

    return result
Example #27
0
def get_agents_summary_os(agent_list=None):
    """Gets a list of available OS.

    :param agent_list: List of agents ID's.
    :return: WazuhResult.
    """
    result = AffectedItemsWazuhResult(
        none_msg='Could not get the operative system of the agents',
        all_msg='Showing the operative system of all specified agents',
        some_msg='Could not get the operative system of some agents')
    if len(agent_list) != 0:
        db_query = WazuhDBQueryAgents(select=['os.platform'],
                                      filters={'id': agent_list},
                                      default_sort_field='os_platform',
                                      min_select_fields=set(),
                                      distinct=True)
        query_data = db_query.run()
        query_data['items'] = [
            row['os']['platform'] for row in query_data['items']
        ]
        result.affected_items = query_data['items']
        result.total_affected_items = len(result.affected_items)

    return result
Example #28
0
def get_upgrade_result(agent_list=None):
    """Read upgrade result output from agent.

    Parameters
    ----------
    agent_list : list
        List of agent ID's.

    Returns
    -------
    Upgrade result.
    """
    result = AffectedItemsWazuhResult(all_msg='All upgrade tasks were returned',
                                      some_msg='Some upgrade tasks were not returned',
                                      none_msg='No upgrade task was returned')

    agent_list = list(map(int, agents_padding(result=result, agent_list=agent_list)))
    agents_result_chunks = [agent_list[x:x + 100] for x in range(0, len(agent_list), 100)]

    task_results = list()
    for agents_chunk in agents_result_chunks:
        task_results.append(core_upgrade_agents(agents_chunk=agents_chunk, get_result=True))

    for task_result_chunk in task_results:
        for task_result in task_result_chunk['data']:
            task_error = task_result.pop('error')
            if task_error == 0:
                task_result['agent'] = str(task_result['agent']).zfill(3)
                result.affected_items.append(task_result)
                result.total_affected_items += 1
            else:
                error = WazuhError(code=1810 + task_error, cmd_error=True, extra_message=task_result['message'])
                result.add_failed_item(id_=str(task_result.pop('agent')).zfill(3), error=error)
    result.affected_items = sorted(result.affected_items, key=lambda k: k['agent'])

    return result
Example #29
0
def create_user(username: str = None, password: str = None):
    """Create a new user

    :param username: Name for the new user
    :param password: Password for the new user
    :return: Status message
    """
    if not _user_password.match(password):
        raise WazuhError(5007)

    result = AffectedItemsWazuhResult(none_msg='User could not be created',
                                      all_msg='User created correctly')
    with AuthenticationManager() as auth:
        if auth.add_user(username, password):
            operation = auth.get_user(username)
            if operation:
                result.affected_items.append(operation)
                result.total_affected_items = 1
            else:
                result.add_failed_item(id_=username, error=WazuhError(5000))
        else:
            result.add_failed_item(id_=username, error=WazuhError(5000))

    return result
Example #30
0
def get_sca_checks(policy_id=None,
                   agent_list=None,
                   q="",
                   offset=0,
                   limit=common.database_limit,
                   sort=None,
                   search=None,
                   select=None,
                   filters=None):
    """ Get a list of checks analyzed for a policy

    Parameters
    ----------
    policy_id : str
        Policy id to get the checks from.
    agent_list : list
        Agent id to get the policies from
    q : str
        Defines query to filter in DB.
    offset : int
        First item to return.
    limit : int
        Maximum number of items to return.
    sort : str
        Sorts the items. Format: {"fields":["field1","field2"],"order":"asc|desc"}.
    search : str
        Looks for items with the specified string. Format: {"fields": ["field1","field2"]}
    select : str
        Select fields to return. Format: {"fields":["field1","field2"]}.
    filters : str
        Define field filters required by the user. Format: {"field1":"value1", "field2":["value2","value3"]}

    Returns
    -------
    AffectedItemsWazuhResult
    """
    result = AffectedItemsWazuhResult(
        all_msg='All selected sca/policy information was returned',
        some_msg='Some sca/policy information was not returned',
        none_msg='No sca/policy information was returned')
    if len(agent_list) != 0:
        sca_checks = list()
        if agent_list[0] in get_agents_info():
            fields_translation = {
                **fields_translation_sca_check,
                **fields_translation_sca_check_compliance,
                **fields_translation_sca_check_rule
            }

            full_select = (
                list(fields_translation_sca_check.keys()) +
                list(fields_translation_sca_check_compliance.keys()) +
                list(fields_translation_sca_check_rule.keys()))

            # Workaround for too long sca_checks results until the chunk algorithm is implemented (1/2)
            db_query = WazuhDBQuerySCA(agent_id=agent_list[0],
                                       offset=0,
                                       limit=None,
                                       sort=None,
                                       filters=filters,
                                       search=None,
                                       select=full_select,
                                       count=True,
                                       get_data=True,
                                       query=f"policy_id={policy_id}",
                                       default_query=default_query_sca_check,
                                       default_sort_field='policy_id',
                                       fields=fields_translation,
                                       count_field='id')
            result_dict = db_query.run()

            if 'items' in result_dict:
                checks = result_dict['items']
            else:
                raise WazuhInternalError(2007)

            groups = groupby(checks, key=itemgetter('id'))
            select_fields = full_select if select is None else select
            select_fields = set([
                field if field != 'compliance' else 'compliance'
                for field in select_fields
                if field in fields_translation_sca_check
            ])
            # Rearrange check and compliance fields

            for _, group in groups:
                group_list = list(group)
                check_dict = {
                    k: v
                    for k, v in group_list[0].items() if k in select_fields
                }

                for extra_field, field_translations in [
                    ('compliance', fields_translation_sca_check_compliance),
                    ('rules', fields_translation_sca_check_rule)
                ]:
                    if (select is None or extra_field in select) \
                            and set(field_translations.keys()) & group_list[0].keys():
                        check_dict[extra_field] = [
                            dict(zip(field_translations.values(), x))
                            for x in set((
                                map(itemgetter(
                                    *field_translations.keys()), group_list)))
                        ]

                sca_checks.append(check_dict)
        else:
            result.add_failed_item(id_=agent_list[0],
                                   error=WazuhResourceNotFound(1701))
            result.total_affected_items = 0

        # Workaround for too long sca_checks results until the chunk algorithm is implemented (2/2)
        data = process_array(
            sca_checks,
            search_text=search['value'] if search else None,
            complementary_search=search['negation'] if search else False,
            sort_by=sort['fields'] if sort else ['policy_id'],
            sort_ascending=False if sort and sort['order'] == 'desc' else True,
            offset=offset,
            limit=limit,
            q=q)

        result.affected_items = data['items']
        result.total_affected_items = data['totalItems']

    return result