Provision restricted SFTP access on web nodes

This commit is contained in:
parkel committed 2026-11-21 10:56:06 +01:00
1 parent 56c4b8e72c
commit a3f7a2e7cb
10 files changed
+350 -19

No files matched your search

+16
View File
@@ -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
+14
View File
@@ -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
@@ -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
+58
View File
@@ -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},
)
+5 -1
View File
@@ -50,7 +50,11 @@ class WebNodeTLSTests(SimpleTestCase):
patch("coulobre.web_node_tls.os.geteuid", return_value=0) patch("coulobre.web_node_tls.os.geteuid", return_value=0)
) )
self.enterContext( 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.enterContext(patch("coulobre.web_node_tls.CERTBOT_ROOT", certbot))
self.webroot = directory / "coulobre-acme" self.webroot = directory / "coulobre-acme"
+91
View File
@@ -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()
+27
View File
@@ -108,6 +108,16 @@ def main(argv=None):
"https-status", help="Check a site's local HTTPS configuration." "https-status", help="Check a site's local HTTPS configuration."
) )
https_status.add_argument("manifest", type=Path) 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 = commands.add_parser(
"restore-directadmin", "restore-directadmin",
help="Restore a DirectAdmin website into an empty web root.", 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 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: try:
payload = json.loads(args.manifest.read_text(encoding="utf-8")) payload = json.loads(args.manifest.read_text(encoding="utf-8"))
site = WebSite.from_manifest(payload) site = WebSite.from_manifest(payload)
@@ -158,6 +180,11 @@ def main(argv=None):
report = https_status(site) report = https_status(site)
print(json.dumps(report, indent=2)) print(json.dumps(report, indent=2))
return 0 if report["state"] == "configured" else 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": elif args.command == "restore-directadmin":
from .web_node_restore import restore_website from .web_node_restore import restore_website
+21 -1
View File
@@ -10,7 +10,12 @@ from contextlib import contextmanager
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path 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") STATE_DIRECTORY = Path("/var/lib/coulobre/web-node")
WEB_ROOT = Path("/srv/coulobre/web") 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): def apply_site(site):
if os.geteuid() != 0: if os.geteuid() != 0:
raise ValueError("Run apply as root on the web node.") raise ValueError("Run apply as root on the web node.")
+99
View File
@@ -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}."
)
+1 -17
View File
@@ -2,12 +2,10 @@ import fcntl
import os import os
import ssl import ssl
import subprocess import subprocess
from contextlib import contextmanager
from pathlib import Path from pathlib import Path
from .node_files import check_root_file, require_root_directory from .node_files import check_root_file, require_root_directory
from .web_node_apply import ( from .web_node_apply import (
STATE_DIRECTORY,
SitePaths, SitePaths,
check_configuration, check_configuration,
check_installation, check_installation,
@@ -16,6 +14,7 @@ from .web_node_apply import (
configuration_installation, configuration_installation,
enable_apache_site, enable_apache_site,
install_configuration, install_configuration,
locked_web_node,
run, run,
) )
@@ -133,21 +132,6 @@ def https_status(site):
return {**report, "state": "configured"} 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): def https_paths(paths):
name = f"{paths.apache.stem}-https.conf" name = f"{paths.apache.stem}-https.conf"
return paths.apache.with_name(name), paths.enabled.with_name(name) return paths.apache.with_name(name), paths.enabled.with_name(name)