diff --git a/deploy/openssh/coulobre-sftp.conf.example b/deploy/openssh/coulobre-sftp.conf.example new file mode 100644 index 0000000..c80a6cc --- /dev/null +++ b/deploy/openssh/coulobre-sftp.conf.example @@ -0,0 +1,16 @@ +Match Group coulobre-sftp + AuthenticationMethods publickey + PubkeyAuthentication yes + PasswordAuthentication no + KbdInteractiveAuthentication no + AuthorizedKeysFile /etc/ssh/coulobre-authorized-keys/%u + AuthorizedKeysCommand none + TrustedUserCAKeys none + ChrootDirectory %h + ForceCommand internal-sftp -d /public -u 0022 -P symlink,hardlink + DisableForwarding yes + PermitTunnel no + PermitTTY no + PermitUserRC no + +Match all diff --git a/deploy/systemd/coulobre-sftp-apply.socket b/deploy/systemd/coulobre-sftp-apply.socket new file mode 100644 index 0000000..2db9df8 --- /dev/null +++ b/deploy/systemd/coulobre-sftp-apply.socket @@ -0,0 +1,14 @@ +[Unit] +Description=Coulobre local SFTP key socket + +[Socket] +ListenStream=/run/coulobre-sftp-apply.sock +SocketUser=root +SocketGroup=coulobre-sftp-provisioning +SocketMode=0660 +Accept=yes +MaxConnections=4 +RemoveOnStop=true + +[Install] +WantedBy=sockets.target diff --git a/deploy/systemd/coulobre-sftp-apply@.service b/deploy/systemd/coulobre-sftp-apply@.service new file mode 100644 index 0000000..d32606f --- /dev/null +++ b/deploy/systemd/coulobre-sftp-apply@.service @@ -0,0 +1,18 @@ +[Unit] +Description=Coulobre local SFTP key request +After=ssh.service +CollectMode=inactive-or-failed + +[Service] +Type=exec +User=root +WorkingDirectory=/opt/coulobre +UMask=0022 +ExecStart=/opt/coulobre/bin/coulobre-web-node sftp-keys-request +StandardInput=socket +StandardOutput=socket +StandardError=journal +RuntimeMaxSec=3min +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true diff --git a/src/coulobre/hosting/test_sftp_keys.py b/src/coulobre/hosting/test_sftp_keys.py new file mode 100644 index 0000000..0f82c57 --- /dev/null +++ b/src/coulobre/hosting/test_sftp_keys.py @@ -0,0 +1,58 @@ +import json +from base64 import b64encode +from contextlib import redirect_stdout +from io import BytesIO, StringIO +from types import SimpleNamespace +from unittest.mock import patch + +from django.test import SimpleTestCase + +from coulobre.sftp_keys import SFTPKeys, read_public_keys +from coulobre.web_node import WebSite, main + + +def public_key(byte=1): + header = b"\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20" + return "ssh-ed25519 " + b64encode(header + bytes([byte]) * 32).decode() + + +class SFTPManifestTests(SimpleTestCase): + def test_public_key_list_discards_comments_and_duplicates(self): + key = public_key() + source = BytesIO(f"# heading\n{key} admin\n{key} duplicate\n".encode()) + self.assertEqual(read_public_keys(source), f"{key}\n") + + def test_rejects_private_keys_options_and_oversized_input(self): + for content in ( + b"-----BEGIN OPENSSH PRIVATE KEY-----\n", + f'restrict,command="whoami" {public_key()}'.encode(), + b"ssh-ed25519 not-a-blob", + b" " * (16 * 1024 + 1), + ): + with ( + self.subTest(length=len(content)), + self.assertRaises(ValueError), + ): + read_public_keys(BytesIO(content)) + + def test_request_returns_identity_and_status_without_the_key(self): + site = WebSite(42, "example.org") + request = SFTPKeys(site, public_key()) + output = StringIO() + with ( + patch( + "sys.stdin", + SimpleNamespace( + buffer=BytesIO(json.dumps(request.manifest()).encode()) + ), + ), + patch("coulobre.web_node_sftp.apply_sftp_keys") as apply, + redirect_stdout(output), + ): + self.assertEqual(main(["sftp-keys-request"]), 0) + + apply.assert_called_once_with(request) + self.assertEqual( + json.loads(output.getvalue()), + site.manifest() | {"state": "configured", "problem": None}, + ) diff --git a/src/coulobre/hosting/test_web_node_tls.py b/src/coulobre/hosting/test_web_node_tls.py index 1bc549f..d3c5233 100644 --- a/src/coulobre/hosting/test_web_node_tls.py +++ b/src/coulobre/hosting/test_web_node_tls.py @@ -50,7 +50,11 @@ class WebNodeTLSTests(SimpleTestCase): patch("coulobre.web_node_tls.os.geteuid", return_value=0) ) self.enterContext( - patch("coulobre.web_node_tls.STATE_DIRECTORY", self.state) + patch("coulobre.web_node_apply.STATE_DIRECTORY", self.state) + ) + self.enterContext(patch("coulobre.web_node_apply.check_root_file")) + self.enterContext( + patch("coulobre.web_node_apply.require_root_directory") ) self.enterContext(patch("coulobre.web_node_tls.CERTBOT_ROOT", certbot)) self.webroot = directory / "coulobre-acme" diff --git a/src/coulobre/sftp_keys.py b/src/coulobre/sftp_keys.py new file mode 100644 index 0000000..2a9c09d --- /dev/null +++ b/src/coulobre/sftp_keys.py @@ -0,0 +1,91 @@ +from base64 import b64decode, b64encode +from binascii import Error +from dataclasses import dataclass +from hashlib import sha256 + +from .web_node import WebSite + +MAX_KEYS_BYTES = 16 * 1024 +KEY_TYPES = frozenset( + { + "ssh-ed25519", + "ssh-rsa", + "ecdsa-sha2-nistp256", + "ecdsa-sha2-nistp384", + "ecdsa-sha2-nistp521", + } +) + + +def read_public_keys(source): + body = source.read(MAX_KEYS_BYTES + 1) + if len(body) > MAX_KEYS_BYTES: + raise ValueError("The SSH public key list exceeds 16 KiB.") + try: + return normalize_public_keys(body.decode("utf-8")) + except UnicodeError: + raise ValueError("Expected a UTF-8 SSH public key list.") from None + + +def normalize_public_keys(value): + if ( + not isinstance(value, str) + or len(value.encode("utf-8")) > MAX_KEYS_BYTES + ): + raise ValueError("Expected an SSH public key list of up to 16 KiB.") + + keys = {} + for number, line in enumerate(value.splitlines(), 1): + parts = line.split(None, 2) + if not parts or parts[0].startswith("#"): + continue + if len(parts) < 2 or parts[0] not in KEY_TYPES: + raise ValueError( + f"Expected a supported SSH public key on line {number}." + ) + key_type, encoded = parts[:2] + prefix = len(key_type).to_bytes(4) + key_type.encode("ascii") + try: + raw = b64decode(encoded, validate=True) + except (Error, ValueError): + raw = b"" + if not raw.startswith(prefix) or len(raw) <= len(prefix): + raise ValueError(f"Invalid SSH public key on line {number}.") + keys[f"{key_type} {b64encode(raw).decode('ascii')}"] = None + return "".join(f"{key}\n" for key in keys) + + +def public_key_fingerprint(key): + _, encoded = key.split(" ", 1) + digest = sha256(b64decode(encoded, validate=True)).digest() + return "SHA256:" + b64encode(digest).decode("ascii").rstrip("=") + + +@dataclass(frozen=True) +class SFTPKeys: + site: WebSite + public_keys: str + + def __post_init__(self): + object.__setattr__( + self, "public_keys", normalize_public_keys(self.public_keys) + ) + + @classmethod + def from_manifest(cls, payload): + if not isinstance(payload, dict) or "public_keys" not in payload: + raise ValueError("Expected a site manifest with SSH public keys.") + site = WebSite.from_manifest( + { + key: value + for key, value in payload.items() + if key != "public_keys" + } + ) + return cls(site, payload["public_keys"]) + + def manifest(self): + return self.site.manifest() | {"public_keys": self.public_keys} + + def identity(self): + return self.site.manifest() diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index f2d4200..0c2a9ba 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -108,6 +108,16 @@ def main(argv=None): "https-status", help="Check a site's local HTTPS configuration." ) https_status.add_argument("manifest", type=Path) + sftp = commands.add_parser( + "set-sftp-keys", + help="Set the SSH public keys for a site's SFTP login.", + ) + sftp.add_argument("manifest", type=Path) + sftp.add_argument("public_keys", type=Path) + commands.add_parser( + "sftp-keys-request", + help="Apply one SFTP key request from standard input.", + ) restore = commands.add_parser( "restore-directadmin", help="Restore a DirectAdmin website into an empty web root.", @@ -133,6 +143,18 @@ def main(argv=None): MANIFEST_VERSION, WebSite.from_manifest, provision_https ) + if args.command == "sftp-keys-request": + from .sftp_keys import MAX_KEYS_BYTES, SFTPKeys + from .web_node_sftp import apply_sftp_keys + + return serve_apply_request( + MANIFEST_VERSION, + SFTPKeys.from_manifest, + apply_sftp_keys, + limit=MAX_KEYS_BYTES + 4096, + identity=SFTPKeys.identity, + ) + try: payload = json.loads(args.manifest.read_text(encoding="utf-8")) site = WebSite.from_manifest(payload) @@ -158,6 +180,11 @@ def main(argv=None): report = https_status(site) print(json.dumps(report, indent=2)) return 0 if report["state"] == "configured" else 2 + elif args.command == "set-sftp-keys": + from .web_node_sftp import set_sftp_keys + + user, count = set_sftp_keys(site, args.public_keys) + print(f"Installed {count} SFTP public key(s) for {user}.") elif args.command == "restore-directadmin": from .web_node_restore import restore_website diff --git a/src/coulobre/web_node_apply.py b/src/coulobre/web_node_apply.py index 760abc3..3ad34c6 100644 --- a/src/coulobre/web_node_apply.py +++ b/src/coulobre/web_node_apply.py @@ -10,7 +10,12 @@ from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path -from .node_files import read_root_file, require_root_directory, write_new_file +from .node_files import ( + check_root_file, + read_root_file, + require_root_directory, + write_new_file, +) STATE_DIRECTORY = Path("/var/lib/coulobre/web-node") WEB_ROOT = Path("/srv/coulobre/web") @@ -42,6 +47,21 @@ class SitePaths: ) +@contextmanager +def locked_web_node(mode): + try: + require_root_directory(STATE_DIRECTORY) + except FileNotFoundError: + raise ValueError( + "Apply the site manifest on the web node first." + ) from None + lock_path = STATE_DIRECTORY / "apply.lock" + check_root_file(lock_path) + with lock_path.open("r") as lock: + fcntl.flock(lock, mode) + yield + + def apply_site(site): if os.geteuid() != 0: raise ValueError("Run apply as root on the web node.") diff --git a/src/coulobre/web_node_sftp.py b/src/coulobre/web_node_sftp.py new file mode 100644 index 0000000..e231139 --- /dev/null +++ b/src/coulobre/web_node_sftp.py @@ -0,0 +1,99 @@ +import fcntl +import os +import subprocess +from pathlib import Path +from tempfile import TemporaryDirectory + +from .node_files import check_root_file, require_root_directory, write_new_file +from .sftp_keys import SFTPKeys, read_public_keys +from .web_node_apply import ( + SitePaths, + check_installation, + check_reservation, + current_group, + locked_web_node, + run, +) + +SFTP_GROUP = "coulobre-sftp" +AUTHORIZED_KEYS = Path("/etc/ssh/coulobre-authorized-keys") + + +def set_sftp_keys(site, public_keys): + with public_keys.open("rb") as source: + return apply_sftp_keys(SFTPKeys(site, read_public_keys(source))) + + +def apply_sftp_keys(request): + if os.geteuid() != 0: + raise ValueError("Run set-sftp-keys as root on the web node.") + + site = request.site + keys = request.public_keys.splitlines() + for number, key in enumerate(keys, 1): + validate_public_key(key, number) + require_root_directory(AUTHORIZED_KEYS) + user = site.configuration()["service_user"] + target = AUTHORIZED_KEYS / user + + with locked_web_node(fcntl.LOCK_EX): + check_reservation(site) + if os.path.lexists(target): + check_root_file(target, mode=0o644) + if keys: + check_installation(site, SitePaths.for_site(site)) + group = current_group(SFTP_GROUP) + if group is None or not group.gr_gid: + raise ValueError(f"Create the {SFTP_GROUP} group first.") + if user not in group.gr_mem: + run("/usr/sbin/usermod", "-a", "-G", SFTP_GROUP, user) + check_sshd(user) + + with TemporaryDirectory(dir=AUTHORIZED_KEYS) as scratch: + staged = Path(scratch) / user + write_new_file(staged, request.public_keys, mode=0o644) + os.replace(staged, target) + + return user, len(keys) + + +def validate_public_key(key, number): + try: + result = subprocess.run( + ("/usr/bin/ssh-keygen", "-l", "-f", "-"), + input=f"{key}\n", + text=True, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=5, + ) + except subprocess.TimeoutExpired: + raise ValueError("SSH public key validation timed out.") from None + if result.returncode: + raise ValueError(f"Invalid SSH public key on line {number}.") + + +def check_sshd(user): + configuration = run( + "/usr/sbin/sshd", + "-T", + "-C", + f"user={user},host=localhost,addr=127.0.0.1", + ) + required = { + "authenticationmethods publickey", + "pubkeyauthentication yes", + f"authorizedkeysfile {AUTHORIZED_KEYS}/%u", + "authorizedkeyscommand none", + "trustedusercakeys none", + "chrootdirectory %h", + "disableforwarding yes", + "permittty no", + "permituserrc no", + "permittunnel no", + "forcecommand internal-sftp -d /public -u 0022 -P symlink,hardlink", + } + if not required.issubset(configuration.splitlines()): + raise ValueError( + f"Configure the Coulobre OpenSSH restrictions for {user}." + ) diff --git a/src/coulobre/web_node_tls.py b/src/coulobre/web_node_tls.py index bfd679d..4ed0193 100644 --- a/src/coulobre/web_node_tls.py +++ b/src/coulobre/web_node_tls.py @@ -2,12 +2,10 @@ import fcntl import os import ssl import subprocess -from contextlib import contextmanager from pathlib import Path from .node_files import check_root_file, require_root_directory from .web_node_apply import ( - STATE_DIRECTORY, SitePaths, check_configuration, check_installation, @@ -16,6 +14,7 @@ from .web_node_apply import ( configuration_installation, enable_apache_site, install_configuration, + locked_web_node, run, ) @@ -133,21 +132,6 @@ def https_status(site): return {**report, "state": "configured"} -@contextmanager -def locked_web_node(mode): - try: - require_root_directory(STATE_DIRECTORY) - except FileNotFoundError: - raise ValueError( - "Apply the site manifest before enabling HTTPS." - ) from None - lock_path = STATE_DIRECTORY / "apply.lock" - check_root_file(lock_path) - with lock_path.open("r") as lock: - fcntl.flock(lock, mode) - yield - - def https_paths(paths): name = f"{paths.apache.stem}-https.conf" return paths.apache.with_name(name), paths.enabled.with_name(name)