diff --git a/docs/deployment.md b/docs/deployment.md index 05994ab..e28b587 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -2166,6 +2166,21 @@ mailbox password and messages. ### Open phpMyAdmin from the panel +On an installer-managed panel with local MariaDB and Apache HTTPS, open +**Server Manager → Operator Settings → Database**. Choose **Configure** for +phpMyAdmin sign-in, enter a dedicated HTTPS hostname, and select **Install +and enable**. Coulobre installs the distribution package, sets up a +dedicated PHP-FPM pool and enables the credential bridge. A configured +integration can be paused from the same settings tab. + +Point the hostname at the panel server before setup. Coulobre uses an +existing Let's Encrypt certificate for that name or requests one over +HTTP-01 using the installed Certbot account. To supply a certificate, +place a root-owned chain and a private key with mode `0600` in +`/etc/coulobre/tool-tls//fullchain.pem` and `privkey.pem`. + +For a custom installation, follow the manual setup below. + Enable database credential access first. Install phpMyAdmin with PHP's MySQL and cURL extensions. Serve phpMyAdmin on a dedicated HTTPS hostname with its own PHP-FPM pool. The pool needs read access to its bridge configuration and @@ -2232,6 +2247,20 @@ database. Sign out of phpMyAdmin to end its session. ### Open a mailbox in Roundcube +On an installer-managed panel with Apache HTTPS, open **Server Manager → +Operator Settings → Email**. Choose **Configure** for Roundcube sign-in +and enter a dedicated hostname with the same DNS and certificate +requirements as phpMyAdmin. Enable mailbox password changes first. For +linked mail, the receiver must be on the same Coulobre release and grant +the panel access to its own mail domains. Existing installations with +manual webmail configuration can continue to use that configuration. + +Coulobre verifies the upstream Roundcube Complete archive, installs it in +`/opt/coulobre-roundcube` and keeps its SQLite data in +`/var/lib/coulobre-roundcube`. Track upstream security updates for the +managed Roundcube application. Use the manual setup below to manage a +custom Roundcube deployment. + Use the Roundcube 1.7 Complete release. Verify the archive and install Roundcube in `/opt/roundcube` following the [upstream manual setup](https://github.com/roundcube/roundcubemail/wiki/Installation). @@ -3109,6 +3138,22 @@ mailbox first and import a private copy of the archived Maildir with Dovecot. The archive is root-only and may contain private credentials. Recover the messages from the Maildir and set a new password separately. +### Send mail from a hosted application + +Open **Email Accounts → Application SMTP** on a managed mail domain and +issue a credential for the application. Save the generated password when +it is displayed. Once the credential is configured, enter the submission +hostname, port 587, STARTTLS, application username and password in the +application. Use the specified sender address for its envelope and From +header. The username is reserved for SMTP submission and has no Maildir. + +The local or linked mail node needs managed Postfix submission, Dovecot +2.4, and Rspamd with per-user submission limits. Each application has its +own rate-limit bucket. For an external DNS provider, publish the records +shown by **Check email DNS**. Check a received test message for aligned +SPF and DKIM under the hosted domain. Rotate a password from the +application list or revoke the credential when the application is retired. + ## Configure installed features in the panel ### Enroll hosting panels diff --git a/src/coulobre/hosting/account_retirement.py b/src/coulobre/hosting/account_retirement.py index c70f6de..a40ed94 100644 --- a/src/coulobre/hosting/account_retirement.py +++ b/src/coulobre/hosting/account_retirement.py @@ -26,6 +26,7 @@ from .models import ( SiteSFTP, SiteStorageLimit, SiteStorageUsage, + SmtpApplication, WebActivation, WebHTTPS, WebsiteAlias, @@ -240,6 +241,14 @@ def request_retirement(account_id, policy, confirmation, digest, actor): raise ValidationError( "Finish the mailbox removal before retiring the account." ) + if ( + SmtpApplication.objects.filter(mail_domain__account=account) + .exclude(revoke=True, finished_at__isnull=False, problem="") + .exists() + ): + raise ValidationError( + "Revoke application SMTP credentials before retiring the account." + ) targets = cleanup_targets(account) if policy == Policy.RELEASE: for kind, target, _ in targets: diff --git a/src/coulobre/hosting/credential_views.py b/src/coulobre/hosting/credential_views.py index edd086c..f5c9271 100644 --- a/src/coulobre/hosting/credential_views.py +++ b/src/coulobre/hosting/credential_views.py @@ -50,11 +50,14 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView): template_name = "hosting/service_credentials.html" rotating = False - def dispatch(self, request, *args, **kwargs): + def access_enabled(self, request): enabled = ( enabled_rotation if self.rotating else enabled_credential_access ) - if not enabled(request, self.kind): + return enabled(request, self.kind) + + def dispatch(self, request, *args, **kwargs): + if not self.access_enabled(request): raise Http404 if getattr(request, "impersonation", None) is not None: return self.handle_no_permission() diff --git a/src/coulobre/hosting/domain_services.py b/src/coulobre/hosting/domain_services.py index bef4ec9..b6dcf97 100644 --- a/src/coulobre/hosting/domain_services.py +++ b/src/coulobre/hosting/domain_services.py @@ -18,7 +18,7 @@ from .dns_forms import zone_record_rows from .domain_policies import managed_mail_domains, policy_for from .independent_websites import account_websites from .installation_features import panel_feature_allowed -from .models import DomainServicePolicy, HostingAccount +from .models import DomainServicePolicy, HostingAccount, SmtpApplication from .resource_requests import ( customer_mailbox_quota_limit, lock_hosting_account, @@ -85,6 +85,20 @@ def save_domain_policy(account_id, domain, customer_id, choices): if domain not in allowed_domains(account): raise Http404 previous = policy_for(account, domain) + if ( + previous.mail_managed + and not choices["mail_managed"] + and ( + SmtpApplication.objects.filter( + mail_domain__account=account, mail_domain__domain=domain + ) + .exclude(revoke=True, finished_at__isnull=False, problem="") + .exists() + ) + ): + raise ValidationError( + "Revoke application SMTP credentials before switching providers." + ) if ( previous.mail_managed and not choices["mail_managed"] @@ -210,6 +224,7 @@ def domain_workspace(request, pk, page): from .mail_policies import mail_policy_available from .mailbox_removal import can_remove_mailbox from .roundcube import roundcube_available + from .smtp_applications import smtp_applications_available defaults = zone_defaults() if page == "dns" else None show_mailbox_credentials = show_credential_action( @@ -243,6 +258,7 @@ def domain_workspace(request, pk, page): "can_edit_routing": mail_policy_available("routing"), "can_edit_mailbox": mail_policy_available("vacation"), "can_remove_mailbox": can_remove_mailbox(request), + "can_manage_smtp_apps": smtp_applications_available(request), "show_mailbox_credentials": show_mailbox_credentials, "show_mailbox_rotation": show_rotation_action( request, CredentialKind.MAILBOX @@ -253,7 +269,8 @@ def domain_workspace(request, pk, page): and not getattr(request, "impersonation", None) ), "roundcube_enabled": ( - show_mailbox_credentials and roundcube_available(request) + not getattr(request, "impersonation", None) + and roundcube_available(request) ), "mail_imap_host": settings.MAIL_IMAP_HOST, "mail_submission_host": settings.MAIL_SUBMISSION_HOST, diff --git a/src/coulobre/hosting/installation_features.py b/src/coulobre/hosting/installation_features.py index 7d6160b..3cbe13e 100644 --- a/src/coulobre/hosting/installation_features.py +++ b/src/coulobre/hosting/installation_features.py @@ -47,7 +47,8 @@ class Feature: return bool( settings.ROUNDCUBE_URL and ( - settings.LOCAL_MAILBOX_CREDENTIALS + settings.ROUNDCUBE_SCOPED_MAIL + or settings.LOCAL_MAILBOX_CREDENTIALS or settings.REMOTE_MAILBOX_CREDENTIALS ) ) @@ -65,11 +66,11 @@ class Feature: @property def socket_ready(self): if self.setting == "ROUNDCUBE_URL": - socket = ( - "coulobre-mail-credentials" - if settings.REMOTE_MAILBOX_CREDENTIALS - else "coulobre-service-credentials" - ) + socket = "coulobre-service-credentials" + if settings.ROUNDCUBE_SCOPED_MAIL: + socket = "coulobre-mail-passwords" + elif settings.REMOTE_MAILBOX_CREDENTIALS: + socket = "coulobre-mail-credentials" return Path(f"/run/{socket}.sock").is_socket() return not self.socket or Path(f"/run/{self.socket}.sock").is_socket() diff --git a/src/coulobre/hosting/installation_views.py b/src/coulobre/hosting/installation_views.py index 3c0b125..c765752 100644 --- a/src/coulobre/hosting/installation_views.py +++ b/src/coulobre/hosting/installation_views.py @@ -18,6 +18,11 @@ from django.views.generic import FormView, TemplateView from coulobre.local_feature_setup import LOCAL_FEATURES, PACKAGE_ASSETS from coulobre.operator_node import SOCKET, OperatorRequest +from coulobre.tool_setup_request import ( + HOSTING_TOOLS, + TOOL_SETUP_ACTION, + ToolSetupRequest, +) from .access import is_tenant from .installation_features import FEATURES, FeaturePolicy @@ -25,10 +30,33 @@ from .models import ( InvitationMailSettings, OperatorOperation, PanelFeaturePolicy, + WebsiteDomain, ) from .operator_tools import package_operation_pending, queue_operator_request from .update_views import inspect_linked_nodes +TOOL_FEATURES = { + "phpmyadmin": ( + "database", + "PHPMYADMIN_URL", + "LOCAL_DATABASE_PROVISIONING", + ), + "roundcube": ("email", "ROUNDCUBE_URL", "MAILBOX_PASSWORD_CHANGES"), +} +TOOL_SETTINGS = { + setting: tool for tool, (_, setting, _) in TOOL_FEATURES.items() +} + + +def managed_tool_available(tool): + _, setting, prerequisite = TOOL_FEATURES[tool] + return ( + Path(SOCKET).is_socket() + and PACKAGE_ASSETS.is_dir() + and not getattr(settings, setting) + and getattr(settings, prerequisite) + ) + @method_decorator(never_cache, name="dispatch") class InstallationView(LoginRequiredMixin, TemplateView): @@ -211,7 +239,15 @@ class FeatureConfigurationView(UserPassesTestMixin, FormView): for feature in form.features_requiring_setup: target = targets.get(feature.setting) job = latest.get(target) - setup.append((feature, target, package_operation_pending(job))) + tool = TOOL_SETTINGS.get(feature.setting) + setup.append( + ( + feature, + target, + package_operation_pending(job), + tool if tool and managed_tool_available(tool) else None, + ) + ) labels = {feature.setting: feature.label for feature in FEATURES} return super().get_context_data( selected_section=section, @@ -334,6 +370,100 @@ class FeatureConfigurationView(UserPassesTestMixin, FormView): ) +class ManagedToolForm(forms.Form): + hostname = forms.CharField(max_length=253, label="HTTPS hostname") + + def __init__(self, *args, tool, **kwargs): + super().__init__(*args, **kwargs) + self.tool = tool + + def clean_hostname(self): + try: + spec = ToolSetupRequest(self.tool, self.cleaned_data["hostname"]) + except ValueError as error: + raise forms.ValidationError(str(error)) from error + if ( + f"https://{spec.hostname}" == settings.PASSWORD_RESET_ORIGIN + or WebsiteDomain.objects.filter(domain=spec.hostname).exists() + ): + raise forms.ValidationError("Use a separate, unused hostname.") + return spec.hostname + + +@method_decorator(never_cache, name="dispatch") +class ManagedToolSetupView(UserPassesTestMixin, FormView): + form_class = ManagedToolForm + template_name = "hosting/managed_tool_setup.html" + + def test_func(self): + return ( + self.request.user.is_superuser and self.request.user.is_verified() + ) + + @property + def tool(self): + tool = self.kwargs["tool"] + if tool not in HOSTING_TOOLS: + raise Http404 + return tool + + def get_form_kwargs(self): + return super().get_form_kwargs() | {"tool": self.tool} + + def get_context_data(self, **kwargs): + job = ( + OperatorOperation.objects.filter( + action=TOOL_SETUP_ACTION, target=self.tool + ) + .order_by("-pk") + .first() + ) + return super().get_context_data( + tool_label=HOSTING_TOOLS[self.tool], + section=TOOL_FEATURES[self.tool][0], + available=managed_tool_available(self.tool), + pending=package_operation_pending(job), + job=job, + **kwargs, + ) + + def get_success_url(self): + return self.request.path + + @transaction.atomic + def form_valid(self, form): + PanelFeaturePolicy.objects.get_or_create(pk=1) + PanelFeaturePolicy.objects.select_for_update().get(pk=1) + if not managed_tool_available(self.tool): + form.add_error( + None, "This installation cannot queue this tool now." + ) + return self.form_invalid(form) + previous = ( + OperatorOperation.objects.filter( + action__in=(TOOL_SETUP_ACTION, "feature-enable") + ) + .order_by("-pk") + .first() + ) + if package_operation_pending(previous): + form.add_error( + None, "Wait for the current feature setup to finish." + ) + return self.form_invalid(form) + spec = ToolSetupRequest(self.tool, form.cleaned_data["hostname"]) + queue_operator_request( + self.request.user, + spec, + retryable=True, + parameters={"hostname": spec.hostname}, + ) + messages.success( + self.request, f"{HOSTING_TOOLS[self.tool]} setup queued." + ) + return super().form_valid(form) + + class InvitationMailSettingsForm(forms.ModelForm): class Meta: model = InvitationMailSettings diff --git a/src/coulobre/hosting/migrations/0086_smtp_applications.py b/src/coulobre/hosting/migrations/0086_smtp_applications.py new file mode 100644 index 0000000..e98c170 --- /dev/null +++ b/src/coulobre/hosting/migrations/0086_smtp_applications.py @@ -0,0 +1,81 @@ +# Generated by Django 5.2.19 on 2026-12-01 13:34 + +import uuid + +import django.db.models.deletion +import django.utils.timezone +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0085_panel_peers"), + ] + + operations = [ + migrations.AlterField( + model_name="accountservicejob", + name="kind", + field=models.CharField( + choices=[ + ("web", "Website"), + ("sftp", "SFTP"), + ("database", "Database"), + ("mailbox", "Mailbox"), + ("smtp", "Application SMTP"), + ], + max_length=8, + ), + ), + migrations.CreateModel( + name="SmtpApplication", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "requested_at", + models.DateTimeField(default=django.utils.timezone.now), + ), + ( + "last_dispatched_at", + models.DateTimeField(blank=True, null=True), + ), + ("started_at", models.DateTimeField(blank=True, null=True)), + ("finished_at", models.DateTimeField(blank=True, null=True)), + ("problem", models.TextField(blank=True)), + ( + "identifier", + models.UUIDField( + default=uuid.uuid4, editable=False, unique=True + ), + ), + ("label", models.CharField(max_length=80)), + ("sender_local", models.CharField(max_length=64)), + ("revision", models.PositiveIntegerField(default=1)), + ("password_hash", models.CharField(blank=True, max_length=96)), + ("revoke", models.BooleanField(default=False)), + ( + "requested_customer_id", + models.PositiveBigIntegerField(null=True), + ), + ( + "mail_domain", + models.ForeignKey( + on_delete=django.db.models.deletion.PROTECT, + related_name="smtp_applications", + to="hosting.hostingmaildomain", + ), + ), + ], + options={ + "abstract": False, + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 4242b33..fb1a70c 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -1112,6 +1112,7 @@ class AccountServiceJob(ProvisioningJob): SFTP = "sftp", "SFTP" DATABASE = "database", "Database" MAILBOX = "mailbox", "Mailbox" + SMTP = "smtp", "Application SMTP" change = models.ForeignKey( AccountServiceChange, on_delete=models.CASCADE, related_name="jobs" @@ -1598,6 +1599,31 @@ class MailboxRemoval(ProvisioningJob): address = models.CharField(max_length=254) +class SmtpApplication(ProvisioningJob): + mail_domain = models.ForeignKey( + HostingMailDomain, + on_delete=models.PROTECT, + related_name="smtp_applications", + ) + identifier = models.UUIDField( + default=uuid.uuid4, unique=True, editable=False + ) + label = models.CharField(max_length=80) + sender_local = models.CharField(max_length=LOCAL_PART_MAX_LENGTH) + revision = models.PositiveIntegerField(default=1) + password_hash = models.CharField(max_length=96, blank=True) + revoke = models.BooleanField(default=False) + requested_customer_id = models.PositiveBigIntegerField(null=True) + + @property + def spec(self): + from coulobre.smtp_application import SmtpApplicationSpec + + return SmtpApplicationSpec( + self.mail_domain.domain, self.identifier.hex, self.sender_local + ) + + class MailPolicyPublication(ProvisioningJob): manifest = models.JSONField() applied_manifest = models.JSONField(default=dict, blank=True) diff --git a/src/coulobre/hosting/operator_tools.py b/src/coulobre/hosting/operator_tools.py index 25b4f84..b99bd1d 100644 --- a/src/coulobre/hosting/operator_tools.py +++ b/src/coulobre/hosting/operator_tools.py @@ -45,13 +45,16 @@ def package_operation_pending(job): ) -def queue_operator_request(user, spec, *, source=None, retryable=False): +def queue_operator_request( + user, spec, *, source=None, retryable=False, parameters=None +): job = OperatorOperation.objects.create( actor=user, action=spec.action, target=spec.target, plan=spec.plan, source=source, + parameters=parameters or {}, ) def dispatch(): diff --git a/src/coulobre/hosting/reseller_accounts.py b/src/coulobre/hosting/reseller_accounts.py index 8d6a591..b9e6a66 100644 --- a/src/coulobre/hosting/reseller_accounts.py +++ b/src/coulobre/hosting/reseller_accounts.py @@ -3,7 +3,7 @@ from django.core.exceptions import NON_FIELD_ERRORS, ValidationError from django.db import connection, transaction from django.db.models import F -from .models import Customer, Reseller, ResellerAuditEvent +from .models import Customer, Reseller, ResellerAuditEvent, SmtpApplication from .resource_requests import ( lock_hosting_account, require_active_services, @@ -172,6 +172,15 @@ def save_operator_account(account, actor, *, changed_fields=None): "Remove folder SFTP logins before changing the customer " "or primary domain." ) + if {"customer", "primary_domain"}.intersection(changed_fields) and ( + SmtpApplication.objects.filter(mail_domain__account=previous) + .exclude(revoke=True, finished_at__isnull=False, problem="") + .exists() + ): + raise ValidationError( + "Revoke application SMTP credentials before changing the " + "customer or primary domain." + ) previous_reseller_id = previous.reseller_id reseller_id = ( account.reseller_id diff --git a/src/coulobre/hosting/roundcube.py b/src/coulobre/hosting/roundcube.py index 8dc4588..ad74a8e 100644 --- a/src/coulobre/hosting/roundcube.py +++ b/src/coulobre/hosting/roundcube.py @@ -10,6 +10,8 @@ from django.views.decorators.debug import ( ) from django.views.decorators.http import require_POST +from coulobre.service_credentials import ServiceCredentialRequest + from .access import customer_for_user from .credential_views import MailboxCredentialView from .installation_features import panel_feature_allowed @@ -20,6 +22,7 @@ from .service_credentials import ( can_reveal_credentials, enabled_credential_access, fetch_service_credentials, + mailbox_password_changes_enabled, ) from .signon import ( bridge_ticket, @@ -30,10 +33,17 @@ from .signon import ( def roundcube_available(request): + transport = ( + request.is_secure() + and not settings.DEBUG + and mailbox_password_changes_enabled() + if settings.ROUNDCUBE_SCOPED_MAIL + else enabled_credential_access(request, CredentialKind.MAILBOX) + ) return bool( panel_feature_allowed("ROUNDCUBE_URL") and settings.ROUNDCUBE_BRIDGE_KEY - and enabled_credential_access(request, CredentialKind.MAILBOX) + and transport ) @@ -64,6 +74,9 @@ def actor_can_open_webmail(actor, mailbox): class RoundcubeLaunch(MailboxCredentialView): http_method_names = ["post"] + def access_enabled(self, request): + return roundcube_available(request) + def dispatch(self, request, *args, **kwargs): response = super().dispatch(request, *args, **kwargs) response["Referrer-Policy"] = "origin" @@ -71,8 +84,6 @@ class RoundcubeLaunch(MailboxCredentialView): @sensitive_variables() def post(self, request, *args, **kwargs): - if not roundcube_available(request): - raise Http404 mailbox = self.resource if not actor_can_open_webmail(request.user, mailbox): raise Http404 @@ -132,7 +143,13 @@ def redeem_roundcube(request): outcome=CredentialOutcome.REQUESTED, ) try: - credentials = fetch_service_credentials(spec) + credentials = ( + fetch_service_credentials( + spec, ServiceCredentialRequest(spec, "webmail") + ) + if settings.ROUNDCUBE_SCOPED_MAIL + else fetch_service_credentials(spec) + ) except (OSError, ValueError): record_outcome(audit, CredentialOutcome.UNAVAILABLE) return JsonResponse( diff --git a/src/coulobre/hosting/service_changes.py b/src/coulobre/hosting/service_changes.py index 8e92a1e..3b9baf9 100644 --- a/src/coulobre/hosting/service_changes.py +++ b/src/coulobre/hosting/service_changes.py @@ -6,6 +6,10 @@ from django.db.models import Q from coulobre.database_node import DatabaseSpec from coulobre.mail_node import MailboxSpec from coulobre.service_access import ServiceAccessRequest +from coulobre.smtp_application import ( + SmtpApplicationRequest, + SmtpApplicationSpec, +) from coulobre.web_node import WebSite from .independent_websites import account_websites, active_websites @@ -15,6 +19,7 @@ from .models import ( DatabaseProvisioning, HostingMailbox, MailboxProvisioning, + SmtpApplication, WebActivation, WebsiteRestoreJob, ) @@ -41,6 +46,11 @@ SERVICES = { MailboxSpec, "/run/coulobre-mail-apply.sock", ), + Kind.SMTP: ( + "LOCAL_MAILBOX_PROVISIONING", + SmtpApplicationSpec, + "/run/coulobre-mail-apply.sock", + ), } @@ -54,13 +64,16 @@ def current_service_jobs(account): mailboxes = MailboxProvisioning.objects.filter( mailbox__mail_domain__account=account ) + applications = SmtpApplication.objects.filter( + mail_domain__account=account + ).exclude(revoke=True, finished_at__isnull=False, problem="") if any( jobs.filter(finished_at__isnull=True).exists() or jobs.exclude(problem="").exists() - for jobs in (activations, databases, mailboxes) + for jobs in (activations, databases, mailboxes, applications) ): raise ValidationError( - "Resolve pending or failed website, database, and mailbox " + "Resolve pending or failed website, database, and email " "provisioning before suspending services." ) websites = account_websites(account).filter(retired_at__isnull=True) @@ -114,6 +127,8 @@ def current_service_jobs(account): or spec.address in restored_mailboxes ): yield Kind.MAILBOX, spec.address, spec.manifest() + for application in applications.select_related("mail_domain"): + yield Kind.SMTP, application.spec.login, application.spec.manifest() @transaction.atomic @@ -191,6 +206,18 @@ def apply_service_change(job): ) spec = resource.from_manifest(job.manifest) suspended = job.change.suspended + if job.kind == Kind.SMTP: + request = SmtpApplicationRequest( + spec, "suspend" if suspended else "resume", 1 + ) + apply_on_local_node( + request, + socket, + job.get_kind_display(), + "service access", + identity=request.identity(), + ) + return {"applied_suspended": suspended} if job.kind == Kind.WEB and spec.site_id is not None and not suspended: website = ( active_websites(job.change.account).filter(pk=spec.site_id).first() diff --git a/src/coulobre/hosting/smtp_applications.py b/src/coulobre/hosting/smtp_applications.py new file mode 100644 index 0000000..4f24aaa --- /dev/null +++ b/src/coulobre/hosting/smtp_applications.py @@ -0,0 +1,256 @@ +import base64 +import hashlib +import secrets + +from django import forms +from django.conf import settings +from django.contrib import messages +from django.contrib.admin.models import ADDITION, CHANGE, LogEntry +from django.core.exceptions import PermissionDenied, ValidationError +from django.db import transaction +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect, render +from django.urls import reverse +from django.views.decorators.cache import never_cache +from django.views.decorators.debug import sensitive_variables +from django.views.decorators.http import require_http_methods + +from coulobre.mail_dns import dkim_key, normalize_rsa_dkim_record +from coulobre.smtp_application import SmtpApplicationRequest + +from .access import can_manage_hosting, customer_for_user +from .domain_policies import require_managed +from .installation_features import panel_feature_allowed +from .mail_dns_setup import sync_mail_dns +from .models import HostingAccount, HostingMailDomain, SmtpApplication +from .node_client import apply_on_local_node +from .resource_requests import lock_hosting_account, require_active_services + +PERMISSIONS = ( + "hosting.view_hostingaccount", + "hosting.view_hostingmaildomain", + "hosting.change_smtpapplication", +) +MAIL_SOCKET = "/run/coulobre-mail-apply.sock" +APPLICATION_LIMIT = 10 + + +def smtp_applications_available(request): + return bool( + settings.LOCAL_MAILBOX_PROVISIONING + and settings.MAIL_SUBMISSION_HOST + and request.is_secure() + and not settings.DEBUG + and getattr(request, "impersonation", None) is None + and can_manage_hosting(request.user, PERMISSIONS) + ) + + +def active_applications(domain): + return domain.smtp_applications.exclude( + revoke=True, finished_at__isnull=False, problem="" + ) + + +class ApplicationForm(forms.Form): + label = forms.CharField( + max_length=80, help_text="For example, Website contact form." + ) + sender_local = forms.CharField( + max_length=64, + label="Sender name before @", + help_text="Use an address on this domain, such as website.", + ) + + +@transaction.atomic +@sensitive_variables() +def request_application(domain, actor, customer_id, action, app_id, values): + account = lock_hosting_account(domain.account_id, customer_id) + if account.retired_at is not None: + raise Http404 + requested = active_applications(domain) + if action != "revoke": + require_managed(account, domain.domain, "mail_managed") + require_active_services(account) + if not panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING"): + raise ValidationError( + "New email requests are paused on this panel." + ) + password = secrets.token_urlsafe(32) + digest = base64.b64encode( + hashlib.sha512(password.encode()).digest() + ).decode() + password_hash = "{SHA512}" + digest + else: + password = password_hash = "" + if action == "issue": + if requested.count() >= APPLICATION_LIMIT: + raise ValidationError( + "This domain has ten application credentials." + ) + if requested.filter(label=values["label"]).exists(): + raise ValidationError( + "An application with this label already exists." + ) + app = SmtpApplication( + mail_domain=domain, + password_hash=password_hash, + requested_customer_id=customer_id, + **values, + ) + try: + app.sender_local = app.spec.sender_local + except ValueError as error: + raise ValidationError(str(error)) from error + app.save() + else: + app = get_object_or_404(requested, pk=app_id) + if app.finished_at is None: + raise ValidationError("Wait for the current credential operation.") + if app.revoke and action == "rotate": + raise ValidationError("Retry revocation for this credential.") + SmtpApplication.objects.requeue( + requested.filter(pk=app.pk), + password_hash=password_hash, + requested_customer_id=customer_id, + revision=app.revision + (not app.revoke), + revoke=action == "revoke", + ) + labels = { + "issue": "Requested application SMTP credential.", + "rotate": "Requested rotation of application SMTP credential.", + "revoke": "Requested revocation of application SMTP credential.", + } + LogEntry.objects.log_actions( + actor.pk, + [app], + ADDITION if action == "issue" else CHANGE, + labels[action], + ) + return app, password + + +def apply_application(request): + return apply_on_local_node( + request, + MAIL_SOCKET, + "mail node", + "SMTP application", + identity=request.identity(), + ) + + +@transaction.atomic +@sensitive_variables() +def apply_application_job(job): + account = lock_hosting_account(job.mail_domain.account_id, None) + if account.retired_at is not None: + raise ValueError("This hosting account is retired.") + if not job.revoke and ( + account.services_suspended + or ( + job.requested_customer_id is not None + and job.requested_customer_id != account.customer_id + ) + ): + raise ValueError("The hosting account access has changed.") + if not job.revoke: + try: + require_managed(account, job.mail_domain.domain, "mail_managed") + except ValidationError as error: + raise ValueError(" ".join(error.messages)) from None + request = SmtpApplicationRequest( + job.spec, + "revoke" if job.revoke else "issue", + job.revision, + job.password_hash, + ) + reply = apply_application(request) + if not job.revoke: + public = reply.get("dkim") + if ( + not isinstance(public, str) + or len(public) > 1024 + or dkim_key(public)[0] != "ok" + ): + raise ValueError( + "The mail node returned an invalid DKIM public key." + ) + public = normalize_rsa_dkim_record(public) + if settings.MANAGE_MAIL_DNS: + sync_mail_dns(job.mail_domain, public_key=public) + else: + HostingMailDomain.objects.filter(pk=job.mail_domain_id).update( + dkim_record=public + ) + return {"password_hash": ""} + + +@never_cache +@require_http_methods(("GET", "HEAD", "POST")) +@sensitive_variables() +def smtp_applications(request, pk): + if not smtp_applications_available(request): + raise PermissionDenied + customer = customer_for_user(request.user) + domains = HostingMailDomain.objects.select_related("account").filter( + account__retired_at__isnull=True + ) + if customer is not None: + domains = domains.filter(account__customer=customer) + domain = get_object_or_404(domains, pk=pk) + action = request.POST.get("action", "") + form = ApplicationForm(request.POST if action == "issue" else None) + password = "" + app = None + if request.method == "POST": + if action not in {"issue", "rotate", "revoke"}: + raise Http404 + app_id = request.POST.get("app", "") + if action != "issue" and not ( + app_id.isascii() and app_id.isdecimal() and len(app_id) <= 18 + ): + raise Http404 + if action != "issue" or form.is_valid(): + try: + app, password = request_application( + domain, + request.user, + customer.pk if customer is not None else None, + action, + app_id, + form.cleaned_data if action == "issue" else {}, + ) + except HostingAccount.DoesNotExist as error: + raise Http404 from error + except ValidationError as error: + messages.error(request, " ".join(error.messages)) + else: + if not password: + messages.success(request, "Credential revocation queued.") + return redirect(request.path) + + account = domain.account + return_url = ( + reverse( + "panel:domain_workspace", + args=[account.pk, "email"], + query={"domain": domain.domain}, + ) + if customer is not None + else account.get_absolute_url() + "#email" + ) + return render( + request, + "hosting/smtp_applications.html", + { + "domain": domain, + "form": form, + "applications": active_applications(domain), + "issued": app if password else None, + "password": password, + "return_url": return_url, + "host": settings.MAIL_SUBMISSION_HOST, + }, + ) diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index ab352fe..8d6813a 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -64,6 +64,7 @@ from .models import ( SiteSFTP, SiteStorageLimit, SiteStorageUsage, + SmtpApplication, SystemBackupJob, WebActivation, WebHTTPS, @@ -116,6 +117,7 @@ from .resource_requests import lock_hosting_account from .service_changes import apply_service_change from .sftp import site_is_active from .sign_in_limits import current_window +from .smtp_applications import apply_application_job from .website_jobs import ( JOB_QUEUE, claim_website_job, @@ -322,6 +324,11 @@ def dispatch_mailbox_provisioning(): dispatch_provisioning_jobs( MailboxRemoval, remove_mailbox, MAILBOX_PROVISIONING_QUEUE ) + dispatch_provisioning_jobs( + SmtpApplication, + configure_smtp_application, + MAILBOX_PROVISIONING_QUEUE, + ) if mail_policy_available("routing"): dispatch_provisioning_jobs( @@ -344,6 +351,7 @@ def dispatch_account_service_changes(): AccountServiceJob.Kind.SFTP: WEB_SFTP_QUEUE, AccountServiceJob.Kind.DATABASE: DATABASE_PROVISIONING_QUEUE, AccountServiceJob.Kind.MAILBOX: MAILBOX_PROVISIONING_QUEUE, + AccountServiceJob.Kind.SMTP: MAILBOX_PROVISIONING_QUEUE, } for kind, queue in queues.items(): dispatch_provisioning_jobs( @@ -823,6 +831,17 @@ def remove_mailbox(removal_id): ) +@shared_task(acks_late=True, reject_on_worker_lost=True) +def configure_smtp_application(job_id): + if settings.LOCAL_MAILBOX_PROVISIONING: + run_provisioning_job( + SmtpApplication.objects.select_related("mail_domain"), + job_id, + apply_application_job, + "Could not reach the mail node. Check its connection and retry.", + ) + + @shared_task(acks_late=True, reject_on_worker_lost=True) def publish_mail_routing(job_id): if mail_policy_available("routing"): @@ -1369,6 +1388,7 @@ def collect_mailbox_usage(mailbox_id, requested_at): def run_operator_operation(job_id): from coulobre.http_defaults import HttpDefaultsRequest from coulobre.operator_node import SOCKET, OperatorRequest + from coulobre.tool_setup_request import TOOL_SETUP_ACTION, ToolSetupRequest from .models import OperatorOperation from .node_client import apply_on_local_node @@ -1380,11 +1400,20 @@ def run_operator_operation(job_id): raise ValueError( "The peer no longer has permission for this action." ) - spec = ( - HttpDefaultsRequest(job.target, job.parameters) - if job.action == "http-defaults" - else OperatorRequest(job.action, job.target, job.plan) - ) + if job.action == TOOL_SETUP_ACTION: + if ( + job.actor is None + or not job.actor.is_active + or not job.actor.is_superuser + ): + raise ValueError( + "The requesting operator no longer has access." + ) + spec = ToolSetupRequest(job.target, job.parameters.get("hostname")) + elif job.action == "http-defaults": + spec = HttpDefaultsRequest(job.target, job.parameters) + else: + spec = OperatorRequest(job.action, job.target, job.plan) result = apply_on_local_node( spec, SOCKET, "operator service", "host operation", timeout=32 * 60 ) diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index de97167..3a2a460 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -282,7 +282,7 @@
- {% if manage_mail_routing %}{% endif %}{% if show_mail_queue %}{% endif %} + {% if manage_mail_routing %}{% endif %}{% if show_mail_queue %}{% endif %}{% if can_manage_smtp_apps %}{% endif %} {% for domain in mail_domains %} @@ -294,6 +294,9 @@ {% if show_mail_queue %} {% endif %} + {% if can_manage_smtp_apps %} + + {% endif %} {% endfor %} diff --git a/src/coulobre/hosting/templates/hosting/domain_workspace.html b/src/coulobre/hosting/templates/hosting/domain_workspace.html index 6e47263..6fef4bf 100644 --- a/src/coulobre/hosting/templates/hosting/domain_workspace.html +++ b/src/coulobre/hosting/templates/hosting/domain_workspace.html @@ -79,7 +79,10 @@ {% endif %} {% endif %} - {% if mail_domain %}

Check email DNS

{% endif %} + {% if mail_domain %}
+ Check email DNS + {% if can_manage_smtp_apps %}Application SMTP{% endif %} +
{% endif %} {% endif %} {% elif mail_domain and policy.mail_managed %} diff --git a/src/coulobre/hosting/templates/hosting/feature_configuration.html b/src/coulobre/hosting/templates/hosting/feature_configuration.html index 8cefd27..781d776 100644 --- a/src/coulobre/hosting/templates/hosting/feature_configuration.html +++ b/src/coulobre/hosting/templates/hosting/feature_configuration.html @@ -49,7 +49,7 @@
DomainDNSRoutingDelivery
DomainDNSRoutingDeliveryApplications
Mail queueApplication SMTP
- {% for feature, target, pending in setup_features %} + {% for feature, target, pending, tool in setup_features %} {% endfor %} diff --git a/src/coulobre/hosting/templates/hosting/managed_tool_setup.html b/src/coulobre/hosting/templates/hosting/managed_tool_setup.html new file mode 100644 index 0000000..60e8ec5 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/managed_tool_setup.html @@ -0,0 +1,34 @@ +{% extends "hosting/workspace_page.html" %} +{% block title %}Set up {{ tool_label }} · Coulobre Panel{% endblock %} +{% block page_title %}Set up {{ tool_label }}{% endblock %} +{% block page_actions %} + ← Operator Settings +{% endblock %} +{% block page_content %} + {% if job %} +
+
+

Latest setup

+ {% if job.finished_at %} +

{{ job.problem|default:"Ready" }}

+ {% elif pending %} +

{{ job.state|capfirst }}

+ {% else %} +

Setup was interrupted. Try again.

+ {% endif %} +
+
+ {% endif %} + {% if available %} +
+

Point a dedicated hostname at this server. Coulobre uses an existing TLS certificate for the hostname or requests one through Let's Encrypt. Keep inbound HTTP available for certificate validation.

+
+ {% csrf_token %} + {{ form.as_p }} +
+ +
+ +
+ {% endif %} +{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/smtp_applications.html b/src/coulobre/hosting/templates/hosting/smtp_applications.html new file mode 100644 index 0000000..2f4f934 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/smtp_applications.html @@ -0,0 +1,55 @@ +{% extends "hosting/workspace_page.html" %} + +{% block title %}Application SMTP · Coulobre Panel{% endblock %} +{% block page_title %}Application SMTP{% endblock %} +{% block page_metadata %}

{{ domain }}

{% endblock %} +{% block page_actions %}← Email{% endblock %} +{% block page_content %} + {% if issued %} +
+

Save this credential

+

Use it after its status changes to Configured. The password appears once.

+
+
Username
{% include "hosting/copy_value.html" with key="smtp-username" value=issued.spec.login label="username" %}
+
Password
{% include "hosting/copy_value.html" with key="smtp-password" value=password label="password" %}
+
Envelope sender
{{ issued.spec.sender }}
+
+
+ {% endif %} +
+

Submission settings

+

{{ host }} · port 587 · STARTTLS required

+
+
+

Add application credential

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

Credentials

+
FeatureSetup
{{ feature.label }} @@ -58,7 +58,10 @@ {% csrf_token %} - {% elif pending %}

Setup in progress

{% endif %} + {% elif pending %}

Setup in progress

+ {% elif tool %} + Configure + {% endif %} {% include "hosting/feature_setup.html" with show_dns_link=True %}
+ + {% for app in applications %} + + + + + {% empty %}{% endfor %} +
ApplicationUsernameSenderStatus and actions
{{ app.label }}{{ app.spec.login }}{{ app.spec.sender }} + {% if app.revoke %}Revocation {% endif %}{{ app.state|capfirst }} + {% if app.problem %}

{{ app.problem }}

{% endif %} + {% if app.finished_at %} +
Manage credential +
+ {% csrf_token %} + {% if not app.revoke %}{% endif %} + +
+
+ {% endif %} +
No application credentials.
+ +{% endblock %} diff --git a/src/coulobre/hosting/test_feature_configuration.py b/src/coulobre/hosting/test_feature_configuration.py index 844564f..d5414d3 100644 --- a/src/coulobre/hosting/test_feature_configuration.py +++ b/src/coulobre/hosting/test_feature_configuration.py @@ -93,6 +93,50 @@ class FeatureConfigurationTests(TestCase): self.assertEqual(operation.actor, self.operator) queue.assert_called_once_with(operation.pk) + @override_settings( + LOCAL_DATABASE_PROVISIONING=True, + PHPMYADMIN_URL="", + PASSWORD_RESET_ORIGIN="https://panel.example", + ) + def test_operator_can_queue_setup_for_a_dedicated_https_tool(self): + setup = reverse("panel:managed_tool_setup", args=["phpmyadmin"]) + payload = {"hostname": "database-tools.example"} + self.sign_in(verified=False) + self.assertEqual(self.client.post(setup, payload).status_code, 403) + self.sign_in() + module = "coulobre.hosting.installation_views" + with ( + patch(f"{module}.Path") as path_factory, + patch(f"{module}.PACKAGE_ASSETS") as assets, + patch( + "coulobre.hosting.operator_tools.run_operator_operation.delay" + ) as queue, + ): + path_factory.return_value.is_socket.return_value = True + assets.is_dir.return_value = True + self.assertContains( + self.client.get( + reverse("panel:operator_settings", args=["database"]) + ), + setup, + ) + self.assertContains( + self.client.post(setup, {"hostname": "panel.example"}), + "Use a separate, unused hostname.", + ) + with self.captureOnCommitCallbacks(execute=True): + reply = self.client.post(setup, payload) + self.assertEqual(reply.status_code, 302) + self.assertContains( + self.client.post(setup, payload), + "Wait for the current feature setup to finish.", + ) + operation = OperatorOperation.objects.get() + self.assertEqual(operation.action, "tool-setup") + self.assertEqual(operation.target, "phpmyadmin") + self.assertEqual(operation.parameters, payload) + queue.assert_called_once_with(operation.pk) + @override_settings(LOCAL_WEB_ACTIVATION=True, WEB_FILE_MANAGER=False) def test_feature_setup_can_retry_after_the_broker_is_offline(self): self.sign_in() diff --git a/src/coulobre/hosting/test_roundcube.py b/src/coulobre/hosting/test_roundcube.py index 3f33526..23d7c67 100644 --- a/src/coulobre/hosting/test_roundcube.py +++ b/src/coulobre/hosting/test_roundcube.py @@ -136,6 +136,34 @@ class RoundcubeSignOnTests(TestCase): self.assertEqual(self.redeem(database_ticket).status_code, 404) self.assertIsNone(PhpMyAdminGrant.objects.get().redeemed_at) + @override_settings( + REMOTE_MAILBOX_CREDENTIALS=False, + ROUNDCUBE_SCOPED_MAIL=True, + LOCAL_MAILBOX_PROVISIONING=True, + MAILBOX_PASSWORD_CHANGES=True, + ) + def test_scoped_webmail_does_not_enable_mailbox_password_reveal(self): + ticket = self.issue(self.first) + with patch( + "coulobre.hosting.roundcube.fetch_service_credentials", + return_value={ + "user": self.first.spec.address, + "password": MAIL_PASSWORD, + }, + ) as node: + response = self.redeem(ticket) + self.assertEqual(response.status_code, 200) + resource, request = node.call_args.args + self.assertEqual(resource, self.first.spec) + self.assertEqual(request.operation, "webmail") + self.assertEqual( + self.client.get( + reverse("panel:mailbox_credentials", args=[self.first.pk]), + secure=True, + ).status_code, + 404, + ) + def test_another_tenant_cannot_launch_and_old_grants_lose_access(self): ticket = self.issue(self.first) self.client.force_login(self.other) diff --git a/src/coulobre/hosting/test_smtp_applications.py b/src/coulobre/hosting/test_smtp_applications.py new file mode 100644 index 0000000..ef10713 --- /dev/null +++ b/src/coulobre/hosting/test_smtp_applications.py @@ -0,0 +1,107 @@ +import base64 +from unittest.mock import patch + +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from django.contrib.auth import get_user_model +from django.test import TestCase, override_settings +from django.urls import reverse + +from .models import ( + Customer, + HostingAccount, + HostingMailDomain, + SmtpApplication, +) +from .tasks import configure_smtp_application + + +@override_settings( + LOCAL_MAILBOX_PROVISIONING=True, + MAIL_SUBMISSION_HOST="mail.example.test", + MANAGE_MAIL_DNS=False, +) +class ApplicationSmtpTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.user = users.create_user("website-owner") + cls.other = users.create_user("other-customer") + Customer.objects.create(user=cls.other) + account = HostingAccount.objects.create( + name="Example site", + primary_domain="site.example", + customer=Customer.objects.create(user=cls.user), + ) + cls.domain = HostingMailDomain.objects.create( + account=account, domain=account.primary_domain + ) + public_key = rsa.generate_private_key( + public_exponent=65537, key_size=2048 + ).public_key() + encoded = public_key.public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo, + ) + cls.dkim = "v=DKIM1; k=rsa; p=" + base64.b64encode(encoded).decode() + + def setUp(self): + self.client.force_login(self.user) + self.url = reverse("panel:smtp_applications", args=[self.domain.pk]) + + def issue(self, *, secure=True): + return self.client.post( + self.url, + {"action": "issue", "label": "Website", "sender_local": "form"}, + secure=secure, + ) + + def test_password_is_shown_once_and_cleared_after_node_acknowledgement( + self, + ): + page = self.issue() + self.assertContains(page, "Save this credential") + self.assertIn("no-store", page.headers["Cache-Control"]) + password = page.context["password"] + application = SmtpApplication.objects.get() + self.assertNotEqual(application.password_hash, password) + self.assertNotContains( + self.client.get(self.url, secure=True), password + ) + with patch( + "coulobre.hosting.smtp_applications.apply_application", + return_value={"dkim": self.dkim}, + ) as send: + configure_smtp_application.run(application.pk) + self.assertEqual( + send.call_args.args[0].application.sender, "form@site.example" + ) + application.refresh_from_db() + self.assertEqual(application.state, "configured") + self.assertFalse(application.password_hash) + self.domain.refresh_from_db() + self.assertTrue(self.domain.dkim_record.startswith("v=DKIM1;")) + + page = self.client.post( + self.url, + {"action": "revoke", "app": application.pk}, + secure=True, + ) + self.assertEqual(page.status_code, 302) + with patch( + "coulobre.hosting.smtp_applications.apply_application", + return_value={}, + ) as send: + configure_smtp_application.run(application.pk) + self.assertEqual(send.call_args.args[0].action, "revoke") + self.assertNotContains( + self.client.get(self.url, secure=True), "form@site.example" + ) + + def test_insecure_and_cross_account_requests_do_not_issue_credentials( + self, + ): + self.assertEqual(self.issue(secure=False).status_code, 403) + self.client.force_login(self.other) + self.assertEqual(self.issue().status_code, 404) + self.assertFalse(SmtpApplication.objects.exists()) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index a462f38..b2d3df1 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -46,6 +46,7 @@ from .installation_views import ( FeatureConfigurationView, InstallationView, InvitationMailSettingsView, + ManagedToolSetupView, ) from .invitations import AcceptInvitation, ManageInvitation from .mail_delivery_views import MailDeliveryView @@ -109,6 +110,7 @@ from .sign_in import ( PanelLoginView, VerifyFactorView, ) +from .smtp_applications import smtp_applications from .system_backup_views import SystemBackupView from .update_views import ChangelogView, UpdateView from .website_file_views import WebsiteFilesView @@ -307,6 +309,11 @@ urlpatterns = [ MailQueueView.as_view(), name="mail_queue", ), + path( + "mail-domains//applications/", + smtp_applications, + name="smtp_applications", + ), path("", views.AccountList.as_view(), name="accounts"), path( "service-health/", ServiceHealthView.as_view(), name="service_health" @@ -327,6 +334,11 @@ urlpatterns = [ InvitationMailSettingsView.as_view(), name="invitation_mail_settings", ), + path( + "settings/tools//", + ManagedToolSetupView.as_view(), + name="managed_tool_setup", + ), path("account/role/", switch_panel_role, name="switch_panel_role"), path("support/getting-started/", getting_started, name="getting_started"), path( diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index cbf8e77..7d9e907 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -165,6 +165,7 @@ from .roundcube import mailbox_can_open_webmail, roundcube_available from .service_changes import request_service_change from .service_credentials import ( CredentialKind, + can_reveal_credentials, show_credential_action, show_rotation_action, ) @@ -174,6 +175,7 @@ from .sftp import ( queue_sftp_keys, site_is_active, ) +from .smtp_applications import smtp_applications_available from .web_node import ( SiteStorageLimitForm, build_web_smoke_bundle, @@ -879,9 +881,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["show_phpmyadmin"] = context[ "show_database_credentials" ] and phpmyadmin_available(self.request) - context["show_webmail"] = context[ - "show_mailbox_credentials" - ] and roundcube_available(self.request) + context["show_webmail"] = can_reveal_credentials( + user, CredentialKind.MAILBOX + ) and roundcube_available(self.request) if tenant or user.has_perm(VIEW_DATABASES): context["automatic_database_provisioning"] = ( automatic_resource_provisioning( @@ -988,6 +990,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): mail_domain__account=self.object ).select_related("mail_domain", "provisioning", "removal") context["can_remove_mailbox"] = can_remove_mailbox(self.request) + context["can_manage_smtp_apps"] = smtp_applications_available( + self.request + ) if context["can_remove_mailbox"] and not tenant: context["archived_mailboxes"] = ( self.object.mailbox_removals.filter( diff --git a/src/coulobre/local_feature_setup.py b/src/coulobre/local_feature_setup.py index c86e670..60810ff 100644 --- a/src/coulobre/local_feature_setup.py +++ b/src/coulobre/local_feature_setup.py @@ -7,6 +7,7 @@ import os import pwd import re import subprocess +from contextlib import contextmanager from dataclasses import dataclass from importlib.metadata import version from pathlib import Path @@ -342,6 +343,13 @@ def enable_feature(key, command): or not active("coulobre-sftp-apply.socket") ): raise ValueError("Enable website SFTP access first.") + with installation_configuration() as config: + apply_feature(key, plan["hostname"], config, command) + return {"enabled": True} + + +@contextmanager +def installation_configuration(): require_root_directory(PACKAGE_ASSETS) config = local_update.CONFIG require_root_directory(config.parent) @@ -361,8 +369,7 @@ def enable_feature(key, command): "recovery_required", }: raise ValueError("Resolve the current installation update first.") - apply_feature(key, plan["hostname"], config, command) - return {"enabled": True} + yield config def apply_feature(key, hostname, config, command): diff --git a/src/coulobre/mail_node.py b/src/coulobre/mail_node.py index 9323857..aca8629 100644 --- a/src/coulobre/mail_node.py +++ b/src/coulobre/mail_node.py @@ -173,6 +173,16 @@ def parse_mailbox_request(data): from .mail_delivery import OPERATION, MailDeliveryRequest from .mail_policy import OPERATIONS, parse_mail_policy from .mail_queue import MailQueueAction, MailQueueRequest + from .smtp_application import ( + SMTP_APPLICATION_OPERATION, + SmtpApplicationRequest, + ) + + if ( + isinstance(data, dict) + and data.get("operation") == SMTP_APPLICATION_OPERATION + ): + return SmtpApplicationRequest.from_manifest(data) if isinstance(data, dict) and data.get("kind") == "mailbox": from .service_credentials import parse_mailbox_password_request @@ -226,8 +236,13 @@ def parse_mailbox_apply(data): def mailbox_request_identity(spec): from .mail_policy import MailPolicy + from .smtp_application import SmtpApplicationRequest - return spec.identity() if isinstance(spec, MailPolicy) else spec.manifest() + return ( + spec.identity() + if isinstance(spec, (MailPolicy, SmtpApplicationRequest)) + else spec.manifest() + ) def apply_mailbox_request(request): @@ -243,6 +258,12 @@ def apply_mailbox_request(request): ServiceCredentialRequest, apply_mailbox_password_request, ) + from .smtp_application import SmtpApplicationRequest + + if isinstance(request, SmtpApplicationRequest): + from .mail_node_smtp_application import apply_smtp_application + + return apply_smtp_application(request) if isinstance(request, ServiceCredentialRequest): return apply_mailbox_password_request(request) diff --git a/src/coulobre/mail_node_smtp_application.py b/src/coulobre/mail_node_smtp_application.py new file mode 100644 index 0000000..7de34fb --- /dev/null +++ b/src/coulobre/mail_node_smtp_application.py @@ -0,0 +1,276 @@ +import json +import re +from collections import defaultdict +from pathlib import Path + +from . import mail_node_apply as mail +from .mail_node_dkim import provision_dkim_key +from .node_files import ( + locked_root_directory, + read_root_file, + replace_configuration, + require_root_directory, + write_new_file, +) +from .smtp_application import SMTP_PASSWORD_HASH, SmtpApplicationSpec + +DOVECOT = Path("/etc/dovecot/dovecot.conf") +AUTH = Path("/etc/dovecot/coulobre-smtp-apps-smtp") +AUTH_CONFIG = AUTH.parent / "coulobre-smtp-apps.conf" +SENDER_MAP = Path("/etc/postfix/coulobre-submission-logins") +APPLICATION_LOGINS = Path("/etc/postfix/coulobre-application-logins") +NULL_SENDER = Path("/etc/postfix/coulobre-application-null-sender") +DEFAULT_MAP = "/^([a-zA-Z0-9_.-]+@[a-zA-Z0-9.-]+)$/ $1\n" +APP_GUARD = "/^coulobre-app-[0-9a-f]{32}_@[^ ]+$/ no-such-owner\n" +INCLUDE = f"!include_try {AUTH_CONFIG}" +BASE_RESTRICTIONS = "reject_authenticated_sender_login_mismatch" +APP_RESTRICTIONS = ( + f"check_sasl_access,regexp:{APPLICATION_LOGINS},{BASE_RESTRICTIONS}" +) +NULL_SENDER_RESTRICTION = f"check_sender_access,regexp:{NULL_SENDER}" + + +def verify_submission(): + settings = { + "smtpd_tls_security_level": "encrypt", + "smtpd_tls_auth_only": "yes", + "smtpd_sasl_auth_enable": "yes", + "smtpd_sasl_type": "dovecot", + "smtpd_sasl_path": "private/auth", + "smtpd_sender_login_maps": f"regexp:{SENDER_MAP}", + } + for key, value in settings.items(): + if mail.run("postconf", "-Ph", f"submission/inet/{key}") != value: + raise ValueError( + f"Configure managed SMTP submission ({key}) first." + ) + milter = mail.run("postconf", "-Ph", "submission/inet/smtpd_milters") + rate_config = mail.run("rspamadm", "configdump", "ratelimit") + if ( + "coulobre-rspamd/submit.sock" not in milter + or "default_action=tempfail" not in milter.replace(" ", "") + or not re.search(r"\buser\s*\{[^}]*\brate\s*=", rate_config, re.DOTALL) + ): + raise ValueError( + "Configure managed per-user submission limits in Rspamd." + ) + + +def restrict_application_sender(): + def service_setting(key): + return mail.run("postconf", "-Ph", f"submission/inet/{key}") + + restrictions = service_setting("smtpd_sender_restrictions") + if restrictions not in (BASE_RESTRICTIONS, APP_RESTRICTIONS): + raise ValueError("Review the existing submission sender restrictions.") + for path, content in ( + ( + APPLICATION_LOGINS, + APP_GUARD.replace("no-such-owner", "coulobre_app_sender"), + ), + ( + NULL_SENDER, + "/^<>$/ REJECT Supply the application's sender address\n", + ), + ): + try: + if read_root_file(path, mode=0o644) != content: + raise ValueError( + f"Review the existing configuration at {path}." + ) + except FileNotFoundError: + write_new_file(path, content, mode=0o644) + if restrictions == BASE_RESTRICTIONS: + inherited = mail.run("postconf", "-h", "smtpd_restriction_classes") + if inherited: + raise ValueError( + "Review the existing Postfix restriction classes." + ) + mail.run( + "postconf", + "-P", + "submission/inet/smtpd_restriction_classes=coulobre_app_sender", + f"submission/inet/coulobre_app_sender={NULL_SENDER_RESTRICTION}", + f"submission/inet/smtpd_sender_restrictions={APP_RESTRICTIONS}", + ) + if ( + service_setting("smtpd_restriction_classes") != "coulobre_app_sender" + or service_setting("coulobre_app_sender") != NULL_SENDER_RESTRICTION + ): + raise ValueError( + "Review the application submission restriction class." + ) + mail.run("postfix", "check") + + +def prepare_dovecot(auth_group): + require_root_directory(DOVECOT.parent) + existing = read_root_file(DOVECOT, mode=0o644) + if ( + "dovecot_config_version = 2.4." not in existing + or "passwd_file_path = /etc/dovecot/coulobre-users" not in existing + or mail.run("doveconf", "-h", "auth_cache_size") != "0" + ): + raise ValueError( + "SMTP applications need a managed Dovecot 2.4 installation." + ) + scoped_path = AUTH.parent / "coulobre-smtp-apps-%{protocol}" + snippet = ( + "passdb coulobre-applications {\n" + " driver = passwd-file\n" + " passdb_username_filter = coulobre-app-*_@*\n" + f" passwd_file_path = {scoped_path}\n" + "}\n" + ) + try: + if read_root_file(AUTH_CONFIG, mode=0o644) != snippet: + raise ValueError( + "Review the existing SMTP application auth configuration." + ) + except FileNotFoundError: + write_new_file(AUTH_CONFIG, snippet, mode=0o644) + try: + mail.read_lookup_table(AUTH, 0o640, auth_group) + if not AUTH.exists(): + write_new_file( + AUTH, mail.MANAGED_HEADER, mode=0o640, group=auth_group + ) + if INCLUDE not in existing.splitlines(): + if "\n!include" in existing: + raise ValueError( + "Review Dovecot includes before enabling application SMTP." + ) + replace_configuration( + DOVECOT, existing.rstrip() + "\n\n" + INCLUDE + "\n" + ) + active = mail.run("doveconf", "-n") + if str(scoped_path) not in active: + raise ValueError( + "Dovecot did not restrict application authentication to SMTP." + ) + mail.run("doveadm", "reload") + except (OSError, ValueError): + if INCLUDE not in existing.splitlines(): + replace_configuration(DOVECOT, existing) + raise + + +def read_registry(path): + try: + records = json.loads(read_root_file(path, mode=0o600)) + except FileNotFoundError: + return {} + if not isinstance(records, dict): + raise ValueError("The SMTP application registry is invalid.") + for login, record in records.items(): + try: + spec = SmtpApplicationSpec.from_manifest(record["scope"]) + if ( + spec.login != login + or type(record["revision"]) is not int + or type(record["suspended"]) is not bool + or not isinstance(record["password_hash"], str) + or ( + record["password_hash"] + and not SMTP_PASSWORD_HASH.fullmatch( + record["password_hash"] + ) + ) + ): + raise ValueError + except (KeyError, TypeError, ValueError): + raise ValueError( + "The SMTP application registry is invalid." + ) from None + return records + + +def desired_record(request, current): + scope = request.application.manifest() + if current is None and request.action in {"suspend", "resume"}: + raise ValueError("The SMTP application has not been configured.") + if current is not None and current["scope"] != scope: + raise ValueError("The SMTP application belongs to a different sender.") + if request.action in {"suspend", "resume"}: + return current | {"suspended": request.action == "suspend"} + record = { + "scope": scope, + "revision": request.revision, + "password_hash": request.password_hash, + "suspended": False, + } + if current is not None and ( + request.revision < current["revision"] + or (request.revision == current["revision"] and record != current) + ): + raise ValueError( + "A newer operation already changed this SMTP credential." + ) + return record + + +def published_tables(records, auth_group): + hashes = set() + senders = defaultdict(set) + for login, record in records.items(): + if not record["password_hash"] or record["suspended"]: + continue + app = SmtpApplicationSpec.from_manifest(record["scope"]) + hashes.add(f"{login}:{record['password_hash']}") + senders[app.sender].update((app.sender, login)) + sender_rows = [ + f"/^{re.escape(sender)}$/ {','.join(sorted(logins))}\n" + for sender, logins in sorted(senders.items()) + ] + return ( + (0o640, auth_group, hashes), + mail.MANAGED_HEADER + "".join(sender_rows) + APP_GUARD + DEFAULT_MAP, + ) + + +def apply_smtp_application(request): + application = request.application + directory = mail.STATE_DIRECTORY / "smtp-applications" + require_root_directory(mail.STATE_DIRECTORY.parent) + require_root_directory(mail.STATE_DIRECTORY, create_mode=0o700) + require_root_directory(directory, create_mode=0o700) + with locked_root_directory(directory): + registry = directory / "registry.json" + records = read_registry(registry) + current = records.get(application.login) + record = desired_record(request, current) + records[application.login] = record + document = json.dumps(records, sort_keys=True) + "\n" + if current is None and request.action == "revoke": + replace_configuration(registry, document, mode=0o600) + return None + _, auth_group, modern = mail.check_services() + if not modern: + raise ValueError("SMTP applications require Dovecot 2.4.") + verify_submission() + observed_map = read_root_file(SENDER_MAP, mode=0o644) + auth_contents = mail.read_lookup_table(AUTH, 0o640, auth_group) + if observed_map != DEFAULT_MAP and not observed_map.startswith( + mail.MANAGED_HEADER + ): + raise ValueError( + "Review the existing Postfix submission sender map." + ) + if auth_contents and not auth_contents.startswith(mail.MANAGED_HEADER): + raise ValueError( + "Review the existing application credential table." + ) + prepare_dovecot(auth_group) + restrict_application_sender() + dkim = ( + provision_dkim_key(application.domain) + if request.action == "issue" + else None + ) + auth_table, sender_table = published_tables(records, auth_group) + replace_configuration(registry, document, mode=0o600) + replace_configuration(SENDER_MAP, sender_table) + mail.run("postfix", "reload") + mail.publish_table(AUTH, auth_table, auth_contents) + mail.run("doveadm", "reload") + return {"dkim": dkim} if dkim else None diff --git a/src/coulobre/managed_tools.py b/src/coulobre/managed_tools.py new file mode 100644 index 0000000..53fb362 --- /dev/null +++ b/src/coulobre/managed_tools.py @@ -0,0 +1,522 @@ +"""Install hosting tools on dedicated HTTPS hosts.""" + +import hashlib +import os +import pwd +import re +import secrets +import sqlite3 +import tarfile +from importlib.metadata import version +from pathlib import Path +from tempfile import TemporaryDirectory +from types import SimpleNamespace +from urllib.parse import urlsplit + +from . import local_update +from .domain_names import canonical_domain +from .linked_updates import REMOTE_MODES, receiver_status +from .local_feature_setup import ( + PACKAGE_ASSETS, + SYSTEMCTL, + SYSTEMD, + active, + create_service_identity, + enable_setting, + install_files, + installation_configuration, + prepare_https, + restart_panel, +) +from .node_files import ( + check_root_file, + read_root_file, + replace_configuration, + require_root_directory, + write_new_file, +) +from .release_updates import UpdateError +from .web_node_tls import ( + CERTBOT_ROOT, + request_certificate, + validate_certificate_files, +) + +WEB_CONFIG = Path("/etc/apache2") +ROUNDCUBE_VERSION = "1.7.7" +ROUNDCUBE_SHA256 = ( + "cc9358a27cda7b3e62c4b6758897bc0f132fe58420d02b2e842be7e10a1dd3fb" +) +ROUNDCUBE_ROOT = Path("/opt/coulobre-roundcube") +APT_GET = "/usr/bin/apt-get" + + +def install_tool(request, command): + try: + plan = local_update.installation_plan() + if plan["access"] not in {"acme", "tls"}: + raise ValueError( + "Managed tool setup requires direct Apache HTTPS." + ) + origin = os.environ.get( + "COULOBRE_PASSWORD_RESET_ORIGIN", f"https://{plan['hostname']}" + ) + panel_host = canonical_domain(plan["hostname"]) + if origin != f"https://{panel_host}": + raise ValueError("Set the installer-managed panel's HTTPS origin.") + if request.hostname == panel_host: + raise ValueError("Use a hostname separate from the panel.") + mail_host = check_prerequisites(request.target, plan) + with installation_configuration() as config: + apply_tool(request, config, origin, mail_host, command) + except UpdateError as error: + raise ValueError(str(error)) from None + return {"enabled": True} + + +def check_prerequisites(target, plan): + if target == "phpmyadmin": + if ( + os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") != "1" + or not active("mariadb.service") + or not active("coulobre-database-apply.socket") + ): + raise ValueError("Start local MariaDB and database provisioning.") + return "" + if ( + os.environ.get("COULOBRE_LOCAL_MAILBOX_PROVISIONING") != "1" + or os.environ.get("COULOBRE_MAILBOX_PASSWORD_CHANGES") != "1" + or not active("coulobre-mail-passwords.socket") + ): + raise ValueError("Enable mailbox provisioning and password changes.") + mail = plan["mail"] + if mail["mode"] in REMOTE_MODES: + node = receiver_status("mail", mail["host"]) + if ( + node["state"] != "configured" + or node["release"] != version("coulobre-panel") + or not node.get("scoped_webmail") + ): + raise ValueError( + "Use a ready, domain-scoped mail receiver on the same release." + ) + host = os.environ.get("COULOBRE_MAIL_IMAP_HOST") + if not host or host != os.environ.get("COULOBRE_MAIL_SUBMISSION_HOST"): + raise ValueError("Set a shared TLS hostname for IMAP and submission.") + return canonical_domain(host) + + +def tool_certificate(hostname, command): + supplied = Path("/etc/coulobre/tool-tls") / hostname + if os.path.lexists(supplied): + require_root_directory(supplied) + files = supplied / "fullchain.pem", supplied / "privkey.pem" + else: + lineage = CERTBOT_ROOT / "live" / hostname + if not os.path.lexists(lineage): + prepare_https(PACKAGE_ASSETS, command) + command(SYSTEMCTL, "reload", "apache2.service") + request_certificate( + SimpleNamespace(domain=hostname, service_user=hostname) + ) + require_root_directory(lineage) + archive = CERTBOT_ROOT / "archive" / hostname + require_root_directory(archive) + files = tuple( + (lineage / name).resolve(strict=True) + for name in ("fullchain.pem", "privkey.pem") + ) + if any(path.parent != archive for path in files): + raise ValueError( + "The tool certificate is outside its ACME archive." + ) + validate_certificate_files(SimpleNamespace(domain=hostname), *files) + return lineage / "fullchain.pem", lineage / "privkey.pem" + validate_certificate_files(SimpleNamespace(domain=hostname), *files) + return files + + +def install_packages(target, command): + extensions = ( + ("curl", "mbstring", "mysql", "xml", "zip") + if target == "phpmyadmin" + else ("curl", "intl", "mbstring", "sqlite3", "xml", "zip") + ) + if target == "phpmyadmin" and os.path.lexists( + WEB_CONFIG / "conf-enabled/phpmyadmin.conf" + ): + raise ValueError( + "Review the existing Apache phpMyAdmin configuration." + ) + packages = ["php-fpm", *(f"php-{name}" for name in extensions)] + if target == "phpmyadmin": + packages.append("phpmyadmin") + if not Path("/usr/share/phpmyadmin/index.php").is_file(): + packages.append("dbconfig-no-thanks") + with TemporaryDirectory() as temp: + answers = Path(temp) / "phpmyadmin" + answers.write_text( + "phpmyadmin phpmyadmin/reconfigure-webserver multiselect\n" + "phpmyadmin phpmyadmin/dbconfig-install boolean false\n" + ) + command("/usr/bin/debconf-set-selections", str(answers)) + try: + command(APT_GET, "update", timeout=360) + command( + APT_GET, + "-o", + "Dpkg::Options::=--force-confold", + "-o", + "DPkg::Lock::Timeout=30", + "--yes", + "--no-remove", + "--no-install-recommends", + "install", + *packages, + timeout=900, + ) + except ValueError: + raise ValueError( + "Could not install the tool packages. Check APT and its logs." + ) from None + if target == "phpmyadmin" and os.path.lexists( + WEB_CONFIG / "conf-enabled/phpmyadmin.conf" + ): + raise ValueError("Disable the global Apache phpMyAdmin alias first.") + depends = command("/usr/bin/dpkg-query", "-W", "-f=${Depends}", "php-fpm") + php = re.search(r"\bphp(\d+\.\d+)-fpm\b", depends) + if php is None: + raise ValueError("Could not identify the distribution's PHP-FPM unit.") + return php[1] + + +def asset(path): + source = PACKAGE_ASSETS / path + require_root_directory(source.parent) + return read_root_file(source) + + +def keep_file(path, content, mode, group=0): + require_root_directory(path.parent) + try: + installed = read_root_file(path, mode=mode) + except FileNotFoundError: + write_new_file(path, content, mode=mode, group=group) + else: + if installed != content or path.stat().st_gid != group: + raise ValueError(f"Review the existing configuration at {path}.") + + +def tool_secret(path, group, new_value): + require_root_directory(path.parent) + try: + value = read_root_file(path, mode=0o640) + except FileNotFoundError: + value = new_value + "\n" + write_new_file(path, value, mode=0o640, group=group) + if path.stat().st_gid != group or not re.fullmatch( + r"[a-zA-Z0-9_-]+\n", value + ): + raise ValueError(f"Review the existing private key at {path}.") + return value.strip() + + +def state_directory(path, user): + require_root_directory(path.parent) + try: + path.mkdir(mode=0o700) + except FileExistsError: + pass + else: + os.chown(path, user.pw_uid, user.pw_gid) + info = path.lstat() + if ( + not path.is_dir() + or path.is_symlink() + or (info.st_uid, info.st_gid, info.st_mode & 0o777) + != (user.pw_uid, user.pw_gid, 0o700) + ): + raise ValueError(f"Review the existing state directory at {path}.") + + +def prepare_phpmyadmin(origin, private, state, user, command): + config = Path("/etc/phpmyadmin/conf.d") + require_root_directory(config) + for name in ("tmp", "sessions"): + state_directory(state / name, user) + tool_secret(private / "session.key", user.pw_gid, secrets.token_hex(32)) + keep_file( + private / "bridge.php", + asset("phpmyadmin/bridge.php.example").replace( + "https://panel.example.org", origin + ), + 0o640, + user.pw_gid, + ) + bridge_dir = state / "bridge" + require_root_directory(bridge_dir, create_mode=0o755) + keep_file( + bridge_dir / "coulobre-signon.php", + asset("phpmyadmin/coulobre-signon.php"), + 0o644, + ) + keep_file( + config / "99-coulobre-signon.php", + asset("phpmyadmin/config.inc.php.example"), + 0o644, + ) + create_service_identity("coulobre-credential-requests", "", command) + install_files( + ( + (PACKAGE_ASSETS / "systemd" / name, SYSTEMD / name, 0o644) + for name in ( + "coulobre-panel.service.d/credentials.conf", + "coulobre-service-credentials.socket", + "coulobre-service-credentials@.service", + "coulobre-service-credentials@.service.d/database.conf", + ) + ), + package_assets=True, + ) + + +def unpack_roundcube(command): + if os.path.lexists(ROUNDCUBE_ROOT): + require_root_directory(ROUNDCUBE_ROOT) + if ( + read_root_file(ROUNDCUBE_ROOT / ".coulobre-release") + != ROUNDCUBE_VERSION + ): + raise ValueError("Review the existing Roundcube application.") + return + filename = f"roundcubemail-{ROUNDCUBE_VERSION}-complete.tar.gz" + cache = Path("/var/cache/coulobre") / filename + with TemporaryDirectory(dir=ROUNDCUBE_ROOT.parent) as temp: + staging = Path(temp) + if os.path.lexists(cache): + require_root_directory(cache.parent) + check_root_file(cache) + archive = cache + else: + archive = staging / filename + command( + "/usr/bin/curl", + "--fail", + "--silent", + "--show-error", + "--location", + "--proto", + "=https", + "--proto-redir", + "=https", + "--max-filesize", + "20000000", + "--output", + str(archive), + f"https://github.com/roundcube/roundcubemail/releases/download/" + f"{ROUNDCUBE_VERSION}/{filename}", + timeout=120, + ) + with archive.open("rb") as stream: + checksum = hashlib.file_digest(stream, "sha256").hexdigest() + if not secrets.compare_digest(checksum, ROUNDCUBE_SHA256): + raise ValueError("Roundcube failed its release checksum check.") + root = f"roundcubemail-{ROUNDCUBE_VERSION}" + with tarfile.open(archive, "r:gz") as source: + files = source.getmembers() + if any( + Path(member.name).parts[:1] != (root,) + or not (member.isfile() or member.isdir()) + for member in files + ): + raise ValueError("Roundcube has an unexpected archive layout.") + source.extractall(staging, members=files, filter="data") + app = staging / root + write_new_file( + app / ".coulobre-release", ROUNDCUBE_VERSION, mode=0o644 + ) + app.rename(ROUNDCUBE_ROOT) + + +def prepare_roundcube(origin, mail_host, private, state, user, command): + unpack_roundcube(command) + app = ROUNDCUBE_ROOT + for name in ("db", "temp", "logs"): + state_directory(state / name, user) + dbdir = state / "db" + db = dbdir / "roundcube.sqlite" + if not os.path.lexists(db): + schema = read_root_file(app / "SQL/sqlite.initial.sql") + with TemporaryDirectory(dir=state) as temp: + built = Path(temp) / "roundcube.sqlite" + with sqlite3.connect(built) as database: + database.executescript(schema) + os.chown(built, user.pw_uid, user.pw_gid) + built.chmod(0o600) + os.link(built, db) + des_key = tool_secret( + private / "session.key", user.pw_gid, secrets.token_urlsafe(18) + ) + plugin = app / "plugins/coulobre_webmail" + require_root_directory(plugin, create_mode=0o755) + keep_file( + plugin / "coulobre_webmail.php", + asset("roundcube/coulobre_webmail.php"), + 0o644, + ) + sample = read_root_file(app / "config/config.inc.php.sample").rstrip() + settings = asset("roundcube/config.inc.php.example").split("\n", 1)[1] + settings = settings.replace("https://panel.example.org", origin).replace( + "mail.example.org", mail_host + ) + settings += ( + f"\n$config['db_dsnw'] = 'sqlite:///{db}';\n" + f"$config['des_key'] = '{des_key}';\n" + f"$config['smtp_host'] = 'tls://{mail_host}:587';\n" + "$config['smtp_user'] = '%u';\n" + "$config['smtp_pass'] = '%p';\n" + "$config['smtp_conn_options'] = " + "['ssl' => ['verify_peer' => true, 'verify_peer_name' => true]];\n" + f"$config['temp_dir'] = '{state / 'temp'}';\n" + f"$config['log_dir'] = '{state / 'logs'}';\n" + ) + keep_file( + app / "config/config.inc.php", + sample + "\n" + settings, + 0o640, + user.pw_gid, + ) + + +def apply_tool(request, config, origin, mail_host, command): + target, hostname = request.target, request.hostname + base = f"coulobre-{target}" + url = f"https://{hostname}" + ( + "/phpmyadmin" if target == "phpmyadmin" else "" + ) + prefix = f"COULOBRE_{target.upper()}" + original = read_root_file(config, mode=0o600) + marker = f"{prefix}_URL={url}" + keys = re.findall( + rf"^[ \t]*{prefix}_(?:URL|BRIDGE_KEY)[ \t]*=.*$", original, re.M + ) + if keys and marker not in keys: + raise ValueError("Review the existing tool integration before setup.") + if not keys and original.rstrip("\n").endswith("\\"): + raise ValueError("Review the end of the panel configuration.") + existing = command("/usr/sbin/apache2ctl", "-S") + site = WEB_CONFIG / "sites-available" / f"{base}.conf" + if ( + re.search(rf"\b{re.escape(hostname)}\b", existing) + and f"/{site.name}:" not in existing + ): + raise ValueError("Choose a hostname Apache does not already serve.") + chain, key = tool_certificate(hostname, command) + php = install_packages(target, command) + create_service_identity(base, base, command) + user = pwd.getpwnam(base) + private = Path("/etc") / base + state = Path("/var/lib") / base + require_root_directory(private, create_mode=0o750) + if private.stat().st_gid not in {0, user.pw_gid}: + raise ValueError("Review the tool configuration directory.") + os.chown(private, 0, user.pw_gid) + require_root_directory(state, create_mode=0o755) + bridge = tool_secret( + private / "bridge.key", user.pw_gid, secrets.token_hex(32) + ) + if keys and set(keys) != {marker, f"{prefix}_BRIDGE_KEY={bridge}"}: + raise ValueError("Review the existing tool integration before setup.") + if target == "phpmyadmin": + prepare_phpmyadmin(origin, private, state, user, command) + setting = "LOCAL_DATABASE_CREDENTIALS" + else: + prepare_roundcube(origin, mail_host, private, state, user, command) + setting = "ROUNDCUBE_SCOPED_MAIL" + updated = enable_setting(original, setting) + if not keys: + updated = ( + updated.rstrip("\n") + + f"\n{marker}\n{prefix}_BRIDGE_KEY={bridge}\n" + ) + configure_apache(target, hostname, chain, key, site, php, command) + activate_tool(site, php, config, original, updated, url, origin, command) + + +def configure_apache(target, hostname, chain, key, site, php, command): + vhost = asset(f"{target}/apache.conf.example") + if target == "phpmyadmin": + vhost = vhost.replace("tools.example.org", hostname) + vhost = vhost.replace( + "/etc/ssl/coulobre-tools/fullchain.pem", str(chain) + ) + vhost = vhost.replace("/etc/ssl/coulobre-tools/privkey.pem", str(key)) + vhost = vhost.replace( + " Include /etc/phpmyadmin/apache.conf", + ' Alias "/phpmyadmin/coulobre-signon.php" ' + '"/var/lib/coulobre-phpmyadmin/bridge/coulobre-signon.php"\n' + ' \n' + " Options None\n" + " AllowOverride None\n" + ' \n' + " Require all granted\n" + ' SetHandler "proxy:unix:/run/php/coulobre-phpmyadmin.sock|fcgi://localhost/"\n' + " \n" + " \n\n" + " Include /etc/phpmyadmin/apache.conf", + ) + else: + vhost = vhost.replace("webmail.example.org", hostname) + vhost = vhost.replace( + "/etc/ssl/coulobre-webmail/fullchain.pem", str(chain) + ) + vhost = vhost.replace( + "/etc/ssl/coulobre-webmail/privkey.pem", str(key) + ) + vhost = vhost.replace("/opt/roundcube", str(ROUNDCUBE_ROOT)) + keep_file(site, vhost, 0o644) + pool = Path(f"/etc/php/{php}/fpm/pool.d/coulobre-{target}.conf") + keep_file(pool, asset(f"{target}/pool.conf.example"), 0o644) + command(f"/usr/sbin/php-fpm{php}", "--test") + command("/usr/sbin/a2enmod", "ssl", "proxy_fcgi") + + +def activate_tool(site, php, config, original, updated, url, origin, command): + enabled = WEB_CONFIG / "sites-enabled" / site.name + was_enabled = os.path.lexists(enabled) + if was_enabled and (not enabled.is_symlink() or enabled.resolve() != site): + raise ValueError("Review the existing enabled Apache site.") + panel_changed = False + hostname = urlsplit(url).hostname + command(SYSTEMCTL, "daemon-reload") + try: + command(SYSTEMCTL, "reload-or-restart", f"php{php}-fpm.service") + command("/usr/sbin/a2ensite", site.name) + command("/usr/sbin/apache2ctl", "configtest") + command(SYSTEMCTL, "reload", "apache2.service") + command( + "/usr/bin/curl", + "--fail", + "--silent", + "--show-error", + "--resolve", + f"{hostname}:443:127.0.0.1", + "--output", + "/dev/null", + url + "/", + ) + replace_configuration(config, updated, mode=0o600) + panel_changed = True + restart_panel(command, urlsplit(origin).hostname) + except (OSError, ValueError, UpdateError): + if panel_changed: + replace_configuration(config, original, mode=0o600) + if not was_enabled: + command("/usr/sbin/a2dissite", site.name) + command(SYSTEMCTL, "reload", "apache2.service") + if panel_changed: + restart_panel(command, urlsplit(origin).hostname) + raise ValueError( + "The tool did not pass its HTTPS or service check. Review the " + "hostname, certificate and Apache/PHP-FPM logs, then retry." + ) from None diff --git a/src/coulobre/node_probe.py b/src/coulobre/node_probe.py index 8ea2298..5bb27ea 100644 --- a/src/coulobre/node_probe.py +++ b/src/coulobre/node_probe.py @@ -42,13 +42,16 @@ def parse_status_probe(body, role): raise ValueError( "The receiver returned no trusted release status." ) from error - return { + result = { "role": role, "protocol": reply["version"], "release": reply["release"], "state": reply["state"], "upgrade_target": target, } + if role == "mail" and reply.get("scoped_webmail") is True: + result["scoped_webmail"] = True + return result def check_receiver(role): diff --git a/src/coulobre/node_requests.py b/src/coulobre/node_requests.py index c8c3bb9..cbdfbed 100644 --- a/src/coulobre/node_requests.py +++ b/src/coulobre/node_requests.py @@ -51,6 +51,16 @@ def serve_apply_request( with authorized_request(probe_role): check_receiver(probe_role) target = rollout_target(probe_role) + if payload == STATUS_PROBE and probe_role == "mail": + from .receiver_scope import LOCAL_WORKERS, socket_peer + + peer = socket_peer() + if peer in ( + None, + "root", + LOCAL_WORKERS["mail"], + ) or peer.startswith("coulobre-mail-p-"): + report["scoped_webmail"] = True if target and payload == PROBE: raise ValueError("The receiver is in upgrade maintenance.") if target: diff --git a/src/coulobre/operator_node.py b/src/coulobre/operator_node.py index 8c1701c..abc8f6e 100644 --- a/src/coulobre/operator_node.py +++ b/src/coulobre/operator_node.py @@ -267,6 +267,8 @@ def apply_request(request): def main(): from .http_defaults import HttpDefaultsRequest, apply_http_defaults + from .managed_tools import install_tool + from .tool_setup_request import TOOL_SETUP_ACTION, ToolSetupRequest def parse(payload): if ( @@ -274,11 +276,19 @@ def main(): and payload.get("operation") == "http-defaults" ): return HttpDefaultsRequest.from_manifest(payload) + if ( + isinstance(payload, dict) + and payload.get("operation") == TOOL_SETUP_ACTION + ): + return ToolSetupRequest.from_manifest(payload) return OperatorRequest.from_manifest(payload) def apply(request): if isinstance(request, HttpDefaultsRequest): return apply_http_defaults(request) + if isinstance(request, ToolSetupRequest): + with locked_root_directory(STATE): + return install_tool(request, command) return apply_request(request) return serve_apply_request(1, parse, apply, include_result=True) diff --git a/src/coulobre/service_credentials.py b/src/coulobre/service_credentials.py index 2157ad1..70f2109 100644 --- a/src/coulobre/service_credentials.py +++ b/src/coulobre/service_credentials.py @@ -7,7 +7,7 @@ from .database_login import LOGIN_KIND, DatabaseLoginSpec from .database_node import DEFAULT_SOCKET, DatabaseSpec from .mail_node import MailboxSpec from .node_requests import serve_apply_request -from .receiver_scope import check_mail_service_peer +from .receiver_scope import LOCAL_WORKERS, check_mail_service_peer, socket_peer REQUEST_VERSION = 1 CREDENTIAL_SOCKET = "/run/coulobre-service-credentials.sock" @@ -31,7 +31,11 @@ class ServiceCredentialRequest: and self.operation != "read" ): raise ValueError("This login supports credential retrieval only.") - if self.operation in ("read", "generation"): + if self.operation == "webmail" and not isinstance( + self.resource, MailboxSpec + ): + raise ValueError("Webmail requires a mailbox.") + if self.operation in ("read", "generation", "webmail"): if self.rotation_id is None and self.previous_id is None: return elif ( @@ -62,7 +66,7 @@ class ServiceCredentialRequest: raise ValueError("Expected a service credential request.") fields = {"version", "kind", "resource"} operation = data.get("operation", "read") - if operation == "generation": + if operation in ("generation", "webmail"): fields.add("operation") elif operation == "rotate": fields.update(("operation", "rotation_id", "previous_id")) @@ -123,6 +127,8 @@ def main(argv=None): def parse(payload): request = ServiceCredentialRequest.from_manifest(payload) + if request.operation == "webmail": + raise ValueError("Use the scoped mailbox socket for webmail.") if request.kind == "mailbox": check_mail_service_peer() if args.mailbox_only and request.kind != "mailbox": @@ -139,6 +145,7 @@ def parse_mailbox_password_request(payload): if request.kind != "mailbox" or request.operation not in { "generation", "rotate", + "webmail", }: raise ValueError("Expected a mailbox password change request.") return request @@ -152,7 +159,7 @@ def relay_mailbox_password_request(request): request, "/run/coulobre-mail-apply.sock", "mail node", - "mailbox password change", + "mailbox access request", timeout=ROTATION_TIMEOUT_SECONDS, ) if request.operation == "generation" and valid_generation( @@ -160,7 +167,7 @@ def relay_mailbox_password_request(request): ): return {"generation": reply["generation"]} if ( - request.operation == "rotate" + request.operation in {"rotate", "webmail"} and reply.get("user") == request.resource.address ): password = reply["password"] @@ -176,6 +183,13 @@ def relay_mailbox_password_request(request): def apply_mailbox_password_request(request): + if request.operation == "webmail": + peer = socket_peer() + if peer not in (None, "root", LOCAL_WORKERS["mail"]) and ( + not peer.startswith("coulobre-mail-p-") + ): + raise ValueError("Webmail requires a domain-scoped mail receiver.") + return read_mailbox_credentials(request.resource, active_only=True) if request.operation == "generation": return { "generation": read_mailbox_credentials( @@ -243,7 +257,9 @@ def read_database_credentials(database, *, generation_only=False): } -def read_mailbox_credentials(mailbox, *, generation_only=False): +def read_mailbox_credentials( + mailbox, *, generation_only=False, active_only=False +): from .mail_node_apply import ( configured_mail_account, credential_path, @@ -255,6 +271,8 @@ def read_mailbox_credentials(mailbox, *, generation_only=False): if configured_mail_account(mailbox) is None: raise ValueError(CREDENTIALS_UNAVAILABLE) credentials = load_credentials(credential_path(mailbox)) + if active_only and credentials.suspended: + raise ValueError(CREDENTIALS_UNAVAILABLE) if generation_only: return credentials.rotation_id return {"user": mailbox.address, "password": credentials.password} diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index 7c775be..fe719a9 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -357,6 +357,7 @@ if PHPMYADMIN_URL: ROUNDCUBE_URL = os.environ.get("COULOBRE_ROUNDCUBE_URL", "").rstrip("/") ROUNDCUBE_BRIDGE_KEY = os.environ.get("COULOBRE_ROUNDCUBE_BRIDGE_KEY", "") +ROUNDCUBE_SCOPED_MAIL = os.environ.get("COULOBRE_ROUNDCUBE_SCOPED_MAIL") == "1" if ROUNDCUBE_URL: roundcube = urlsplit(ROUNDCUBE_URL) if ( diff --git a/src/coulobre/smtp_application.py b/src/coulobre/smtp_application.py new file mode 100644 index 0000000..4991fa9 --- /dev/null +++ b/src/coulobre/smtp_application.py @@ -0,0 +1,110 @@ +import re +from dataclasses import dataclass +from uuid import UUID + +from .mail_node import MailboxSpec + +SMTPS_ACTIONS = frozenset({"issue", "revoke", "suspend", "resume"}) +SMTP_APPLICATION_OPERATION = "smtp_application" +SMTP_PASSWORD_HASH = re.compile(r"\{SHA512\}[A-Za-z0-9+/]{86}==") + + +@dataclass(frozen=True) +class SmtpApplicationSpec: + domain: str + identifier: str + sender_local: str + + def __post_init__(self): + sender = MailboxSpec(self.domain, self.sender_local) + try: + identity = UUID(self.identifier) + if identity.hex != self.identifier or len(sender.domain) > 206: + raise ValueError + except (AttributeError, TypeError, ValueError): + raise ValueError("Invalid SMTP application identity.") from None + object.__setattr__(self, "domain", sender.domain) + object.__setattr__(self, "sender_local", sender.local_part) + + @property + def login(self): + return f"coulobre-app-{self.identifier}_@{self.domain}" + + @property + def sender(self): + return f"{self.sender_local}@{self.domain}" + + def manifest(self): + return { + "domain": self.domain, + "identifier": self.identifier, + "sender_local": self.sender_local, + } + + @classmethod + def from_manifest(cls, data): + if not isinstance(data, dict) or set(data) != { + "domain", + "identifier", + "sender_local", + }: + raise ValueError("Expected an SMTP application identity.") + return cls(**data) + + +@dataclass(frozen=True) +class SmtpApplicationRequest: + application: SmtpApplicationSpec + action: str + revision: int + password_hash: str = "" + + def __post_init__(self): + if ( + not isinstance(self.action, str) + or self.action not in SMTPS_ACTIONS + or type(self.revision) is not int + or not 1 <= self.revision <= 2**31 - 1 + or not isinstance(self.password_hash, str) + or ( + not SMTP_PASSWORD_HASH.fullmatch(self.password_hash) + if self.action == "issue" + else bool(self.password_hash) + ) + ): + raise ValueError("Expected an SMTP application operation.") + + def identity(self): + return self.application.manifest() | { + "operation": SMTP_APPLICATION_OPERATION, + "action": self.action, + "revision": self.revision, + } + + def manifest(self): + return self.identity() | {"password_hash": self.password_hash} + + @classmethod + def from_manifest(cls, data): + fields = {"domain", "identifier", "sender_local"} + if ( + not isinstance(data, dict) + or set(data) + != fields + | { + "operation", + "action", + "revision", + "password_hash", + } + or data["operation"] != SMTP_APPLICATION_OPERATION + ): + raise ValueError("Expected an SMTP application request.") + return cls( + SmtpApplicationSpec.from_manifest( + {field: data[field] for field in fields} + ), + data["action"], + data["revision"], + data["password_hash"], + ) diff --git a/src/coulobre/tool_setup_request.py b/src/coulobre/tool_setup_request.py new file mode 100644 index 0000000..01e8298 --- /dev/null +++ b/src/coulobre/tool_setup_request.py @@ -0,0 +1,63 @@ +from dataclasses import dataclass +from ipaddress import ip_address + +from .domain_names import canonical_domain + +TOOL_SETUP_ACTION = "tool-setup" +HOSTING_TOOLS = { + "phpmyadmin": "phpMyAdmin", + "roundcube": "Roundcube", +} + + +@dataclass(frozen=True) +class ToolSetupRequest: + target: str + hostname: str + + @property + def action(self): + return TOOL_SETUP_ACTION + + @property + def plan(self): + return "" + + def __post_init__(self): + if ( + not isinstance(self.target, str) + or self.target not in HOSTING_TOOLS + ): + raise ValueError("Choose a supported hosting tool.") + if not isinstance(self.hostname, str): + raise ValueError("Enter a dedicated HTTPS hostname.") + hostname = canonical_domain(self.hostname) + try: + ip_address(hostname) + except ValueError: + pass + else: + raise ValueError( + "Use a hostname for the tool's HTTPS certificate." + ) + object.__setattr__(self, "hostname", hostname) + + def manifest(self): + return { + "version": 1, + "operation": TOOL_SETUP_ACTION, + "target": self.target, + "hostname": self.hostname, + } + + @classmethod + def from_manifest(cls, data): + if ( + not isinstance(data, dict) + or set(data) != {"version", "operation", "target", "hostname"} + or type(data["version"]) is not int + or data["version"] != 1 + or data["operation"] != TOOL_SETUP_ACTION + ): + raise ValueError("Expected a hosting tool setup request.") + return cls(data["target"], data["hostname"])