diff --git a/deploy/apache/panel-proxy.inc b/deploy/apache/panel-proxy.inc index ea06fc7..dd7e0d3 100644 --- a/deploy/apache/panel-proxy.inc +++ b/deploy/apache/panel-proxy.inc @@ -5,6 +5,7 @@ RequestHeader unset X-Forwarded-Protocol RequestHeader unset X-Forwarded-Ssl RequestHeader set X-Forwarded-Proto "https" RequestHeader set X-Forwarded-For "expr=%{REMOTE_ADDR}" +RequestHeader set X-Coulobre-Client-IP "expr=%{REMOTE_ADDR}" ProxyPass /static/ ! Alias /static/ /var/www/coulobre-panel-static/ diff --git a/deploy/panel.env.example b/deploy/panel.env.example index 9a69392..595cb18 100644 --- a/deploy/panel.env.example +++ b/deploy/panel.env.example @@ -1,6 +1,16 @@ DJANGO_SETTINGS_MODULE=coulobre.settings COULOBRE_ALLOWED_HOSTS=panel.example.net COULOBRE_HTTPS_PROXY=1 +COULOBRE_REQUIRE_PRIVILEGED_MFA=1 +COULOBRE_TRUST_APACHE_CLIENT_IP=1 +# Set an SMTP relay for email verification and customer password resets. +# COULOBRE_SMTP_HOST=smtp.example.net +# COULOBRE_SMTP_PORT=587 +# COULOBRE_SMTP_USER= +# COULOBRE_SMTP_PASSWORD= +# COULOBRE_SMTP_STARTTLS=1 +# COULOBRE_EMAIL_FROM=panel@example.net +# COULOBRE_PASSWORD_RESET_ORIGIN=https://panel.example.net COULOBRE_STATIC_ROOT=/var/www/coulobre-panel-static COULOBRE_SECRET_KEY= COULOBRE_DB_NAME=coulobre_panel diff --git a/docs/deployment.md b/docs/deployment.md index 52340e8..3fd7257 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -162,6 +162,69 @@ The addresses for hosted sites, mail, and authoritative DNS can differ from the panel hostname. Configure the corresponding public DNS records for each service using its reachable address. +## Protect panel sign-in + +The HTTPS deployment requires a second factor for administrators, staff, +resellers, and other operator logins. Existing unverified privileged sessions +return to sign-in after the upgrade. Apply the database migrations before +restarting the panel, worker, and scheduler. + +A privileged user signs in with a password to start first-time setup. The +setup session can only enroll a second factor or sign out. Choose an +authenticator app, enter the displayed time-based key, and confirm a code +from the app. Use the authenticator's code at future sign-ins. Keep the +panel host and authenticator device clocks synchronized. + +If an SMTP relay is configured and the account already has a valid email +address, the user can instead register one-time email codes. The panel uses +the address assigned to the account at enrollment. These codes expire in +five minutes and can be requested once a minute. An authenticator is the +preferred option for privileged accounts. + +Save the recovery codes shown after enrollment. Each code works once and +can be entered after the account password. If the user loses the factor +and all recovery codes, verify their identity and issue a replacement +enrollment code on the panel host. + +```sh +panel_manage issue_panel_enrollment operator +``` + +This revokes the previous factor, recovery codes, and sessions verified +with that factor. Deliver the one-time enrollment code to the account +owner through a trusted channel. It expires in 20 minutes. The user signs +in with their password and enters the code to set up a replacement. + +### Configure email delivery and customer password recovery + +Set `COULOBRE_SMTP_HOST`, `COULOBRE_SMTP_PORT`, and +`COULOBRE_EMAIL_FROM` in the panel environment. Add the relay's username +and password if it requires authentication. The default uses STARTTLS on +port 587. Keep the environment file restricted to the service operators. + +Set `COULOBRE_PASSWORD_RESET_ORIGIN` to the panel's public HTTPS origin +to enable **Forgot your password?**. Make sure the default Celery worker +is running. The worker sends 30-minute, single-use links only to active +customer accounts. Keep customer email addresses up to date. Privileged +accounts use administrator-assisted password recovery, followed by their +existing second factor or the enrollment recovery flow. + +### Verify client identification + +Coulobre limits sign-in, verification, and reset attempts using counters +in the panel database. The scheduler expires old counters. A limit returns +HTTP 429 and a `Retry-After` header. The default allows eight password +attempts per username and client and forty per client in a five-minute +window. IPv6 clients share a counter within a /64. + +For Apache deployments, install the current `panel-proxy.inc` and set +`COULOBRE_TRUST_APACHE_CLIENT_IP=1` when Gunicorn listens on the +restricted Unix socket. Apache overwrites the client IP header using its +resolved peer address. With a separate reverse proxy, use the trusted +peer configuration above so Apache supplies the visitor address. Keep +the Gunicorn socket private to the panel service and the front-end server. +A direct TCP connection uses its network peer address for rate limiting. + ## Protect a host with nftables and Fail2ban Enable protection independently on a panel, web, mail, or DNS host. Use the diff --git a/pyproject.toml b/pyproject.toml index 07181c6..ed338b1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,6 +11,7 @@ requires-python = ">=3.12" license = "Apache-2.0" dependencies = [ "Django>=5.2.8,<5.3", + "django-otp>=1.7.5,<2", "celery>=5.6,<6", "cryptography>=45", "dnspython>=2.7,<3", @@ -42,6 +43,7 @@ server = ["gunicorn>=27.0.1,<28"] "templates/hosting/*.conf", "templates/hosting/*.html", "templates/hosting/*.php", + "templates/hosting/*.txt", ] [tool.ruff] diff --git a/src/coulobre/admin.py b/src/coulobre/admin.py index 3f2679b..fe2b40a 100644 --- a/src/coulobre/admin.py +++ b/src/coulobre/admin.py @@ -8,6 +8,26 @@ class CoulobreAdminSite(AdminSite): def has_permission(self, request): return super().has_permission(request) and not is_tenant(request.user) + def login(self, request, extra_context=None): + from django.contrib.auth.views import redirect_to_login + from django.core.exceptions import PermissionDenied + from django.shortcuts import redirect + from django.urls import reverse + from django.utils.http import url_has_allowed_host_and_scheme + + destination = request.GET.get("next") + if not url_has_allowed_host_and_scheme( + destination, + {request.get_host()}, + require_https=request.is_secure(), + ): + destination = reverse("admin:index") + if request.user.is_authenticated: + if not self.has_permission(request): + raise PermissionDenied + return redirect(destination) + return redirect_to_login(destination, login_url="panel:login") + class CoulobreAdminConfig(AdminConfig): default_site = "coulobre.admin.CoulobreAdminSite" diff --git a/src/coulobre/hosting/management/commands/issue_panel_enrollment.py b/src/coulobre/hosting/management/commands/issue_panel_enrollment.py new file mode 100644 index 0000000..4480353 --- /dev/null +++ b/src/coulobre/hosting/management/commands/issue_panel_enrollment.py @@ -0,0 +1,28 @@ +from django.contrib.auth import get_user_model +from django.core.management.base import BaseCommand, CommandError + +from ...panel_factors import ENROLLMENT_MINUTES, issue_recovery_enrollment + + +class Command(BaseCommand): + help = "Revoke a panel factor and issue a recovery enrollment code." + + def add_arguments(self, parser): + parser.add_argument("username") + + def handle(self, *, username, **options): + users = get_user_model()._default_manager + try: + user = users.get_by_natural_key(username) + except users.model.DoesNotExist: + raise CommandError("No panel user has that username.") from None + if not user.is_active: + raise CommandError("The panel user is inactive.") + try: + code = issue_recovery_enrollment(user) + except ValueError as error: + raise CommandError(str(error)) from error + self.stdout.write( + f"Enrollment code (valid for {ENROLLMENT_MINUTES} minutes)" + ) + self.stdout.write(code) diff --git a/src/coulobre/hosting/migrations/0045_panel_authentication.py b/src/coulobre/hosting/migrations/0045_panel_authentication.py new file mode 100644 index 0000000..6c53302 --- /dev/null +++ b/src/coulobre/hosting/migrations/0045_panel_authentication.py @@ -0,0 +1,93 @@ +# Generated by Django 5.2.19 on 2026-11-22 10:23 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0044_mail_parity"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="PanelFactorEnrollment", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("digest", models.CharField(max_length=64)), + ("expires_at", models.DateTimeField(db_index=True)), + ( + "user", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + to=settings.AUTH_USER_MODEL, + ), + ), + ], + ), + migrations.CreateModel( + name="SignInWindow", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("digest", models.CharField(max_length=64)), + ("slot", models.PositiveBigIntegerField(db_index=True)), + ("attempts", models.PositiveSmallIntegerField(default=0)), + ], + options={ + "constraints": [ + models.UniqueConstraint( + fields=("digest", "slot"), + name="hosting_unique_sign_in_window", + ) + ], + }, + ), + migrations.CreateModel( + name="PanelRecoveryCode", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("digest", models.CharField(max_length=64)), + ( + "user", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to=settings.AUTH_USER_MODEL, + ), + ), + ], + options={ + "constraints": [ + models.UniqueConstraint( + fields=("user", "digest"), + name="hosting_unique_panel_recovery_code", + ) + ], + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 2b01259..f7f3cb8 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -1088,3 +1088,40 @@ class ServiceHealth(models.Model): name="hosting_service_health_identity", ) ] + + +class SignInWindow(models.Model): + digest = models.CharField(max_length=64) + slot = models.PositiveBigIntegerField(db_index=True) + attempts = models.PositiveSmallIntegerField(default=0) + + class Meta: + constraints = [ + models.UniqueConstraint( + fields=("digest", "slot"), + name="hosting_unique_sign_in_window", + ) + ] + + +class PanelFactorEnrollment(models.Model): + user = models.OneToOneField( + settings.AUTH_USER_MODEL, on_delete=models.CASCADE + ) + digest = models.CharField(max_length=64) + expires_at = models.DateTimeField(db_index=True) + + +class PanelRecoveryCode(models.Model): + user = models.ForeignKey( + settings.AUTH_USER_MODEL, on_delete=models.CASCADE + ) + digest = models.CharField(max_length=64) + + class Meta: + constraints = [ + models.UniqueConstraint( + fields=("user", "digest"), + name="hosting_unique_panel_recovery_code", + ) + ] diff --git a/src/coulobre/hosting/panel_factors.py b/src/coulobre/hosting/panel_factors.py new file mode 100644 index 0000000..659ef80 --- /dev/null +++ b/src/coulobre/hosting/panel_factors.py @@ -0,0 +1,270 @@ +import secrets +from datetime import timedelta +from smtplib import SMTPException + +import django_otp +from django.conf import settings +from django.contrib.auth import get_user_model, login +from django.core.exceptions import ValidationError +from django.core.validators import validate_email +from django.db import connection, transaction +from django.db.models import F +from django.middleware.csrf import rotate_token +from django.utils import timezone +from django.utils.crypto import constant_time_compare, salted_hmac +from django.views.decorators.debug import sensitive_variables +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 + +DEVICE_NAME = "Coulobre Panel" +DEVICE_TYPES = {"authenticator": TOTPDevice, "email": EmailDevice} +CHALLENGE_SESSION = "coulobre_panel_challenge" +SETUP_SESSION = "coulobre_panel_factor_device" +SETUP_EXPIRES = "coulobre_panel_factor_expiry" +SETUP_DESTINATION = "coulobre_panel_factor_destination" +CHALLENGE_SECONDS = 300 +ENROLLMENT_MINUTES = 20 + + +def privileged_user(user): + return user.is_authenticated and ( + user.is_staff + or user.is_superuser + or hasattr(user, "hosting_reseller") + or not hasattr(user, "hosting_customer") + ) + + +def requires_panel_factor(user): + return settings.REQUIRE_PRIVILEGED_MFA and privileged_user(user) + + +def lock_user(user_id): + users = get_user_model()._default_manager.filter(pk=user_id) + if connection.vendor == "sqlite": + users.update(last_login=F("last_login")) + return users.select_for_update().get() + + +def user_devices(user, device_type): + return device_type.objects.filter(user=user, name=DEVICE_NAME) + + +def confirmed_device(user): + for device_type in DEVICE_TYPES.values(): + device = user_devices(user, device_type).filter(confirmed=True).first() + if device: + return device + return None + + +def device_for_user(user, device_id, *, confirmed): + device = Device.from_persistent_id(device_id) if device_id else None + if ( + isinstance(device, (EmailDevice, TOTPDevice)) + and device.user_id == user.pk + and device.name == DEVICE_NAME + and device.confirmed == confirmed + ): + return device + return None + + +def email_factor_available(user): + if not settings.EMAIL_HOST or not user.email: + return False + try: + validate_email(user.email) + except ValidationError: + return False + return True + + +def recovery_required(user): + return PanelFactorEnrollment.objects.filter(user=user).exists() + + +def secret_digest(kind, token): + return salted_hmac( + f"coulobre.panel-factor.{kind}", token, algorithm="sha256" + ).hexdigest() + + +@sensitive_variables("code") +@transaction.atomic +def issue_recovery_enrollment(user): + user = lock_user(user.pk) + if not (confirmed_device(user) or recovery_required(user)): + raise ValueError("This user can enroll a factor after signing in.") + for device_type in DEVICE_TYPES.values(): + user_devices(user, device_type).delete() + PanelRecoveryCode.objects.filter(user=user).delete() + code = secrets.token_urlsafe(24) + PanelFactorEnrollment.objects.update_or_create( + user=user, + defaults={ + "digest": secret_digest("enrollment", code), + "expires_at": timezone.now() + + timedelta(minutes=ENROLLMENT_MINUTES), + }, + ) + return code + + +@sensitive_variables("recovery_code") +@transaction.atomic +def begin_enrollment(user, method, *, recovery_code=None): + user = lock_user(user.pk) + if confirmed_device(user): + return None + enrollment = PanelFactorEnrollment.objects.filter(user=user).first() + if enrollment is not None and ( + not recovery_code + or enrollment.expires_at <= timezone.now() + or not constant_time_compare( + enrollment.digest, secret_digest("enrollment", recovery_code) + ) + ): + return None + if enrollment is None and recovery_code is not None: + return None + fields = {} + if method == "email": + if not email_factor_available(user): + return None + fields["email"] = user.email + for device_type in DEVICE_TYPES.values(): + user_devices(user, device_type).filter(confirmed=False).delete() + device = user_devices(user, DEVICE_TYPES[method]).create( + user=user, name=DEVICE_NAME, confirmed=False, **fields + ) + if enrollment: + enrollment.digest = "" + enrollment.save(update_fields=["digest"]) + return device + + +def start_initial_setup(request, destination): + request.session[SETUP_DESTINATION] = destination + request.session[SETUP_EXPIRES] = int(timezone.now().timestamp()) + 900 + + +def initial_setup_active(request): + return request.session.get(SETUP_EXPIRES, 0) > int( + timezone.now().timestamp() + ) + + +def start_challenge(request, user, destination): + request.session.cycle_key() + rotate_token(request) + request.session.pop(SETUP_SESSION, None) + request.session[CHALLENGE_SESSION] = { + "user": user.pk, + "backend": user.backend, + "auth_hash": user.get_session_auth_hash(), + "expires": int(timezone.now().timestamp()) + CHALLENGE_SECONDS, + "next": destination, + } + + +def pending_user(request): + data = request.session.get(CHALLENGE_SESSION) + if request.user.is_authenticated or not data: + return None + user = ( + get_user_model() + ._default_manager.filter(pk=data["user"], is_active=True) + .first() + ) + if ( + data["expires"] > int(timezone.now().timestamp()) + and user is not None + and requires_panel_factor(user) + and constant_time_compare( + data["auth_hash"], user.get_session_auth_hash() + ) + ): + return user + request.session.pop(CHALLENGE_SESSION, None) + request.session.pop(SETUP_SESSION, None) + return None + + +def complete_challenge(request, user, device): + request.session.pop(SETUP_SESSION, None) + if request.user.is_authenticated: + request.session.pop(SETUP_EXPIRES, None) + destination = request.session.pop(SETUP_DESTINATION) + request.session.cycle_key() + rotate_token(request) + else: + data = request.session.pop(CHALLENGE_SESSION) + login(request, user, backend=data["backend"]) + destination = data["next"] + django_otp.login(request, device) + return destination + + +@sensitive_variables("token", "codes") +@transaction.atomic +def confirm_enrollment(user, device_id, token): + user = lock_user(user.pk) + device = device_for_user(user, device_id, confirmed=False) + if ( + device is None + or confirmed_device(user) + or not device.verify_token(token) + ): + return None, [] + device.confirmed = True + device.save(update_fields=["confirmed"]) + PanelFactorEnrollment.objects.filter(user=user).delete() + codes = [secrets.token_hex(10) for _ in range(10)] + PanelRecoveryCode.objects.bulk_create( + [ + PanelRecoveryCode( + user=user, digest=secret_digest("recovery", code) + ) + for code in codes + ] + ) + return device, codes + + +@sensitive_variables("code") +@transaction.atomic +def verify_factor(user, code): + user = lock_user(user.pk) + device = confirmed_device(user) + if device is None: + return None + if len(code) == 20: + deleted, _ = PanelRecoveryCode.objects.filter( + user=user, digest=secret_digest("recovery", code) + ).delete() + return device if deleted else None + return device if device.verify_token(code) else None + + +def send_factor_code(user, device_id, *, confirmed): + try: + with transaction.atomic(): + user = lock_user(user.pk) + device = device_for_user(user, device_id, confirmed=confirmed) + if ( + not isinstance(device, EmailDevice) + or not device.email + or not settings.EMAIL_HOST + ): + return "Email codes are unavailable for this account." + allowed, _ = device.generate_is_allowed() + if not allowed: + return "Wait a minute before requesting another email code." + device.generate_challenge() + except (OSError, SMTPException): + return "The email code could not be sent. Try again later." + return "A code was sent to the account email address." diff --git a/src/coulobre/hosting/password_reset.py b/src/coulobre/hosting/password_reset.py new file mode 100644 index 0000000..8fd3037 --- /dev/null +++ b/src/coulobre/hosting/password_reset.py @@ -0,0 +1,130 @@ +from urllib.parse import urlsplit + +from django.conf import settings +from django.contrib.auth.forms import PasswordResetForm +from django.contrib.auth.views import ( + INTERNAL_RESET_SESSION_TOKEN, + PasswordResetConfirmView, + PasswordResetDoneView, + PasswordResetView, +) +from django.db import transaction +from django.http import Http404, HttpResponse, HttpResponseRedirect +from django.urls import reverse_lazy +from django.utils.decorators import method_decorator +from django.views.decorators.cache import never_cache +from kombu.exceptions import OperationalError + +from .panel_factors import lock_user, privileged_user +from .sign_in_limits import limit_attempt + + +def reset_enabled(): + return bool(settings.PASSWORD_RESET_ORIGIN and settings.EMAIL_HOST) + + +def can_reset_password(user): + return ( + user.is_active + and user.has_usable_password() + and not privileged_user(user) + ) + + +class CustomerPasswordResetForm(PasswordResetForm): + def get_users(self, email): + return ( + user + for user in super().get_users(email) + if can_reset_password(user) + ) + + +def send_customer_reset_email(email): + if reset_enabled(): + form = CustomerPasswordResetForm({"email": email}) + if form.is_valid(): + form.save( + domain_override=urlsplit( + settings.PASSWORD_RESET_ORIGIN + ).netloc, + use_https=True, + email_template_name="hosting/password_reset_email.txt", + subject_template_name="hosting/password_reset_subject.txt", + ) + + +class PasswordResetAvailable: + def get_context_data(self, **kwargs): + return super().get_context_data(auth_screen=True, **kwargs) + + def dispatch(self, request, *args, **kwargs): + if not reset_enabled(): + raise Http404 + return super().dispatch(request, *args, **kwargs) + + +@method_decorator(never_cache, name="dispatch") +class CustomerPasswordResetView(PasswordResetAvailable, PasswordResetView): + template_name = "hosting/password_reset_request.html" + form_class = CustomerPasswordResetForm + success_url = reverse_lazy("panel:password_reset_done") + + def post(self, request, *args, **kwargs): + limited = limit_attempt( + request, + "reset", + request.POST.get("email", "")[:254], + address_limit=20, + identity_limit=4, + ) + return limited or super().post(request, *args, **kwargs) + + def form_valid(self, form): + from .tasks import send_customer_password_reset + + try: + send_customer_password_reset.apply_async( + args=[form.cleaned_data["email"]], retry=False, expires=300 + ) + except OperationalError: + return HttpResponse( + "Password reset is temporarily unavailable. Try again later.", + content_type="text/plain", + status=503, + ) + # Use the same queue and response for all addresses. + return HttpResponseRedirect(self.get_success_url()) + + +class CustomerResetDoneView(PasswordResetAvailable, PasswordResetDoneView): + template_name = "hosting/password_reset_done.html" + + +class CustomerResetConfirmView( + PasswordResetAvailable, PasswordResetConfirmView +): + template_name = "hosting/password_reset_confirm.html" + success_url = reverse_lazy("panel:password_reset_complete") + + def get_user(self, uidb64): + user = super().get_user(uidb64) + return user if user is not None and can_reset_password(user) else None + + @transaction.atomic + def form_valid(self, form): + user = lock_user(self.user.pk) + token = self.request.session.get(INTERNAL_RESET_SESSION_TOKEN) + if not can_reset_password( + user + ) or not self.token_generator.check_token(user, token): + self.request.session.pop(INTERNAL_RESET_SESSION_TOKEN, None) + self.validlink = False + return self.render_to_response(self.get_context_data()) + form.user = user + return super().form_valid(form) + + +class CustomerResetCompleteView(PasswordResetAvailable, PasswordResetDoneView): + template_name = "hosting/password_reset_complete.html" + title = "Password changed" diff --git a/src/coulobre/hosting/sign_in.py b/src/coulobre/hosting/sign_in.py new file mode 100644 index 0000000..e7b8924 --- /dev/null +++ b/src/coulobre/hosting/sign_in.py @@ -0,0 +1,322 @@ +import base64 + +from django import forms +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.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 +from django_otp.plugins.otp_email.models import EmailDevice + +from .panel_factors import ( + SETUP_SESSION, + begin_enrollment, + complete_challenge, + confirm_enrollment, + confirmed_device, + device_for_user, + email_factor_available, + initial_setup_active, + pending_user, + recovery_required, + requires_panel_factor, + send_factor_code, + start_challenge, + start_initial_setup, + verify_factor, +) +from .password_reset import reset_enabled +from .sign_in_limits import limit_attempt + + +class PrivilegedFactorMiddleware: + 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): + view = request.resolver_match.view_name + if ( + not requires_panel_factor(request.user) + or request.user.is_verified() + or view == "panel:logout" + ): + return None + if ( + initial_setup_active(request) + and not confirmed_device(request.user) + and not recovery_required(request.user) + ): + if view in ("panel:factor_enroll", "panel:factor_confirm"): + return None + return redirect("panel:factor_enroll") + destination = reverse("panel:accounts") + if request.method in ("GET", "HEAD") and view != "panel:login": + destination = request.get_full_path() + logout(request) + return redirect_to_login(destination) + + +class PanelLoginView(LoginView): + template_name = "hosting/login.html" + redirect_authenticated_user = True + + def post(self, request, *args, **kwargs): + limited = limit_attempt( + request, + "password", + request.POST.get("username", "")[:150], + address_limit=40, + identity_limit=8, + ) + return limited or super().post(request, *args, **kwargs) + + def get_context_data(self, **kwargs): + return super().get_context_data( + password_reset_enabled=reset_enabled(), **kwargs + ) + + def form_valid(self, form): + user = form.get_user() + if not requires_panel_factor(user): + return super().form_valid(form) + 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) + start_initial_setup(self.request, destination) + return redirect("panel:factor_enroll") + + +class FactorForm(forms.Form): + code = forms.CharField( + label="Verification or recovery code", + max_length=32, + widget=forms.TextInput(attrs={"autocomplete": "one-time-code"}), + ) + + def clean_code(self): + return self.cleaned_data["code"].lower().replace(" ", "") + + +class EnrollmentForm(forms.Form): + method = forms.ChoiceField( + label="Verification method", widget=forms.RadioSelect + ) + code = forms.CharField( + label="Enrollment code", + max_length=32, + widget=forms.PasswordInput(attrs={"autocomplete": "off"}), + ) + + def __init__(self, *args, email_available, recovery, **kwargs): + super().__init__(*args, **kwargs) + choices = [("authenticator", "Authenticator app")] + if email_available: + choices.append(("email", "Email code")) + self.fields["method"].choices = choices + self.initial["method"] = "authenticator" + if not recovery: + del self.fields["code"] + + +class ConfirmFactorForm(FactorForm): + code = forms.RegexField( + r"^[0-9]{6}$", + label="Verification code", + widget=forms.TextInput( + attrs={"autocomplete": "one-time-code", "inputmode": "numeric"} + ), + ) + + +@method_decorator(never_cache, name="dispatch") +@method_decorator(sensitive_post_parameters("code"), name="dispatch") +class FactorView(FormView): + template_name = "hosting/authentication.html" + + def get_context_data(self, **kwargs): + return super().get_context_data( + title=self.heading, + heading=self.heading, + instructions=self.instructions, + submit_label=self.submit_label, + back_to_login=not self.initial_setup, + auth_screen=True, + **kwargs, + ) + + def dispatch(self, request, *args, **kwargs): + self.initial_setup = ( + requires_panel_factor(request.user) + and initial_setup_active(request) + and not request.user.is_verified() + ) + self.user = ( + request.user if self.initial_setup else pending_user(request) + ) + if self.user is None: + return redirect("panel:login") + return super().dispatch(request, *args, **kwargs) + + def post(self, request, *args, **kwargs): + limited = limit_attempt( + request, + "factor", + str(self.user.pk), + address_limit=30, + identity_limit=10, + ) + if limited: + return limited + if "send_code" in request.POST: + device = self.current_device() + if not isinstance(device, EmailDevice): + return redirect(request.path) + return self.render_to_response( + self.get_context_data( + form=self.form_class(), + code_notice=send_factor_code( + self.user, + device.persistent_id, + confirmed=device.confirmed, + ), + ) + ) + return super().post(request, *args, **kwargs) + + def current_device(self): + return None + + def rejected(self, form, message): + form.add_error("code", message) + return self.form_invalid(form) + + +class VerifyFactorView(FactorView): + heading = "Verify your sign-in" + instructions = ( + "Enter a verification code or one of your saved recovery codes." + ) + submit_label = "Verify" + form_class = FactorForm + + def current_device(self): + return confirmed_device(self.user) + + def get(self, request, *args, **kwargs): + if self.current_device() is None: + return redirect("panel:factor_enroll") + return super().get(request, *args, **kwargs) + + def get_context_data(self, **kwargs): + return super().get_context_data( + email_factor=isinstance(self.current_device(), EmailDevice), + **kwargs, + ) + + 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"]) + if verified is None: + return self.rejected( + form, "Invalid or unavailable code. Try again." + ) + return redirect(complete_challenge(self.request, self.user, verified)) + + +class EnrollFactorView(FactorView): + heading = "Set up your second factor" + instructions = "Choose how you want to verify future sign-ins." + submit_label = "Continue" + form_class = EnrollmentForm + + def get(self, request, *args, **kwargs): + if confirmed_device(self.user): + return redirect("panel:factor_verify") + return super().get(request, *args, **kwargs) + + def get_form_kwargs(self): + return super().get_form_kwargs() | { + "email_available": email_factor_available(self.user), + "recovery": not self.initial_setup, + } + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + if not self.initial_setup: + context["instructions"] = ( + "Use the enrollment code provided by your hosting operator." + ) + return context + + def form_valid(self, form): + device = begin_enrollment( + self.user, + form.cleaned_data["method"], + recovery_code=form.cleaned_data.get("code"), + ) + if device is None: + form.add_error( + None, "Could not start setup. Sign in and try again." + ) + return self.form_invalid(form) + self.request.session[SETUP_SESSION] = device.persistent_id + return redirect("panel:factor_confirm") + + +class ConfirmFactorView(FactorView): + heading = "Confirm your second factor" + instructions = "Enter a code to complete setup." + submit_label = "Confirm" + form_class = ConfirmFactorForm + + def current_device(self): + return device_for_user( + self.user, self.request.session.get(SETUP_SESSION), confirmed=False + ) + + def get(self, request, *args, **kwargs): + if self.current_device() is None: + return redirect("panel:factor_enroll") + return super().get(request, *args, **kwargs) + + def get_context_data(self, **kwargs): + device = self.current_device() + context = {} + if isinstance(device, EmailDevice): + context["email_factor"] = True + elif device: + context = { + "setup_key": base64.b32encode(device.bin_key).decode(), + "configuration_url": device.config_url, + } + return super().get_context_data(**context, **kwargs) + + @sensitive_variables("codes") + def form_valid(self, form): + device, codes = confirm_enrollment( + self.user, + self.request.session.get(SETUP_SESSION), + form.cleaned_data["code"], + ) + if device is None: + return self.rejected( + form, "Invalid or unavailable code. Try again." + ) + destination = complete_challenge(self.request, self.user, device) + return render( + self.request, + "hosting/factor_recovery_codes.html", + {"codes": codes, "destination": destination}, + ) diff --git a/src/coulobre/hosting/sign_in_limits.py b/src/coulobre/hosting/sign_in_limits.py new file mode 100644 index 0000000..e06ef2d --- /dev/null +++ b/src/coulobre/hosting/sign_in_limits.py @@ -0,0 +1,73 @@ +from ipaddress import ip_address, ip_network +from unicodedata import normalize + +from django.conf import settings +from django.db.models import F +from django.http import HttpResponse +from django.utils import timezone +from django.utils.crypto import salted_hmac + +from .models import SignInWindow + +WINDOW_SECONDS = 300 + + +def client_address(request): + peer = request.META.get("REMOTE_ADDR") or "" + address = peer + if settings.TRUST_APACHE_CLIENT_IP and not peer: + address = request.META.get("HTTP_X_COULOBRE_CLIENT_IP", "") + try: + if "%" in address: + raise ValueError + parsed = ip_address(address) + except ValueError: + return "unknown" + if parsed.version == 6: + if parsed.ipv4_mapped: + return str(parsed.ipv4_mapped) + return str(ip_network((parsed, 64), strict=False)) + return str(parsed) + + +def current_window(): + return int(timezone.now().timestamp()) // WINDOW_SECONDS + + +def reserve_attempt(purpose, key, slot, limit): + digest = salted_hmac( + f"coulobre.sign-in.{purpose}", key, algorithm="sha256" + ).hexdigest() + window, _ = SignInWindow.objects.get_or_create(digest=digest, slot=slot) + changed = SignInWindow.objects.filter( + pk=window.pk, attempts__lt=limit + ).update(attempts=F("attempts") + 1) + return bool(changed) + + +def limit_attempt( + request, purpose, identity, *, address_limit, identity_limit +): + address = client_address(request) + slot = current_window() + identity = normalize("NFKC", identity).casefold()[:254] + if reserve_attempt( + f"{purpose}.address", address, slot, address_limit + ) and ( + reserve_attempt( + f"{purpose}.identity", + f"{address}|{identity}", + slot, + identity_limit, + ) + ): + return None + response = HttpResponse( + "Too many attempts. Try again in a few minutes.", + status=429, + content_type="text/plain", + ) + retry_after = (slot + 1) * WINDOW_SECONDS - int(timezone.now().timestamp()) + response["Retry-After"] = max(1, retry_after) + response["Cache-Control"] = "no-store" + return response diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 808d92d..e0b115e 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -48,6 +48,7 @@ from .models import ( MailboxProvisioning, MailRoutingPublication, MailVacationPublication, + SignInWindow, SitePhpSettings, SitePhpVersion, SiteSFTP, @@ -79,9 +80,11 @@ from .node_client import ( update_local_sftp, update_local_website_alias, ) +from .password_reset import send_customer_reset_email from .php_settings import plan_php_versions from .service_changes import apply_service_change from .sftp import site_is_active +from .sign_in_limits import current_window REDISPATCH_AFTER = timedelta(minutes=5) ACCOUNT_BACKUP_LEASE = timedelta(seconds=BACKUP_TIMEOUT_SECONDS + 60) @@ -909,3 +912,13 @@ def run_provisioning_job( except ValueError as error: problem = str(error) running.update(finished_at=timezone.now(), problem=problem, **updates) + + +@shared_task +def expire_sign_in_windows(): + SignInWindow.objects.filter(slot__lt=current_window() - 1).delete() + + +@shared_task +def send_customer_password_reset(email): + send_customer_reset_email(email) diff --git a/src/coulobre/hosting/templates/hosting/authentication.html b/src/coulobre/hosting/templates/hosting/authentication.html new file mode 100644 index 0000000..06c1ffc --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/authentication.html @@ -0,0 +1,15 @@ +{% extends "hosting/base.html" %} +{% block title %}{{ title }} · Coulobre Panel{% endblock %} +{% block public_content %} +
+
+ + +
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/authentication_card.html b/src/coulobre/hosting/templates/hosting/authentication_card.html new file mode 100644 index 0000000..ba36a51 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/authentication_card.html @@ -0,0 +1,25 @@ +

{{ heading }}

+{% if instructions %}

{{ instructions }}

{% endif %} +{% if code_notice %}

{{ code_notice }}

{% endif %} +{% if configuration_url %} +

Open in an authenticator app or add a time-based account using this key.

+

{{ setup_key }}

+{% endif %} +{% if form %} +
+ {% csrf_token %} + {{ form.as_div }} + {% if next %}{% endif %} + + {% if email_factor %} + + {% endif %} +
+{% endif %} +{% if back_to_login %}

Back to sign-in

{% endif %} +{% if request.user.is_authenticated %} +
+ {% csrf_token %} + +
+{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index 85f0143..c82d43f 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -7,7 +7,7 @@ -{% if request.user.is_authenticated %} +{% if request.user.is_authenticated and not auth_screen %}
diff --git a/src/coulobre/hosting/templates/hosting/password_reset_complete.html b/src/coulobre/hosting/templates/hosting/password_reset_complete.html new file mode 100644 index 0000000..46e1c60 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/password_reset_complete.html @@ -0,0 +1,6 @@ +{% extends "hosting/authentication.html" %} +{% block title %}Password changed · Coulobre Panel{% endblock %} +{% block authentication_content %} +

Password changed

+ Sign in +{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/password_reset_confirm.html b/src/coulobre/hosting/templates/hosting/password_reset_confirm.html new file mode 100644 index 0000000..321265c --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/password_reset_confirm.html @@ -0,0 +1,15 @@ +{% extends "hosting/authentication.html" %} +{% block title %}Choose a new password · Coulobre Panel{% endblock %} +{% block authentication_content %} + {% if validlink %} +

Choose a new password

+
+ {% csrf_token %} + {{ form.as_div }} + +
+ {% else %} +

Reset link expired or already used

+

Request a new link

+ {% endif %} +{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/password_reset_done.html b/src/coulobre/hosting/templates/hosting/password_reset_done.html new file mode 100644 index 0000000..d99d38c --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/password_reset_done.html @@ -0,0 +1,7 @@ +{% extends "hosting/authentication.html" %} +{% block title %}Check your email · Coulobre Panel{% endblock %} +{% block authentication_content %} +

Check your email

+

If the address belongs to an eligible customer account, we will send a reset link.

+

Back to sign-in

+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/password_reset_email.txt b/src/coulobre/hosting/templates/hosting/password_reset_email.txt new file mode 100644 index 0000000..1401f9d --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/password_reset_email.txt @@ -0,0 +1,5 @@ +Use this link within 30 minutes to choose a new password for your Coulobre Panel account. + +{{ protocol }}://{{ domain }}{% url 'panel:password_reset_confirm' uidb64=uid token=token %} + +You can ignore this message if you did not request a password reset. diff --git a/src/coulobre/hosting/templates/hosting/password_reset_request.html b/src/coulobre/hosting/templates/hosting/password_reset_request.html new file mode 100644 index 0000000..db6d2f6 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/password_reset_request.html @@ -0,0 +1,12 @@ +{% extends "hosting/authentication.html" %} +{% block title %}Reset your password · Coulobre Panel{% endblock %} +{% block authentication_content %} +

Reset your password

+

Enter the email address associated with your customer account.

+
+ {% csrf_token %} + {{ form.as_div }} + +
+

Back to sign-in

+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/password_reset_subject.txt b/src/coulobre/hosting/templates/hosting/password_reset_subject.txt new file mode 100644 index 0000000..f177135 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/password_reset_subject.txt @@ -0,0 +1 @@ +Reset your Coulobre Panel password diff --git a/src/coulobre/hosting/test_customers.py b/src/coulobre/hosting/test_customers.py index d5937cc..84278a0 100644 --- a/src/coulobre/hosting/test_customers.py +++ b/src/coulobre/hosting/test_customers.py @@ -160,6 +160,7 @@ class CustomerAccessTests(TestCase): self.assertRedirects( self.client.get(admin_url), f"{reverse('admin:login')}?next={admin_url}", + target_status_code=403, ) def test_customer_requests_respect_database_and_mailbox_plan_limits( diff --git a/src/coulobre/hosting/test_panel_authentication.py b/src/coulobre/hosting/test_panel_authentication.py new file mode 100644 index 0000000..35bb6a9 --- /dev/null +++ b/src/coulobre/hosting/test_panel_authentication.py @@ -0,0 +1,323 @@ +from datetime import datetime, timedelta +from io import StringIO +from types import SimpleNamespace +from unittest.mock import patch +from urllib.parse import urlsplit + +from django.contrib.auth import SESSION_KEY, get_user_model +from django.contrib.auth.tokens import default_token_generator +from django.core import mail +from django.core.management import call_command +from django.test import Client, RequestFactory, TestCase, override_settings +from django.urls import reverse +from django_otp.oath import TOTP, totp +from django_otp.plugins.otp_email.models import EmailDevice +from django_otp.plugins.otp_totp.models import TOTPDevice + +from .models import Customer, HostingAccount, PanelRecoveryCode, Reseller +from .sign_in_limits import client_address +from .tasks import send_customer_password_reset + +PASSWORD = "test-password-for-panel" +NEW_PASSWORD = "rotated-password-for-a-customer" + + +@override_settings( + REQUIRE_PRIVILEGED_MFA=True, + EMAIL_HOST="smtp.example.test", + EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend", + PASSWORD_RESET_ORIGIN="https://panel.example.test", +) +class PanelAuthenticationTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.operator = users.create_superuser( + "operator", password=PASSWORD, email="operator@example.test" + ) + cls.reseller = users.create_user( + "reseller", password=PASSWORD, email="reseller@example.test" + ) + reseller = Reseller.objects.create(user=cls.reseller) + cls.customer = users.create_user( + "customer", password=PASSWORD, email="customer@example.test" + ) + customer = Customer.objects.create(user=cls.customer) + cls.account = HostingAccount.objects.create( + name="Customer website", + primary_domain="customer.example.test", + reseller=reseller, + customer=customer, + ) + cls.other = HostingAccount.objects.create( + name="Separate website", primary_domain="other.example.test" + ) + + def login(self, user, client=None, **fields): + client = client or self.client + return client.post( + reverse("panel:login"), + {"username": user.username, "password": PASSWORD, **fields}, + ) + + def enroll_authenticator(self, user): + enroll = reverse("panel:factor_enroll") + confirm = reverse("panel:factor_confirm") + self.assertRedirects(self.login(user), enroll) + self.assertIn(SESSION_KEY, self.client.session) + self.assertContains(self.client.get(enroll), "Authenticator app") + self.assertNotContains(self.client.get(enroll), "Enrollment code") + self.assertRedirects(self.client.get(reverse("admin:index")), enroll) + self.assertRedirects( + self.client.post(enroll, {"method": "authenticator"}), confirm + ) + device = TOTPDevice.objects.get(user=user) + response = self.client.post( + confirm, {"code": f"{totp(device.bin_key):06d}"} + ) + self.assertContains(response, "Save your recovery codes") + self.assertIn("no-store", response.headers["Cache-Control"]) + return response.context["codes"] + + def test_first_password_login_enrolls_and_later_logins_require_a_factor( + self, + ): + codes = self.enroll_authenticator(self.operator) + account = self.account.get_absolute_url() + self.assertContains(self.client.get(account), "Customer website") + self.assertEqual(PanelRecoveryCode.objects.count(), 10) + other_browser = Client() + verify = reverse("panel:factor_verify") + self.assertRedirects( + self.login(self.operator, other_browser, next=account), verify + ) + self.assertNotIn(SESSION_KEY, other_browser.session) + self.assertRedirects( + other_browser.post(verify, {"code": codes[0]}), account + ) + self.assertEqual(PanelRecoveryCode.objects.count(), 9) + fresh_browser = Client() + self.assertRedirects(self.login(self.operator, fresh_browser), verify) + self.assertContains( + fresh_browser.post(verify, {"code": codes[0]}), + "Invalid or unavailable code", + ) + self.assertNotIn(SESSION_KEY, fresh_browser.session) + + def test_later_sign_in_accepts_a_fresh_authenticator_code(self): + self.enroll_authenticator(self.operator) + device = TOTPDevice.objects.get(user=self.operator) + code_generator = TOTP(device.bin_key) + code_generator.time = (device.last_t + 1) * device.step + 1 + browser = Client() + verify = reverse("panel:factor_verify") + self.assertRedirects(self.login(self.operator, browser), verify) + data = {"code": f"{code_generator.token():06d}"} + with patch( + "django_otp.plugins.otp_totp.models.time", + SimpleNamespace(time=lambda: code_generator.time), + ): + self.assertRedirects( + browser.post(verify, data), reverse("panel:accounts") + ) + another_browser = Client() + self.assertRedirects( + self.login(self.operator, another_browser), verify + ) + self.assertContains( + another_browser.post(verify, data), + "Invalid or unavailable code", + ) + + def test_operator_recovery_requires_a_one_time_enrollment_code(self): + self.enroll_authenticator(self.operator) + output = StringIO() + call_command("issue_panel_enrollment", "operator", stdout=output) + code = output.getvalue().splitlines()[-1] + account = self.account.get_absolute_url() + self.assertRedirects( + self.client.get(account), + f"{reverse('panel:login')}?next={account}", + ) + verify = reverse("panel:factor_verify") + enroll = reverse("panel:factor_enroll") + confirm = reverse("panel:factor_confirm") + self.assertRedirects( + self.login(self.operator), verify, fetch_redirect_response=False + ) + self.assertRedirects(self.client.get(verify), enroll) + self.assertContains( + self.client.post( + enroll, {"method": "authenticator", "code": "wrong"} + ), + "Could not start setup", + ) + data = {"method": "authenticator", "code": code} + self.assertRedirects(self.client.post(enroll, data), confirm) + self.assertContains( + self.client.post(enroll, data), "Could not start setup" + ) + self.assertEqual(PanelRecoveryCode.objects.count(), 0) + device = TOTPDevice.objects.get(user=self.operator) + self.assertContains( + self.client.post(confirm, {"code": f"{totp(device.bin_key):06d}"}), + "Save your recovery codes", + ) + self.assertContains(self.client.get(account), "Customer website") + + def test_email_factor_sends_to_the_saved_address_and_is_single_use(self): + enroll = reverse("panel:factor_enroll") + confirm = reverse("panel:factor_confirm") + self.assertRedirects(self.login(self.reseller), enroll) + self.assertContains(self.client.get(enroll), "Email code") + self.assertRedirects( + self.client.post(enroll, {"method": "email"}), confirm + ) + self.assertContains( + self.client.post( + confirm, {"send_code": "1", "email": "ignored@example.test"} + ), + "sent to the account email address", + ) + device = EmailDevice.objects.get(user=self.reseller) + self.assertEqual(mail.outbox[0].to, ["reseller@example.test"]) + self.assertIn(device.token, mail.outbox[0].body) + self.assertContains( + self.client.post(confirm, {"send_code": "1"}), + "Wait a minute", + ) + self.assertEqual(len(mail.outbox), 1) + self.assertContains( + self.client.post(confirm, {"code": device.token}), + "Save your recovery codes", + ) + self.assertEqual( + self.client.get(self.other.get_absolute_url()).status_code, 404 + ) + self.assertContains( + self.client.get(self.account.get_absolute_url()), + "Customer website", + ) + verify = reverse("panel:factor_verify") + new_client = Client() + self.assertRedirects(self.login(self.reseller, new_client), verify) + self.assertContains( + new_client.post(verify, {"code": device.token}), + "Invalid or unavailable code", + ) + + def test_customer_has_password_only_login_and_scoped_single_use_reset( + self, + ): + self.assertRedirects( + self.login(self.customer), reverse("panel:accounts") + ) + self.client.post(reverse("panel:logout")) + with patch.object( + send_customer_password_reset, "apply_async" + ) as enqueue: + for email in (self.customer.email, "unknown@example.test"): + self.assertRedirects( + self.client.post( + reverse("panel:password_reset"), {"email": email} + ), + reverse("panel:password_reset_done"), + ) + self.assertEqual(enqueue.call_count, 2) + for email in ( + self.customer.email, + self.operator.email, + "unknown@example.test", + ): + send_customer_password_reset.run(email) + self.assertEqual(len(mail.outbox), 1) + reset_url = next( + line + for line in mail.outbox[0].body.splitlines() + if line.startswith("https:") + ) + self.assertEqual(urlsplit(reset_url).netloc, "panel.example.test") + path = urlsplit(reset_url).path + another_browser = Client() + form_path = self.client.get(path)["Location"] + self.assertEqual(another_browser.get(path)["Location"], form_path) + data = {"new_password1": NEW_PASSWORD, "new_password2": NEW_PASSWORD} + response = self.client.post(form_path, data) + self.assertRedirects( + response, reverse("panel:password_reset_complete") + ) + self.assertNotIn(SESSION_KEY, self.client.session) + self.assertContains( + another_browser.post(form_path, data), + "Reset link expired or already used", + ) + self.customer.refresh_from_db() + self.assertTrue(self.customer.check_password(NEW_PASSWORD)) + + def test_expired_reset_link_displays_generic_error(self): + past = datetime(2026, 1, 1, 0, 0) + with patch.object(default_token_generator, "_now", return_value=past): + send_customer_password_reset.run(self.customer.email) + reset_path = urlsplit( + next( + line + for line in mail.outbox[0].body.splitlines() + if line.startswith("https:") + ) + ).path + with patch.object( + default_token_generator, + "_now", + return_value=past + timedelta(minutes=31), + ): + self.assertContains( + self.client.get(reset_path), + "Reset link expired or already used", + ) + + def test_django_admin_uses_the_panel_login(self): + self.assertRedirects( + self.client.get(reverse("admin:login")), + f"{reverse('panel:login')}?next=/admin/", + ) + self.client.force_login(self.operator) + response = self.client.get(reverse("admin:index")) + self.assertEqual( + response["Location"], f"{reverse('panel:login')}?next=/admin/" + ) + + +class SignInLimitsTests(TestCase): + @override_settings(TRUST_APACHE_CLIENT_IP=True) + def test_forwarded_address_requires_the_unix_socket(self): + factory = RequestFactory() + request = factory.get( + "/", + HTTP_X_COULOBRE_CLIENT_IP="192.0.2.1", + REMOTE_ADDR="192.0.2.20", + ) + self.assertEqual(client_address(request), "192.0.2.20") + request.META["REMOTE_ADDR"] = "" + self.assertEqual(client_address(request), "192.0.2.1") + request.META["HTTP_X_COULOBRE_CLIENT_IP"] = "192.0.2.1, 192.0.2.2" + self.assertEqual(client_address(request), "unknown") + + @override_settings(TRUST_APACHE_CLIENT_IP=False) + def test_sign_in_limit_cannot_be_reset_with_a_forwarded_header(self): + url = reverse("panel:login") + for attempt in range(9): + response = self.client.post( + url, + {"username": "missing", "password": "wrong"}, + REMOTE_ADDR="203.0.113.10", + HTTP_X_FORWARDED_FOR=f"192.0.2.{attempt + 1}", + HTTP_X_COULOBRE_CLIENT_IP=f"192.0.2.{attempt + 1}", + ) + self.assertEqual(response.status_code, 429) + self.assertTrue(response["Retry-After"].isdigit()) + response = self.client.post( + url, + {"username": "missing", "password": "wrong"}, + REMOTE_ADDR="203.0.113.20", + ) + self.assertEqual(response.status_code, 200) diff --git a/src/coulobre/hosting/test_resellers.py b/src/coulobre/hosting/test_resellers.py index 6dd8e62..13c4c09 100644 --- a/src/coulobre/hosting/test_resellers.py +++ b/src/coulobre/hosting/test_resellers.py @@ -126,6 +126,7 @@ class ResellerAccessTests(TestCase): reverse("admin:hosting_hostingaccount_changelist") ), reverse("admin:login") + "?next=/admin/hosting/hostingaccount/", + target_status_code=403, ) self.assertEqual(WebProvisioningPlan.objects.count(), 2) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 5de53f2..9baa78a 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -1,4 +1,4 @@ -from django.contrib.auth.views import LoginView, LogoutView +from django.contrib.auth.views import LogoutView from django.urls import path from . import views @@ -7,6 +7,12 @@ from .credential_views import DatabaseCredentialView, MailboxCredentialView from .health_views import ServiceHealthView from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup from .mail_policy_views import MailRoutingEditor, MailVacationEditor +from .password_reset import ( + CustomerPasswordResetView, + CustomerResetCompleteView, + CustomerResetConfirmView, + CustomerResetDoneView, +) from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin from .reseller_views import ( ResellerCreate, @@ -16,6 +22,12 @@ from .reseller_views import ( ) from .retirement_views import RetirementList, RetirementView from .roundcube import RoundcubeLaunch, redeem_roundcube +from .sign_in import ( + ConfirmFactorView, + EnrollFactorView, + PanelLoginView, + VerifyFactorView, +) app_name = "panel" @@ -24,13 +36,31 @@ urlpatterns = [ path( "service-health/", ServiceHealthView.as_view(), name="service_health" ), + path("sign-in/", PanelLoginView.as_view(), name="login"), + path("sign-in/verify/", VerifyFactorView.as_view(), name="factor_verify"), + path("sign-in/enroll/", EnrollFactorView.as_view(), name="factor_enroll"), path( - "sign-in/", - LoginView.as_view( - template_name="hosting/login.html", - redirect_authenticated_user=True, - ), - name="login", + "sign-in/confirm/", ConfirmFactorView.as_view(), name="factor_confirm" + ), + path( + "password-reset/", + CustomerPasswordResetView.as_view(), + name="password_reset", + ), + path( + "password-reset/requested/", + CustomerResetDoneView.as_view(), + name="password_reset_done", + ), + path( + "password-reset///", + CustomerResetConfirmView.as_view(), + name="password_reset_confirm", + ), + path( + "password-reset/complete/", + CustomerResetCompleteView.as_view(), + name="password_reset_complete", ), path("sign-out/", LogoutView.as_view(), name="logout"), path( diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index 0a8ce48..123aeab 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -42,6 +42,16 @@ def ip_addresses_env(name, limit): SECRET_KEY = required_env("COULOBRE_SECRET_KEY") HTTPS_PROXY = os.environ.get("COULOBRE_HTTPS_PROXY") == "1" +REQUIRE_PRIVILEGED_MFA = ( + os.environ.get( + "COULOBRE_REQUIRE_PRIVILEGED_MFA", "1" if HTTPS_PROXY else "0" + ) + == "1" +) +OTP_TOTP_ISSUER = "Coulobre Panel" +TRUST_APACHE_CLIENT_IP = ( + os.environ.get("COULOBRE_TRUST_APACHE_CLIENT_IP") == "1" +) DEBUG = not HTTPS_PROXY and os.environ.get("COULOBRE_DEBUG") == "1" ALLOWED_HOSTS = os.environ.get( "COULOBRE_ALLOWED_HOSTS", "localhost,127.0.0.1,[::1]" @@ -61,6 +71,9 @@ INSTALLED_APPS = [ "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", + "django_otp", + "django_otp.plugins.otp_totp", + "django_otp.plugins.otp_email", "coulobre.hosting", ] @@ -70,6 +83,8 @@ MIDDLEWARE = [ "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", + "django_otp.middleware.OTPMiddleware", + "coulobre.hosting.sign_in.PrivilegedFactorMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "coulobre.hosting.impersonation.CustomerImpersonationMiddleware", @@ -141,6 +156,42 @@ LOGIN_URL = "panel:login" LOGIN_REDIRECT_URL = "panel:accounts" LOGOUT_REDIRECT_URL = "panel:login" +PASSWORD_RESET_TIMEOUT = 1800 +PASSWORD_RESET_ORIGIN = os.environ.get("COULOBRE_PASSWORD_RESET_ORIGIN", "") +if PASSWORD_RESET_ORIGIN: + try: + reset_origin = urlsplit(PASSWORD_RESET_ORIGIN) + if ( + reset_origin.scheme != "https" + or not reset_origin.hostname + or reset_origin.username is not None + or reset_origin.path not in ("", "/") + or reset_origin.query + or reset_origin.fragment + or reset_origin.port == 0 + or any(char.isspace() for char in PASSWORD_RESET_ORIGIN) + ): + raise ValueError + except ValueError: + raise ImproperlyConfigured( + "Set COULOBRE_PASSWORD_RESET_ORIGIN to the HTTPS panel origin." + ) from None + +EMAIL_HOST = os.environ.get("COULOBRE_SMTP_HOST", "") +EMAIL_PORT = int(os.environ.get("COULOBRE_SMTP_PORT", "587")) +EMAIL_HOST_USER = os.environ.get("COULOBRE_SMTP_USER", "") +EMAIL_HOST_PASSWORD = os.environ.get("COULOBRE_SMTP_PASSWORD", "") +EMAIL_USE_TLS = os.environ.get("COULOBRE_SMTP_STARTTLS", "1") == "1" +EMAIL_TIMEOUT = 10 +DEFAULT_FROM_EMAIL = os.environ.get( + "COULOBRE_EMAIL_FROM", "Coulobre Panel " +) +OTP_EMAIL_SUBJECT = "Your Coulobre Panel verification code" +OTP_EMAIL_BODY_TEMPLATE = ( + "Your Coulobre Panel verification code is {{ token }}. " + "It expires in five minutes." +) + CELERY_BROKER_URL = os.environ.get( "COULOBRE_BROKER_URL", "amqp://guest:guest@127.0.0.1:5672//" ) @@ -282,6 +333,10 @@ if (LOCAL_ACCOUNT_BACKUP_MAIL and REMOTE_ACCOUNT_BACKUP_MAIL) or ( "Choose one mailbox transport for backup and one for restore." ) CELERY_BEAT_SCHEDULE = { + "expire-panel-sign-in-windows": { + "task": "coulobre.hosting.tasks.expire_sign_in_windows", + "schedule": 600.0, + }, "dispatch-account-retirements": { "task": "coulobre.hosting.tasks.dispatch_account_retirements", "schedule": 5.0,