Ejemplo n.º 1
0
def edit_run_as(user_id: str = None, allow_run_as: bool = False):
    """Enable/Disable the user's allow_run_as flag

    Parameters
    ----------
    user_id : str
        User ID
    allow_run_as : bool
        Enable or disable authorization context login method for the specified user

    Returns
    -------
    result : AffectedItemsWazuhResult
        Status message
    """
    result = AffectedItemsWazuhResult(
        none_msg=f"The parameter allow_run_as could not be "
        f"{'enabled' if allow_run_as else 'disabled'} for the user",
        all_msg=f"Parameter allow_run_as has been "
        f"{'enabled' if allow_run_as else 'disabled'} for the user")
    with AuthenticationManager() as auth:
        user_id = int(user_id)
        query = auth.edit_run_as(user_id, allow_run_as)
        if query is False:
            result.add_failed_item(id_=user_id, error=WazuhError(5001))
        elif query == SecurityError.INVALID:
            result.add_failed_item(id_=user_id, error=WazuhError(5010))
        else:
            result.affected_items.append(auth.get_user_id(user_id))
            result.total_affected_items += 1
            invalid_users_tokens(users=[user_id])

    return result
Ejemplo n.º 2
0
def update_user(user_id: str = None, password: str = None):
    """Update a specified user

    Parameters
    ----------
    user_id : list
        User ID
    password : str
        Password for the new user

    Returns
    -------
    Status message
    """
    if password 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)
        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
Ejemplo n.º 3
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 unlinked from role {role_id[0]}',
                                      some_msg=f'Some policies could not be 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:
            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_=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_=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_users_tokens(roles=[role])
            result.affected_items.sort(key=str)

    return result
Ejemplo n.º 4
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
Ejemplo n.º 5
0
def update_user(user_id: str = None,
                password: str = None,
                allow_run_as: bool = None):
    """Update a specified user

    Parameters
    ----------
    user_id : str
        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 and 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(user_id[0], password, allow_run_as)
        if query is False:
            result.add_failed_item(id_=user_id[0], error=WazuhError(5001))
        else:
            result.affected_items.append(auth.get_user_id(user_id[0]))
            result.total_affected_items += 1
            invalid_users_tokens(users=user_id)

    return result
Ejemplo n.º 6
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 could not be updated',
                                      all_msg='Policy updated correctly')
    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_=policy_id[0], error=WazuhError(4013))
        elif status == SecurityError.INVALID:
            result.add_failed_item(id_=policy_id[0], error=WazuhError(4006))
        elif status == SecurityError.POLICY_NOT_EXIST:
            result.add_failed_item(id_=policy_id[0], error=WazuhError(4007))
        elif status == SecurityError.ADMIN_RESOURCES:
            result.add_failed_item(id_=policy_id[0], error=WazuhError(4008))
        else:
            updated = pm.get_policy_id(policy_id[0])
            result.affected_items.append(updated)
            result.total_affected_items += 1
            invalid_users_tokens(roles=updated['roles'])

    return result
Ejemplo n.º 7
0
def remove_policies(policy_ids=None):
    """Removes a certain policy from the system

    :param policy_ids: ID of the policy to be removed (All for all policies)
    :return Result of operation
    """
    result = AffectedItemsWazuhResult(none_msg='No policies were deleted',
                                      some_msg='Some policies could not be deleted',
                                      all_msg='All specified policies were deleted')
    with PoliciesManager() as pm:
        for p_id in policy_ids:
            policy = pm.get_policy_id(int(p_id))
            if policy != SecurityError.POLICY_NOT_EXIST and int(p_id) not in admin_policy_ids:
                related_users = check_relationships(policy['roles'])
            policy_delete = pm.delete_policy(int(p_id))
            if policy_delete == SecurityError.ADMIN_RESOURCES:
                result.add_failed_item(id_=p_id, error=WazuhError(4008))
            elif not policy_delete:
                result.add_failed_item(id_=p_id, error=WazuhError(4007))
            elif policy:
                result.affected_items.append(policy)
                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
Ejemplo n.º 8
0
def update_role(role_id=None, name=None, rule=None):
    """Updates a role in the system

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

    return result
Ejemplo n.º 9
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
Ejemplo n.º 10
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 could not be deleted',
                                      all_msg='Users deleted correctly')
    with AuthenticationManager() as auth:
        for user_id in user_ids:
            current_user = auth.get_user(common.current_user.get())
            if not isinstance(current_user, bool) and int(user_id) == int(current_user['id']):
                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 user:
                result.affected_items.append(user)
                result.total_affected_items += 1
                invalid_users_tokens(users=[user_id])
        result.affected_items.sort(key=str)

    return result
Ejemplo n.º 11
0
def update_user(user_id=None, password=None):
    """Update a specified user

    Parameters
    ----------
    user_id : str
        User ID
    password : str
        Password for the new user

    Returns
    -------
    Status message
    """
    if not _user_password.match(password):
        raise WazuhError(5007)
    result = AffectedItemsWazuhResult(all_msg='User modified correctly',
                                      none_msg='User could not be updated')
    with AuthenticationManager() as auth:
        query = auth.update_user(user_id[0], password)
        if not query:
            result.add_failed_item(id_=user_id[0], error=WazuhError(5001))
        else:
            result.affected_items.append(auth.get_user_id(user_id[0]))
            result.total_affected_items += 1
            invalid_users_tokens(users=[user_id[0]])

    return result
Ejemplo n.º 12
0
def set_user_role(user_id, role_ids, position=None):
    """Create a relationship between a user and a role.

    Parameters
    ----------
    user_id : list
        User ID
    role_ids : list of int
        List of role ids
    position : int
        Position where the new role will be inserted

    Returns
    -------
    Dict
        User-Roles information
    """
    if position is not None and position < 0:
        raise WazuhError(4018)

    username = get_username(user_id=user_id)
    result = AffectedItemsWazuhResult(
        none_msg=f'No link was created to user {username}',
        some_msg=f'Some roles were not linked to user {username}',
        all_msg=f'All roles were linked to user {username}')
    success = False
    with UserRolesManager() as urm:
        for role_id in role_ids:
            user_role = urm.add_role_to_user(user_id=int(user_id[0]),
                                             role_id=int(role_id),
                                             position=position)
            if user_role == SecurityError.ALREADY_EXIST:
                result.add_failed_item(id_=int(role_id),
                                       error=WazuhError(4017))
            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 position is not None:
                    position += 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
Ejemplo n.º 13
0
def revoke_current_user_tokens():
    """Revoke all current user's tokens"""
    with AuthenticationManager() as am:
        invalid_users_tokens(
            users=[am.get_user(common.current_user.get())['id']])

    return WazuhResult({
        'message':
        f'User {common.current_user.get()} was successfully logged out'
    })
Ejemplo n.º 14
0
def test_invalid_users_tokens(db_setup, user_list, expected_users):
    """Check that the argument passed to `TokenManager.add_user_roles_rules` formed by `users` is correct.

    Parameters
    ----------
    user_list : list
        List of users.
    expected_users : set
        Expected users.
    """
    with patch('wazuh.security.TokenManager.add_user_roles_rules') as TM_mock:
        _, _, core_security = db_setup
        core_security.invalid_users_tokens(users=[user_id for user_id in user_list])
        related_users = TM_mock.call_args.kwargs['users']
        assert set(related_users) == expected_users
Ejemplo n.º 15
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 created to role {role_id[0]}',
                                      some_msg=f'Some policies could not be 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:
            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_=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_=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_users_tokens(roles=[role])
            result.affected_items.sort(key=str)

    return result
Ejemplo n.º 16
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_=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