diff --git a/README.md b/README.md index 6462bd1b..d8ad7e64 100644 --- a/README.md +++ b/README.md @@ -783,7 +783,7 @@ What an update from an older version changes for operators and users. `manage.py - Requests for a host not in `ALLOWED_HOSTS` get 400. The installer writes the server's names and IPs; add more with the `ALLOWED_HOSTS` env var. The cloud-init datasource host must be allowed too. - Logging out needs a POST; a GET to `/accounts/logout/` gets 405. - The API accepts only a session from the login form or an API token (no HTTP Basic), and the API docs need a login. Sessions opened through the old password-only doors skip OTP; end them once after the update (everyone signs in again): `manage.py shell -c "from django.contrib.sessions.models import Session; Session.objects.all().delete()"`. -- Failed logins lock a user (django-axes): the sign-in page then says how long. The limit and lock time are on the Settings page; unlock with `manage.py axes_reset_username `. A sign-in notice set there (e.g. planned maintenance) is shown above the sign-in form. +- Failed logins lock a user (django-axes): the sign-in page then says how long. The limit and lock time are on the Settings page; a locked user is marked on the Users page, and a superuser ends the lock with Unlock sign-in on the user's page. A sign-in lasts the session length set on the Settings page (24 hours by default). A sign-in notice set there (e.g. planned maintenance) is shown above the sign-in form. - Changing one's own password is the "Can change password" permission (per user or group; new users have it); `SHOW_PROFILE_EDIT_PASSWORD` is gone. - The admin's first-login password change survives losing `data/admin_password` (migration `accounts.0007`); run `migrate` as a user who can read that file. - A new VM and each clone get a random VNC password of their own (clones no longer share their source's). The console page sends it for a user with **Open a console without the VM's console password**, which a new user has unless unticked; others are asked for it. Existing VMs keep theirs. diff --git a/accounts/apps.py b/accounts/apps.py index 56925b7a..7ac5bf2b 100644 --- a/accounts/apps.py +++ b/accounts/apps.py @@ -112,4 +112,9 @@ class AccountsConfig(AppConfig): from django.db.models.signals import post_save post_save.connect(grant_change_password, sender=settings.AUTH_USER_MODEL) + from django.contrib.auth.signals import user_logged_in + + from .lockout import start_session + + user_logged_in.connect(start_session, dispatch_uid="accounts.session_length") from . import checks # noqa: F401 diff --git a/accounts/lockout.py b/accounts/lockout.py index 8bfa4785..84b8ae95 100644 --- a/accounts/lockout.py +++ b/accounts/lockout.py @@ -1,17 +1,22 @@ """ -Settings for django-axes, read from the Settings page (AppSettings) on each -use, so an administrator can change them without a restart. +Settings for django-axes and the session length, read from the Settings page +(AppSettings) on each use, so an administrator can change them without a +restart. """ from datetime import timedelta from ipaddress import ip_address, ip_network from appsettings.models import AppSettings +from axes.models import AccessAttempt from django.conf import settings +from django.db.models import Sum from django.shortcuts import render +from django.utils import timezone DEFAULT_FAILURE_LIMIT = 5 DEFAULT_LOCKOUT_MINUTES = 15 +DEFAULT_SESSION_HOURS = 24 def _positive_int(key, default): @@ -59,3 +64,26 @@ def lockout_response(request, original_response, credentials): """AXES_LOCKOUT_CALLABLE: the locked sign-in page, with the lock time.""" minutes = cooloff_time(request) // timedelta(minutes=1) return render(request, "accounts/lockout.html", {"minutes": minutes}, status=429) + + +def locked_usernames(): + """The usernames, in lower case, locked now from some address. As django-axes + counts them, a username's recent failures from one address add up over + the browsers they came from.""" + since = timezone.now() - cooloff_time(None) + per_address = (AccessAttempt.objects.filter(attempt_time__gte=since).values("username", "ip_address") + .annotate(failures=Sum("failures_since_start")).filter(failures__gte=failure_limit(None, {}))) + return {row["username"].lower() for row in per_address} + + +def unlock(username): + """End the username's locks, from every address and in any letter case; + returns how many records went.""" + return AccessAttempt.objects.filter(username__iexact=username).delete()[1].get(AccessAttempt._meta.label, 0) + + +def start_session(sender, request, user, **kwargs): + """user_logged_in: a session ends LOGIN_SESSION_HOURS after the sign-in (a + date, as a number of seconds would count again from each session save).""" + hours = _positive_int("LOGIN_SESSION_HOURS", DEFAULT_SESSION_HOURS) + request.session.set_expiry(timezone.now() + timedelta(hours=hours)) diff --git a/accounts/otp.py b/accounts/otp.py index fc95da79..694347cb 100644 --- a/accounts/otp.py +++ b/accounts/otp.py @@ -12,6 +12,8 @@ ignored. from django.contrib.auth.signals import user_login_failed from django.core.exceptions import ValidationError +from django.utils.translation import gettext_lazy as _ +from django.utils.translation import ngettext_lazy from django_otp.forms import OTPAuthenticationForm from django_otp.plugins.otp_totp.models import TOTPDevice @@ -19,6 +21,19 @@ from accounts.forms import BoundedUsernameMixin class SingleDeviceOTPForm(BoundedUsernameMixin, OTPAuthenticationForm): + # the errors this form can give, here so that the panel's catalogs translate them + otp_error_messages = dict( + OTPAuthenticationForm.otp_error_messages, + token_required=_("Please enter your OTP token."), + invalid_token=_("Invalid token. Please make sure you have entered it correctly."), + n_failed_attempts=ngettext_lazy( + "Verification temporarily disabled because of %(failure_count)d failed attempt, please try again soon.", + "Verification temporarily disabled because of %(failure_count)d failed attempts, please try again soon.", + "failure_count", + ), + verification_not_allowed=_("Verification of the token is currently disabled"), + ) + def _confirmed_totp(self, user, for_verify=False): """The user's oldest confirmed TOTP device, or None. With for_verify the row is locked (select_for_update) so the token's replay and diff --git a/accounts/templates/account.html b/accounts/templates/account.html index 77a2a14c..e143e51d 100644 --- a/accounts/templates/account.html +++ b/accounts/templates/account.html @@ -19,6 +19,7 @@ {% trans "Template editor" %} {% endif %} {% if not user.is_active %}{% trans "Blocked" %}{% endif %} + {% if locked %}{% trans "Sign-in locked" %}{% endif %}
{{ user.username }} @@ -32,6 +33,11 @@
{% bs_icon 'pencil' %} {% trans "Edit user" %} + {% if locked %} +
{% csrf_token %} + +
+ {% endif %} {% if otp_enabled %}
{% csrf_token %} diff --git a/accounts/templates/accounts/lockout.html b/accounts/templates/accounts/lockout.html index 485ef882..219c958f 100644 --- a/accounts/templates/accounts/lockout.html +++ b/accounts/templates/accounts/lockout.html @@ -8,7 +8,7 @@
-
+

{% trans "Sign-in locked" %}

{% blocktrans trimmed count minutes=minutes %} diff --git a/accounts/templates/accounts/otp_login.html b/accounts/templates/accounts/otp_login.html index 89e45c50..83212346 100644 --- a/accounts/templates/accounts/otp_login.html +++ b/accounts/templates/accounts/otp_login.html @@ -1,7 +1,6 @@ {% extends "base.html" %} {% load static %} {% load i18n %} -{% load django_bootstrap5 %} {% block title %}{% trans "WebVirtCloud" %} - {% trans "Sign In with OTP" %}{% endblock title %} @@ -26,7 +25,7 @@ {% if form.errors %}

{% endif %} diff --git a/accounts/tests/test_login_page.py b/accounts/tests/test_login_page.py index 98196335..165576bc 100644 --- a/accounts/tests/test_login_page.py +++ b/accounts/tests/test_login_page.py @@ -1,6 +1,7 @@ """The sign-in page: a failed sign-in keeps the username and puts the cursor on the password, a locked user gets a page with the lock time, and the -administrator's notice from the Settings page is shown above the form.""" +administrator's notice from the Settings page is shown above the form; a sign-in +lasts the hours set there, and a superuser can end a lock.""" from appsettings.models import AppSettings from django.contrib.auth import get_user_model @@ -54,3 +55,72 @@ class LoginPageTests(TestCase): self.assertNotContains(self.client.get(reverse("accounts:login")), "alert-info") AppSettings.objects.filter(key="LOGIN_NOTICE").update(value="Maintenance at <22:00>") self.assertContains(self.client.get(reverse("accounts:login")), "Maintenance at <22:00>") + + +@override_settings(OTP_ENABLED=False) +class SessionLengthTests(TestCase): + def test_a_sign_in_lasts_the_hours_from_the_settings_page(self): + get_user_model().objects.create_user("sl-user", password="right-pass-1") + self.client.post(reverse("accounts:login"), {"username": "sl-user", "password": "right-pass-1"}) + self.assertAlmostEqual(self.client.session.get_expiry_age(), 24 * 3600, delta=5) + AppSettings.objects.filter(key="LOGIN_SESSION_HOURS").update(value="2") + self.client.post(reverse("accounts:logout")) + self.client.post(reverse("accounts:login"), {"username": "sl-user", "password": "right-pass-1"}) + self.assertAlmostEqual(self.client.session.get_expiry_age(), 2 * 3600, delta=5) + # a later save of the session does not move the end + end = self.client.session.get_expiry_date() + session = self.client.session + session["touched"] = True + session.save() + self.assertEqual(self.client.session.get_expiry_date(), end) + + +@override_settings(OTP_ENABLED=False) +class UnlockTests(TestCase): + def setUp(self): + User = get_user_model() + self.user = User.objects.create_user("ul-user", password="right-pass-1") + self.admin = User.objects.create_superuser("ul-admin", "ul@example.com", "admin-pass-1") + AppSettings.objects.filter(key="LOGIN_FAILURE_LIMIT").update(value="2") + # one failure from each of two browsers at the same address, one typed in capitals + self.client.post(reverse("accounts:login"), {"username": "ul-user", "password": "wrong"}, + HTTP_USER_AGENT="browser-a") + self.client.post(reverse("accounts:login"), {"username": "UL-User", "password": "wrong"}, + HTTP_USER_AGENT="browser-b") + self.client.post(reverse("accounts:login"), {"username": "ul-user", "password": "wrong"}, + HTTP_USER_AGENT="browser-b") + + def sign_in_works(self): + client = self.client_class() + return client.post(reverse("accounts:login"), {"username": "ul-user", "password": "right-pass-1"}).status_code == 302 + + def test_the_lock_is_shown_and_a_superuser_ends_it(self): + self.assertFalse(self.sign_in_works()) + self.client.force_login(self.admin) + self.assertContains(self.client.get(reverse("admin:user_list")), "Sign-in locked") + self.assertContains(self.client.get(reverse("accounts:account", args=[self.user.pk])), "Unlock sign-in") + self.client.post(reverse("accounts:admin_unlock", args=[self.user.pk])) + self.assertTrue(self.sign_in_works()) + self.assertNotContains(self.client.get(reverse("accounts:account", args=[self.user.pk])), "Sign-in locked") + from logs.models import Logs + self.assertTrue(Logs.objects.filter(message__icontains="unlock sign-in").exists()) + + def test_only_a_superuser_unlocks(self): + other = get_user_model().objects.create_user("ul-other", password="other-pass-1") + self.client.force_login(other) + self.assertEqual(self.client.post(reverse("accounts:admin_unlock", args=[self.user.pk])).status_code, 403) + self.assertFalse(self.sign_in_works()) + + +@override_settings(OTP_ENABLED=False) +class BlockEndsSessionsTests(TestCase): + def test_a_blocked_user_is_signed_out(self): + User = get_user_model() + User.objects.create_user("bl-user", password="right-pass-1") + user_client = self.client_class() + user_client.post(reverse("accounts:login"), {"username": "bl-user", "password": "right-pass-1"}) + self.client.force_login(User.objects.create_superuser("bl-admin", "bl@example.com", "admin-pass-1")) + self.client.post(reverse("admin:user_block", args=[User.objects.get(username="bl-user").pk])) + self.assertEqual(user_client.get(reverse("instances:index")).status_code, 302) + from django.contrib.sessions.models import Session + self.assertEqual(Session.objects.count(), 1) # the administrator's diff --git a/accounts/urls.py b/accounts/urls.py index 1aec7c35..58b4a9a4 100644 --- a/accounts/urls.py +++ b/accounts/urls.py @@ -45,6 +45,7 @@ urlpatterns = [ name="admin_email_otp", ), path("admin_reset_otp//", views.admin_reset_otp, name="admin_reset_otp"), + path("admin_unlock//", views.admin_unlock, name="admin_unlock"), ] if settings.OTP_ENABLED: diff --git a/accounts/views.py b/accounts/views.py index 42aab5ed..6c158db4 100644 --- a/accounts/views.py +++ b/accounts/views.py @@ -33,6 +33,7 @@ from accounts.forms import ApiTokenForm, EmailOTPForm, ProfileForm, UserSSHKeyFo from accounts.models import ApiToken, User, UserAttributes, UserInstance, UserSSHKey from . import forms +from .lockout import locked_usernames, unlock from .utils import OTP_LINK, OTP_LINK_MAX_AGE, get_existing_totp_device, get_user_totp_device, otp_qr_svg, send_email_with_otp @@ -206,6 +207,7 @@ def account(request, user_id): "api_tokens": ApiToken.objects.filter(user_id=user_id), "otp_enabled": settings.OTP_ENABLED, "has_otp": TOTPDevice.objects.filter(user=user).exists(), + "locked": user.username.lower() in locked_usernames(), }, ) @@ -409,6 +411,17 @@ def admin_email_otp(request, user_id): return redirect("accounts:account", user.id) +@require_POST +@superuser_only +def admin_unlock(request, user_id): + """End the user's lock after failed sign-ins, from every address.""" + user = get_object_or_404(get_user_model(), pk=user_id) + with audit(request, None, f"User {user.username}", "unlock sign-in") as entry: + entry.skip = not unlock(user.username) # another administrator was first, or the lock ran out + messages.success(request, _("The sign-in lock of %(user)s is ended.") % {"user": user}) + return redirect("accounts:account", user.id) + + @require_POST @superuser_only def admin_reset_otp(request, user_id): diff --git a/admin/templates/admin/user_list.html b/admin/templates/admin/user_list.html index 61810df9..09d9c205 100644 --- a/admin/templates/admin/user_list.html +++ b/admin/templates/admin/user_list.html @@ -21,7 +21,7 @@
{% for user in users %} -
+
{{ user.username }} @@ -38,6 +38,9 @@ {% else %} {% trans "Blocked" %} {% endif %} + {% if user.username|lower in locked %} + {% trans "Sign-in locked" %} + {% endif %}
diff --git a/admin/views.py b/admin/views.py index 6cee548f..2dd8cda0 100644 --- a/admin/views.py +++ b/admin/views.py @@ -1,13 +1,15 @@ from contextlib import contextmanager from datetime import timedelta +from accounts.lockout import locked_usernames from accounts.models import ApiToken, Instance, UserAttributes, UserInstance from appsettings.settings import app_settings from computes.utils import lock_ownership, users_lock from django.conf import settings from django.contrib import messages -from django.contrib.auth import update_session_auth_hash +from django.contrib.auth import SESSION_KEY, update_session_auth_hash from django.contrib.auth.models import Group, Permission, User +from django.contrib.sessions.models import Session from django.core.paginator import Paginator from django.http import HttpResponse from django.db import IntegrityError, transaction @@ -179,6 +181,7 @@ def user_list(request): "admin/user_list.html", { "users": users, + "locked": locked_usernames(), "title": _("Users"), }, ) @@ -259,6 +262,7 @@ def user_update(request, pk): attributes = attributes_form.save() if not user.is_active: # as user_block ApiToken.objects.filter(user=user).delete() + end_sessions(user) fields = set(changed_fields(before, snapshot(user))) | set(changed_fields(before_attributes, snapshot(attributes))) fields = sorted(fields - {"password", "last_login"}) entry.action = "change " + ", ".join(fields) @@ -342,6 +346,14 @@ def user_delete(request, pk): ) +def end_sessions(user): + """Sign a blocked user out: django-auth-ldap does not check is_active for + an open session, so a blocked LDAP user would keep theirs.""" + for session in Session.objects.filter(expire_date__gt=timezone.now()): + if session.get_decoded().get(SESSION_KEY) == str(user.pk): + session.delete() + + @require_POST @superuser_only def user_block(request, pk): @@ -356,6 +368,7 @@ def user_block(request, pk): user.save(update_fields=["is_active"]) # not the rest as read before the lock # an unblock must not bring back the tokens of someone who took the account over ApiToken.objects.filter(user=user).delete() + end_sessions(user) except (NoSuperuser, claims.Busy) as err: refused(request, err) return redirect("admin:user_list") diff --git a/appsettings/migrations/0030_login_session_hours.py b/appsettings/migrations/0030_login_session_hours.py new file mode 100644 index 00000000..2e0dc538 --- /dev/null +++ b/appsettings/migrations/0030_login_session_hours.py @@ -0,0 +1,29 @@ +from django.core.management.color import no_style +from django.db import migrations +from django.utils.translation import gettext_noop as _ + +SETTING = (_("Session length (hours)"), "LOGIN_SESSION_HOURS", "24", + _("How long a sign-in lasts; a change applies from the next sign-in")) + + +def add_setting(apps, schema_editor): + setting = apps.get_model("appsettings", "AppSettings") + db_alias = schema_editor.connection.alias + # see 0014: move a PostgreSQL id sequence past the fixed ids first + with schema_editor.connection.cursor() as cursor: + for sql in schema_editor.connection.ops.sequence_reset_sql(no_style(), [setting]): + cursor.execute(sql) + name, key, value, description = SETTING + setting.objects.using(db_alias).get_or_create( + key=key, defaults={"name": name, "value": value, "choices": "", "description": description}) + + +def del_setting(apps, schema_editor): + apps.get_model("appsettings", "AppSettings").objects.using(schema_editor.connection.alias).filter( + key=SETTING[1]).delete() + + +class Migration(migrations.Migration): + dependencies = [("appsettings", "0029_login_notice")] + + operations = [migrations.RunPython(add_setting, del_setting)] diff --git a/appsettings/views.py b/appsettings/views.py index bfeeec8f..1be7f671 100644 --- a/appsettings/views.py +++ b/appsettings/views.py @@ -30,6 +30,7 @@ NUMBERS = { "LOGS_PER_PAGE": (1, 1000), "LOGIN_FAILURE_LIMIT": (1, 1000), "LOGIN_LOCKOUT_MINUTES": (1, 10080), + "LOGIN_SESSION_HOURS": (1, 8760), "SNAPSHOT_FREE_SPACE_PERCENT": (0, 100), "SNAPSHOT_FREE_SPACE_MIN_GIB": (0, 100000), "INSTANCE_VOLUME_DEFAULT_OWNER_UID": (0, 4294967294), @@ -57,7 +58,8 @@ GROUPS = [ (gettext_noop("Snapshots and jobs"), ["SNAPSHOT_FREE_SPACE_PERCENT", "SNAPSHOT_FREE_SPACE_MIN_GIB", "WORKER_CONCURRENCY", "JOB_RETENTION_DAYS"]), (gettext_noop("Migrations"), ["MIGRATION_BANDWIDTH"]), - (gettext_noop("Login"), ["LOGIN_FAILURE_LIMIT", "LOGIN_LOCKOUT_MINUTES", "LOGIN_NOTICE"]), + (gettext_noop("Login"), ["LOGIN_FAILURE_LIMIT", "LOGIN_LOCKOUT_MINUTES", "LOGIN_SESSION_HOURS", + "LOGIN_NOTICE"]), (gettext_noop("Alerts"), ["ALERT_EMAILS", "ALERT_WEBHOOK"]), (gettext_noop("Lists and pages"), ["VIEW_INSTANCES_LIST_STYLE", "VM_DRBD_STATUS", "LOGS_PER_PAGE", "LOG_RETENTION_DAYS"]), diff --git a/locale/tr/LC_MESSAGES/django.mo b/locale/tr/LC_MESSAGES/django.mo index 333554d7..6825c706 100644 Binary files a/locale/tr/LC_MESSAGES/django.mo and b/locale/tr/LC_MESSAGES/django.mo differ diff --git a/locale/tr/LC_MESSAGES/django.po b/locale/tr/LC_MESSAGES/django.po index ffc1204b..4b40bf0d 100644 --- a/locale/tr/LC_MESSAGES/django.po +++ b/locale/tr/LC_MESSAGES/django.po @@ -13047,3 +13047,36 @@ msgid "" "Shown above the sign-in form, e.g. planned maintenance or a terms-of-use " "line; empty: none" msgstr "Oturum açma formunun üstünde gösterilir; örneğin planlı bakım ya da kullanım koşulları satırı; boş: yok" + +#: accounts/templates/account.html:38 +msgid "Unlock sign-in" +msgstr "Oturum açma kilidini kaldır" + +#: accounts/views.py:427 +#, python-format +msgid "The sign-in lock of %(user)s is ended." +msgstr "%(user)s kullanıcısının oturum açma kilidi kaldırıldı." + +#: appsettings/migrations/0030_login_session_hours.py:5 +msgid "Session length (hours)" +msgstr "Oturum süresi (saat)" + +#: appsettings/migrations/0030_login_session_hours.py:6 +msgid "How long a sign-in lasts; a change applies from the next sign-in" +msgstr "Bir oturum ne kadar açık kalır; değişiklik bir sonraki oturum açmadan itibaren geçerlidir" + +#. django-otp's sign-in errors, shown on the OTP sign-in page +msgid "Please enter your OTP token." +msgstr "Lütfen doğrulama kodunuzu girin." + +msgid "Invalid token. Please make sure you have entered it correctly." +msgstr "Geçersiz kod. Lütfen doğru girdiğinizden emin olun." + +#, python-format +msgid "Verification temporarily disabled because of %(failure_count)d failed attempt, please try again soon." +msgid_plural "Verification temporarily disabled because of %(failure_count)d failed attempts, please try again soon." +msgstr[0] "%(failure_count)d başarısız deneme nedeniyle doğrulama geçici olarak kapatıldı; lütfen biraz sonra tekrar deneyin." +msgstr[1] "%(failure_count)d başarısız deneme nedeniyle doğrulama geçici olarak kapatıldı; lütfen biraz sonra tekrar deneyin." + +msgid "Verification of the token is currently disabled" +msgstr "Kod doğrulaması şu anda kapalı" diff --git a/locale/zh/LC_MESSAGES/django.mo b/locale/zh/LC_MESSAGES/django.mo index 600bd8c1..355cd220 100644 Binary files a/locale/zh/LC_MESSAGES/django.mo and b/locale/zh/LC_MESSAGES/django.mo differ diff --git a/locale/zh/LC_MESSAGES/django.po b/locale/zh/LC_MESSAGES/django.po index 7ce5daa5..d5885b32 100644 --- a/locale/zh/LC_MESSAGES/django.po +++ b/locale/zh/LC_MESSAGES/django.po @@ -12219,3 +12219,35 @@ msgid "" "Shown above the sign-in form, e.g. planned maintenance or a terms-of-use " "line; empty: none" msgstr "显示在登录表单上方,例如计划维护或使用条款;留空:不显示" + +#: accounts/templates/account.html:38 +msgid "Unlock sign-in" +msgstr "解除登录锁定" + +#: accounts/views.py:427 +#, python-format +msgid "The sign-in lock of %(user)s is ended." +msgstr "%(user)s 的登录锁定已解除。" + +#: appsettings/migrations/0030_login_session_hours.py:5 +msgid "Session length (hours)" +msgstr "会话时长(小时)" + +#: appsettings/migrations/0030_login_session_hours.py:6 +msgid "How long a sign-in lasts; a change applies from the next sign-in" +msgstr "一次登录保持多久;修改从下次登录起生效" + +#. django-otp's sign-in errors, shown on the OTP sign-in page +msgid "Please enter your OTP token." +msgstr "请输入您的验证码。" + +msgid "Invalid token. Please make sure you have entered it correctly." +msgstr "验证码无效。请确认输入正确。" + +#, python-format +msgid "Verification temporarily disabled because of %(failure_count)d failed attempt, please try again soon." +msgid_plural "Verification temporarily disabled because of %(failure_count)d failed attempts, please try again soon." +msgstr[0] "由于 %(failure_count)d 次验证失败,验证已暂时停用,请稍后再试。" + +msgid "Verification of the token is currently disabled" +msgstr "当前已停用验证码验证"