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/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)