diff --git a/src/coulobre/hosting/account_security.py b/src/coulobre/hosting/account_security.py
new file mode 100644
index 0000000..50dc7f9
--- /dev/null
+++ b/src/coulobre/hosting/account_security.py
@@ -0,0 +1,463 @@
+import secrets
+from datetime import timedelta
+from smtplib import SMTPException
+
+import django_otp
+from django import forms
+from django.conf import settings
+from django.contrib import messages
+from django.contrib.auth import update_session_auth_hash
+from django.contrib.auth.hashers import check_password
+from django.contrib.auth.mixins import LoginRequiredMixin
+from django.contrib.auth.password_validation import validate_password
+from django.core.exceptions import PermissionDenied
+from django.core.mail import send_mail
+from django.db import transaction
+from django.shortcuts import redirect, render
+from django.urls import reverse_lazy
+from django.utils import timezone
+from django.utils.crypto import constant_time_compare
+from django.utils.decorators import method_decorator
+from django.views.decorators.cache import never_cache
+from django.views.decorators.debug import (
+ sensitive_post_parameters,
+ sensitive_variables,
+)
+from django.views.generic import FormView, TemplateView
+from django_otp.plugins.otp_email.models import EmailDevice
+from django_otp.plugins.otp_totp.models import TOTPDevice
+
+from .models import PanelEmailChange, PanelSecurityEvent
+from .panel_factors import (
+ DEVICE_NAME,
+ DEVICE_TYPES,
+ RECOVERY_SIGN_IN,
+ confirmed_device,
+ device_for_user,
+ lock_user,
+ replace_recovery_codes,
+ secret_digest,
+ send_factor_code,
+ user_devices,
+)
+from .panel_sessions import (
+ preserve_session,
+ record_security_event,
+ revoke_other_sessions,
+ session_is_current,
+)
+from .sign_in import ConfirmFactorForm, authenticator_setup
+from .sign_in_limits import limit_attempt
+
+Action = PanelSecurityEvent.Action
+ACCOUNT_URL = reverse_lazy("panel:account_security")
+FACTOR_SETUP = "coulobre_account_factor_setup"
+
+
+class AccountSecurityMixin(LoginRequiredMixin):
+ @method_decorator(never_cache)
+ def dispatch(self, request, *args, **kwargs):
+ if getattr(request, "impersonation", None):
+ raise PermissionDenied
+ return super().dispatch(request, *args, **kwargs)
+
+
+class AccountSecurityView(AccountSecurityMixin, TemplateView):
+ template_name = "hosting/account_security.html"
+
+ def get_context_data(self, **kwargs):
+ user = self.request.user
+ device = confirmed_device(user)
+ factor = "Authenticator app" if device else "Not set up"
+ if isinstance(device, EmailDevice):
+ factor = "Email code"
+ return super().get_context_data(
+ factor=factor,
+ factor_enabled=device is not None,
+ email_available=bool(settings.EMAIL_HOST),
+ events=PanelSecurityEvent.objects.filter(user=user).order_by(
+ "-id"
+ )[:10],
+ **kwargs,
+ )
+
+
+class AuthorizeForm(forms.Form):
+ password = forms.CharField(
+ label="Current password",
+ strip=False,
+ max_length=4096,
+ widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}),
+ )
+ code = ConfirmFactorForm.base_fields["code"]
+
+
+class PasswordForm(AuthorizeForm):
+ new_password = forms.CharField(
+ max_length=4096,
+ strip=False,
+ widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
+ )
+ confirm_password = forms.CharField(
+ max_length=4096,
+ strip=False,
+ widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
+ )
+
+ def clean(self):
+ cleaned = super().clean()
+ if (
+ "new_password" in cleaned
+ and "confirm_password" in cleaned
+ and cleaned["new_password"] != cleaned["confirm_password"]
+ ):
+ self.add_error("confirm_password", "The passwords differ.")
+ return cleaned
+
+
+class EmailForm(AuthorizeForm):
+ email = forms.EmailField(label="New email address", max_length=254)
+
+
+class VerifyEmailForm(forms.Form):
+ code = forms.RegexField(
+ r"\A[0-9a-fA-F]{12}\Z",
+ label="Email verification code",
+ widget=forms.TextInput(attrs={"autocomplete": "one-time-code"}),
+ )
+
+
+@method_decorator(sensitive_post_parameters(), name="dispatch")
+class SecurityFormView(AccountSecurityMixin, FormView):
+ template_name = "hosting/account_security_form.html"
+ success_url = ACCOUNT_URL
+ instructions = ""
+
+ def get_context_data(self, **kwargs):
+ return super().get_context_data(
+ heading=self.heading, instructions=self.instructions, **kwargs
+ )
+
+ def post(self, request, *args, **kwargs):
+ return limit_attempt(
+ request,
+ "account-security",
+ str(request.user.pk),
+ address_limit=30,
+ identity_limit=10,
+ ) or super().post(request, *args, **kwargs)
+
+ def locked_user(self):
+ user = lock_user(self.request.user.pk)
+ if (
+ not user.is_active
+ or not session_is_current(self.request, user)
+ or not constant_time_compare(
+ user.get_session_auth_hash(),
+ self.request.user.get_session_auth_hash(),
+ )
+ ):
+ raise PermissionDenied
+ return user
+
+ def changed_access(self, user, action):
+ version = revoke_other_sessions(user)
+ record_security_event(user, action)
+ self.request.session.pop(RECOVERY_SIGN_IN, None)
+ self.request.session.pop(FACTOR_SETUP, None)
+ preserve_session(self.request, version)
+
+ @sensitive_variables("codes")
+ def show_recovery_codes(self, codes):
+ return render(
+ self.request,
+ "hosting/factor_recovery_codes.html",
+ {
+ "recovery_codes": "\n".join(codes),
+ "destination": self.success_url,
+ },
+ )
+
+
+class AuthorizedSecurityChange(SecurityFormView):
+ form_class = AuthorizeForm
+
+ def get_form(self, form_class=None):
+ form = super().get_form(form_class)
+ if confirmed_device(self.request.user) is None:
+ del form.fields["code"]
+ return form
+
+ def get_context_data(self, **kwargs):
+ return super().get_context_data(
+ can_send_code=isinstance(
+ confirmed_device(self.request.user), EmailDevice
+ ),
+ **kwargs,
+ )
+
+ def post(self, request, *args, **kwargs):
+ if "send_code" not in request.POST:
+ return super().post(request, *args, **kwargs)
+ device = confirmed_device(request.user)
+ if not isinstance(device, EmailDevice):
+ raise PermissionDenied
+ messages.info(
+ request,
+ send_factor_code(
+ request.user, device.persistent_id, confirmed=True
+ ),
+ )
+ return redirect(request.path)
+
+ @transaction.atomic
+ @sensitive_variables("form")
+ def form_valid(self, form):
+ user = self.locked_user()
+ if not check_password(form.cleaned_data["password"], user.password):
+ form.add_error("password", "The current password is incorrect.")
+ return self.form_invalid(form)
+
+ self.validate_change(user, form)
+ if form.errors:
+ return self.form_invalid(form)
+
+ if not self.verify_current_factor(user, form):
+ form.add_error(
+ "code", "Enter a valid code from your current factor."
+ )
+ return self.form_invalid(form)
+ return self.apply_change(user, form)
+
+ def verify_current_factor(self, user, form):
+ device = confirmed_device(user)
+ return device is None or device.verify_token(
+ form.cleaned_data.get("code", "")
+ )
+
+ def validate_change(self, user, form):
+ pass
+
+
+class ChangePasswordView(AuthorizedSecurityChange):
+ heading = "Change password"
+ instructions = "Changing your password signs out your other sessions."
+ form_class = PasswordForm
+
+ def validate_change(self, user, form):
+ try:
+ validate_password(form.cleaned_data["new_password"], user)
+ except forms.ValidationError as error:
+ form.add_error("new_password", error)
+
+ @sensitive_variables("form")
+ def apply_change(self, user, form):
+ user.set_password(form.cleaned_data["new_password"])
+ user.save(update_fields=["password"])
+ update_session_auth_hash(self.request, user)
+ self.changed_access(user, Action.PASSWORD)
+ messages.success(self.request, "Your password was changed.")
+ return redirect(self.success_url)
+
+
+class ChangeEmailView(AuthorizedSecurityChange):
+ heading = "Change email address"
+ instructions = "We will send a verification code to your new address."
+ form_class = EmailForm
+
+ def dispatch(self, request, *args, **kwargs):
+ if not settings.EMAIL_HOST:
+ raise PermissionDenied
+ return super().dispatch(request, *args, **kwargs)
+
+ def validate_change(self, user, form):
+ if form.cleaned_data["email"].casefold() == user.email.casefold():
+ form.add_error("email", "Enter a different email address.")
+
+ @sensitive_variables("code")
+ def apply_change(self, user, form):
+ email = form.cleaned_data["email"]
+ code = secrets.token_hex(6)
+ try:
+ sent = send_mail(
+ "Verify your new Coulobre Panel email address",
+ f"Enter {code} on the page where you requested the change. "
+ "The code expires in 15 minutes.",
+ None,
+ [email],
+ )
+ except (OSError, SMTPException):
+ sent = 0
+ if sent != 1:
+ form.add_error(None, "The verification email could not be sent.")
+ return self.form_invalid(form)
+
+ PanelEmailChange.objects.update_or_create(
+ user=user,
+ defaults={
+ "email": email,
+ "digest": secret_digest("email-change", code),
+ "session_digest": self.session_digest(),
+ "expires_at": timezone.now() + timedelta(minutes=15),
+ },
+ )
+ return redirect("panel:account_email_verify")
+
+ def session_digest(self):
+ return secret_digest("email-session", self.request.session.session_key)
+
+
+def notify_old_address(email):
+ send_mail(
+ "Your Coulobre Panel email address changed",
+ "The email address on your account was changed. Contact your hosting "
+ "provider if you did not request this change.",
+ None,
+ [email],
+ )
+
+
+class VerifyEmailView(SecurityFormView):
+ heading = "Verify your new email address"
+ form_class = VerifyEmailForm
+
+ @sensitive_variables("form")
+ @transaction.atomic
+ def form_valid(self, form):
+ user = self.locked_user()
+ pending = PanelEmailChange.objects.filter(user=user).first()
+ session_digest = secret_digest(
+ "email-session", self.request.session.session_key
+ )
+ code_digest = secret_digest(
+ "email-change", form.cleaned_data["code"].lower()
+ )
+ if (
+ pending is None
+ or pending.expires_at <= timezone.now()
+ or not constant_time_compare(
+ pending.session_digest, session_digest
+ )
+ or not constant_time_compare(pending.digest, code_digest)
+ ):
+ form.add_error(
+ "code", "The verification code is invalid or expired."
+ )
+ return self.form_invalid(form)
+
+ previous_email = user.email
+ user.email = pending.email
+ user.save(update_fields=["email"])
+ user_devices(user, EmailDevice).update(
+ email=user.email, token=None, valid_until=timezone.now()
+ )
+ self.changed_access(user, Action.EMAIL)
+ if previous_email:
+ transaction.on_commit(
+ lambda: notify_old_address(previous_email), robust=True
+ )
+ messages.success(self.request, "Your email address was changed.")
+ return redirect(self.success_url)
+
+
+class StartAuthenticatorView(AuthorizedSecurityChange):
+ heading = "Set up an authenticator app"
+ instructions = "Your current factor works until you verify the new app."
+
+ def recently_used_recovery_code(self, user):
+ recovery = self.request.session.get(RECOVERY_SIGN_IN, {})
+ if recovery.get("expires", 0) <= int(timezone.now().timestamp()):
+ return False
+ device = confirmed_device(user)
+ return device is not None and recovery.get("device") == (
+ device.persistent_id
+ )
+
+ def get_form(self, form_class=None):
+ form = super().get_form(form_class)
+ if self.recently_used_recovery_code(self.request.user):
+ form.fields.pop("code", None)
+ return form
+
+ def verify_current_factor(self, user, form):
+ return self.recently_used_recovery_code(
+ user
+ ) or super().verify_current_factor(user, form)
+
+ def apply_change(self, user, form):
+ self.request.session.pop(RECOVERY_SIGN_IN, None)
+ for device_type in DEVICE_TYPES.values():
+ user_devices(user, device_type).filter(confirmed=False).delete()
+ pending = TOTPDevice.objects.create(
+ user=user, name=DEVICE_NAME, confirmed=False
+ )
+ self.request.session[FACTOR_SETUP] = {
+ "device": pending.persistent_id,
+ "expires": int(timezone.now().timestamp()) + 600,
+ }
+ return redirect("panel:account_authenticator_confirm")
+
+
+class ConfirmAuthenticatorView(SecurityFormView):
+ heading = "Verify your authenticator app"
+ form_class = ConfirmFactorForm
+
+ def pending_device(self, user):
+ setup = self.request.session.get(FACTOR_SETUP, {})
+ if setup.get("expires", 0) <= int(timezone.now().timestamp()):
+ return None
+ return device_for_user(user, setup.get("device"), confirmed=False)
+
+ def get(self, request, *args, **kwargs):
+ if self.pending_device(request.user) is None:
+ return redirect("panel:account_authenticator")
+ return super().get(request, *args, **kwargs)
+
+ def get_context_data(self, **kwargs):
+ pending = self.pending_device(self.request.user)
+ context = authenticator_setup(pending) if pending else {}
+ return super().get_context_data(**context, **kwargs)
+
+ @sensitive_variables("form")
+ @transaction.atomic
+ def form_valid(self, form):
+ user = self.locked_user()
+ pending = self.pending_device(user)
+ if pending is None or not pending.verify_token(
+ form.cleaned_data["code"]
+ ):
+ form.add_error(
+ "code", "The verification code is invalid or expired."
+ )
+ return self.form_invalid(form)
+ for device_type in DEVICE_TYPES.values():
+ user_devices(user, device_type).filter(confirmed=True).delete()
+ pending.confirmed = True
+ pending.save(update_fields=["confirmed"])
+ django_otp.login(self.request, pending)
+ self.request.session.pop(FACTOR_SETUP, None)
+ self.changed_access(user, Action.FACTOR)
+ return self.show_recovery_codes(replace_recovery_codes(user))
+
+
+class ReplaceRecoveryCodesView(AuthorizedSecurityChange):
+ heading = "Generate new recovery codes"
+ instructions = "Generating new codes invalidates all your existing codes."
+
+ def validate_change(self, user, form):
+ if confirmed_device(user) is None:
+ form.add_error(None, "Set up a second factor first.")
+
+ def apply_change(self, user, form):
+ self.changed_access(user, Action.RECOVERY)
+ return self.show_recovery_codes(replace_recovery_codes(user))
+
+
+class SignOutOtherSessionsView(AuthorizedSecurityChange):
+ heading = "Sign out other sessions"
+ instructions = "This browser stays signed in."
+
+ def apply_change(self, user, form):
+ self.changed_access(user, Action.SESSIONS)
+ messages.success(self.request, "Your other sessions were signed out.")
+ return redirect(self.success_url)
diff --git a/src/coulobre/hosting/migrations/0057_panel_account_security.py b/src/coulobre/hosting/migrations/0057_panel_account_security.py
new file mode 100644
index 0000000..a4af61b
--- /dev/null
+++ b/src/coulobre/hosting/migrations/0057_panel_account_security.py
@@ -0,0 +1,108 @@
+# Generated by Django 5.2.19 on 2026-11-22 23:08
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("hosting", "0056_dns_zone_defaults"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="PanelAccountSecurity",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("session_version", models.PositiveBigIntegerField(default=0)),
+ (
+ "user",
+ models.OneToOneField(
+ on_delete=django.db.models.deletion.CASCADE,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ ),
+ migrations.CreateModel(
+ name="PanelEmailChange",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("email", models.EmailField(max_length=254)),
+ ("digest", models.CharField(max_length=64)),
+ ("session_digest", models.CharField(max_length=64)),
+ ("expires_at", models.DateTimeField()),
+ (
+ "user",
+ models.OneToOneField(
+ on_delete=django.db.models.deletion.CASCADE,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ ),
+ migrations.CreateModel(
+ name="PanelSecurityEvent",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("username", models.CharField(max_length=150)),
+ (
+ "action",
+ models.CharField(
+ choices=[
+ ("password", "Password changed"),
+ ("email", "Email address changed"),
+ ("factor", "Authenticator updated"),
+ ("recovery", "Recovery codes replaced"),
+ ("reset", "Operator-issued factor recovery"),
+ ("sessions", "Other sessions signed out"),
+ ],
+ max_length=12,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "user",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "indexes": [
+ models.Index(
+ fields=["user", "-id"],
+ name="hosting_pan_user_id_9e9e3e_idx",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py
index 55bba3f..749b761 100644
--- a/src/coulobre/hosting/models.py
+++ b/src/coulobre/hosting/models.py
@@ -1354,3 +1354,40 @@ class PanelRecoveryCode(models.Model):
name="hosting_unique_panel_recovery_code",
)
]
+
+
+class PanelAccountSecurity(models.Model):
+ user = models.OneToOneField(
+ settings.AUTH_USER_MODEL, on_delete=models.CASCADE
+ )
+ session_version = models.PositiveBigIntegerField(default=0)
+
+
+class PanelEmailChange(models.Model):
+ user = models.OneToOneField(
+ settings.AUTH_USER_MODEL, on_delete=models.CASCADE
+ )
+ email = models.EmailField()
+ digest = models.CharField(max_length=64)
+ session_digest = models.CharField(max_length=64)
+ expires_at = models.DateTimeField()
+
+
+class PanelSecurityEvent(models.Model):
+ class Action(models.TextChoices):
+ PASSWORD = "password", "Password changed"
+ EMAIL = "email", "Email address changed"
+ FACTOR = "factor", "Authenticator updated"
+ RECOVERY = "recovery", "Recovery codes replaced"
+ RESET = "reset", "Operator-issued factor recovery"
+ SESSIONS = "sessions", "Other sessions signed out"
+
+ user = models.ForeignKey(
+ settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
+ )
+ username = models.CharField(max_length=150)
+ action = models.CharField(max_length=12, choices=Action.choices)
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ indexes = [models.Index(fields=["user", "-id"])]
diff --git a/src/coulobre/hosting/panel_factors.py b/src/coulobre/hosting/panel_factors.py
index 659ef80..1aaffd6 100644
--- a/src/coulobre/hosting/panel_factors.py
+++ b/src/coulobre/hosting/panel_factors.py
@@ -17,7 +17,17 @@ from django_otp.models import Device
from django_otp.plugins.otp_email.models import EmailDevice
from django_otp.plugins.otp_totp.models import TOTPDevice
-from .models import PanelFactorEnrollment, PanelRecoveryCode
+from .models import (
+ PanelFactorEnrollment,
+ PanelRecoveryCode,
+ PanelSecurityEvent,
+)
+from .panel_sessions import (
+ SESSION_VERSION,
+ record_security_event,
+ revoke_other_sessions,
+ session_version,
+)
DEVICE_NAME = "Coulobre Panel"
DEVICE_TYPES = {"authenticator": TOTPDevice, "email": EmailDevice}
@@ -25,6 +35,7 @@ CHALLENGE_SESSION = "coulobre_panel_challenge"
SETUP_SESSION = "coulobre_panel_factor_device"
SETUP_EXPIRES = "coulobre_panel_factor_expiry"
SETUP_DESTINATION = "coulobre_panel_factor_destination"
+RECOVERY_SIGN_IN = "coulobre_panel_recovery_sign_in"
CHALLENGE_SECONDS = 300
ENROLLMENT_MINUTES = 20
@@ -39,7 +50,12 @@ def privileged_user(user):
def requires_panel_factor(user):
- return settings.REQUIRE_PRIVILEGED_MFA and privileged_user(user)
+ return user.is_authenticated and (
+ settings.REQUIRE_PRIVILEGED_MFA
+ and privileged_user(user)
+ or confirmed_device(user) is not None
+ or recovery_required(user)
+ )
def lock_user(user_id):
@@ -111,6 +127,8 @@ def issue_recovery_enrollment(user):
+ timedelta(minutes=ENROLLMENT_MINUTES),
},
)
+ revoke_other_sessions(user)
+ record_security_event(user, PanelSecurityEvent.Action.RESET)
return code
@@ -162,10 +180,12 @@ def start_challenge(request, user, destination):
request.session.cycle_key()
rotate_token(request)
request.session.pop(SETUP_SESSION, None)
+ request.session.pop(RECOVERY_SIGN_IN, None)
request.session[CHALLENGE_SESSION] = {
"user": user.pk,
"backend": user.backend,
"auth_hash": user.get_session_auth_hash(),
+ "session_version": session_version(user),
"expires": int(timezone.now().timestamp()) + CHALLENGE_SECONDS,
"next": destination,
}
@@ -184,6 +204,7 @@ def pending_user(request):
data["expires"] > int(timezone.now().timestamp())
and user is not None
and requires_panel_factor(user)
+ and data.get("session_version", 0) == session_version(user)
and constant_time_compare(
data["auth_hash"], user.get_session_auth_hash()
)
@@ -204,6 +225,7 @@ def complete_challenge(request, user, device):
else:
data = request.session.pop(CHALLENGE_SESSION)
login(request, user, backend=data["backend"])
+ request.session[SESSION_VERSION] = data.get("session_version", 0)
destination = data["next"]
django_otp.login(request, device)
return destination
@@ -223,6 +245,12 @@ def confirm_enrollment(user, device_id, token):
device.confirmed = True
device.save(update_fields=["confirmed"])
PanelFactorEnrollment.objects.filter(user=user).delete()
+ return device, replace_recovery_codes(user)
+
+
+@sensitive_variables("codes")
+def replace_recovery_codes(user):
+ PanelRecoveryCode.objects.filter(user=user).delete()
codes = [secrets.token_hex(10) for _ in range(10)]
PanelRecoveryCode.objects.bulk_create(
[
@@ -232,7 +260,7 @@ def confirm_enrollment(user, device_id, token):
for code in codes
]
)
- return device, codes
+ return codes
@sensitive_variables("code")
diff --git a/src/coulobre/hosting/panel_sessions.py b/src/coulobre/hosting/panel_sessions.py
new file mode 100644
index 0000000..d5bbe20
--- /dev/null
+++ b/src/coulobre/hosting/panel_sessions.py
@@ -0,0 +1,73 @@
+from django.contrib.auth import logout
+from django.contrib.auth.views import redirect_to_login
+from django.db.models import F
+from django.middleware.csrf import rotate_token
+
+from .models import (
+ PanelAccountSecurity,
+ PanelEmailChange,
+ PanelSecurityEvent,
+ PhpMyAdminGrant,
+ RoundcubeGrant,
+)
+
+SESSION_VERSION = "coulobre_account_session_version"
+
+
+def session_version(user):
+ return (
+ PanelAccountSecurity.objects.filter(user=user)
+ .values_list("session_version", flat=True)
+ .first()
+ or 0
+ )
+
+
+def session_is_current(request, user):
+ return request.session.get(SESSION_VERSION, 0) == session_version(user)
+
+
+def revoke_other_sessions(user):
+ state, _ = PanelAccountSecurity.objects.get_or_create(user=user)
+ PanelAccountSecurity.objects.filter(pk=state.pk).update(
+ session_version=F("session_version") + 1
+ )
+ PanelEmailChange.objects.filter(user=user).delete()
+ for grants in (PhpMyAdminGrant, RoundcubeGrant):
+ grants.objects.filter(actor=user, redeemed_at__isnull=True).delete()
+ return session_version(user)
+
+
+def preserve_session(request, new_version):
+ request.session.cycle_key()
+ request.session[SESSION_VERSION] = new_version
+ rotate_token(request)
+
+
+def record_security_event(user, action):
+ PanelSecurityEvent.objects.create(
+ user=user, username=user.get_username(), action=action
+ )
+
+
+class PanelSessionMiddleware:
+ def __init__(self, get_response):
+ self.get_response = get_response
+
+ def __call__(self, request):
+ return self.get_response(request)
+
+ def process_view(self, request, view_func, view_args, view_kwargs):
+ if request.user.is_authenticated and not session_is_current(
+ request, request.user
+ ):
+ logout(request)
+ if request.resolver_match.view_name == "panel:logout":
+ return None
+ destination = (
+ request.get_full_path()
+ if request.method in {"GET", "HEAD"}
+ else "/"
+ )
+ return redirect_to_login(destination)
+ return None
diff --git a/src/coulobre/hosting/sign_in.py b/src/coulobre/hosting/sign_in.py
index 4e6b503..530aa68 100644
--- a/src/coulobre/hosting/sign_in.py
+++ b/src/coulobre/hosting/sign_in.py
@@ -6,6 +6,7 @@ from django.contrib.auth import logout
from django.contrib.auth.views import LoginView, redirect_to_login
from django.shortcuts import redirect, render
from django.urls import reverse
+from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.decorators.debug import (
@@ -17,6 +18,8 @@ from django_otp.plugins.otp_email.models import EmailDevice
from qrcode.image.svg import SvgPathFillImage
from .panel_factors import (
+ CHALLENGE_SECONDS,
+ RECOVERY_SIGN_IN,
SETUP_SESSION,
begin_enrollment,
complete_challenge,
@@ -33,10 +36,24 @@ from .panel_factors import (
start_initial_setup,
verify_factor,
)
+from .panel_sessions import SESSION_VERSION, session_version
from .password_reset import reset_enabled
from .sign_in_limits import limit_attempt
+@sensitive_variables("configuration_url")
+def authenticator_setup(device):
+ configuration_url = device.config_url
+ qr = qrcode.make(
+ configuration_url, image_factory=SvgPathFillImage
+ ).to_string(encoding="utf-8")
+ return {
+ "setup_key": base64.b32encode(device.bin_key).decode(),
+ "configuration_url": configuration_url,
+ "qr_image": base64.b64encode(qr).decode("ascii"),
+ }
+
+
class PrivilegedFactorMiddleware:
def __init__(self, get_response):
self.get_response = get_response
@@ -88,13 +105,17 @@ class PanelLoginView(LoginView):
def form_valid(self, form):
user = form.get_user()
+ current_version = session_version(user)
if not requires_panel_factor(user):
- return super().form_valid(form)
+ response = super().form_valid(form)
+ self.request.session[SESSION_VERSION] = current_version
+ return response
destination = self.get_success_url()
if confirmed_device(user) or recovery_required(user):
start_challenge(self.request, user, destination)
return redirect("panel:factor_verify")
super().form_valid(form)
+ self.request.session[SESSION_VERSION] = current_version
start_initial_setup(self.request, destination)
if not email_factor_available(user):
device = begin_enrollment(user, "authenticator")
@@ -234,12 +255,19 @@ class VerifyFactorView(FactorView):
def form_valid(self, form):
if self.current_device() is None:
return redirect("panel:factor_enroll")
- verified = verify_factor(self.user, form.cleaned_data["code"])
+ code = form.cleaned_data["code"]
+ verified = verify_factor(self.user, code)
if verified is None:
return self.rejected(
form, "Invalid or unavailable code. Try again."
)
- return redirect(complete_challenge(self.request, self.user, verified))
+ destination = complete_challenge(self.request, self.user, verified)
+ if len(code) == 20:
+ self.request.session[RECOVERY_SIGN_IN] = {
+ "device": verified.persistent_id,
+ "expires": int(timezone.now().timestamp()) + CHALLENGE_SECONDS,
+ }
+ return redirect(destination)
class EnrollFactorView(FactorView):
@@ -309,15 +337,7 @@ class ConfirmFactorView(FactorView):
if isinstance(device, EmailDevice):
context["email_factor"] = True
elif device:
- configuration_url = device.config_url
- qr = qrcode.make(
- configuration_url, image_factory=SvgPathFillImage
- ).to_string(encoding="utf-8")
- context = {
- "setup_key": base64.b32encode(device.bin_key).decode(),
- "configuration_url": configuration_url,
- "qr_image": base64.b64encode(qr).decode("ascii"),
- }
+ context = authenticator_setup(device)
return super().get_context_data(**context, **kwargs)
@sensitive_variables("codes")
diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css
index d20974b..63b5bdf 100644
--- a/src/coulobre/hosting/static/hosting/panel.css
+++ b/src/coulobre/hosting/static/hosting/panel.css
@@ -326,6 +326,11 @@ button, input, select, textarea {
font-weight: 650;
}
+.sidebar-account a {
+ color: inherit;
+ text-underline-offset: 0.2em;
+}
+
.sidebar-account button {
padding: 0;
border: 0;
diff --git a/src/coulobre/hosting/templates/hosting/account_security.html b/src/coulobre/hosting/templates/hosting/account_security.html
new file mode 100644
index 0000000..1e152fb
--- /dev/null
+++ b/src/coulobre/hosting/templates/hosting/account_security.html
@@ -0,0 +1,35 @@
+{% extends "hosting/base.html" %}
+{% block title %}My account · Coulobre Panel{% endblock %}
+{% block content %}
+ My account
{{ message }}
{% endfor %} +Email changes require configured panel email delivery.
{% endif %} +| Action | Time (UTC) |
|---|---|
| {{ event.get_action_display }} | {{ event.created_at|date:"j M Y, H:i" }} |
{{ message }}
{% endfor %} +{{ instructions }}
{% endif %} + {% include "hosting/authenticator_setup.html" %} + +{{ instructions }}
{% endif %} {% if code_notice %}{{ code_notice }}
{% endif %} -{% if configuration_url %} -Scan this QR code with your authenticator app.
-