diff --git a/deploy/panel_installer/cli.py b/deploy/panel_installer/cli.py index f878df0..1db2c64 100644 --- a/deploy/panel_installer/cli.py +++ b/deploy/panel_installer/cli.py @@ -1,7 +1,10 @@ import argparse +import json import os import sys from getpass import getpass +from pathlib import Path +from tempfile import TemporaryDirectory from .config import ( REMOTE_MODES, @@ -27,55 +30,122 @@ def number(value, label): raise InstallError(f"Enter a numeric port for {label}.") from None -def interactive_plan(): - panel = {"hostname": prompt("Panel hostname")} - access = panel["access"] = prompt( - "Panel access (tls, acme, or proxy)", "tls" +def comma_separated(values): + return [value.strip() for value in values.split(",") if value.strip()] + + +def interactive_plan(previous=None): + if previous is None: + preset = prompt( + "Installation profile (full-service or custom)", "full-service" + ) + if preset not in {"full-service", "custom"}: + raise InstallError("Choose full-service or custom.") + defaults = {} + else: + preset = "custom" + defaults = export_parameters(previous, None) + + def ask(label, section, name, fallback=""): + return prompt( + label, str(defaults.get(section, {}).get(name, fallback)) + ) + + full_service = preset == "full-service" + panel = {"hostname": ask("Panel hostname", "panel", "hostname")} + access = panel["access"] = ask( + "Panel access (tls, acme, or proxy)", + "panel", + "access", + "acme" if full_service else "tls", ) if access == "tls": - panel["certificate"] = prompt("Panel certificate path") - panel["key"] = prompt("Panel private key path") + panel["certificate"] = ask( + "Panel certificate path", "panel", "certificate" + ) + panel["key"] = ask("Panel private key path", "panel", "key") elif access == "proxy": - panel["origin_ip"] = prompt("Private origin address") - panel["proxy_ip"] = prompt("Trusted proxy address") + panel["origin_ip"] = ask( + "Private origin address", "panel", "origin_ip" + ) + panel["proxy_ip"] = ask("Trusted proxy address", "panel", "proxy_ip") panel["origin_port"] = number( - prompt("Origin port", "8080"), "the origin" + ask("Origin port", "panel", "origin_port", "8080"), "the origin" ) data = { "panel": panel, "admin": { - "username": prompt("Administrator username", "operator"), - "email": prompt("Administrator email"), + "username": ask( + "Administrator username", "admin", "username", "operator" + ), + "email": ask("Administrator email", "admin", "email"), }, } for name in ("dns", "mail"): - mode = prompt( + mode = ask( f"{name.upper()} role (off, local, remote, or remote-install)", - "off", + name, + "mode", + "local" if full_service else "off", ) target = data[name] = {"mode": mode} if mode in REMOTE_MODES: - target["host"] = prompt( - f"{name.upper()} node SSH hostname or address" + target["host"] = ask( + f"{name.upper()} node SSH hostname or address", name, "host" ) target["port"] = number( - prompt("SSH port", "22"), f"the {name} node" + ask("SSH port", name, "port", "22"), f"the {name} node" + ) + target["host_key"] = ask( + "Verified SSH host public key file", name, "host_key" ) - target["host_key"] = prompt("Verified SSH host public key file") if mode == "remote-install": - target["ssh_user"] = prompt("SSH administrator username") - target["ssh_identity"] = prompt( - "SSH administrator private key file" + target["ssh_user"] = ask( + "SSH administrator username", name, "ssh_user" + ) + target["ssh_identity"] = ask( + "SSH administrator private key file", name, "ssh_identity" ) if name == "mail" and mode in {"local", "remote-install"}: field = "host" if mode == "local" else "mail_hostname" - target[field] = prompt("Public mail hostname") - target["tls"] = prompt("Mail TLS (provided or acme)", "provided") + target[field] = ask( + "Public mail hostname", + name, + field, + panel["hostname"] if mode == "local" else "", + ) + target["tls"] = ask( + "Mail TLS (provided or acme)", + name, + "tls", + "acme" if access == "acme" and mode == "local" else "provided", + ) if target["tls"] == "provided": - target["certificate"] = prompt( - "Certificate path on the mail host" + target["certificate"] = ask( + "Certificate path on the mail host", name, "certificate" ) - target["key"] = prompt("Private key path on the mail host") + target["key"] = ask( + "Private key path on the mail host", name, "key" + ) + hosting = data["hosting"] = {} + for name, label in ( + ("public_addresses", "IP addresses for hosted websites"), + ("nameservers", "Nameservers for new DNS zones"), + ("mail_sending_addresses", "Public sending IPs for hosted email"), + ): + if name == "nameservers" and data["dns"]["mode"] == "off": + continue + if name == "mail_sending_addresses" and data["mail"]["mode"] not in { + "local", + "remote-install", + }: + continue + previous_values = defaults.get("hosting", {}).get(name, []) + value = prompt( + f"{label} (comma-separated, or none)", + ", ".join(previous_values) or "none", + ) + hosting[name] = [] if value == "none" else comma_separated(value) return parse_plan(data) @@ -86,10 +156,85 @@ def get_password(path): raise InstallError( "Use a terminal or provide a private password file." ) - password = check_password(getpass("Administrator password: ")) - if getpass("Repeat the administrator password: ") != password: - raise InstallError("The administrator passwords differ.") - return password + while True: + try: + password = check_password(getpass("Administrator password: ")) + if getpass("Repeat the administrator password: ") == password: + return password + raise InstallError("The administrator passwords differ.") + except InstallError as error: + print(error, file=sys.stderr) + + +def export_parameters(plan, password_path): + panel = {"hostname": plan.hostname, "access": plan.access} + if plan.access == "tls": + panel.update(certificate=plan.certificate, key=plan.key) + elif plan.access == "proxy": + panel.update( + origin_ip=plan.origin_ip, + origin_port=plan.origin_port, + proxy_ip=plan.proxy_ip, + ) + admin = {"username": plan.admin_username, "email": plan.admin_email} + if password_path: + admin["password_file"] = password_path + parameters = { + "panel": panel, + "admin": admin, + "hosting": plan.hosting.parameters(), + } + for name, role in (("dns", plan.dns), ("mail", plan.mail)): + fields = parameters[name] = {"mode": role.mode} + if role.mode in REMOTE_MODES: + fields.update( + host=role.host, host_key=role.host_key, port=role.port + ) + if role.mode == "remote-install": + fields.update( + ssh_user=role.ssh_user, ssh_identity=role.ssh_identity + ) + if name == "mail" and role.mode in {"local", "remote-install"}: + host_key = "host" if role.mode == "local" else "mail_hostname" + fields[host_key] = role.mail_hostname + fields["tls"] = role.tls + if role.tls == "provided": + fields.update(certificate=role.certificate, key=role.key) + return parameters + + +def save_interactive_plan(plan, password_path): + destination = prompt("Save settings to a TOML path (Enter to skip)") + if not destination: + return + path = Path(destination).expanduser() + exists = os.path.lexists(path) + if exists and prompt(f"Replace {path} (yes or no)", "no") != "yes": + return + with TemporaryDirectory(dir=path.parent) as directory: + temporary = Path(directory) / "installation.toml" + with temporary.open("w", encoding="utf-8") as output: + temporary.chmod(0o600) + for section, fields in export_parameters( + plan, password_path + ).items(): + output.write(f"[{section}]\n") + for name, value in fields.items(): + encoded = json.dumps(value, ensure_ascii=False).replace( + "\x7f", "\\u007f" + ) + output.write(f"{name} = {encoded}\n") + output.write("\n") + if exists: + os.replace(temporary, path) + else: + os.link(temporary, path) + print(f"Saved installation settings to {path}.") + if not password_path: + print( + "Provide a private administrator password file " + "when reusing the plan." + ) def main(argv=None): @@ -154,19 +299,32 @@ def main(argv=None): ) password = read_password(password_path) else: - plan = interactive_plan() - print(plan.description(), flush=True) - if ( - prompt("Install with these settings (yes or no)", "no").lower() - != "yes" - ): + plan = None + while True: + plan = interactive_plan(plan) + print(plan.description(), flush=True) + if plan.access == "acme" or plan.mail.tls == "acme": + print( + "Let's Encrypt requires public DNS and inbound HTTP " + "for each selected hostname." + ) + decision = prompt( + "Install with these settings (yes, edit, or no)", "no" + ).lower() + if decision != "edit": + break + if decision != "yes": return 0 + save_interactive_plan(plan, options.admin_password_file) password = get_password(options.admin_password_file) if options.check: print(plan.description()) return 0 installer = Installer( - plan, password, lambda message: print(message, flush=True) + plan, + password, + lambda message: print(message, flush=True), + heartbeat=sys.stdout.isatty(), ) installer.install() return 0 diff --git a/deploy/panel_installer/config.py b/deploy/panel_installer/config.py index 9fa39d4..6d84303 100644 --- a/deploy/panel_installer/config.py +++ b/deploy/panel_installer/config.py @@ -214,6 +214,41 @@ def role(table, name): ) +@dataclass(frozen=True) +class HostingDefaults: + public_addresses: tuple[str, ...] = () + nameservers: tuple[str, ...] = () + mail_sending_addresses: tuple[str, ...] = () + + def parameters(self): + return {name: list(value) for name, value in asdict(self).items()} + + +def hosting_defaults(table): + keys( + table, + {"public_addresses", "nameservers", "mail_sending_addresses"}, + "hosting", + ) + + def entries(name, validate): + values = table.get(name, []) + if not isinstance(values, list) or len(values) > 4: + raise InstallError(f"Enter up to four values for {name}.") + return tuple(dict.fromkeys(validate(value, name) for value in values)) + + public_addresses = entries("public_addresses", address) + nameservers = entries("nameservers", hostname) + mail_sending_addresses = entries("mail_sending_addresses", address) + if any( + not ip_address(value).is_global for value in mail_sending_addresses + ): + raise InstallError("Enter public IP addresses for outgoing mail.") + return HostingDefaults( + public_addresses, nameservers, mail_sending_addresses + ) + + @dataclass(frozen=True) class Plan: hostname: str @@ -227,6 +262,7 @@ class Plan: admin_email: str dns: Role mail: Role + hosting: HostingDefaults = HostingDefaults() def description(self): def target(role): @@ -234,18 +270,27 @@ class Plan: return f"{role.mode} ({role.host}, SSH port {role.port})" return role.mode - return ( + summary = ( f"https://{self.hostname}/ · {self.access} · " f"DNS {target(self.dns)} · mail {target(self.mail)} · " f"Administrator {self.admin_username}" ) + if self.hosting.public_addresses: + summary += " · Web IPs " + ", ".join(self.hosting.public_addresses) + if self.hosting.nameservers: + summary += " · Nameservers " + ", ".join(self.hosting.nameservers) + if self.hosting.mail_sending_addresses: + summary += " · Mail sending IPs " + ", ".join( + self.hosting.mail_sending_addresses + ) + return summary def record(self): - return asdict(self) + return {**asdict(self), "hosting": self.hosting.parameters()} def parse_plan(data): - keys(data, {"panel", "admin", "dns", "mail"}, "installation") + keys(data, {"panel", "admin", "dns", "mail", "hosting"}, "installation") panel = data.get("panel") admin = data.get("admin") keys(admin, {"username", "email", "password_file"}, "admin") @@ -288,6 +333,13 @@ def parse_plan(data): ) else: raise InstallError("Choose tls, acme, or proxy for panel access.") + mail = role(data.get("mail", {}), "mail") + defaults = hosting_defaults(data.get("hosting", {})) + if defaults.mail_sending_addresses and not mail.mail_hostname: + raise InstallError( + "Provide a local or installer-managed mail hostname when setting " + "mail sending addresses." + ) return Plan( host, access, @@ -299,7 +351,8 @@ def parse_plan(data): username, email, role(data.get("dns", {}), "dns"), - role(data.get("mail", {}), "mail"), + mail, + defaults, ) diff --git a/deploy/panel_installer/engine.py b/deploy/panel_installer/engine.py index 882e052..4211370 100644 --- a/deploy/panel_installer/engine.py +++ b/deploy/panel_installer/engine.py @@ -4,15 +4,17 @@ import json import os import pwd import secrets +import smtplib import socket import stat import subprocess import sys import time import tomllib -from contextlib import contextmanager +from contextlib import contextmanager, nullcontext from pathlib import Path from tempfile import TemporaryDirectory +from threading import Event, Thread from . import certificates, roles from .config import REMOTE_MODES, InstallError, platform_settings @@ -198,7 +200,7 @@ def systemctl(*args): ) -def install_packages(packages, *, mail_host=""): +def install_packages(packages, *, mail_host="", step=nullcontext): status = subprocess.run( ["dpkg-query", "-W", "-f=${db:Status-Status} ${Package}\n", *packages], stdin=subprocess.DEVNULL, @@ -224,26 +226,28 @@ def install_packages(packages, *, mail_host=""): source=answers.encode(), label="Choose the local Postfix installation profile", ) - run( - "apt-get", - "update", - label="Refresh the configured APT repositories", - env=apt_env, - timeout=600, - ) - run( - "apt-get", - "install", - "--yes", - "--no-upgrade", - *packages, - label="Install the required APT packages", - env=apt_env, - timeout=1800, - ) + with step("Refreshing APT repositories"): + run( + "apt-get", + "update", + label="Refresh the configured APT repositories", + env=apt_env, + timeout=600, + ) + with step("Installing system packages"): + run( + "apt-get", + "install", + "--yes", + "--no-upgrade", + *packages, + label="Install the required APT packages", + env=apt_env, + timeout=1800, + ) -def install_release(release): +def install_release(release, *, step=nullcontext): root_directory(VENV.parent) if os.path.lexists(VENV): root_directory(VENV) @@ -276,15 +280,16 @@ def install_release(release): for key in ("PIP_NO_INDEX", "PIP_FIND_LINKS") if key in os.environ } - run( - BINDIR / "pip", - "install", - "--disable-pip-version-check", - with_extras, - label="Install Coulobre and its Python dependencies", - env=pip_env, - timeout=1200, - ) + with step("Installing Coulobre and its Python dependencies"): + run( + BINDIR / "pip", + "install", + "--disable-pip-version-check", + with_extras, + label="Install Coulobre and its Python dependencies", + env=pip_env, + timeout=1200, + ) @contextmanager @@ -308,15 +313,45 @@ def install_lock(): class Installer: - def __init__(self, plan, password, progress): + def __init__(self, plan, password, progress, *, heartbeat=False): self.plan = plan self.password = password self.progress = progress + self.heartbeat = heartbeat self.state_file = STATE / "installation.json" self.php, self.modern_mail = platform_settings() with (SOURCE / "pyproject.toml").open("rb") as project: self.release = tomllib.load(project)["project"]["version"] + @contextmanager + def step(self, label): + started = time.monotonic() + finished = Event() + self.progress(f"{label}.") + + def report_elapsed(): + while not finished.wait(15): + elapsed = int(time.monotonic() - started) + self.progress(f"{label}… {elapsed}s elapsed.") + + thread = Thread(target=report_elapsed) if self.heartbeat else None + if thread is not None: + thread.start() + try: + yield + except (InstallError, OSError, ValueError): + self.progress( + f"{label} failed after {int(time.monotonic() - started)}s." + ) + raise + finally: + finished.set() + if thread is not None: + thread.join() + self.progress( + f"{label} completed in {int(time.monotonic() - started)}s." + ) + def save_state(self): put_file( self.state_file, @@ -421,10 +456,13 @@ class Installer: "Environment=RABBITMQ_CONFIG_FILE=/etc/coulobre-rabbitmq.conf\n", ) systemctl("daemon-reload") - systemctl( - "enable", "--now", "mariadb.service", "rabbitmq-server.service" - ) - systemctl("restart", "mariadb.service", "rabbitmq-server.service") + for name, unit in ( + ("MariaDB", "mariadb.service"), + ("RabbitMQ", "rabbitmq-server.service"), + ): + with self.step(f"Starting {name} on loopback"): + systemctl("enable", "--now", unit) + systemctl("restart", unit) def mariadb(sql): return run( @@ -514,6 +552,7 @@ class Installer: "COULOBRE_ALLOWED_HOSTS": self.plan.hostname, "COULOBRE_HTTPS_PROXY": "1", "COULOBRE_REQUIRE_PRIVILEGED_MFA": "1", + "COULOBRE_PASSWORD_RESET_ORIGIN": f"https://{self.plan.hostname}", "COULOBRE_TRUST_APACHE_CLIENT_IP": "1", "COULOBRE_STATIC_ROOT": str(STATIC), "COULOBRE_SECRET_KEY": self.state["secret_key"], @@ -535,8 +574,49 @@ class Installer: options["COULOBRE_LOCAL_MAILBOX_PROVISIONING"] = "1" if self.plan.mail.mode in {"local", "remote-install"}: options["COULOBRE_MAIL_NODE_DKIM"] = "1" + if self.plan.mail.mode == "local": + options.update( + COULOBRE_SMTP_HOST="127.0.0.1", + COULOBRE_SMTP_PORT="25", + COULOBRE_SMTP_STARTTLS="0", + COULOBRE_EMAIL_FROM=f"panel@{self.plan.mail.host}", + ) + hosting = self.plan.hosting + if hosting.public_addresses: + options["COULOBRE_HOSTING_PUBLIC_ADDRESSES"] = ",".join( + hosting.public_addresses + ) + if hosting.nameservers: + options["COULOBRE_HOSTING_NAMESERVERS"] = ",".join( + hosting.nameservers + ) + if hosting.mail_sending_addresses: + options.update( + COULOBRE_MAIL_MX_HOST=self.plan.mail.mail_hostname, + COULOBRE_MAIL_SENDING_IPS=",".join( + hosting.mail_sending_addresses + ), + COULOBRE_MANAGE_MAIL_DNS="1", + ) return "".join(f"{key}={value}\n" for key, value in options.items()) + def verify_notification_mail(self): + if self.plan.mail.mode != "local": + return + try: + with smtplib.SMTP("127.0.0.1", 25, timeout=8) as relay: + relay.ehlo_or_helo_if_needed() + mail_code, _ = relay.mail(f"panel@{self.plan.mail.host}") + recipient_code, _ = relay.rcpt("smtp-check@example.invalid") + relay.rset() + if mail_code != 250 or recipient_code not in (250, 251): + raise OSError("Loopback SMTP relay rejected the envelope.") + except OSError as error: + raise InstallError( + "Local Postfix did not accept outgoing panel mail over " + "loopback. Check journalctl -u postfix and the relay policy." + ) from error + def prepare_panel(self): panel = identity("coulobre-panel") root_directory(ETC, mode=0o750) @@ -671,6 +751,7 @@ class Installer: "Coulobre is already installed with these settings." ) self.verify_panel() + self.verify_notification_mail() return self.progress( "Installing system packages and the Coulobre release." @@ -679,11 +760,13 @@ class Installer: install_packages( self.packages(), mail_host=mail.host if mail.mode == "local" else "", + step=self.step, ) - install_release(self.release) + install_release(self.release, step=self.step) self.install_certificates() self.progress("Preparing MariaDB and RabbitMQ on loopback.") - self.configure_stores() + with self.step("Configuring database and message broker access"): + self.configure_stores() self.progress( "Configuring hosting service identities and provisioning." ) @@ -754,6 +837,9 @@ class Installer: ) systemctl("reload", "apache2.service") self.verify_panel() + if self.plan.mail.mode == "local": + with self.step("Checking Postfix for outgoing panel email"): + self.verify_notification_mail() for key in ("secret_key", "database_password", "broker_password"): self.state.pop(key, None) self.state["complete"] = True diff --git a/deploy/panel_installer/roles.py b/deploy/panel_installer/roles.py index 9cbe672..3191865 100644 --- a/deploy/panel_installer/roles.py +++ b/deploy/panel_installer/roles.py @@ -132,6 +132,7 @@ def configure_mail(target, modern): "myhostname": target.host, "mydestination": "$myhostname, localhost", "inet_interfaces": "all", + "mynetworks": "127.0.0.0/8 [::1]/128", "virtual_mailbox_domains": ( "proxy:texthash:/etc/postfix/coulobre-domains" ), diff --git a/deploy/panel_installer/web.py b/deploy/panel_installer/web.py index 77bcc93..aef6f0b 100644 --- a/deploy/panel_installer/web.py +++ b/deploy/panel_installer/web.py @@ -1,4 +1,5 @@ import hmac +import re import secrets import time from dataclasses import dataclass, field @@ -8,18 +9,21 @@ from http.server import BaseHTTPRequestHandler, HTTPServer from threading import Thread from urllib.parse import parse_qs -from .cli import number +from .cli import comma_separated, number from .config import REMOTE_MODES, InstallError, parse_plan, port from .engine import Installer COOKIE = "coulobre_installer" MAX_FORM = 16384 FORM = """
+

Full-service setup is recommended for a public single server. The panel, +websites, databases, DNS and mail run locally. Adjust the settings below +for a different deployment.

Panel @@ -32,6 +36,13 @@ FORM = """
{dns}{mail} +
New hosting accounts +

Separate multiple values with commas. You can also set these later.

+ + + +
""" STYLE = """body{font:1rem system-ui,sans-serif;max-width:46rem;margin:auto; padding:1rem;color:#14372e} fieldset{margin:1rem 0;border:1px solid #a9beb2; @@ -49,8 +60,9 @@ def role_form(name): "' '' + "" "' "