Install and enrol remote mail and DNS nodes #84

Merged
parkel merged 2 commits from feature/remote-node-bootstrap into main 2026-11-22 00:19:46 +01:00
10 changed files with 862 additions and 11 deletions

No files matched your search

+66
View File
@@ -0,0 +1,66 @@
#!/bin/sh
set -eu
if [ "$(id -u)" -ne 0 ] || [ "$#" -eq 0 ]; then
echo "Run as root with one or more roles: dns mail" >&2
exit 1
fi
dns=
mail=
for role in "$@"; do
case "$role" in
dns) dns=1 ;;
mail) mail=1 ;;
*) echo "Unknown node role: $role" >&2; exit 1 ;;
esac
done
cd "$(dirname "$0")/.."
venv=/opt/coulobre
release=$(python3 -c '
import tomllib
with open("pyproject.toml", "rb") as project:
print(tomllib.load(project)["project"]["version"])
')
python3 - "$venv" <<'PY'
import os
import stat
import sys
from pathlib import Path
venv = Path(sys.argv[1])
for directory in (venv.parent, venv, venv / "bin"):
if not os.path.lexists(directory):
continue
info = directory.lstat()
if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
sys.exit(f"Expected a root-controlled directory at {directory}.")
PY
installed=
if [ -x "$venv/bin/python" ]; then
installed=$("$venv/bin/python" -c '
from importlib.metadata import PackageNotFoundError, version
try:
print(version("coulobre-panel"))
except PackageNotFoundError:
pass
')
if [ -n "$installed" ] && [ "$installed" != "$release" ]; then
echo "Use the matching source release or upgrade Coulobre first." >&2
exit 1
fi
fi
# Package arguments below are fixed for each supported role.
apt-get update
apt-get install --yes --no-upgrade python3-venv openssh-server socat \
${dns:+bind9 bind9-utils} \
${mail:+postfix dovecot-core dovecot-imapd dovecot-lmtpd}
if [ ! -x "$venv/bin/python" ]; then
python3 -m venv "$venv"
fi
if [ -z "$installed" ]; then
"$venv/bin/pip" install .
fi
exec "$venv/bin/coulobre-node-setup" install-receiver "$@"
+85
View File
@@ -1394,6 +1394,91 @@ Use the values for each service below when following the commands.
| Worker unit | `coulobre-dns-publisher.service` | `coulobre-mailbox-provisioner.service` | | Worker unit | `coulobre-dns-publisher.service` | `coulobre-mailbox-provisioner.service` |
| Panel flag | `COULOBRE_LOCAL_DNS_PUBLISHING=1` | `COULOBRE_LOCAL_MAILBOX_PROVISIONING=1` | | Panel flag | `COULOBRE_LOCAL_DNS_PUBLISHING=1` | `COULOBRE_LOCAL_MAILBOX_PROVISIONING=1` |
### Install and enrol a node
Use the same verified Coulobre source release on the panel host and the
destination. The destination needs a systemd host running Debian 13,
Ubuntu 24.04, or Ubuntu 26.04, with access to its APT repositories and Python
dependencies. Open the destination's SSH port to the panel host. Use your
existing administrator account to install the node.
From the unpacked release on the destination, run the installer for the roles
you want. The installer uses the distribution's packages, installs Coulobre in
`/opt/coulobre`, and enables the receiver sockets.
```sh
sudo ./deploy/install-node.sh dns mail
```
For an installation started from the central host, run the same command
through your existing administrative SSH connection after copying and
verifying the source release on the destination.
```sh
ssh -t operator@node.example.org 'cd /path/to/coulobre-release && sudo ./deploy/install-node.sh dns'
```
Set up [BIND9](development.md#apply-a-zone-manifest) or
[Postfix and Dovecot](development.md#apply-a-mailbox-manifest) for the role
before enrolment. This includes the BIND9 control channel or the Postfix
lookups, Dovecot LMTP socket, and mail TLS configuration. Configure a fresh
service once. Repeat the installer to add roles or restore missing receiver
units. It reuses the installed release and preserves service configuration,
zone files, and mailbox data. Use the normal release upgrade procedure to
change Coulobre versions.
Run `sudo /opt/coulobre/bin/coulobre-node-setup check-receiver dns`
or use `mail` to check the destination configuration locally.
On the panel host, prepare its identity for the role. This example uses DNS.
For mail, substitute `mail` and the corresponding worker and flag from the
table.
```sh
sudo apt install openssh-client
sudo /opt/coulobre/bin/coulobre-node-setup prepare-panel dns > panel-dns.pub
```
Transfer `panel-dns.pub` to the destination and authorize it there. Repeating
this command keeps the same key. Run it once for each panel that shares the
receiver.
```sh
sudo /opt/coulobre/bin/coulobre-node-setup authorize-panel dns panel-dns.pub
```
Get the destination's SSH host **public** key through the administrator
connection and save it as `node-host.pub` on the panel host. Verify the node
host and fingerprint before enrolling it. From the unpacked release on the
panel host, run the following commands. Set `--port` if the destination uses
a different SSH port.
```sh
sudo /opt/coulobre/bin/coulobre-node-setup enrol-panel dns node.example.org node-host.pub
sudo /opt/coulobre/bin/coulobre-node-setup check-panel dns
```
Enrolment checks the pinned SSH host identity and the restricted receiver
account, verifies the destination services and release, and tests the panel's
systemd relay socket. The check reads service status on the node. To activate
the feature, set the panel flag from the table in `/etc/coulobre/panel.env`,
restart the panel, general worker and scheduler, and enable the role worker.
```sh
sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat
sudo systemctl enable --now coulobre-dns-publisher.service
```
Use **Publish zone** or **Provision mailbox** on a test hosting account and
verify the result. If the panel already has a local service or a different
relay configured for this role, follow the service migration steps before
changing destinations.
### Manual setup
The following commands show the files and identities used by the installer.
Use them for an existing deployment with its own SSH or systemd configuration.
### Prepare the panel's SSH identity ### Prepare the panel's SSH identity
Start from the same Coulobre source release on both hosts. For DNS, set these Start from the same Coulobre source release on both hosts. For DNS, set these
+1
View File
@@ -23,6 +23,7 @@ coulobre-database-node = "coulobre.database_node:main"
coulobre-directadmin = "coulobre.directadmin:main" coulobre-directadmin = "coulobre.directadmin:main"
coulobre-dns-node = "coulobre.dns_node:main" coulobre-dns-node = "coulobre.dns_node:main"
coulobre-mail-node = "coulobre.mail_node:main" coulobre-mail-node = "coulobre.mail_node:main"
coulobre-node-setup = "coulobre.node_setup:main"
coulobre-service-credentials = "coulobre.service_credentials:main" coulobre-service-credentials = "coulobre.service_credentials:main"
coulobre-service-health = "coulobre.service_health:main" coulobre-service-health = "coulobre.service_health:main"
coulobre-web-node = "coulobre.web_node:main" coulobre-web-node = "coulobre.web_node:main"
+1
View File
@@ -358,6 +358,7 @@ def main(argv=None):
apply, apply,
limit=DNS_REQUEST_LIMIT, limit=DNS_REQUEST_LIMIT,
identity=identity, identity=identity,
probe_role="dns",
) )
try: try:
+106
View File
@@ -0,0 +1,106 @@
import json
from base64 import b64encode
from contextlib import nullcontext, redirect_stdout
from io import BytesIO, StringIO
from pathlib import Path
from tempfile import TemporaryDirectory
from types import SimpleNamespace
from unittest.mock import patch
from django.test import SimpleTestCase
from coulobre import dns_node, mail_node, node_setup
from coulobre.node_probe import PROBE, probe_identity, verify_probe
def key_text(byte):
key_type = b"ssh-ed25519"
wire = len(key_type).to_bytes(4) + key_type
wire += (32).to_bytes(4) + byte * 32
return f"ssh-ed25519 {b64encode(wire).decode()}"
class NodeProbeTests(SimpleTestCase):
def test_probe_reports_the_role_without_calling_the_apply_handler(self):
for node, role, apply_path in (
(dns_node, "dns", "coulobre.dns_node_apply.apply_zone"),
(mail_node, "mail", "coulobre.mail_node.apply_mailbox_request"),
):
with (
self.subTest(role=role),
patch(
"sys.stdin",
SimpleNamespace(
buffer=BytesIO(json.dumps(PROBE).encode())
),
),
patch(apply_path) as apply,
patch("coulobre.node_probe.check_receiver") as check,
redirect_stdout(StringIO()) as output,
):
self.assertEqual(node.main(["apply-request"]), 0)
apply.assert_not_called()
check.assert_called_once_with(role)
verify_probe(output.getvalue().encode(), role)
def test_failed_probe_and_other_release_cannot_enrol(self):
expected = probe_identity("dns") | {
"state": "configured",
"problem": None,
}
for changes in (
{"role": "mail"},
{"release": "0.invalid"},
{"version": True},
{"state": "failed", "problem": "BIND9 is unavailable."},
):
with self.subTest(changes=changes), self.assertRaises(ValueError):
verify_probe(json.dumps(expected | changes).encode(), "dns")
class NodeAuthorizationTests(SimpleTestCase):
def test_repeat_authorization_keeps_existing_key_options_and_other_panels(
self,
):
directory = Path(self.enterContext(TemporaryDirectory()))
role = node_setup.ROLES["dns"]
key = directory / "panel.pub"
receiver = directory / role.receiver
first, second = key_text(b"x"), key_text(b"y")
entry = f'from="192.0.2.1",restrict {first} existing panel\n'
receiver.write_text(entry)
with (
patch.object(node_setup, "NODE_KEYS", directory),
patch.object(
node_setup, "locked_root_directory", return_value=nullcontext()
),
patch.object(node_setup, "check_ssh_receiver"),
patch.object(node_setup, "read_root_file", return_value=entry),
):
key.write_text(first + "\n")
node_setup.authorize_panel(role, key)
self.assertEqual(receiver.read_text(), entry)
key.write_text(second + "\n")
node_setup.authorize_panel(role, key)
self.assertEqual(
receiver.read_text(),
entry + f'command="{role.relay}",restrict {second}\n',
)
def test_ssh_host_is_normalized_or_rejected_before_template_substitution(
self,
):
self.assertEqual(
node_setup.normalize_host("2001:0db8::5"), "2001:db8::5"
)
self.assertEqual(
node_setup.normalize_host("Node.example.org"), "node.example.org"
)
for invalid in (
"",
"mail example.org",
"::1%eth0",
"node.example.org\n",
):
with self.subTest(invalid=invalid), self.assertRaises(ValueError):
node_setup.normalize_host(invalid)
+1
View File
@@ -218,6 +218,7 @@ def main(argv=None):
parse_mailbox_request, parse_mailbox_request,
apply_mailbox_request, apply_mailbox_request,
include_result=True, include_result=True,
probe_role="mail",
) )
try: try:
+7 -6
View File
@@ -509,7 +509,7 @@ def ensure_mail_home(home, account, *, create):
) )
def check_services(mailbox): def check_services(mailbox=None):
try: try:
account = pwd.getpwnam(MAIL_USER) account = pwd.getpwnam(MAIL_USER)
except KeyError: except KeyError:
@@ -536,11 +536,12 @@ def check_services(mailbox):
raise ValueError( raise ValueError(
f"Configure Postfix {name} for Coulobre mailboxes." f"Configure Postfix {name} for Coulobre mailboxes."
) )
local_domains = run("postconf", "-hx", "mydestination") if mailbox is not None:
if mailbox.domain in re.split(r"[\s,]+", local_domains.lower()): local_domains = run("postconf", "-hx", "mydestination")
raise ValueError( if mailbox.domain in re.split(r"[\s,]+", local_domains.lower()):
"The requested mail domain is a local Postfix destination." raise ValueError(
) "The requested mail domain is a local Postfix destination."
)
modern = check_dovecot_maildir() modern = check_dovecot_maildir()
first_uid = int(run("doveconf", "-h", "first_valid_uid")) first_uid = int(run("doveconf", "-h", "first_valid_uid"))
last_uid = int(run("doveconf", "-h", "last_valid_uid")) last_uid = int(run("doveconf", "-h", "last_valid_uid"))
+65
View File
@@ -0,0 +1,65 @@
import json
import re
from importlib.metadata import version
PROBE = {"version": 1, "operation": "probe"}
PROBE_BYTES = (json.dumps(PROBE) + "\n").encode()
PROBE_LIMIT = 4096
def probe_identity(role):
return PROBE | {"role": role, "release": version("coulobre-panel")}
def check_receiver(role):
if role == "dns":
from .dns_node_apply import RNDC, ZONE_DIRECTORY, run
from .node_files import require_root_directory
require_root_directory(ZONE_DIRECTORY)
configuration = run("named-checkconf", "-p", "-x")
if not re.search(r"(?m)^\s*allow-new-zones\s+yes;", configuration):
raise ValueError(
"Enable allow-new-zones in the BIND9 configuration."
)
run(*RNDC, "status")
else:
from .mail_node_apply import (
DOVECOT_USERS,
POSTFIX_DOMAINS,
POSTFIX_MAILBOXES,
check_services,
)
from .node_files import check_root_file
_, auth_group, _ = check_services()
for path in (POSTFIX_DOMAINS, POSTFIX_MAILBOXES):
check_root_file(path, mode=0o644)
check_root_file(DOVECOT_USERS, mode=0o640)
if DOVECOT_USERS.lstat().st_gid != auth_group:
raise ValueError("Check the group of the Dovecot lookup file.")
def verify_probe(body, role):
try:
if len(body) > PROBE_LIMIT:
raise ValueError
reply = json.loads(body)
if (
not isinstance(reply, dict)
or type(reply.get("version")) is not int
):
raise ValueError
expected = probe_identity(role)
if any(reply.get(field) != value for field, value in expected.items()):
raise ValueError
except (ValueError, RecursionError):
raise ValueError(
f"Expected a Coulobre {role} receiver on the same release."
) from None
if reply == expected | {"state": "configured", "problem": None}:
return
raise ValueError(
f"The {role} receiver is reachable but its services are not ready. "
"Check the destination socket service and node configuration."
)
+18 -5
View File
@@ -12,6 +12,7 @@ def serve_apply_request(
limit=MAX_REQUEST_BYTES, limit=MAX_REQUEST_BYTES,
identity=None, identity=None,
include_result=False, include_result=False,
probe_role=None,
): ):
report = {"version": manifest_version} report = {"version": manifest_version}
try: try:
@@ -22,11 +23,23 @@ def serve_apply_request(
payload = json.loads(body.decode("utf-8")) payload = json.loads(body.decode("utf-8"))
except (ValueError, RecursionError): except (ValueError, RecursionError):
raise ValueError("Expected a UTF-8 JSON manifest.") from None raise ValueError("Expected a UTF-8 JSON manifest.") from None
spec = parse_manifest(payload) if (
report = spec.manifest() if identity is None else identity(spec) probe_role is not None
result = apply(spec) and isinstance(payload, dict)
if include_result and result is not None: and payload.get("operation") == "probe"
report.update(result) ):
from .node_probe import PROBE, check_receiver, probe_identity
if payload != PROBE or type(payload.get("version")) is not int:
raise ValueError("Expected a version 1 node probe.")
report = probe_identity(probe_role)
check_receiver(probe_role)
else:
spec = parse_manifest(payload)
report = spec.manifest() if identity is None else identity(spec)
result = apply(spec)
if include_result and result is not None:
report.update(result)
except (OSError, ValueError) as error: except (OSError, ValueError) as error:
print(json.dumps({**report, "state": "failed", "problem": str(error)})) print(json.dumps({**report, "state": "failed", "problem": str(error)}))
return 1 return 1
+512
View File
@@ -0,0 +1,512 @@
import argparse
import grp
import ipaddress
import os
import pwd
import re
import shlex
import socket
import stat
import subprocess
import tomllib
from dataclasses import dataclass
from importlib.metadata import version
from pathlib import Path
from tempfile import TemporaryDirectory
from .domain_names import canonical_domain
from .node_files import (
locked_root_directory,
read_root_file,
replace_configuration,
require_root_directory,
write_new_file,
)
from .node_probe import PROBE_BYTES, PROBE_LIMIT, check_receiver, verify_probe
from .sftp_keys import read_public_keys
PANEL_SSH = Path("/etc/coulobre-remote")
NODE_KEYS = Path("/etc/ssh/coulobre-node-keys")
SSH_DROP_IN = Path("/etc/ssh/sshd_config.d/00-coulobre-node-requests.conf")
SYSTEMD = Path("/etc/systemd/system")
COMMAND_ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"}
@dataclass(frozen=True)
class NodeRole:
name: str
worker: str
worker_unit: str
@property
def group(self):
return f"coulobre-{self.name}-provisioning"
@property
def receiver(self):
return f"coulobre-{self.name}-request"
@property
def unit(self):
return f"coulobre-{self.name}-apply"
@property
def relay(self):
return (
f"/usr/bin/socat -t 185 STDIO UNIX-CONNECT:/run/{self.unit}.sock"
)
@property
def directory(self):
return PANEL_SSH / self.name
ROLES = {
"dns": NodeRole("dns", "coulobre-dns-publisher", "coulobre-dns-publisher"),
"mail": NodeRole(
"mail", "coulobre-mail-provisioner", "coulobre-mailbox-provisioner"
),
}
def run(*command):
result = subprocess.run(
command,
stdin=subprocess.DEVNULL,
capture_output=True,
env=COMMAND_ENV,
timeout=30,
)
if result.returncode:
detail = result.stderr.decode(errors="replace").strip()
raise ValueError(f"{command[0]} failed. {detail}".strip())
return result.stdout
def release_assets(source):
with (source / "pyproject.toml").open("rb") as stream:
project = tomllib.load(stream).get("project", {})
if project.get("name") != "coulobre-panel" or project.get(
"version"
) != version("coulobre-panel"):
raise ValueError("Use the source release matching /opt/coulobre.")
return source / "deploy"
def put_file(path, content, *, mode=0o644, group=0):
if os.path.lexists(path):
if (
path.lstat().st_gid != group
or read_root_file(path, mode=mode) != content
):
raise ValueError(f"Existing configuration differs at {path}.")
return False
write_new_file(path, content, mode=mode, group=group)
return True
def install_unit(assets, name):
return put_file(SYSTEMD / name, (assets / "systemd" / name).read_text())
def ensure_identity(name, *, home, shell, group=None):
groups = []
if group is not None:
try:
grp.getgrnam(group)
except KeyError:
run("groupadd", "--system", group)
groups.extend(("--groups", group))
try:
account = pwd.getpwnam(name)
except KeyError:
run(
"useradd",
"--system",
"--user-group",
"--no-create-home",
"--home-dir",
home,
"--shell",
shell,
*groups,
name,
)
account = pwd.getpwnam(name)
try:
primary_group = grp.getgrnam(name).gr_gid
except KeyError:
raise ValueError(f"Expected a private group for {name}.") from None
expected = {primary_group}
if group is not None:
expected.add(grp.getgrnam(group).gr_gid)
if (
not account.pw_uid
or not account.pw_gid
or account.pw_gid != primary_group
or account.pw_dir != home
or account.pw_shell != shell
or set(os.getgrouplist(name, account.pw_gid)) != expected
):
raise ValueError(f"Unexpected account or groups for {name}.")
return account
def install_receiver(assets, role):
if os.path.lexists(SYSTEMD / f"{role.unit}@.service.d/remote.conf"):
raise ValueError("This host already relays this role to another node.")
ensure_identity(role.receiver, home="/", shell="/bin/sh", group=role.group)
if role.name == "dns":
from .dns_node_apply import ZONE_DIRECTORY
require_root_directory(ZONE_DIRECTORY, create_mode=0o755)
install_unit(assets, f"{role.unit}.socket")
install_unit(assets, f"{role.unit}@.service")
def install_receivers(assets, roles):
require_root_directory(SYSTEMD)
require_root_directory(NODE_KEYS, create_mode=0o755)
require_root_directory(SSH_DROP_IN.parent)
with locked_root_directory(NODE_KEYS):
for role in roles:
install_receiver(assets, role)
config = assets / "openssh/coulobre-node-requests.conf.example"
added = put_file(SSH_DROP_IN, config.read_text())
try:
require_root_directory(Path("/run/sshd"), create_mode=0o755)
run("/usr/sbin/sshd", "-t")
for role in roles:
check_ssh_receiver(role)
run("systemctl", "reload-or-restart", "ssh.service")
except (OSError, ValueError, subprocess.TimeoutExpired):
if added:
SSH_DROP_IN.unlink()
raise
run("systemctl", "daemon-reload")
run(
"systemctl",
"enable",
"--now",
*(f"{role.unit}.socket" for role in roles),
)
def check_ssh_receiver(role):
live = run(
"/usr/sbin/sshd",
"-T",
"-C",
f"user={role.receiver},host=localhost,addr=127.0.0.1",
).decode()
expected = {
f"forcecommand {role.relay}",
f"authorizedkeysfile {NODE_KEYS}/%u",
"authenticationmethods publickey",
"disableforwarding yes",
"permituserrc no",
"permittty no",
"pubkeyauthentication yes",
"passwordauthentication no",
"kbdinteractiveauthentication no",
"trustedusercakeys none",
"authorizedkeyscommand none",
}
if not expected <= set(live.splitlines()):
raise ValueError(
f"Check the effective SSH policy for {role.receiver}."
)
def one_public_key(path):
with path.open("rb") as source:
keys = read_public_keys(source).splitlines()
if len(keys) != 1:
raise ValueError(f"Expected one SSH public key in {path}.")
return keys[0]
def authorize_panel(role, key_path):
key = one_public_key(key_path)
with locked_root_directory(NODE_KEYS):
check_ssh_receiver(role)
destination = NODE_KEYS / role.receiver
old = (
read_root_file(destination, mode=0o644)
if os.path.lexists(destination)
else ""
)
if any(has_authorized_key(line, key) for line in old.splitlines()):
return
entry = f'command="{role.relay}",restrict {key}\n'
if os.path.lexists(destination):
replace_configuration(destination, old.rstrip("\n") + "\n" + entry)
else:
write_new_file(destination, entry, mode=0o644)
def has_authorized_key(line, key):
if line.lstrip().startswith("#"):
return False
try:
tokens = shlex.split(line)
except ValueError:
return False
return any(" ".join(tokens[start : start + 2]) == key for start in (0, 1))
def prepare_panel(role):
require_root_directory(PANEL_SSH, create_mode=0o755)
with locked_root_directory(PANEL_SSH):
try:
grp.getgrnam(role.group)
except KeyError:
run("groupadd", "--system", role.group)
worker = ensure_identity(
role.worker, home="/nonexistent", shell="/usr/sbin/nologin"
)
directory = role.directory
require_root_directory(directory, create_mode=0o750)
os.chown(directory, 0, worker.pw_gid)
os.chmod(directory, 0o750)
key = directory / "id_ed25519"
public = key.with_suffix(".pub")
if not os.path.lexists(key):
if os.path.lexists(public):
raise ValueError(f"The private key is missing at {key}.")
with TemporaryDirectory(dir=directory) as scratch:
generated = Path(scratch) / "key"
run(
"ssh-keygen",
"-q",
"-t",
"ed25519",
"-N",
"",
"-f",
str(generated),
)
os.chown(generated, worker.pw_uid, worker.pw_gid)
os.link(generated, key)
info = key.lstat()
if (
not stat.S_ISREG(info.st_mode)
or stat.S_IMODE(info.st_mode) != 0o600
or info.st_uid != worker.pw_uid
):
raise ValueError(f"Expected a private key owned by {role.worker}.")
public_key = run("ssh-keygen", "-y", "-f", str(key)).decode().split()
if len(public_key) < 2 or public_key[0] != "ssh-ed25519":
raise ValueError("Expected an Ed25519 panel identity.")
public_key = " ".join(public_key[:2])
if not os.path.lexists(public):
write_new_file(public, public_key + "\n", mode=0o644)
elif one_public_key(public) != public_key:
raise ValueError(f"The public key does not match {key}.")
return public_key, worker.pw_gid
def normalize_host(host):
if not re.fullmatch(r"[a-zA-Z0-9.:-]+", host):
raise ValueError("Enter an SSH hostname or IP address.")
try:
return str(ipaddress.ip_address(host))
except ValueError:
return canonical_domain(host)
def ssh_setup(assets, role, host, port):
config = (
assets / f"openssh/{role.name}-node-client.conf.example"
).read_text()
return config.replace(
f"HostName {role.name}.example.org", f"HostName {host}"
).replace("Port 22", f"Port {port}")
def stage_ssh_settings(role, config, known_hosts, group):
with TemporaryDirectory(dir=role.directory, prefix=".enrol-") as directory:
scratch = Path(directory)
os.chown(scratch, 0, group)
os.chmod(scratch, 0o750)
pinned = role.directory / "known_hosts"
candidate = scratch / "ssh_config"
put_file(
candidate,
config.replace(str(pinned), str(scratch / "known_hosts")),
mode=0o640,
group=group,
)
put_file(scratch / "known_hosts", known_hosts, mode=0o640, group=group)
probe = subprocess.run(
(
"/usr/sbin/runuser",
"-u",
role.worker,
"--",
"/usr/bin/ssh",
"-T",
"-F",
str(candidate),
f"coulobre-{role.name}-node",
),
input=PROBE_BYTES,
capture_output=True,
env=COMMAND_ENV,
timeout=25,
)
if not probe.stdout:
raise ValueError(
"The receiver could not be reached with the pinned host key "
"and panel identity. Check the host, port and authorized key."
)
verify_probe(probe.stdout, role.name)
if probe.returncode:
raise ValueError(
"The receiver closed the SSH connection with an error."
)
def enrol_panel(assets, role, host, port, host_key):
host = normalize_host(host)
key = one_public_key(host_key)
entry = host if port == 22 else f"[{host}]:{port}"
known_hosts = f"{entry} {key}\n"
config = ssh_setup(assets, role, host, port)
_, group = prepare_panel(role)
require_root_directory(SYSTEMD)
with locked_root_directory(PANEL_SSH):
local_units = (
SYSTEMD / f"{role.unit}@.service",
SYSTEMD / f"{role.unit}.socket",
)
drop_in = SYSTEMD / f"{role.unit}@.service.d/remote.conf"
if any(map(os.path.lexists, local_units)) and not os.path.lexists(
drop_in
):
raise ValueError(
"A local service is already installed. Use the documented "
"service migration procedure before changing destinations."
)
files = {
role.directory / "known_hosts": known_hosts,
role.directory / "ssh_config": config,
}
for path, wanted in files.items():
if (
os.path.lexists(path)
and read_root_file(path, mode=0o640) != wanted
):
raise ValueError(
f"Existing SSH configuration differs at {path}."
)
stage_ssh_settings(role, config, known_hosts, group)
for path, wanted in files.items():
put_file(path, wanted, mode=0o640, group=group)
require_root_directory(drop_in.parent, create_mode=0o755)
put_file(
drop_in,
(
assets / "systemd" / drop_in.parent.name / "remote.conf"
).read_text(),
)
install_unit(assets, f"{role.unit}@.service")
install_unit(assets, f"{role.unit}.socket")
install_unit(assets, f"{role.worker_unit}.service")
run("systemctl", "daemon-reload")
run("systemctl", "enable", "--now", f"{role.unit}.socket")
check_panel(role)
def check_panel(role):
drop_in = SYSTEMD / f"{role.unit}@.service.d/remote.conf"
require_root_directory(drop_in.parent)
read_root_file(drop_in)
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
client.settimeout(25)
client.connect(f"/run/{role.unit}.sock")
client.sendall(PROBE_BYTES)
client.shutdown(socket.SHUT_WR)
with client.makefile("rb") as response:
verify_probe(response.read(PROBE_LIMIT + 1), role.name)
def ssh_port(value):
port = int(value)
if not 1 <= port <= 65535:
raise argparse.ArgumentTypeError("Enter an SSH port from 1 to 65535.")
return port
def main(argv=None):
parser = argparse.ArgumentParser(prog="coulobre-node-setup")
parser.add_argument("--source", type=Path, default=Path.cwd())
commands = parser.add_subparsers(dest="command", required=True)
install = commands.add_parser(
"install-receiver", help="Install local receiver units."
)
install.add_argument("roles", nargs="+", choices=ROLES)
for command, help_text in (
("prepare-panel", "Prepare and print the panel's public SSH key."),
("authorize-panel", "Authorize a panel public key on this receiver."),
("check-receiver", "Check the service configuration on this node."),
(
"enrol-panel",
"Verify and install a remote relay on the panel host.",
),
(
"check-panel",
"Check the enrolled receiver through the panel socket.",
),
):
action = commands.add_parser(command, help=help_text)
action.add_argument("role", choices=ROLES)
if command == "authorize-panel":
action.add_argument("public_key", type=Path)
if command == "enrol-panel":
action.add_argument("host")
action.add_argument("host_key", type=Path)
action.add_argument("--port", type=ssh_port, default=22)
args = parser.parse_args(argv)
if os.geteuid() != 0:
parser.exit(1, "coulobre-node-setup: Run this command as root.\n")
try:
if args.command == "install-receiver":
install_receivers(
release_assets(args.source),
[ROLES[name] for name in dict.fromkeys(args.roles)],
)
print(
"Installed receiver sockets. Configure the requested "
"services before enrolment."
)
return 0
role = ROLES[args.role]
if args.command == "prepare-panel":
key, _ = prepare_panel(role)
print(key)
elif args.command == "authorize-panel":
authorize_panel(role, args.public_key)
print(f"Authorized the panel key for the {role.name} receiver.")
elif args.command == "check-receiver":
check_receiver(role.name)
print(f"The local {role.name} services are ready.")
elif args.command == "enrol-panel":
enrol_panel(
release_assets(args.source),
role,
args.host,
args.port,
args.host_key,
)
print(
f"Verified the {role.name} receiver. "
"Enable its panel flag and worker."
)
else:
check_panel(role)
print(f"The enrolled {role.name} receiver is ready.")
except (OSError, ValueError, subprocess.TimeoutExpired) as error:
parser.exit(1, f"coulobre-node-setup: {error}\n")
return 0