Пример #1
0
def test_check_credentials_local_user_disallow_locked(with_user):
    user_id, password = with_user
    assert userdb.check_credentials(user_id, password) == user_id

    users = _load_users_uncached(lock=True)

    users[user_id]["locked"] = True
    userdb.save_users(users)

    assert userdb.check_credentials(user_id, password) is False
Пример #2
0
def test_check_credentials_local_user_disallow_locked(
        with_user: tuple[UserId, str]) -> None:
    now = datetime.now()
    user_id, password = with_user
    assert userdb.check_credentials(user_id, password, now) == user_id

    users = _load_users_uncached(lock=True)

    users[user_id]["locked"] = True
    userdb.save_users(users, now)

    assert userdb.check_credentials(user_id, password, now) is False
Пример #3
0
    def _do_login(self) -> None:
        """handle the sent login form"""
        if not html.request.var('_login'):
            return

        try:
            if not config.user_login:
                raise MKUserError(None,
                                  _('Login is not allowed on this site.'))

            username_var = html.request.get_unicode_input('_username', '')
            assert username_var is not None
            username = UserId(username_var.rstrip())
            if not username:
                raise MKUserError('_username', _('No username given.'))

            password = html.request.var('_password', '')
            if not password:
                raise MKUserError('_password', _('No password given.'))

            default_origtarget = config.url_prefix() + "check_mk/"
            origtarget = html.get_url_input("_origtarget", default_origtarget)

            # Disallow redirections to:
            #  - logout.py: Happens after login
            #  - side.py: Happens when invalid login is detected during sidebar refresh
            if "logout.py" in origtarget or 'side.py' in origtarget:
                origtarget = default_origtarget

            result = userdb.check_credentials(username, password)
            if result:
                # use the username provided by the successful login function, this function
                # might have transformed the username provided by the user. e.g. switched
                # from mixed case to lower case.
                username = result

                session_id = userdb.on_succeeded_login(username)

                # The login succeeded! Now:
                # a) Set the auth cookie
                # b) Unset the login vars in further processing
                # c) Redirect to really requested page
                _create_auth_session(username, session_id)

                # Never use inplace redirect handling anymore as used in the past. This results
                # in some unexpected situations. We simpy use 302 redirects now. So we have a
                # clear situation.
                # userdb.need_to_change_pw returns either False or the reason description why the
                # password needs to be changed
                change_pw_result = userdb.need_to_change_pw(username)
                if change_pw_result:
                    raise HTTPRedirect(
                        'user_change_pw.py?_origtarget=%s&reason=%s' %
                        (html.urlencode(origtarget), change_pw_result))
                raise HTTPRedirect(origtarget)

            userdb.on_failed_login(username)
            raise MKUserError(None, _('Invalid credentials.'))
        except MKUserError as e:
            html.add_user_error(e.varname, e)
Пример #4
0
def test_check_credentials_managed_wrong_customer_user_is_denied(
        with_user: tuple[UserId, str]) -> None:
    if not is_managed_repo():
        pytest.skip("not relevant")

    user_id, password = with_user
    assert userdb.check_credentials(user_id, password) is False
Пример #5
0
def test_check_credentials_managed_global_user_is_allowed(
        with_user: tuple[UserId, str]) -> None:
    if not is_managed_repo():
        pytest.skip("not relevant")

    user_id, password = with_user
    assert userdb.check_credentials(user_id, password) == user_id
Пример #6
0
    def _action(self) -> None:
        assert user.id is not None

        users = userdb.load_users(lock=True)
        user_spec = users[user.id]

        cur_password = request.get_str_input_mandatory("cur_password")
        password = request.get_str_input_mandatory("password")
        password2 = request.get_str_input_mandatory("password2", "")

        # Force change pw mode
        if not cur_password:
            raise MKUserError("cur_password", _("You need to provide your current password."))

        if not password:
            raise MKUserError("password", _("You need to change your password."))

        if cur_password == password:
            raise MKUserError("password", _("The new password must differ from your current one."))

        if userdb.check_credentials(user.id, cur_password) is False:
            raise MKUserError("cur_password", _("Your old password is wrong."))

        if password2 and password != password2:
            raise MKUserError("password2", _("The both new passwords do not match."))

        watolib.verify_password_policy(password)
        user_spec["password"] = hash_password(password)
        user_spec["last_pw_change"] = int(time.time())

        # In case the user was enforced to change it's password, remove the flag
        try:
            del user_spec["enforce_pw_change"]
        except KeyError:
            pass

        # Increase serial to invalidate old authentication cookies
        if "serial" not in user_spec:
            user_spec["serial"] = 1
        else:
            user_spec["serial"] += 1

        userdb.save_users(users)

        flash(_("Successfully changed password."))

        # Set the new cookie to prevent logout for the current user
        login.update_auth_cookie(user.id)

        # In distributed setups with remote sites where the user can login, start the
        # user profile replication now which will redirect the user to the destination
        # page after completion. Otherwise directly open up the destination page.
        origtarget = request.get_str_input_mandatory("_origtarget", "user_change_pw.py")
        if user.authorized_login_sites():
            raise redirect(
                makeuri_contextless(
                    request, [("back", origtarget)], filename="user_profile_replicate.py"
                )
            )
        raise redirect(origtarget)
Пример #7
0
def test_check_credentials_managed_wrong_customer_user_is_denied(
        with_user: tuple[UserId, str]) -> None:
    user_id, password = with_user
    now = datetime.now()
    users = _load_users_uncached(lock=True)
    users[user_id]["customer"] = "wrong-customer"
    userdb.save_users(users, now)
    assert userdb.check_credentials(user_id, password, now) is False
Пример #8
0
def gui_user_auth(user_id: UserId, secret: str) -> Optional[RFC7662]:
    try:
        if userdb.check_credentials(user_id, secret):
            return rfc7662_subject(user_id, "cookie")
    except MKUserError:
        # This is the case of "Automation user rejected". We don't care about that in the REST API
        # because every type of user is allowed in.
        return None

    return None
Пример #9
0
def test_check_credentials_managed_global_user_is_allowed(
        with_user: tuple[UserId, str]) -> None:
    user_id, password = with_user
    now = datetime.now()
    import cmk.gui.cme.managed as managed  # pylint: disable=no-name-in-module

    users = _load_users_uncached(lock=True)
    users[user_id]["customer"] = managed.SCOPE_GLOBAL
    userdb.save_users(users, now)
    assert userdb.check_credentials(user_id, password, now) == user_id
Пример #10
0
    def _action(self) -> bool:
        assert config.user.id is not None

        users = userdb.load_users(lock=True)
        user = users[config.user.id]

        cur_password = html.request.get_str_input_mandatory('cur_password')
        password = html.request.get_str_input_mandatory('password')
        password2 = html.request.get_str_input_mandatory('password2', '')

        # Force change pw mode
        if not cur_password:
            raise MKUserError("cur_password",
                              _("You need to provide your current password."))

        if not password:
            raise MKUserError("password",
                              _("You need to change your password."))

        if cur_password == password:
            raise MKUserError(
                "password",
                _("The new password must differ from your current one."))

        if userdb.check_credentials(config.user.id, cur_password) is False:
            raise MKUserError("cur_password", _("Your old password is wrong."))

        if password2 and password != password2:
            raise MKUserError("password2",
                              _("The both new passwords do not match."))

        watolib.verify_password_policy(password)
        user['password'] = hash_password(password)
        user['last_pw_change'] = int(time.time())

        # In case the user was enforced to change it's password, remove the flag
        try:
            del user['enforce_pw_change']
        except KeyError:
            pass

        # Increase serial to invalidate old authentication cookies
        if 'serial' not in user:
            user['serial'] = 1
        else:
            user['serial'] += 1

        userdb.save_users(users)

        # Set the new cookie to prevent logout for the current user
        login.update_auth_cookie(config.user.id)

        return True
Пример #11
0
def test_check_credentials_local_user_create_htpasswd_user_ad_hoc() -> None:
    user_id = UserId("someuser")
    assert userdb.user_exists(user_id) is False
    assert userdb._user_exists_according_to_profile(user_id) is False
    assert user_id not in _load_users_uncached(lock=False)

    htpasswd.Htpasswd(Path(cmk.utils.paths.htpasswd_file)).save(
        {user_id: htpasswd.hash_password("cmk")})
    # Once a user exists in the htpasswd, the GUI treats the user as existing user and will
    # automatically initialize the missing data structures
    assert userdb.user_exists(user_id) is True
    assert userdb._user_exists_according_to_profile(user_id) is False
    assert str(user_id) in _load_users_uncached(lock=False)

    assert userdb.check_credentials(user_id, "cmk") == user_id

    # Nothing changes during regular access
    assert userdb.user_exists(user_id) is True
    assert userdb._user_exists_according_to_profile(user_id) is False
    assert str(user_id) in _load_users_uncached(lock=False)
Пример #12
0
def test_check_credentials_local_user(with_user: tuple[UserId, str]) -> None:
    username, password = with_user
    assert userdb.check_credentials(username, password) == username
Пример #13
0
def test_check_credentials_managed_customer_user_is_allowed(with_user):
    if not is_managed_repo():
        pytest.skip("not relevant")

    user_id, password = with_user
    assert userdb.check_credentials(user_id, password) == user_id
Пример #14
0
def test_check_credentials_local_user(with_user):
    username, password = with_user
    assert userdb.check_credentials(username, password) == username
Пример #15
0
    def _do_login(self) -> None:
        """handle the sent login form"""
        if not request.var("_login"):
            return

        try:
            if not active_config.user_login:
                raise MKUserError(None,
                                  _("Login is not allowed on this site."))

            username_var = request.get_str_input("_username", "")
            assert username_var is not None
            username = UserId(username_var.rstrip())
            if not username:
                raise MKUserError("_username", _("Missing username"))

            password = request.var("_password", "")
            if not password:
                raise MKUserError("_password", _("Missing password"))

            default_origtarget = url_prefix() + "check_mk/"
            origtarget = request.get_url_input("_origtarget",
                                               default_origtarget)

            # Disallow redirections to:
            #  - logout.py: Happens after login
            #  - side.py: Happens when invalid login is detected during sidebar refresh
            if "logout.py" in origtarget or "side.py" in origtarget:
                origtarget = default_origtarget

            result = userdb.check_credentials(username, password)
            if result:
                # use the username provided by the successful login function, this function
                # might have transformed the username provided by the user. e.g. switched
                # from mixed case to lower case.
                username = result

                session_id = userdb.on_succeeded_login(username)

                # The login succeeded! Now:
                # a) Set the auth cookie
                # b) Unset the login vars in further processing
                # c) Redirect to really requested page
                _create_auth_session(username, session_id)

                # Never use inplace redirect handling anymore as used in the past. This results
                # in some unexpected situations. We simpy use 302 redirects now. So we have a
                # clear situation.
                # userdb.need_to_change_pw returns either False or the reason description why the
                # password needs to be changed
                change_pw_result = userdb.need_to_change_pw(username)
                if change_pw_result:
                    raise HTTPRedirect(
                        "user_change_pw.py?_origtarget=%s&reason=%s" %
                        (urlencode(origtarget), change_pw_result))

                if userdb.is_two_factor_login_enabled(username):
                    raise HTTPRedirect(
                        "user_login_two_factor.py?_origtarget=%s" %
                        urlencode(makeuri(request, [])))

                raise HTTPRedirect(origtarget)

            userdb.on_failed_login(username)
            raise MKUserError(None, _("Invalid login"))
        except MKUserError as e:
            user_errors.add(e)