diff --git a/README.md b/README.md index 44571f3..cf1b12d 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,8 @@ work items in [Gitea issues][issues]. Published versions and their release notes are available on [Gitea Releases][releases]. See [Contributing](CONTRIBUTING.md) for the project workflow. +See [Security](docs/security.md) for deployment hardening and private +vulnerability reporting. [milestones]: https://code.hosting.hippogrief.nl/hippogrief/coulobre/milestones [issues]: https://code.hosting.hippogrief.nl/hippogrief/coulobre/issues diff --git a/deploy/install-node.sh b/deploy/install-node.sh index b0faf88..f88b5c9 100755 --- a/deploy/install-node.sh +++ b/deploy/install-node.sh @@ -61,6 +61,7 @@ if [ ! -x "$venv/bin/python" ]; then python3 -m venv "$venv" fi if [ -z "$installed" ]; then - "$venv/bin/pip" install . + "$venv/bin/python" -m pip install --only-binary=:all: 'pip>=26.2' + "$venv/bin/python" -m pip install . fi exec "$venv/bin/coulobre-node-setup" install-receiver "$@" diff --git a/deploy/panel_installer/engine.py b/deploy/panel_installer/engine.py index dd10348..dc8dbd0 100644 --- a/deploy/panel_installer/engine.py +++ b/deploy/panel_installer/engine.py @@ -282,6 +282,18 @@ def install_release(release, *, step=nullcontext): if key in os.environ } with step("Installing Coulobre and its Python dependencies"): + run( + BINDIR / "python", + "-m", + "pip", + "install", + "--disable-pip-version-check", + "--only-binary=:all:", + "pip>=26.2", + label="Update the virtual environment installer", + env=pip_env, + timeout=1200, + ) run( BINDIR / "pip", "install", @@ -860,12 +872,9 @@ class Installer: HEALTH_TIMER, ): install_unit(unit) - if not REMOTE_MODES.intersection( - (self.plan.dns.mode, self.plan.mail.mode) - ): - install_unit("coulobre-update.socket") - install_unit("coulobre-update@.service") - workers.append("coulobre-update.socket") + install_unit("coulobre-update.socket") + install_unit("coulobre-update@.service") + workers.append("coulobre-update.socket") systemctl("daemon-reload") systemctl( "enable", "--now", *PANEL_UNITS, *workers, "apache2.service" diff --git a/deploy/systemd/coulobre-update@.service b/deploy/systemd/coulobre-update@.service index f7bb4a2..e7bb110 100644 --- a/deploy/systemd/coulobre-update@.service +++ b/deploy/systemd/coulobre-update@.service @@ -9,7 +9,7 @@ User=root WorkingDirectory=/opt/coulobre EnvironmentFile=/etc/coulobre/panel.env StateDirectory=coulobre-update -StateDirectoryMode=0755 +StateDirectoryMode=0700 UMask=0077 ExecStart=/opt/coulobre/bin/coulobre-update StandardInput=socket diff --git a/docs/deployment.md b/docs/deployment.md index c793c7e..047d1eb 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -542,7 +542,8 @@ From the unpacked source release, upgrade the existing virtual environment and use the [management command helper](#prepare-the-panel). ```sh -sudo /opt/coulobre/bin/pip install --upgrade '.[server,mariadb]' +sudo /opt/coulobre/bin/python -m pip install --only-binary=:all: 'pip>=26.2' +sudo /opt/coulobre/bin/python -m pip install --upgrade '.[server,mariadb]' panel_manage migrate --noinput panel_manage collectstatic --noinput ``` @@ -587,9 +588,9 @@ without service checks, follow [the collector setup](#monitor-local-and-remote-s ### Install a compatible release from the panel -The installer enables **Updates** for single-server deployments. On an -existing installer-managed single server, install the updater units from the -v0.10.1 source release after upgrading the package: +The installer enables **Updates** for installer-managed panels. On an +existing panel, install the updater units from the source release matching +the installed package: ```sh sudo install -m 0644 deploy/systemd/coulobre-update.socket \ @@ -602,9 +603,10 @@ A superuser with a verified second factor can choose a compatible release from **Server and services → Updates**. The updater uses the official Gitea release over HTTPS and checks the wheel against its published SHA-256 hash. It supports the installer-managed local MariaDB database and installer -layout. Use the in-place procedure for linked mail or DNS receivers, custom -service unit changes, and releases requiring new dependencies. The update -manifest lists the tested starting versions. +layout. The update manifest lists the tested starting versions. Use the +in-place procedure for custom service unit changes and for environments +missing a dependency required by the target version. From 0.11 onward, the +updater checks installed dependencies before stopping panel services. The panel and its workers pause during the upgrade. Refresh **Updates** after the panel returns. The latest update status names the recovery directory in @@ -623,6 +625,78 @@ verify sign-in and service health. Archive `status.json` as root after recovery to allow a later update. Check that `panel.sql` and `venv` exist before restoring from a directory created by an interrupted update. +### Coordinate a release across linked mail and DNS receivers + +Use the in-place procedure for the first upgrade from 0.10 to 0.11 in a +linked deployment. The older web updater supports single-server upgrades. +Bring the receiver and all attached panels to the same release before +resuming provisioning. For manually configured relays, including separate +mail credential and archive relays, use the in-place procedure for the +whole fleet. + +The **Updates** page in 0.11 reports the release, host, and status probe +protocol of each installer-enrolled receiver. Protocol 1 reports readiness +and release. Protocol 2 also reports a staged maintenance target. This is +a read-only addition to the probe. The mail and DNS apply request formats +keep their existing per-operation versions. Active provisioning requires +matching package releases. During a coordinated upgrade, the receiver +keeps provisioning requests paused while panels are on different releases. +Normal mail delivery, IMAP, and existing DNS answers can continue while +the provisioning socket is stopped or paused. + +1. At each receiver, list the authorized panel keys. Match each fingerprint + to a panel and confirm its installed version on that host. Include every + key, including panels operated by another team. Back up the panels, the + receiver packages, and the managed mail or DNS configuration. Pause + new provisioning requests and let current jobs finish. + + ```sh + sudo /opt/coulobre/bin/coulobre-node-setup list-panels dns + ``` + +2. Save a root-owned JSON inventory with mode 0600, the target package version and a + fingerprint-to-version map. Replace the fingerprints and versions with + your actual values. Make a separate inventory for each role on a host. + + ```json + { + "target": "0.11.1rc1", + "panels": { + "SHA256:panel-one-fingerprint": "0.11.0rc1", + "SHA256:panel-two-fingerprint": "0.11.0rc1" + } + } + ``` + +3. Stop the receiver socket and let instances of the corresponding apply + service finish. Stage the inventory, update the receiver to the target, + then start its socket again. Replace `dns` with `mail` for a mail receiver. + The staged receiver answers status probes and rejects apply requests. + + ```sh + sudo systemctl stop coulobre-dns-apply.socket + sudo /opt/coulobre/bin/coulobre-node-setup begin-maintenance dns /root/dns-upgrade.json + # Install the reviewed target package using its release instructions. + sudo systemctl start coulobre-dns-apply.socket + ``` + +4. Refresh **Updates** on each panel. Install the target when all its + receivers report that release in maintenance mode and the compatible + release is offered. Use the in-place procedure if its update requires + additional dependencies or unit changes. Keep the receivers staged if + any panel upgrade is interrupted. Check the recovery files and repair or + roll back before reopening provisioning. +5. Once every panel is running and verified at the target, update each + inventory with the observed installed versions. Finish maintenance on each + receiver, then resume provisioning and retry any affected operations. + The command checks the receiver release and the inventory against the + current authorized keys. The receiver administrator is responsible for + checking the installed version reported by every panel operator. + + ```sh + sudo /opt/coulobre/bin/coulobre-node-setup finish-maintenance dns /root/dns-upgrade.json + ``` + ### Upgrade from v0.9 to v0.10 Use the in-place procedure above with the v0.10 source release. Keep a copy diff --git a/docs/security.md b/docs/security.md new file mode 100644 index 0000000..b1b441a --- /dev/null +++ b/docs/security.md @@ -0,0 +1,60 @@ +# Security + +## Report vulnerabilities privately + +Contact a project maintainer privately with the affected release, the +deployment layout, the affected roles, and a description of the impact. +Share minimal evidence using test data. Remove credentials, tokens, +customer data, private keys, and identifiable account information. If you +cannot find a private channel, open a Gitea issue requesting private +contact and leave the technical details out of the issue. + +Maintainers confirm scope, coordinate remediation with the reporter, and +publish an advisory with the fixed releases and any operational mitigations +after users have a way to update. + +## Panel and account access + +- Serve the panel over HTTPS. If you use a reverse proxy, restrict the + private origin to that proxy and let the managed Apache configuration set + the forwarding headers. Keep debug mode off on shared or public hosts. +- Require two-factor authentication for staff and customer managers. Use an + authenticator app for administrative accounts and keep recovery codes in a + protected location. The **My account** page lets users verify a new email + address, replace their authenticator, renew recovery codes, and revoke + other panel sessions. Revoking panel sessions also clears unused service + login tickets. Webmail, database, and SSH sessions established separately + have their own lifetimes. +- During customer impersonation, use only the approved support + actions. Review impersonation and credential access events. Account + security actions are recorded separately and visible to the account owner. +- Verify that the panel can deliver account messages and email factors. + Treat an address used for password recovery or an email factor as a + credential and check it after changing it. + +## Service boundaries and recovery + +- Restrict the panel database and RabbitMQ to local access. Expose only + the client-facing ports for the functions you run. Keep Unix sockets and + environment files restricted to the identities listed in the deployment + guide. Keep each site's PHP-FPM pool and SFTP keys scoped to that site. +- Pin SSH host keys for linked nodes and off-site backups. Use dedicated + receiver keys and accounts. The panel receiver protocol is authenticated + by the enrolled panel key. Share a receiver only among cooperating + administrators who agree on service ownership and coordinate releases. + The linked-node upgrade runbook accounts for every authorized panel key. +- Review DNS delegation, mail routing permissions, and allowed forwarding. + Keep private DKIM material on the mail receiver and publish the matching + public records. Verify the mail configuration after changing packages. +- Store backup destinations and their keys separately from hosted content. + Protect recovery copies of the virtual environment and database. Test + website, database, and mailbox restores with isolated accounts and check + ownership and access afterwards. +- Keep Ubuntu or Debian packages and the panel's Python environment on + security-supported versions. Check installed dependencies against a + vulnerability advisory source such as OSV before a release. Verify both + distribution files against the reviewed Git revision and check the + wheel digest before enabling a web update. + +Use the [deployment guide](deployment.md) for operating-system support, +configuration and recovery steps. diff --git a/pyproject.toml b/pyproject.toml index c1a311a..fa9ffc3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,18 +4,18 @@ build-backend = "setuptools.build_meta" [project] name = "coulobre-panel" -version = "0.10.2rc1" +version = "0.11.0rc1" description = "A web hosting control panel for hosting providers and resellers." readme = "README.md" requires-python = ">=3.12" license = "Apache-2.0" dependencies = [ - "Django>=5.2.8,<5.3", + "Django>=5.2.17,<5.3", "django-otp>=1.7.5,<2", "celery>=5.6,<6", - "cryptography>=45", - "dnspython>=2.7,<3", - "idna>=3,<4", + "cryptography>=50", + "dnspython>=2.9.2,<3", + "idna>=3.15,<4", "qrcode>=8.2,<9", ] diff --git a/src/coulobre/hosting/account_security.py b/src/coulobre/hosting/account_security.py new file mode 100644 index 0000000..50dc7f9 --- /dev/null +++ b/src/coulobre/hosting/account_security.py @@ -0,0 +1,463 @@ +import secrets +from datetime import timedelta +from smtplib import SMTPException + +import django_otp +from django import forms +from django.conf import settings +from django.contrib import messages +from django.contrib.auth import update_session_auth_hash +from django.contrib.auth.hashers import check_password +from django.contrib.auth.mixins import LoginRequiredMixin +from django.contrib.auth.password_validation import validate_password +from django.core.exceptions import PermissionDenied +from django.core.mail import send_mail +from django.db import transaction +from django.shortcuts import redirect, render +from django.urls import reverse_lazy +from django.utils import timezone +from django.utils.crypto import constant_time_compare +from django.utils.decorators import method_decorator +from django.views.decorators.cache import never_cache +from django.views.decorators.debug import ( + sensitive_post_parameters, + sensitive_variables, +) +from django.views.generic import FormView, TemplateView +from django_otp.plugins.otp_email.models import EmailDevice +from django_otp.plugins.otp_totp.models import TOTPDevice + +from .models import PanelEmailChange, PanelSecurityEvent +from .panel_factors import ( + DEVICE_NAME, + DEVICE_TYPES, + RECOVERY_SIGN_IN, + confirmed_device, + device_for_user, + lock_user, + replace_recovery_codes, + secret_digest, + send_factor_code, + user_devices, +) +from .panel_sessions import ( + preserve_session, + record_security_event, + revoke_other_sessions, + session_is_current, +) +from .sign_in import ConfirmFactorForm, authenticator_setup +from .sign_in_limits import limit_attempt + +Action = PanelSecurityEvent.Action +ACCOUNT_URL = reverse_lazy("panel:account_security") +FACTOR_SETUP = "coulobre_account_factor_setup" + + +class AccountSecurityMixin(LoginRequiredMixin): + @method_decorator(never_cache) + def dispatch(self, request, *args, **kwargs): + if getattr(request, "impersonation", None): + raise PermissionDenied + return super().dispatch(request, *args, **kwargs) + + +class AccountSecurityView(AccountSecurityMixin, TemplateView): + template_name = "hosting/account_security.html" + + def get_context_data(self, **kwargs): + user = self.request.user + device = confirmed_device(user) + factor = "Authenticator app" if device else "Not set up" + if isinstance(device, EmailDevice): + factor = "Email code" + return super().get_context_data( + factor=factor, + factor_enabled=device is not None, + email_available=bool(settings.EMAIL_HOST), + events=PanelSecurityEvent.objects.filter(user=user).order_by( + "-id" + )[:10], + **kwargs, + ) + + +class AuthorizeForm(forms.Form): + password = forms.CharField( + label="Current password", + strip=False, + max_length=4096, + widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}), + ) + code = ConfirmFactorForm.base_fields["code"] + + +class PasswordForm(AuthorizeForm): + new_password = forms.CharField( + max_length=4096, + strip=False, + widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), + ) + confirm_password = forms.CharField( + max_length=4096, + strip=False, + widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), + ) + + def clean(self): + cleaned = super().clean() + if ( + "new_password" in cleaned + and "confirm_password" in cleaned + and cleaned["new_password"] != cleaned["confirm_password"] + ): + self.add_error("confirm_password", "The passwords differ.") + return cleaned + + +class EmailForm(AuthorizeForm): + email = forms.EmailField(label="New email address", max_length=254) + + +class VerifyEmailForm(forms.Form): + code = forms.RegexField( + r"\A[0-9a-fA-F]{12}\Z", + label="Email verification code", + widget=forms.TextInput(attrs={"autocomplete": "one-time-code"}), + ) + + +@method_decorator(sensitive_post_parameters(), name="dispatch") +class SecurityFormView(AccountSecurityMixin, FormView): + template_name = "hosting/account_security_form.html" + success_url = ACCOUNT_URL + instructions = "" + + def get_context_data(self, **kwargs): + return super().get_context_data( + heading=self.heading, instructions=self.instructions, **kwargs + ) + + def post(self, request, *args, **kwargs): + return limit_attempt( + request, + "account-security", + str(request.user.pk), + address_limit=30, + identity_limit=10, + ) or super().post(request, *args, **kwargs) + + def locked_user(self): + user = lock_user(self.request.user.pk) + if ( + not user.is_active + or not session_is_current(self.request, user) + or not constant_time_compare( + user.get_session_auth_hash(), + self.request.user.get_session_auth_hash(), + ) + ): + raise PermissionDenied + return user + + def changed_access(self, user, action): + version = revoke_other_sessions(user) + record_security_event(user, action) + self.request.session.pop(RECOVERY_SIGN_IN, None) + self.request.session.pop(FACTOR_SETUP, None) + preserve_session(self.request, version) + + @sensitive_variables("codes") + def show_recovery_codes(self, codes): + return render( + self.request, + "hosting/factor_recovery_codes.html", + { + "recovery_codes": "\n".join(codes), + "destination": self.success_url, + }, + ) + + +class AuthorizedSecurityChange(SecurityFormView): + form_class = AuthorizeForm + + def get_form(self, form_class=None): + form = super().get_form(form_class) + if confirmed_device(self.request.user) is None: + del form.fields["code"] + return form + + def get_context_data(self, **kwargs): + return super().get_context_data( + can_send_code=isinstance( + confirmed_device(self.request.user), EmailDevice + ), + **kwargs, + ) + + def post(self, request, *args, **kwargs): + if "send_code" not in request.POST: + return super().post(request, *args, **kwargs) + device = confirmed_device(request.user) + if not isinstance(device, EmailDevice): + raise PermissionDenied + messages.info( + request, + send_factor_code( + request.user, device.persistent_id, confirmed=True + ), + ) + return redirect(request.path) + + @transaction.atomic + @sensitive_variables("form") + def form_valid(self, form): + user = self.locked_user() + if not check_password(form.cleaned_data["password"], user.password): + form.add_error("password", "The current password is incorrect.") + return self.form_invalid(form) + + self.validate_change(user, form) + if form.errors: + return self.form_invalid(form) + + if not self.verify_current_factor(user, form): + form.add_error( + "code", "Enter a valid code from your current factor." + ) + return self.form_invalid(form) + return self.apply_change(user, form) + + def verify_current_factor(self, user, form): + device = confirmed_device(user) + return device is None or device.verify_token( + form.cleaned_data.get("code", "") + ) + + def validate_change(self, user, form): + pass + + +class ChangePasswordView(AuthorizedSecurityChange): + heading = "Change password" + instructions = "Changing your password signs out your other sessions." + form_class = PasswordForm + + def validate_change(self, user, form): + try: + validate_password(form.cleaned_data["new_password"], user) + except forms.ValidationError as error: + form.add_error("new_password", error) + + @sensitive_variables("form") + def apply_change(self, user, form): + user.set_password(form.cleaned_data["new_password"]) + user.save(update_fields=["password"]) + update_session_auth_hash(self.request, user) + self.changed_access(user, Action.PASSWORD) + messages.success(self.request, "Your password was changed.") + return redirect(self.success_url) + + +class ChangeEmailView(AuthorizedSecurityChange): + heading = "Change email address" + instructions = "We will send a verification code to your new address." + form_class = EmailForm + + def dispatch(self, request, *args, **kwargs): + if not settings.EMAIL_HOST: + raise PermissionDenied + return super().dispatch(request, *args, **kwargs) + + def validate_change(self, user, form): + if form.cleaned_data["email"].casefold() == user.email.casefold(): + form.add_error("email", "Enter a different email address.") + + @sensitive_variables("code") + def apply_change(self, user, form): + email = form.cleaned_data["email"] + code = secrets.token_hex(6) + try: + sent = send_mail( + "Verify your new Coulobre Panel email address", + f"Enter {code} on the page where you requested the change. " + "The code expires in 15 minutes.", + None, + [email], + ) + except (OSError, SMTPException): + sent = 0 + if sent != 1: + form.add_error(None, "The verification email could not be sent.") + return self.form_invalid(form) + + PanelEmailChange.objects.update_or_create( + user=user, + defaults={ + "email": email, + "digest": secret_digest("email-change", code), + "session_digest": self.session_digest(), + "expires_at": timezone.now() + timedelta(minutes=15), + }, + ) + return redirect("panel:account_email_verify") + + def session_digest(self): + return secret_digest("email-session", self.request.session.session_key) + + +def notify_old_address(email): + send_mail( + "Your Coulobre Panel email address changed", + "The email address on your account was changed. Contact your hosting " + "provider if you did not request this change.", + None, + [email], + ) + + +class VerifyEmailView(SecurityFormView): + heading = "Verify your new email address" + form_class = VerifyEmailForm + + @sensitive_variables("form") + @transaction.atomic + def form_valid(self, form): + user = self.locked_user() + pending = PanelEmailChange.objects.filter(user=user).first() + session_digest = secret_digest( + "email-session", self.request.session.session_key + ) + code_digest = secret_digest( + "email-change", form.cleaned_data["code"].lower() + ) + if ( + pending is None + or pending.expires_at <= timezone.now() + or not constant_time_compare( + pending.session_digest, session_digest + ) + or not constant_time_compare(pending.digest, code_digest) + ): + form.add_error( + "code", "The verification code is invalid or expired." + ) + return self.form_invalid(form) + + previous_email = user.email + user.email = pending.email + user.save(update_fields=["email"]) + user_devices(user, EmailDevice).update( + email=user.email, token=None, valid_until=timezone.now() + ) + self.changed_access(user, Action.EMAIL) + if previous_email: + transaction.on_commit( + lambda: notify_old_address(previous_email), robust=True + ) + messages.success(self.request, "Your email address was changed.") + return redirect(self.success_url) + + +class StartAuthenticatorView(AuthorizedSecurityChange): + heading = "Set up an authenticator app" + instructions = "Your current factor works until you verify the new app." + + def recently_used_recovery_code(self, user): + recovery = self.request.session.get(RECOVERY_SIGN_IN, {}) + if recovery.get("expires", 0) <= int(timezone.now().timestamp()): + return False + device = confirmed_device(user) + return device is not None and recovery.get("device") == ( + device.persistent_id + ) + + def get_form(self, form_class=None): + form = super().get_form(form_class) + if self.recently_used_recovery_code(self.request.user): + form.fields.pop("code", None) + return form + + def verify_current_factor(self, user, form): + return self.recently_used_recovery_code( + user + ) or super().verify_current_factor(user, form) + + def apply_change(self, user, form): + self.request.session.pop(RECOVERY_SIGN_IN, None) + for device_type in DEVICE_TYPES.values(): + user_devices(user, device_type).filter(confirmed=False).delete() + pending = TOTPDevice.objects.create( + user=user, name=DEVICE_NAME, confirmed=False + ) + self.request.session[FACTOR_SETUP] = { + "device": pending.persistent_id, + "expires": int(timezone.now().timestamp()) + 600, + } + return redirect("panel:account_authenticator_confirm") + + +class ConfirmAuthenticatorView(SecurityFormView): + heading = "Verify your authenticator app" + form_class = ConfirmFactorForm + + def pending_device(self, user): + setup = self.request.session.get(FACTOR_SETUP, {}) + if setup.get("expires", 0) <= int(timezone.now().timestamp()): + return None + return device_for_user(user, setup.get("device"), confirmed=False) + + def get(self, request, *args, **kwargs): + if self.pending_device(request.user) is None: + return redirect("panel:account_authenticator") + return super().get(request, *args, **kwargs) + + def get_context_data(self, **kwargs): + pending = self.pending_device(self.request.user) + context = authenticator_setup(pending) if pending else {} + return super().get_context_data(**context, **kwargs) + + @sensitive_variables("form") + @transaction.atomic + def form_valid(self, form): + user = self.locked_user() + pending = self.pending_device(user) + if pending is None or not pending.verify_token( + form.cleaned_data["code"] + ): + form.add_error( + "code", "The verification code is invalid or expired." + ) + return self.form_invalid(form) + for device_type in DEVICE_TYPES.values(): + user_devices(user, device_type).filter(confirmed=True).delete() + pending.confirmed = True + pending.save(update_fields=["confirmed"]) + django_otp.login(self.request, pending) + self.request.session.pop(FACTOR_SETUP, None) + self.changed_access(user, Action.FACTOR) + return self.show_recovery_codes(replace_recovery_codes(user)) + + +class ReplaceRecoveryCodesView(AuthorizedSecurityChange): + heading = "Generate new recovery codes" + instructions = "Generating new codes invalidates all your existing codes." + + def validate_change(self, user, form): + if confirmed_device(user) is None: + form.add_error(None, "Set up a second factor first.") + + def apply_change(self, user, form): + self.changed_access(user, Action.RECOVERY) + return self.show_recovery_codes(replace_recovery_codes(user)) + + +class SignOutOtherSessionsView(AuthorizedSecurityChange): + heading = "Sign out other sessions" + instructions = "This browser stays signed in." + + def apply_change(self, user, form): + self.changed_access(user, Action.SESSIONS) + messages.success(self.request, "Your other sessions were signed out.") + return redirect(self.success_url) diff --git a/src/coulobre/hosting/migrations/0057_panel_account_security.py b/src/coulobre/hosting/migrations/0057_panel_account_security.py new file mode 100644 index 0000000..a4af61b --- /dev/null +++ b/src/coulobre/hosting/migrations/0057_panel_account_security.py @@ -0,0 +1,108 @@ +# Generated by Django 5.2.19 on 2026-11-22 23:08 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0056_dns_zone_defaults"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="PanelAccountSecurity", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("session_version", models.PositiveBigIntegerField(default=0)), + ( + "user", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + to=settings.AUTH_USER_MODEL, + ), + ), + ], + ), + migrations.CreateModel( + name="PanelEmailChange", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("email", models.EmailField(max_length=254)), + ("digest", models.CharField(max_length=64)), + ("session_digest", models.CharField(max_length=64)), + ("expires_at", models.DateTimeField()), + ( + "user", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + to=settings.AUTH_USER_MODEL, + ), + ), + ], + ), + migrations.CreateModel( + name="PanelSecurityEvent", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("username", models.CharField(max_length=150)), + ( + "action", + models.CharField( + choices=[ + ("password", "Password changed"), + ("email", "Email address changed"), + ("factor", "Authenticator updated"), + ("recovery", "Recovery codes replaced"), + ("reset", "Operator-issued factor recovery"), + ("sessions", "Other sessions signed out"), + ], + max_length=12, + ), + ), + ("created_at", models.DateTimeField(auto_now_add=True)), + ( + "user", + models.ForeignKey( + null=True, + on_delete=django.db.models.deletion.SET_NULL, + to=settings.AUTH_USER_MODEL, + ), + ), + ], + options={ + "indexes": [ + models.Index( + fields=["user", "-id"], + name="hosting_pan_user_id_9e9e3e_idx", + ) + ], + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 55bba3f..749b761 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -1354,3 +1354,40 @@ class PanelRecoveryCode(models.Model): name="hosting_unique_panel_recovery_code", ) ] + + +class PanelAccountSecurity(models.Model): + user = models.OneToOneField( + settings.AUTH_USER_MODEL, on_delete=models.CASCADE + ) + session_version = models.PositiveBigIntegerField(default=0) + + +class PanelEmailChange(models.Model): + user = models.OneToOneField( + settings.AUTH_USER_MODEL, on_delete=models.CASCADE + ) + email = models.EmailField() + digest = models.CharField(max_length=64) + session_digest = models.CharField(max_length=64) + expires_at = models.DateTimeField() + + +class PanelSecurityEvent(models.Model): + class Action(models.TextChoices): + PASSWORD = "password", "Password changed" + EMAIL = "email", "Email address changed" + FACTOR = "factor", "Authenticator updated" + RECOVERY = "recovery", "Recovery codes replaced" + RESET = "reset", "Operator-issued factor recovery" + SESSIONS = "sessions", "Other sessions signed out" + + user = models.ForeignKey( + settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True + ) + username = models.CharField(max_length=150) + action = models.CharField(max_length=12, choices=Action.choices) + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + indexes = [models.Index(fields=["user", "-id"])] diff --git a/src/coulobre/hosting/node_client.py b/src/coulobre/hosting/node_client.py index 1d4fd83..c7f26c6 100644 --- a/src/coulobre/hosting/node_client.py +++ b/src/coulobre/hosting/node_client.py @@ -1,5 +1,6 @@ import json import socket +from importlib.metadata import version from django.views.decorators.debug import sensitive_variables @@ -11,8 +12,10 @@ from coulobre.account_restore_request import ( RESTORE_SOCKET, RESTORE_TIMEOUT_SECONDS, ) +from coulobre.linked_updates import ROLES, UNIT_DIR, read_probe from coulobre.mail_dns import dkim_key from coulobre.mail_node import MailboxQuotaUpdate, MailboxSigningRequest +from coulobre.node_probe import PROBE_BYTES, parse_status_probe from coulobre.php_pool_settings import PhpPoolSettings from coulobre.php_runtime import validate_php_version from coulobre.web_node import ( @@ -250,6 +253,7 @@ def encode_manifest(manifest): def apply_on_local_node( spec, socket_path, node, resource, *, identity=None, timeout=195 ): + require_matching_receiver(socket_path) manifest = spec.manifest() expected = manifest if identity is None else identity with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: @@ -284,3 +288,23 @@ def apply_on_local_node( if state == "failed" and isinstance(problem, str) and problem.strip(): raise ValueError(problem.strip()[:2000]) raise NodeReplyError(invalid_response) + + +def require_matching_receiver(socket_path): + for role in ROLES: + unit = f"coulobre-{role}-apply" + if str(socket_path) != f"/run/{unit}.sock": + continue + if not (UNIT_DIR / f"{unit}@.service.d/remote.conf").exists(): + return + try: + report = parse_status_probe(read_probe(role, PROBE_BYTES), role) + if report["state"] == "configured" and report[ + "release" + ] == version("coulobre-panel"): + return + except (OSError, ValueError): + pass + raise NodeReplyError( + f"The linked {role} receiver is not ready for this release." + ) diff --git a/src/coulobre/hosting/panel_factors.py b/src/coulobre/hosting/panel_factors.py index 659ef80..1aaffd6 100644 --- a/src/coulobre/hosting/panel_factors.py +++ b/src/coulobre/hosting/panel_factors.py @@ -17,7 +17,17 @@ from django_otp.models import Device from django_otp.plugins.otp_email.models import EmailDevice from django_otp.plugins.otp_totp.models import TOTPDevice -from .models import PanelFactorEnrollment, PanelRecoveryCode +from .models import ( + PanelFactorEnrollment, + PanelRecoveryCode, + PanelSecurityEvent, +) +from .panel_sessions import ( + SESSION_VERSION, + record_security_event, + revoke_other_sessions, + session_version, +) DEVICE_NAME = "Coulobre Panel" DEVICE_TYPES = {"authenticator": TOTPDevice, "email": EmailDevice} @@ -25,6 +35,7 @@ CHALLENGE_SESSION = "coulobre_panel_challenge" SETUP_SESSION = "coulobre_panel_factor_device" SETUP_EXPIRES = "coulobre_panel_factor_expiry" SETUP_DESTINATION = "coulobre_panel_factor_destination" +RECOVERY_SIGN_IN = "coulobre_panel_recovery_sign_in" CHALLENGE_SECONDS = 300 ENROLLMENT_MINUTES = 20 @@ -39,7 +50,12 @@ def privileged_user(user): def requires_panel_factor(user): - return settings.REQUIRE_PRIVILEGED_MFA and privileged_user(user) + return user.is_authenticated and ( + settings.REQUIRE_PRIVILEGED_MFA + and privileged_user(user) + or confirmed_device(user) is not None + or recovery_required(user) + ) def lock_user(user_id): @@ -111,6 +127,8 @@ def issue_recovery_enrollment(user): + timedelta(minutes=ENROLLMENT_MINUTES), }, ) + revoke_other_sessions(user) + record_security_event(user, PanelSecurityEvent.Action.RESET) return code @@ -162,10 +180,12 @@ def start_challenge(request, user, destination): request.session.cycle_key() rotate_token(request) request.session.pop(SETUP_SESSION, None) + request.session.pop(RECOVERY_SIGN_IN, None) request.session[CHALLENGE_SESSION] = { "user": user.pk, "backend": user.backend, "auth_hash": user.get_session_auth_hash(), + "session_version": session_version(user), "expires": int(timezone.now().timestamp()) + CHALLENGE_SECONDS, "next": destination, } @@ -184,6 +204,7 @@ def pending_user(request): data["expires"] > int(timezone.now().timestamp()) and user is not None and requires_panel_factor(user) + and data.get("session_version", 0) == session_version(user) and constant_time_compare( data["auth_hash"], user.get_session_auth_hash() ) @@ -204,6 +225,7 @@ def complete_challenge(request, user, device): else: data = request.session.pop(CHALLENGE_SESSION) login(request, user, backend=data["backend"]) + request.session[SESSION_VERSION] = data.get("session_version", 0) destination = data["next"] django_otp.login(request, device) return destination @@ -223,6 +245,12 @@ def confirm_enrollment(user, device_id, token): device.confirmed = True device.save(update_fields=["confirmed"]) PanelFactorEnrollment.objects.filter(user=user).delete() + return device, replace_recovery_codes(user) + + +@sensitive_variables("codes") +def replace_recovery_codes(user): + PanelRecoveryCode.objects.filter(user=user).delete() codes = [secrets.token_hex(10) for _ in range(10)] PanelRecoveryCode.objects.bulk_create( [ @@ -232,7 +260,7 @@ def confirm_enrollment(user, device_id, token): for code in codes ] ) - return device, codes + return codes @sensitive_variables("code") diff --git a/src/coulobre/hosting/panel_sessions.py b/src/coulobre/hosting/panel_sessions.py new file mode 100644 index 0000000..d5bbe20 --- /dev/null +++ b/src/coulobre/hosting/panel_sessions.py @@ -0,0 +1,73 @@ +from django.contrib.auth import logout +from django.contrib.auth.views import redirect_to_login +from django.db.models import F +from django.middleware.csrf import rotate_token + +from .models import ( + PanelAccountSecurity, + PanelEmailChange, + PanelSecurityEvent, + PhpMyAdminGrant, + RoundcubeGrant, +) + +SESSION_VERSION = "coulobre_account_session_version" + + +def session_version(user): + return ( + PanelAccountSecurity.objects.filter(user=user) + .values_list("session_version", flat=True) + .first() + or 0 + ) + + +def session_is_current(request, user): + return request.session.get(SESSION_VERSION, 0) == session_version(user) + + +def revoke_other_sessions(user): + state, _ = PanelAccountSecurity.objects.get_or_create(user=user) + PanelAccountSecurity.objects.filter(pk=state.pk).update( + session_version=F("session_version") + 1 + ) + PanelEmailChange.objects.filter(user=user).delete() + for grants in (PhpMyAdminGrant, RoundcubeGrant): + grants.objects.filter(actor=user, redeemed_at__isnull=True).delete() + return session_version(user) + + +def preserve_session(request, new_version): + request.session.cycle_key() + request.session[SESSION_VERSION] = new_version + rotate_token(request) + + +def record_security_event(user, action): + PanelSecurityEvent.objects.create( + user=user, username=user.get_username(), action=action + ) + + +class PanelSessionMiddleware: + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + return self.get_response(request) + + def process_view(self, request, view_func, view_args, view_kwargs): + if request.user.is_authenticated and not session_is_current( + request, request.user + ): + logout(request) + if request.resolver_match.view_name == "panel:logout": + return None + destination = ( + request.get_full_path() + if request.method in {"GET", "HEAD"} + else "/" + ) + return redirect_to_login(destination) + return None diff --git a/src/coulobre/hosting/sign_in.py b/src/coulobre/hosting/sign_in.py index 4e6b503..530aa68 100644 --- a/src/coulobre/hosting/sign_in.py +++ b/src/coulobre/hosting/sign_in.py @@ -6,6 +6,7 @@ from django.contrib.auth import logout from django.contrib.auth.views import LoginView, redirect_to_login from django.shortcuts import redirect, render from django.urls import reverse +from django.utils import timezone from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache from django.views.decorators.debug import ( @@ -17,6 +18,8 @@ from django_otp.plugins.otp_email.models import EmailDevice from qrcode.image.svg import SvgPathFillImage from .panel_factors import ( + CHALLENGE_SECONDS, + RECOVERY_SIGN_IN, SETUP_SESSION, begin_enrollment, complete_challenge, @@ -33,10 +36,24 @@ from .panel_factors import ( start_initial_setup, verify_factor, ) +from .panel_sessions import SESSION_VERSION, session_version from .password_reset import reset_enabled from .sign_in_limits import limit_attempt +@sensitive_variables("configuration_url") +def authenticator_setup(device): + configuration_url = device.config_url + qr = qrcode.make( + configuration_url, image_factory=SvgPathFillImage + ).to_string(encoding="utf-8") + return { + "setup_key": base64.b32encode(device.bin_key).decode(), + "configuration_url": configuration_url, + "qr_image": base64.b64encode(qr).decode("ascii"), + } + + class PrivilegedFactorMiddleware: def __init__(self, get_response): self.get_response = get_response @@ -88,13 +105,17 @@ class PanelLoginView(LoginView): def form_valid(self, form): user = form.get_user() + current_version = session_version(user) if not requires_panel_factor(user): - return super().form_valid(form) + response = super().form_valid(form) + self.request.session[SESSION_VERSION] = current_version + return response destination = self.get_success_url() if confirmed_device(user) or recovery_required(user): start_challenge(self.request, user, destination) return redirect("panel:factor_verify") super().form_valid(form) + self.request.session[SESSION_VERSION] = current_version start_initial_setup(self.request, destination) if not email_factor_available(user): device = begin_enrollment(user, "authenticator") @@ -234,12 +255,19 @@ class VerifyFactorView(FactorView): def form_valid(self, form): if self.current_device() is None: return redirect("panel:factor_enroll") - verified = verify_factor(self.user, form.cleaned_data["code"]) + code = form.cleaned_data["code"] + verified = verify_factor(self.user, code) if verified is None: return self.rejected( form, "Invalid or unavailable code. Try again." ) - return redirect(complete_challenge(self.request, self.user, verified)) + destination = complete_challenge(self.request, self.user, verified) + if len(code) == 20: + self.request.session[RECOVERY_SIGN_IN] = { + "device": verified.persistent_id, + "expires": int(timezone.now().timestamp()) + CHALLENGE_SECONDS, + } + return redirect(destination) class EnrollFactorView(FactorView): @@ -309,15 +337,7 @@ class ConfirmFactorView(FactorView): if isinstance(device, EmailDevice): context["email_factor"] = True elif device: - configuration_url = device.config_url - qr = qrcode.make( - configuration_url, image_factory=SvgPathFillImage - ).to_string(encoding="utf-8") - context = { - "setup_key": base64.b32encode(device.bin_key).decode(), - "configuration_url": configuration_url, - "qr_image": base64.b64encode(qr).decode("ascii"), - } + context = authenticator_setup(device) return super().get_context_data(**context, **kwargs) @sensitive_variables("codes") diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index d20974b..63b5bdf 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -326,6 +326,11 @@ button, input, select, textarea { font-weight: 650; } +.sidebar-account a { + color: inherit; + text-underline-offset: 0.2em; +} + .sidebar-account button { padding: 0; border: 0; diff --git a/src/coulobre/hosting/templates/hosting/account_security.html b/src/coulobre/hosting/templates/hosting/account_security.html new file mode 100644 index 0000000..1e152fb --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/account_security.html @@ -0,0 +1,35 @@ +{% extends "hosting/base.html" %} +{% block title %}My account · Coulobre Panel{% endblock %} +{% block content %} +

My account

+ {% for message in messages %}

{{ message }}

{% endfor %} +
+

Sign-in and security

+
+
Username
{{ request.user.get_username }}
+
Email address
{{ request.user.email|default:"No email address" }}
+
Two-factor authentication
{{ factor }}
+
+ {% if not email_available %}

Email changes require configured panel email delivery.

{% endif %} +
+ Change password + {% if email_available %}Change email address{% endif %} + {% if factor_enabled %}Change{% else %}Set up{% endif %} authenticator app + {% if factor_enabled %}Generate recovery codes{% endif %} + Sign out other sessions +
+
+ {% if events %} +
+

Recent security activity

+
+ + + + {% for event in events %}{% endfor %} + +
ActionTime (UTC)
{{ event.get_action_display }}{{ event.created_at|date:"j M Y, H:i" }}
+
+
+ {% endif %} +{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/account_security_form.html b/src/coulobre/hosting/templates/hosting/account_security_form.html new file mode 100644 index 0000000..466d1f5 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/account_security_form.html @@ -0,0 +1,21 @@ +{% extends "hosting/base.html" %} +{% block title %}{{ heading }} · Coulobre Panel{% endblock %} +{% block content %} + ← My account +

{{ heading }}

+ {% for message in messages %}

{{ message }}

{% endfor %} +
+ {% if instructions %}

{{ instructions }}

{% endif %} + {% include "hosting/authenticator_setup.html" %} +
+ {% csrf_token %} + {{ form.as_div }} +
+ + {% if can_send_code %} + + {% endif %} +
+
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/authentication_card.html b/src/coulobre/hosting/templates/hosting/authentication_card.html index 365d15c..55774f7 100644 --- a/src/coulobre/hosting/templates/hosting/authentication_card.html +++ b/src/coulobre/hosting/templates/hosting/authentication_card.html @@ -1,23 +1,7 @@ -{% load static %}

{{ heading }}

{% if instructions %}

{{ instructions }}

{% endif %} {% if code_notice %}

{{ code_notice }}

{% endif %} -{% if configuration_url %} -
-

Scan this QR code with your authenticator app.

- Authenticator setup QR code -

Open in an authenticator app

-
- Enter the setup key manually -
- - -
-

-
-
- -{% endif %} +{% include "hosting/authenticator_setup.html" %} {% if form %}
{% csrf_token %} diff --git a/src/coulobre/hosting/templates/hosting/authenticator_setup.html b/src/coulobre/hosting/templates/hosting/authenticator_setup.html new file mode 100644 index 0000000..9dabf97 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/authenticator_setup.html @@ -0,0 +1,17 @@ +{% load static %} +{% if configuration_url %} +
+

Scan this QR code with your authenticator app.

+ Authenticator setup QR code +

Open in an authenticator app

+
+ Enter the setup key manually +
+ + +
+

+
+
+ +{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index c5672e9..efc886d 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -86,7 +86,11 @@ {% endwith %}