diff --git a/deploy/panel.env.example b/deploy/panel.env.example index 90ed0f3..cb1f6b6 100644 --- a/deploy/panel.env.example +++ b/deploy/panel.env.example @@ -10,6 +10,7 @@ COULOBRE_DB_HOST=/run/mysqld/mysqld.sock COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre # COULOBRE_LOCAL_WEB_ACTIVATION=1 # COULOBRE_LOCAL_WEB_HTTPS=1 +# COULOBRE_LOCAL_WEB_SFTP=1 # COULOBRE_LOCAL_DATABASE_PROVISIONING=1 # COULOBRE_LOCAL_DNS_PUBLISHING=1 # COULOBRE_LOCAL_MAILBOX_PROVISIONING=1 diff --git a/deploy/systemd/coulobre-sftp-provisioner.service b/deploy/systemd/coulobre-sftp-provisioner.service new file mode 100644 index 0000000..8524bac --- /dev/null +++ b/deploy/systemd/coulobre-sftp-provisioner.service @@ -0,0 +1,26 @@ +[Unit] +Description=Coulobre Panel SFTP key worker +Requires=coulobre-sftp-apply.socket +Wants=network-online.target +After=network-online.target coulobre-sftp-apply.socket mariadb.service rabbitmq-server.service + +[Service] +Type=exec +User=coulobre-sftp-provisioner +Group=coulobre-sftp-provisioner +SupplementaryGroups=coulobre-sftp-provisioning +EnvironmentFile=/etc/coulobre/panel.env +WorkingDirectory=/opt/coulobre +UMask=0077 +ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-web-sftp --hostname=sftp-provisioner@%H --concurrency=1 +KillMode=mixed +TimeoutStopSec=4min +Restart=on-failure +RestartSec=5s +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict + +[Install] +WantedBy=multi-user.target diff --git a/docs/deployment.md b/docs/deployment.md index dab51f2..109c781 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -261,6 +261,57 @@ and the expected lineage name. The panel can then enable HTTPS using that certificate. Certbot renews it with its saved authenticator. [Certbot DNS plugins](https://eff-certbot.readthedocs.io/en/stable/using.html#dns-plugins) +## Set up SFTP access for hosted websites + +Use OpenSSH on the local web node. The site account starts in `/public` +inside its hosting directory. OpenSSH allows public key authentication +and restricts the connection to file transfers. +[OpenSSH server configuration](https://man.openbsd.org/sshd_config) + +```sh +sudo apt install openssh-server +sudo groupadd --system coulobre-sftp +sudo install -d -m 0755 /etc/ssh/coulobre-authorized-keys +sudo install -m 0644 deploy/openssh/coulobre-sftp.conf.example \ + /etc/ssh/sshd_config.d/00-coulobre-sftp.conf +sudo sshd -t +sudo systemctl reload-or-restart ssh.service +``` + +Install the worker and socket to manage keys from the panel. + +```sh +sudo groupadd --system coulobre-sftp-provisioning +sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \ + --shell /usr/sbin/nologin coulobre-sftp-provisioner +sudo install -m 0644 deploy/systemd/coulobre-sftp-apply.socket \ + deploy/systemd/coulobre-sftp-apply@.service \ + deploy/systemd/coulobre-sftp-provisioner.service /etc/systemd/system/ +sudo systemctl daemon-reload +``` + +Set `COULOBRE_LOCAL_WEB_SFTP=1` in `/etc/coulobre/panel.env`, then apply +pending migrations and restart the panel services. + +```sh +panel_manage migrate --noinput +sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat +sudo systemctl enable --now coulobre-sftp-apply.socket \ + coulobre-sftp-provisioner.service +``` + +On an active hosting account, open **SFTP access**. Assigned customers +can manage keys for their accounts. Operators need **Can view hosting +account** and **Can change site SFTP access**. + +Select one or more `.pub` files to add keys to the hosting account. +A file can contain one OpenSSH public key per line. Each key has its own +fingerprint and **Remove key** action. Use **Revoke SFTP access** to +remove all keys for new connections. Revoke access and close any existing +SFTP sessions before transferring the hosting account to another customer. +Connect to the web node's SSH hostname and port, which may differ from +the hostname that a reverse proxy uses for web traffic. + ## Provision local databases from the panel Enable the [database provisioning socket](development.md#enable-local-database-provisioning) diff --git a/docs/development.md b/docs/development.md index fe65d94..38fff1c 100644 --- a/docs/development.md +++ b/docs/development.md @@ -754,6 +754,29 @@ read the JSON reply to EOF. A `configured` reply includes the account ID and domain. A `failed` reply includes a diagnostic in `problem`. Retry the same manifest if the connection closes before a reply arrives. +## Install SFTP keys on a web node + +Generate an Ed25519 key on the computer that will connect and choose a +passphrase when prompted. With the default filename, +`~/.ssh/id_ed25519.pub` is the public key file. Keep the private key on +that computer. + +```sh +ssh-keygen -t ed25519 +``` + +Enable the OpenSSH configuration on the web node and apply the site's +deployment manifest. Use the public key file to set the account's keys +directly on that node. Running the command with an empty file removes +the configured keys for new connections. +[SFTP deployment setup](deployment.md#set-up-sftp-access-for-hosted-websites) + +```sh +sudo /opt/coulobre/bin/coulobre-web-node set-sftp-keys \ + coulobre-web-plan-1.json site-access.pub +sftp coulobre-1@web-node.example.org +``` + ## Run an isolated PHP test site Open a completed preview for the account's current domain and select **Download diff --git a/src/coulobre/hosting/impersonation.py b/src/coulobre/hosting/impersonation.py index 5a7cb0d..749e146 100644 --- a/src/coulobre/hosting/impersonation.py +++ b/src/coulobre/hosting/impersonation.py @@ -20,6 +20,7 @@ PREVIEW_VIEWS = frozenset( "panel:account", "panel:database_create", "panel:mailbox_create", + "panel:sftp_keys", } ) EndReason = CustomerImpersonation.EndReason diff --git a/src/coulobre/hosting/migrations/0019_site_sftp.py b/src/coulobre/hosting/migrations/0019_site_sftp.py new file mode 100644 index 0000000..e2c03b1 --- /dev/null +++ b/src/coulobre/hosting/migrations/0019_site_sftp.py @@ -0,0 +1,62 @@ +# Generated by Django 5.2.19 on 2026-11-21 09:38 + +import django.db.models.deletion +import django.utils.timezone +from django.db import migrations, models + +import coulobre.hosting.fields + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0018_web_https"), + ] + + operations = [ + migrations.CreateModel( + name="SiteSFTP", + 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)), + ( + "domain", + coulobre.hosting.fields.DomainNameField(max_length=253), + ), + ("public_keys", models.TextField(blank=True)), + ( + "requested_customer_id", + models.PositiveBigIntegerField(blank=True, null=True), + ), + ( + "account", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + related_name="sftp", + to="hosting.hostingaccount", + ), + ), + ], + options={ + "verbose_name": "site SFTP access", + "verbose_name_plural": "site SFTP access", + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 0ebbbde..ce4988d 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -352,6 +352,21 @@ class WebHTTPS(ProvisioningJob): verbose_name = "website HTTPS request" +class SiteSFTP(ProvisioningJob): + account = models.OneToOneField( + HostingAccount, on_delete=models.CASCADE, related_name="sftp" + ) + domain = DomainNameField(max_length=253) + public_keys = models.TextField(blank=True) + requested_customer_id = models.PositiveBigIntegerField( + null=True, blank=True + ) + + class Meta: + verbose_name = "site SFTP access" + verbose_name_plural = "site SFTP access" + + class DatabaseProvisioning(ProvisioningJob): database = models.OneToOneField( HostingDatabase, on_delete=models.CASCADE, related_name="provisioning" diff --git a/src/coulobre/hosting/node_client.py b/src/coulobre/hosting/node_client.py index b246da1..f6920cd 100644 --- a/src/coulobre/hosting/node_client.py +++ b/src/coulobre/hosting/node_client.py @@ -16,6 +16,16 @@ def enable_local_https(site): ) +def update_local_sftp(keys): + apply_on_local_node( + keys, + "/run/coulobre-sftp-apply.sock", + "web node", + "SFTP key request", + identity=keys.identity(), + ) + + def provision_local_database(database): apply_on_local_node( database, diff --git a/src/coulobre/hosting/sftp.py b/src/coulobre/hosting/sftp.py new file mode 100644 index 0000000..cdbab29 --- /dev/null +++ b/src/coulobre/hosting/sftp.py @@ -0,0 +1,136 @@ +from django import forms +from django.core.exceptions import ValidationError +from django.db import transaction + +from coulobre.sftp_keys import ( + MAX_KEYS_BYTES, + public_key_fingerprint, + read_public_keys, +) + +from .access import customer_for_user, is_tenant +from .models import SiteSFTP +from .resource_requests import lock_hosting_account + + +def can_manage_sftp(user): + return customer_for_user(user) is not None or ( + not is_tenant(user) + and user.has_perms( + ("hosting.view_hostingaccount", "hosting.change_sitesftp") + ) + ) + + +def site_is_active(account): + return account.webprovisioningplan_set.filter( + primary_domain=account.primary_domain, + activation__finished_at__isnull=False, + activation__problem="", + ).exists() + + +@transaction.atomic +def queue_sftp_keys( + account_id, operation, *, public_keys="", fingerprint="", customer_id=None +): + account = lock_hosting_account(account_id, customer_id) + request = SiteSFTP.objects.filter(account=account).first() + previous = request.public_keys if request is not None else "" + keys = change_key_list(previous, operation, public_keys, fingerprint) + if operation == "remove" and keys == previous: + return + if keys and not site_is_active(account): + raise ValidationError( + "Activate the site for the current domain first." + ) + if not keys and request is None: + return + updates = { + "domain": account.primary_domain if keys else request.domain, + "public_keys": keys, + "requested_customer_id": customer_id, + } + if request is None: + SiteSFTP.objects.create(account=account, **updates) + return + same_keys = ( + request.domain == updates["domain"] + and request.public_keys == keys + and request.requested_customer_id == customer_id + ) + if request.finished_at is None: + if not same_keys: + raise ValidationError( + "Wait for the current SFTP key request to finish." + ) + elif not same_keys or request.problem: + SiteSFTP.objects.requeue( + SiteSFTP.objects.filter(pk=request.pk), **updates + ) + + +def change_key_list(previous, operation, public_keys, fingerprint): + if operation == "revoke": + return "" + if operation == "remove": + return "".join( + f"{key}\n" + for key in previous.splitlines() + if public_key_fingerprint(key) != fingerprint + ) + return merge_public_keys(previous, public_keys) + + +def merge_public_keys(*lists): + keys = dict.fromkeys(key for keys in lists for key in keys.splitlines()) + value = "".join(f"{key}\n" for key in keys) + if len(value.encode("utf-8")) > MAX_KEYS_BYTES: + raise ValidationError("The site's SSH key list exceeds 16 KiB.") + return value + + +class PublicKeyFileInput(forms.FileInput): + allow_multiple_selected = True + + +class SFTPKeyUploadForm(forms.Form): + operation = forms.ChoiceField( + choices=(("add", "Add"), ("remove", "Remove"), ("revoke", "Revoke")) + ) + fingerprint = forms.RegexField( + r"\ASHA256:[A-Za-z0-9+/]{43}\Z", required=False + ) + public_keys = forms.Field( + label="SSH public key files", + required=False, + widget=PublicKeyFileInput, + help_text="Choose .pub files or a list with one public key per line.", + ) + + def clean(self): + cleaned = super().clean() + if cleaned.get("operation") == "remove" and not cleaned.get( + "fingerprint" + ): + self.add_error(None, "Select an SSH key to remove.") + if cleaned.get("operation") != "add": + cleaned["public_keys"] = "" + return cleaned + uploads = cleaned.get("public_keys") + if not uploads: + self.add_error("public_keys", "Choose an SSH public key file.") + return cleaned + try: + keys = merge_public_keys( + *(read_public_keys(file) for file in uploads) + ) + if not keys: + raise ValueError("The files do not contain an SSH public key.") + except ValueError as error: + self.add_error("public_keys", str(error)) + except ValidationError as error: + self.add_error("public_keys", error) + else: + cleaned["public_keys"] = keys + return cleaned diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 72586af..d72e4ea 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -6,12 +6,14 @@ from django.db.models import Q from django.utils import timezone from coulobre.dns_node import DnsZone +from coulobre.sftp_keys import SFTPKeys from coulobre.web_node import WebSite from .models import ( DatabaseProvisioning, DnsPublication, MailboxProvisioning, + SiteSFTP, WebActivation, WebHTTPS, WebProvisioningPlan, @@ -22,11 +24,14 @@ from .node_client import ( provision_local_database, provision_local_mailbox, publish_local_zone, + update_local_sftp, ) +from .sftp import site_is_active REDISPATCH_AFTER = timedelta(minutes=5) WEB_ACTIVATION_QUEUE = "coulobre-web-activation" WEB_HTTPS_QUEUE = "coulobre-web-https" +WEB_SFTP_QUEUE = "coulobre-web-sftp" DATABASE_PROVISIONING_QUEUE = "coulobre-database-provisioning" DNS_PUBLISHING_QUEUE = "coulobre-dns-publishing" MAILBOX_PROVISIONING_QUEUE = "coulobre-mailbox-provisioning" @@ -81,6 +86,12 @@ def dispatch_web_https(): dispatch_provisioning_jobs(WebHTTPS, enable_web_https, WEB_HTTPS_QUEUE) +@shared_task +def dispatch_web_sftp(): + if settings.LOCAL_WEB_SFTP: + dispatch_provisioning_jobs(SiteSFTP, update_web_sftp, WEB_SFTP_QUEUE) + + @shared_task def dispatch_database_provisioning(): if settings.LOCAL_DATABASE_PROVISIONING: @@ -169,6 +180,33 @@ def apply_web_https(provisioning): enable_local_https(WebSite(plan.account_id, plan.primary_domain)) +@shared_task(acks_late=True, reject_on_worker_lost=True) +def update_web_sftp(request_id): + if settings.LOCAL_WEB_SFTP: + run_provisioning_job( + SiteSFTP.objects.select_related("account__customer__user"), + request_id, + apply_web_sftp, + "Could not contact the local SFTP service. " + "Check its socket and try again.", + ) + + +def apply_web_sftp(request): + account = request.account + if request.requested_customer_id is not None and ( + request.requested_customer_id != account.customer_id + or not account.customer.user.is_active + ): + raise ValueError("The customer no longer has access to this account.") + if request.public_keys and ( + request.domain != account.primary_domain or not site_is_active(account) + ): + raise ValueError("Activate the site for the current domain first.") + site = WebSite(request.account_id, request.domain) + update_local_sftp(SFTPKeys(site, request.public_keys)) + + @shared_task(acks_late=True, reject_on_worker_lost=True) def provision_database(provisioning_id): if settings.LOCAL_DATABASE_PROVISIONING: diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index b30893a..cfb6b9b 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -7,8 +7,15 @@
+ {% if request_status.state == "configured" %} + {% if request_status.public_keys %}SSH keys installed.{% else %}SFTP access revoked.{% endif %} + {% elif request_status.state == "failed" %} + {{ request_status.problem }} + {% elif request_status.state == "running" %} + Applying SSH keys. + {% else %} + SSH key request queued. + {% endif %} +
+ {% endif %} +Run this command on your computer.
+ssh-keygen -t ed25519
+ Choose a passphrase when prompted. Use a different filename if you already have a key. With the default filename, upload ~/.ssh/id_ed25519.pub. Keep the private key on your computer.
Use the web node's SSH hostname and port with the username coulobre-{{ account.pk }}. The SFTP session starts in /public.
| Key type | +Fingerprint | + {% if can_edit_keys %}Actions | {% endif %} +
|---|---|---|
| {{ key_type }} | +{{ fingerprint }} | + {% if can_edit_keys %} ++ + | + {% endif %} +