diff --git a/deploy/panel_installer/engine.py b/deploy/panel_installer/engine.py index b41ef3d..335d6ea 100644 --- a/deploy/panel_installer/engine.py +++ b/deploy/panel_installer/engine.py @@ -348,6 +348,7 @@ class Installer: self.heartbeat = heartbeat self.scopes = scopes or {} self.state_file = STATE / "installation.json" + self.folder_sftp_supported = False self.php, self.modern_mail = platform_settings() with (SOURCE / "pyproject.toml").open("rb") as project: self.release = tomllib.load(project)["project"]["version"] @@ -451,7 +452,7 @@ class Installer: def packages(self): packages = list(BASE_PACKAGES) if self.php: - packages.append(f"php{self.php}-fpm") + packages.extend((f"php{self.php}-fpm", "openssh-server")) if self.plan.dns.mode == "local": packages.extend(("bind9", "bind9-utils")) if self.plan.mail.mode == "local": @@ -664,7 +665,12 @@ class Installer: COULOBRE_WEB_FILE_MANAGER="1", COULOBRE_WEBSITE_JOBS="1", COULOBRE_LOCAL_ACCOUNT_BACKUPS="1", + COULOBRE_LOCAL_WEB_SFTP="1", ) + if self.folder_sftp_supported: + options["COULOBRE_LOCAL_FOLDER_SFTP"] = "1" + if self.plan.access != "proxy": + options["COULOBRE_SFTP_HOST"] = self.plan.hostname if self.plan.access == "acme": options["COULOBRE_LOCAL_WEB_HTTPS"] = "1" if self.plan.dns.mode != "off": @@ -917,19 +923,33 @@ class Installer: label="Enable website usage logging", ) workers.append("coulobre-website-usage.socket") - features = ["website-files", "website-jobs", "account-backups"] + features = [ + "website-files", + "website-jobs", + "account-backups", + "website-sftp", + "folder-sftp", + ] if self.plan.access == "acme": features.append("website-https") - workers.extend( - run( - BINDIR / "python", - "-m", - "coulobre.local_feature_setup", - ASSETS, - *features, - label="Configure local hosting tools", - ).splitlines() + local_workers = run( + BINDIR / "python", + "-m", + "coulobre.local_feature_setup", + "--skip-unsupported-folder-sftp", + ASSETS, + *features, + label="Configure local hosting tools", + ).splitlines() + workers.extend(local_workers) + self.folder_sftp_supported = ( + "coulobre-folder-sftp.socket" in local_workers ) + if not self.folder_sftp_supported: + self.progress( + "Folder SFTP needs a filesystem with ID-mapped mount " + "support. Website SFTP is available." + ) for name in ("dns", "mail"): target = getattr(self.plan, name) if target.mode != "off": diff --git a/docs/deployment.md b/docs/deployment.md index 945772f..b215f74 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -1541,6 +1541,14 @@ that certificate. Certbot renews it with its saved authenticator. ## Set up SFTP access for hosted websites +Supported full-service installs configure key-based SFTP. On an existing +installer-managed panel, open **Operator Settings → Server** to enable +website SFTP and folder-scoped logins. Set `COULOBRE_SFTP_HOST` and +`COULOBRE_SFTP_PORT` in `/etc/coulobre/panel.env` when customers connect to a +different host or port. The panel displays these values in **SFTP Users**. + +For a manual installation, configure OpenSSH and the worker directly. + 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. diff --git a/src/coulobre/hosting/folder_sftp_views.py b/src/coulobre/hosting/folder_sftp_views.py index 909617a..1aafdf3 100644 --- a/src/coulobre/hosting/folder_sftp_views.py +++ b/src/coulobre/hosting/folder_sftp_views.py @@ -11,6 +11,7 @@ from coulobre.sftp_keys import normalize_public_keys from coulobre.website_files import directory_parts from .access import customer_for_user +from .installation_features import panel_feature_allowed from .models import FolderSftpLogin, HostingAccount from .resource_requests import ( lock_hosting_account, @@ -119,12 +120,16 @@ def folder_sftp_users(request, pk): initial={"public_keys": login.public_keys} if edit else {}, ) enabled = settings.LOCAL_FOLDER_SFTP + accepts_keys = panel_feature_allowed( + "LOCAL_WEB_SFTP" + ) and panel_feature_allowed("LOCAL_FOLDER_SFTP") problem = "" if request.method == "POST": if ( not enabled or action not in {"create", "keys", "remove"} or ((action != "create") != edit) + or (action != "remove" and not accepts_keys) ): raise Http404 if action == "remove" or form.is_valid(): @@ -150,7 +155,10 @@ def folder_sftp_users(request, pk): "form": form, "login": login, "enabled": enabled, + "accepts_keys": accepts_keys, "logins": account.folder_sftp_logins.order_by("label"), "problem": problem, + "sftp_host": settings.SFTP_HOST, + "sftp_port": settings.SFTP_PORT, }, ) diff --git a/src/coulobre/hosting/installation_features.py b/src/coulobre/hosting/installation_features.py index 8437857..7d6160b 100644 --- a/src/coulobre/hosting/installation_features.py +++ b/src/coulobre/hosting/installation_features.py @@ -107,6 +107,22 @@ FEATURES = ( "Install the task worker and allow tasks in the hosting package.", "coulobre-website-jobs", ), + Feature( + "LOCAL_WEB_SFTP", + "Website SFTP access", + "OpenSSH Server and the website SFTP worker", + "set-up-sftp-access-for-hosted-websites", + "Check OpenSSH Server and enable the website SFTP worker.", + "coulobre-sftp-apply", + ), + Feature( + "LOCAL_FOLDER_SFTP", + "Folder-scoped SFTP accounts", + "Website SFTP access and ID-mapped mounts", + "enable-folder-scoped-sftp-logins", + "Enable website SFTP and check the filesystem for ID-mapped mounts.", + "coulobre-folder-sftp", + ), Feature( "LOCAL_DNS_PUBLISHING", "DNS publishing", diff --git a/src/coulobre/hosting/installation_views.py b/src/coulobre/hosting/installation_views.py index 7ddaca5..3c0b125 100644 --- a/src/coulobre/hosting/installation_views.py +++ b/src/coulobre/hosting/installation_views.py @@ -68,6 +68,8 @@ OPERATOR_FEATURE_SECTIONS = { "LOCAL_WEB_ACTIVATION", "WEB_FILE_MANAGER", "WEBSITE_JOBS", + "LOCAL_WEB_SFTP", + "LOCAL_FOLDER_SFTP", "LOCAL_DNS_PUBLISHING", "DEFAULT_DNS_ZONES", ), @@ -251,6 +253,7 @@ class FeatureConfigurationView(UserPassesTestMixin, FormView): key != "account-backups" or settings.LOCAL_DATABASE_PROVISIONING ) + and (key != "folder-sftp" or settings.LOCAL_WEB_SFTP) } def post(self, request, *args, **kwargs): diff --git a/src/coulobre/hosting/templates/hosting/folder_sftp_users.html b/src/coulobre/hosting/templates/hosting/folder_sftp_users.html index c6a461d..1b16332 100644 --- a/src/coulobre/hosting/templates/hosting/folder_sftp_users.html +++ b/src/coulobre/hosting/templates/hosting/folder_sftp_users.html @@ -9,13 +9,14 @@

Primary hosting login

Access to the hosting account, including files in /backups.

Manage SSH keys
+

Connect to {% if sftp_host %}{{ sftp_host }}{% else %}your web node's SSH hostname{% endif %} on port {{ sftp_port }} with the username shown for each login.

{% for entry in logins %} {% empty %}{% endfor %}
Folder loginWebsite folderStateActions
{{ entry.label }}
{{ entry.spec.username }}
{{ entry.folder|default:"Entire website" }} {{ entry.state|capfirst }}{% if entry.problem %}

{{ entry.problem }}

{% endif %}
{% if enabled and entry.finished_at %} - Manage keys + {% if accepts_keys %}Manage keys{% endif %}
{% csrf_token %}
@@ -23,9 +24,10 @@
No folder logins.
- {% if enabled %} + {% if enabled and accepts_keys %}

{% if login %}SSH keys for {{ login.label }}{% else %}Add folder login{% endif %}

+

Generate a key on your computer with ssh-keygen -t ed25519. Paste the contents of the .pub file here and keep the private key on your computer.

{% csrf_token %}{{ form.as_div }}
@@ -33,5 +35,6 @@
+ {% elif enabled %}

New folder access and key changes are paused.

{% else %}

Folder logins require the scoped SFTP worker on the web server.

{% endif %} {% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/sftp_keys.html b/src/coulobre/hosting/templates/hosting/sftp_keys.html index 775b3cd..4fe8a4f 100644 --- a/src/coulobre/hosting/templates/hosting/sftp_keys.html +++ b/src/coulobre/hosting/templates/hosting/sftp_keys.html @@ -35,7 +35,7 @@

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.

+

Connect as coulobre-{{ account.pk }} on {% if sftp_host %}{{ sftp_host }}{% else %}your web node's SSH hostname{% endif %}, port {{ sftp_port }}. The SFTP session starts in /public.

{{ form.non_field_errors }} @@ -79,15 +79,15 @@ {% endif %} - {% if can_edit_keys or can_revoke_keys %} + {% if can_edit_keys and can_add_keys or can_revoke_keys %}
{% include "hosting/customer_action_fields.html" %} - {% if can_edit_keys %} + {% if can_edit_keys and can_add_keys %} {{ form.public_keys.as_field_group }} {% endif %}
- {% if can_edit_keys %}{% endif %} + {% if can_edit_keys and can_add_keys %}{% endif %} {% if can_revoke_keys %} {% endif %} @@ -95,5 +95,6 @@
{% endif %} + {% if not can_add_keys %}

New SFTP access is paused.

{% endif %} {% endwith %} {% endblock %} diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 310e3c8..9f1401d 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -1854,6 +1854,9 @@ class SiteSFTPKeys(PermissionRequiredMixin, FormView): for key in keys ], can_edit_keys=editable and idle and site_is_active(self.account), + can_add_keys=panel_feature_allowed("LOCAL_WEB_SFTP"), + sftp_host=settings.SFTP_HOST, + sftp_port=settings.SFTP_PORT, can_revoke_keys=editable and idle and status is not None @@ -1867,6 +1870,9 @@ class SiteSFTPKeys(PermissionRequiredMixin, FormView): def form_valid(self, form): customer = customer_for_user(self.request.user) operation = form.cleaned_data["operation"] + if operation == "add" and not panel_feature_allowed("LOCAL_WEB_SFTP"): + form.add_error(None, "New SFTP access is paused in the panel.") + return self.form_invalid(form) try: with support_write_session(self.request) as session: change = queue_sftp_keys( diff --git a/src/coulobre/local_feature_setup.py b/src/coulobre/local_feature_setup.py index 654ff55..c86e670 100644 --- a/src/coulobre/local_feature_setup.py +++ b/src/coulobre/local_feature_setup.py @@ -10,6 +10,7 @@ import subprocess from dataclasses import dataclass from importlib.metadata import version from pathlib import Path +from tempfile import TemporaryDirectory from . import local_update from .linked_updates import REMOTE_MODES, receiver_status @@ -26,6 +27,12 @@ PACKAGE_ASSETS = Path("/usr/share/coulobre-panel/source/deploy") SYSTEMD = Path("/etc/systemd/system") SYSTEMCTL = "/usr/bin/systemctl" CERTBOT = Path("/usr/bin/certbot") +SSHD = Path("/usr/sbin/sshd") +SFTP_SSHD_CONFIG = Path("/etc/ssh/sshd_config.d/00-coulobre-sftp.conf") + + +class UnsupportedFolderSftpError(ValueError): + pass @dataclass(frozen=True) @@ -35,6 +42,7 @@ class LocalFeature: socket: str worker: str = "" drop_in: str = "" + extra_units: tuple[str, ...] = () @property def units(self): @@ -43,6 +51,7 @@ class LocalFeature: f"{self.socket}@.service", *((f"{self.worker}.service",) if self.worker else ()), *((self.drop_in,) if self.drop_in else ()), + *self.extra_units, ) @property @@ -65,6 +74,18 @@ LOCAL_FEATURES = { "coulobre-website-jobs", worker="coulobre-website-job-worker", ), + "website-sftp": LocalFeature( + "LOCAL_WEB_SFTP", + "coulobre-sftp-provisioning", + "coulobre-sftp-apply", + worker="coulobre-sftp-provisioner", + ), + "folder-sftp": LocalFeature( + "LOCAL_FOLDER_SFTP", + "coulobre-sftp-provisioning", + "coulobre-folder-sftp", + extra_units=("coulobre-folder-sftp-mounts.service",), + ), "account-backups": LocalFeature( "LOCAL_ACCOUNT_BACKUPS", "coulobre-backup-requests", @@ -174,8 +195,71 @@ def prepare_https(assets, command): command("/usr/sbin/apache2ctl", "configtest") +def prepare_sftp(assets, command): + from .web_node_sftp import AUTHORIZED_KEYS, SFTP_GROUP + + if not SSHD.is_file(): + raise ValueError("Install OpenSSH Server before enabling SFTP.") + command(str(SSHD), "-t") + require_root_directory(AUTHORIZED_KEYS, create_mode=0o755) + create_service_identity(SFTP_GROUP, "", command) + created = not os.path.lexists(SFTP_SSHD_CONFIG) + install_files( + ( + ( + assets / "openssh/coulobre-sftp.conf.example", + SFTP_SSHD_CONFIG, + 0o644, + ), + ), + package_assets=assets == PACKAGE_ASSETS, + ) + try: + command(str(SSHD), "-t") + if active("ssh.service"): + command(SYSTEMCTL, "reload", "ssh.service") + except (OSError, ValueError): + if created: + SFTP_SSHD_CONFIG.unlink() + raise + + +def check_folder_sftp_filesystem(): + from .web_node_apply import WEB_ROOT + from .web_node_folder_sftp import ( + JAIL_ROOT, + bind_folder, + is_bound, + run_mount, + ) + + require_root_directory(WEB_ROOT, create_mode=0o755) + require_root_directory(JAIL_ROOT, create_mode=0o755) + with ( + TemporaryDirectory(dir=WEB_ROOT) as source, + TemporaryDirectory(dir=JAIL_ROOT) as target, + ): + mountpoint = Path(target) + fd = os.open(source, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + bind_folder(fd, os.fstat(fd), mountpoint, 65534, 65534) + except ValueError: + raise UnsupportedFolderSftpError( + "The filesystem or kernel does not support ID-mapped SFTP " + "mounts for the website directory." + ) from None + finally: + os.close(fd) + if is_bound(mountpoint): + run_mount("/usr/bin/umount", str(mountpoint)) + + def prepare_feature(key, assets, command): feature = LOCAL_FEATURES[key] + if key == "website-sftp": + prepare_sftp(assets, command) + if key == "folder-sftp": + check_folder_sftp_filesystem() install_files( ( (assets / "systemd" / unit, SYSTEMD / unit, 0o644) @@ -253,6 +337,11 @@ def enable_feature(key, command): os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") != "1" ): raise ValueError("Enable local database provisioning first.") + if key == "folder-sftp" and ( + os.environ.get("COULOBRE_LOCAL_WEB_SFTP") != "1" + or not active("coulobre-sftp-apply.socket") + ): + raise ValueError("Enable website SFTP access first.") require_root_directory(PACKAGE_ASSETS) config = local_update.CONFIG require_root_directory(config.parent) @@ -281,7 +370,9 @@ def apply_feature(key, hostname, config, command): updated = enable_setting(original, LOCAL_FEATURES[key].setting) feature = prepare_feature(key, PACKAGE_ASSETS, command) unit = feature.activation_unit - units = tuple(dict.fromkeys((unit, f"{feature.socket}.socket"))) + units = tuple( + dict.fromkeys((unit, f"{feature.socket}.socket", *feature.extra_units)) + ) inactive = tuple(name for name in units if not active(name)) already_running = bool(feature.worker and unit not in inactive) panel_restart_started = False @@ -321,6 +412,7 @@ def main(): from .operator_node import command parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--skip-unsupported-folder-sftp", action="store_true") parser.add_argument("assets", type=Path) parser.add_argument("feature", choices=LOCAL_FEATURES, nargs="+") args = parser.parse_args() @@ -328,11 +420,13 @@ def main(): parser.exit(1, "Run local feature setup as root.\n") try: for key in args.feature: - print( - prepare_feature( - key, args.assets.resolve(), command - ).activation_unit - ) + try: + feature = prepare_feature(key, args.assets.resolve(), command) + except UnsupportedFolderSftpError: + if not args.skip_unsupported_folder_sftp: + raise + continue + print(feature.activation_unit) except (OSError, ValueError) as error: parser.exit(1, f"{error}\n") diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index 4aab8e2..7dafcaf 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -243,6 +243,10 @@ LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1" WEB_FILE_MANAGER = os.environ.get("COULOBRE_WEB_FILE_MANAGER") == "1" WEBSITE_JOBS = os.environ.get("COULOBRE_WEBSITE_JOBS") == "1" LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1" +SFTP_HOST = os.environ.get("COULOBRE_SFTP_HOST", "").strip() +SFTP_PORT = int(os.environ.get("COULOBRE_SFTP_PORT", "22")) +if not 1 <= SFTP_PORT <= 65535: + raise ImproperlyConfigured("COULOBRE_SFTP_PORT must be a valid TCP port.") SYSTEM_BACKUPS = os.environ.get("COULOBRE_SYSTEM_BACKUPS") == "1" SERVER_PACKAGE_UPDATES = ( os.environ.get("COULOBRE_SERVER_PACKAGE_UPDATES") == "1"