Protect panel sign-in and customer password recovery #99

Merged
parkel merged 2 commits from feature/protect-panel-sign-in into main 2026-11-22 11:36:02 +01:00
27 changed files with 1195 additions and 8 deletions
Showing only changes of commit 2e9caf5498 - Show all commits

No files matched your search

+1
View File
@@ -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/
+10
View File
@@ -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
+2
View File
@@ -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]
+20
View File
@@ -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"
@@ -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)
@@ -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",
)
],
},
),
]
+37
View File
@@ -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",
)
]
+270
View File
@@ -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."
+130
View File
@@ -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"
+322
View File
@@ -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},
)
+73
View File
@@ -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
+13
View File
@@ -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)
@@ -0,0 +1,15 @@
{% extends "hosting/base.html" %}
{% block title %}{{ title }} · Coulobre Panel{% endblock %}
{% block public_content %}
<main class="sign-in">
<div class="sign-in-inner">
<div class="brand sign-in-brand">
<span class="brand-mark" aria-hidden="true">C</span>
<span>Coulobre <span class="brand-product">Panel</span></span>
</div>
<section class="sign-in-card">
{% block authentication_content %}{% include "hosting/authentication_card.html" %}{% endblock %}
</section>
</div>
</main>
{% endblock %}
@@ -0,0 +1,25 @@
<h1>{{ heading }}</h1>
{% if instructions %}<p>{{ instructions }}</p>{% endif %}
{% if code_notice %}<p role="status">{{ code_notice }}</p>{% endif %}
{% if configuration_url %}
<p><a href="{{ configuration_url }}" rel="noreferrer">Open in an authenticator app</a> or add a time-based account using this key.</p>
<p><code>{{ setup_key }}</code></p>
{% endif %}
{% if form %}
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
{% if next %}<input type="hidden" name="next" value="{{ next }}">{% endif %}
<button class="button primary" type="submit">{{ submit_label }}</button>
{% if email_factor %}
<button class="button secondary" type="submit" name="send_code" value="1" formnovalidate>Send email code</button>
{% endif %}
</form>
{% endif %}
{% if back_to_login %}<p><a href="{% url 'panel:login' %}">Back to sign-in</a></p>{% endif %}
{% if request.user.is_authenticated %}
<form method="post" action="{% url 'panel:logout' %}">
{% csrf_token %}
<button class="button secondary" type="submit">Sign out</button>
</form>
{% endif %}
@@ -7,7 +7,7 @@
<link rel="stylesheet" href="{% static 'hosting/panel.css' %}">
</head>
<body>
{% if request.user.is_authenticated %}
{% if request.user.is_authenticated and not auth_screen %}
<a class="skip-link" href="#main-content">Skip to content</a>
<div class="panel">
<aside class="sidebar">
@@ -0,0 +1,12 @@
{% extends "hosting/base.html" %}
{% block title %}Save your recovery codes · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><h1>Save your recovery codes</h1></header>
<section class="surface editor-surface">
<p>Keep these codes somewhere safe. Each code lets you sign in once if you lose access to your second factor.</p>
<ul>
{% for code in codes %}<li><code>{{ code }}</code></li>{% endfor %}
</ul>
<a class="button primary" href="{{ destination }}">Continue to the panel</a>
</section>
{% endblock %}
@@ -15,6 +15,9 @@
{% if next %}<input type="hidden" name="next" value="{{ next }}">{% endif %}
<button class="button primary" type="submit">Sign in</button>
</form>
{% if password_reset_enabled %}
<p><a href="{% url 'panel:password_reset' %}">Forgot your password?</a></p>
{% endif %}
</section>
</div>
</main>
@@ -0,0 +1,6 @@
{% extends "hosting/authentication.html" %}
{% block title %}Password changed · Coulobre Panel{% endblock %}
{% block authentication_content %}
<h1>Password changed</h1>
<a class="button primary" href="{% url 'panel:login' %}">Sign in</a>
{% endblock %}
@@ -0,0 +1,15 @@
{% extends "hosting/authentication.html" %}
{% block title %}Choose a new password · Coulobre Panel{% endblock %}
{% block authentication_content %}
{% if validlink %}
<h1>Choose a new password</h1>
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
<button class="button primary" type="submit">Change password</button>
</form>
{% else %}
<h1>Reset link expired or already used</h1>
<p><a href="{% url 'panel:password_reset' %}">Request a new link</a></p>
{% endif %}
{% endblock %}
@@ -0,0 +1,7 @@
{% extends "hosting/authentication.html" %}
{% block title %}Check your email · Coulobre Panel{% endblock %}
{% block authentication_content %}
<h1>Check your email</h1>
<p>If the address belongs to an eligible customer account, we will send a reset link.</p>
<p><a href="{% url 'panel:login' %}">Back to sign-in</a></p>
{% endblock %}
@@ -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.
@@ -0,0 +1,12 @@
{% extends "hosting/authentication.html" %}
{% block title %}Reset your password · Coulobre Panel{% endblock %}
{% block authentication_content %}
<h1>Reset your password</h1>
<p>Enter the email address associated with your customer account.</p>
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
<button class="button primary" type="submit">Request reset link</button>
</form>
<p><a href="{% url 'panel:login' %}">Back to sign-in</a></p>
{% endblock %}
@@ -0,0 +1 @@
Reset your Coulobre Panel password
+1
View File
@@ -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(
+1
View File
@@ -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)
+37 -7
View File
@@ -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/<uidb64>/<token>/",
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(
+55
View File
@@ -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 <panel@localhost>"
)
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,