Exemplo n.º 1
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
Exemplo n.º 2
0
def update_role(role_id=None, name=None):
    """Updates a role in the system

    :param role_id: Role id to be update
    :param name: The new role name
    :return Role information
    """
    if name is None:
        raise WazuhError(4001)
    result = AffectedItemsWazuhResult(none_msg='Role was not updated',
                                      all_msg='Role was successfully updated')
    with RolesManager() as rm:
        status = rm.update_role(role_id=role_id[0], name=name)
        if status == SecurityError.ALREADY_EXIST:
            result.add_failed_item(id_=int(role_id[0]), error=WazuhError(4005))
        elif status == SecurityError.INVALID:
            result.add_failed_item(id_=int(role_id[0]), error=WazuhError(4003))
        elif status == SecurityError.ROLE_NOT_EXIST:
            result.add_failed_item(id_=int(role_id[0]), error=WazuhError(4002))
        elif status == SecurityError.ADMIN_RESOURCES:
            result.add_failed_item(id_=int(role_id[0]), error=WazuhError(4008))
        else:
            updated = rm.get_role_id(int(role_id[0]))
            result.affected_items.append(updated)
            result.total_affected_items += 1
            invalid_roles_tokens(roles=role_id)

    return result
Exemplo n.º 3
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
Exemplo n.º 4
0
def get_user_me():
    """Get the information of the current user

    Returns
    -------
    AffectedItemsWazuhResult with the desired information
    """
    result = AffectedItemsWazuhResult(all_msg='Current user information was returned')
    affected_items = list()
    with AuthenticationManager() as auth:
        user = auth.get_user(common.current_user.get())
        for index, role_id in enumerate(user['roles']):
            with RolesManager() as rm:
                role = rm.get_role_id(role_id=int(role_id))
                role.pop('users')
                for index_r, rule_id in enumerate(role['rules']):
                    with RulesManager() as rum:
                        role['rules'][index_r] = rum.get_rule(rule_id=int(rule_id))
                        role['rules'][index_r].pop('roles')
                for index_p, policy_id in enumerate(role['policies']):
                    with PoliciesManager() as pm:
                        role['policies'][index_p] = pm.get_policy_id(policy_id=int(policy_id))
                        role['policies'][index_p].pop('roles')
                user['roles'][index] = role
        affected_items.append(user) if user else result.add_failed_item(id_=common.current_user.get(),
                                                                        error=WazuhError(5001))

    data = process_array(affected_items)
    result.affected_items = data['items']
    result.total_affected_items = data['totalItems']

    return result
Exemplo n.º 5
0
def remove_roles(role_ids):
    """Removes a certain role from the system

    :param role_ids: List of roles ids (None for all roles)
    :return Result of operation
    """
    result = AffectedItemsWazuhResult(none_msg='No role was deleted',
                                      some_msg='Some roles were not deleted',
                                      all_msg='All specified roles were deleted')
    with RolesManager() as rm:
        for r_id in role_ids:
            role = rm.get_role_id(int(r_id))
            role_delete = rm.delete_role(int(r_id))
            if role_delete == SecurityError.ADMIN_RESOURCES:
                result.add_failed_item(id_=int(r_id), error=WazuhError(4008))
            elif role_delete == SecurityError.RELATIONSHIP_ERROR:
                result.add_failed_item(id_=int(r_id), error=WazuhError(4025))
            elif not role_delete:
                result.add_failed_item(id_=int(r_id), error=WazuhError(4002))
            elif role:
                result.affected_items.append(role)
                result.total_affected_items += 1

        invalid_roles_tokens(roles=[role['id'] for role in result.affected_items])
        result.affected_items = sorted(result.affected_items, key=lambda i: i['id'])

    return result
Exemplo n.º 6
0
def remove_roles(role_ids):
    """Removes a certain role from the system

    :param role_ids: List of roles ids (None for all roles)
    :return Result of operation
    """
    result = AffectedItemsWazuhResult(none_msg='No role were deleted',
                                      some_msg='Some roles could not be delete',
                                      all_msg='All specified roles were deleted')
    with RolesManager() as rm:
        for r_id in role_ids:
            role = rm.get_role_id(int(r_id))
            if role != SecurityError.ROLE_NOT_EXIST and int(r_id) not in admin_role_ids:
                related_users = check_relationships([role])
            role_delete = rm.delete_role(int(r_id))
            if role_delete == SecurityError.ADMIN_RESOURCES:
                result.add_failed_item(id_=r_id, error=WazuhError(4008))
            elif not role_delete:
                result.add_failed_item(id_=r_id, error=WazuhError(4002))
            elif role:
                result.affected_items.append(role)
                result.total_affected_items += 1
                invalid_users_tokens(users=list(related_users))
        result.affected_items = sorted(result.affected_items, key=lambda i: i['id'])

    return result
Exemplo n.º 7
0
def get_roles(role_ids=None, offset=0, limit=common.database_limit, sort_by=None,
              sort_ascending=True, search_text=None, complementary_search=False, search_in_fields=None):
    """Returns information from all system roles, does not return information from its associated policies

    :param role_ids: List of roles ids (None for all roles)
    :param offset: First item to return
    :param limit: Maximum number of items to return
    :param sort_by: Fields to sort the items by. Format: {"fields":["field1","field2"],"order":"asc|desc"}
    :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
    :return: Dictionary: {'items': array of items, 'totalItems': Number of items (without applying the limit)}
    """
    affected_items = list()
    result = AffectedItemsWazuhResult(none_msg='No role was returned',
                                      some_msg='Some roles were not returned',
                                      all_msg='All specified roles were returned')
    with RolesManager() as rm:
        for r_id in role_ids:
            role = rm.get_role_id(int(r_id))
            if role != SecurityError.ROLE_NOT_EXIST:
                affected_items.append(role)
            else:
                # Role id does not exist
                result.add_failed_item(id_=int(r_id), error=WazuhError(4002))

    data = process_array(affected_items, 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)
    result.affected_items = data['items']
    result.total_affected_items = data['totalItems']

    return result
Exemplo n.º 8
0
def _expand_resource(resource):
    """This function expand a specified resource depending of its type.
    
    Parameters
    ----------
    resource : str
        Resource to be expanded

    Returns
    -------
    str
        Result of the resource expansion.
    """
    name, attribute, value = resource.split(':')
    resource_type = ':'.join([name, attribute])

    # This is the special case, expand_group can receive * or the name of the group. That's why it' s always called
    if resource_type == 'agent:group':
        return expand_group(value)

    # We need to transform the wildcard * to the resource of the system
    if value == '*':
        if resource_type == 'agent:id':
            return get_agents_info()
        elif resource_type == 'group:id':
            return get_groups()
        elif resource_type == 'role:id':
            with RolesManager() as rm:
                roles = rm.get_roles()
            return {str(role_id.id) for role_id in roles}
        elif resource_type == 'policy:id':
            with PoliciesManager() as pm:
                policies = pm.get_policies()
            return {str(policy_id.id) for policy_id in policies}
        elif resource_type == 'user:id':
            users_system = set()
            with AuthenticationManager() as auth:
                users = auth.get_users()
            for user in users:
                users_system.add(str(user['user_id']))
            return users_system
        elif resource_type == 'rule:id':
            with RulesManager() as rum:
                rules = rum.get_rules()
            return {str(rule_id.id) for rule_id in rules}
        elif resource_type == 'rule:file':
            return expand_rules()
        elif resource_type == 'decoder:file':
            return expand_decoders()
        elif resource_type == 'list:file':
            return expand_lists()
        elif resource_type == 'node:id':
            return set(cluster_nodes.get())
        elif resource_type == '*:*':  # Resourceless
            return {'*'}
        return set()
    # We return the value casted to set
    else:
        return {value}
Exemplo n.º 9
0
def set_role_policy(role_id, policy_ids, position=None):
    """Create a relationship between a role and a policy

    Parameters
    ----------
    role_id : int
        The new role_id
    policy_ids : list of int
        List of policy IDs
    position : int
        Position where the new role will be inserted

    Returns
    -------
    dict
        Role-Policies information
    """
    result = AffectedItemsWazuhResult(
        none_msg=f'No link was created to role {role_id[0]}',
        some_msg=f'Some policies were not linked to role {role_id[0]}',
        all_msg=f'All policies were linked to role {role_id[0]}')
    success = False
    with RolesPoliciesManager() as rpm:
        for policy_id in policy_ids:
            policy_id = int(policy_id)
            role_policy = rpm.add_policy_to_role(role_id=role_id[0],
                                                 policy_id=policy_id,
                                                 position=position)
            if role_policy == SecurityError.ALREADY_EXIST:
                result.add_failed_item(id_=policy_id, error=WazuhError(4011))
            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 position is not None:
                    position += 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
Exemplo n.º 10
0
def set_role_rule(role_id, rule_ids, run_as=False):
    """Create a relationship between a role and one or more rules.

    Parameters
    ----------
    role_id : int
        The new role_id
    rule_ids : list of int
        List of rule ids
    run_as : dict
        Login with an authorization context or not

    Returns
    -------

    """

    result = AffectedItemsWazuhResult(
        none_msg=f'No link was created to role {role_id[0]}',
        some_msg=f'Some security rules were not linked to role {role_id[0]}',
        all_msg=f'All security rules were linked to role {role_id[0]}')
    success = False
    with RolesRulesManager() as rrm:
        for rule_id in rule_ids:
            role_rule = rrm.add_rule_to_role(role_id=int(role_id[0]),
                                             rule_id=int(rule_id))
            if role_rule == SecurityError.ALREADY_EXIST:
                result.add_failed_item(id_=int(rule_id),
                                       error=WazuhError(4023))
            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_=int(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
Exemplo n.º 11
0
def check_relationships(roles: list = None):
    """Check the users related with the specified list of roles

    Parameters
    ----------
    roles : list
        List of affected roles

    Returns
    -------
    Set with all affected users
    """
    users_affected = set()
    if roles:
        for role in roles:
            with RolesManager() as rm:
                users_affected.update(set(rm.get_role_id(role)['users']))

    return users_affected
Exemplo n.º 12
0
def add_role(name=None):
    """Creates a role in the system

    :param name: The new role name
    :return Role information
    """
    result = AffectedItemsWazuhResult(none_msg='Role was not created',
                                      all_msg='Role was successfully created')
    with RolesManager() as rm:
        status = rm.add_role(name=name)
        if status == SecurityError.ALREADY_EXIST:
            result.add_failed_item(id_=name, error=WazuhError(4005))
        elif status == SecurityError.INVALID:
            result.add_failed_item(id_=name, error=WazuhError(4003))
        else:
            result.affected_items.append(rm.get_role(name=name))
            result.total_affected_items += 1

    return result
Exemplo n.º 13
0
def set_role_rule(role_id, rule_ids):
    """Create 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 link was created to role {role_id[0]}',
        some_msg=f'Some security rules were not linked to role {role_id[0]}',
        all_msg=f'All security rules were linked to role {role_id[0]}')
    success = False
    with RolesRulesManager() as rrm:
        for rule_id in rule_ids:
            role_rule = rrm.add_rule_to_role(role_id=role_id[0],
                                             rule_id=rule_id)
            if role_rule == SecurityError.ALREADY_EXIST:
                result.add_failed_item(id_=rule_id, error=WazuhError(4023))
            elif role_rule == SecurityError.ROLE_NOT_EXIST:
                result.add_failed_item(id_=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_=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
                with AuthenticationManager() as am:
                    user_list = list()
                    for user in am.get_users():
                        if am.user_allow_run_as(username=user['username']):
                            user_list.append(user['user_id'])
                invalid_users_tokens(users=user_list)
            result.affected_items.sort(key=str)

    return result
Exemplo n.º 14
0
def get_role(role_id):
    """Return the role name of the specified role_id.

    Parameters
    ----------
    role_id : str
        Role ID.

    Returns
    -------
    role_check : bool
        True if the role_id exists, False in other case.
    """

    role_check = False

    with RolesManager() as rm:
        role_information = rm.get_role_id(int(role_id))
        if role_information != SecurityError.ROLE_NOT_EXIST:
            role_check = True

    return role_check
Exemplo n.º 15
0
def _expand_resource(resource):
    """This function expand a specified resource depending of it type.

    :param resource: Resource to be expanded
    :return expanded_resource: Returns the result of the resource expansion
    """
    name, attribute, value = resource.split(':')
    resource_type = ':'.join([name, attribute])

    # This is the special case, expand_group can receive * or the name of the group. That's why it' s always called
    if resource_type == 'agent:group':
        return expand_group(value)

    # We need to transform the wildcard * to the resource of the system
    if value == '*':
        if resource_type == 'agent:id':
            return get_agents_info()
        elif resource_type == 'group:id':
            return get_groups()
        elif resource_type == 'role:id':
            with RolesManager() as rm:
                roles = rm.get_roles()
            return {str(role_id.id) for role_id in roles}
        elif resource_type == 'policy:id':
            with PoliciesManager() as pm:
                policies = pm.get_policies()
            return {str(policy_id.id) for policy_id in policies}
        elif resource_type == 'user:id':
            users_system = set()
            with AuthenticationManager() as auth:
                users = auth.get_users()
            for user in users:
                users_system.add(user['user_id'])
            return users_system
        elif resource_type == 'rule:id':
            with RulesManager() as rum:
                rules = rum.get_rules()
            return {str(rule_id.id) for rule_id in rules}
        elif resource_type == 'rule:file':
            tags = ['rule_include', 'rule_exclude', 'rule_dir']
            format_rules = format_rule_decoder_file(
                get_ossec_conf(section='ruleset')['ruleset'], {
                    'status': Status.S_ALL.value,
                    'relative_dirname': None,
                    'filename': None
                }, tags)
            return {rule['filename'] for rule in format_rules}
        elif resource_type == 'decoder:file':
            tags = ['decoder_include', 'decoder_exclude', 'decoder_dir']
            format_decoders = format_rule_decoder_file(
                get_ossec_conf(section='ruleset')['ruleset'], {
                    'status': Status.S_ALL.value,
                    'relative_dirname': None,
                    'filename': None
                }, tags)
            return {decoder['filename'] for decoder in format_decoders}
        elif resource_type == 'list:path':
            return {
                os.path.join(cdb_list['relative_dirname'],
                             cdb_list['filename'])
                for cdb_list in iterate_lists(only_names=True)
            }
        elif resource_type == 'node:id':
            return set(cluster_nodes.get())
        elif resource_type == 'file:path':
            return get_files()
        elif resource_type == '*:*':  # Resourceless
            return {'*'}
        return set()
    # We return the value casted to set
    else:
        return {value}
Exemplo n.º 16
0
def get_roles(role_ids=None,
              offset=0,
              limit=common.database_limit,
              sort_by=None,
              select=None,
              sort_ascending=True,
              search_text=None,
              complementary_search=False,
              search_in_fields=None):
    """Return information from all system roles, does not return information from its associated policies.

    Parameters
    ----------
    role_ids : list, optional
        List of roles ids to be obtained
    offset : int, optional
        First item to return
    limit : int, optional
        Maximum number of items to return
    sort_by : dict
        Fields to sort the items by. Format: {"fields":["field1","field2"],"order":"asc|desc"}
    sort_ascending : bool
        Sort in ascending (true) or descending (false) order
    search_text : str
        Text to search
    select : str
        Select which fields to return (separated by comma)
    complementary_search : bool
        Find items without the text to search
    search_in_fields : list
        Fields to search in

    Returns
    -------
    Roles information
    """
    affected_items = list()
    result = AffectedItemsWazuhResult(
        none_msg='No role was returned',
        some_msg='Some roles were not returned',
        all_msg='All specified roles were returned')
    with RolesManager() as rm:
        for r_id in role_ids:
            role = rm.get_role_id(int(r_id))
            if role != SecurityError.ROLE_NOT_EXIST:
                affected_items.append(role)
            else:
                # Role id does not exist
                result.add_failed_item(id_=int(r_id), error=WazuhError(4002))

    data = process_array(affected_items,
                         search_text=search_text,
                         search_in_fields=search_in_fields,
                         select=select,
                         complementary_search=complementary_search,
                         sort_by=sort_by,
                         sort_ascending=sort_ascending,
                         offset=offset,
                         limit=limit,
                         allowed_sort_fields=SORT_FIELDS,
                         required_fields=REQUIRED_FIELDS)
    result.affected_items = data['items']
    result.total_affected_items = data['totalItems']

    return result