diff --git a/deploy/panel_installer/__init__.py b/deploy/panel_installer/__init__.py new file mode 100644 index 0000000..26deb21 --- /dev/null +++ b/deploy/panel_installer/__init__.py @@ -0,0 +1 @@ +"""Coulobre source-release installer.""" diff --git a/deploy/panel_installer/config.py b/deploy/panel_installer/config.py new file mode 100644 index 0000000..3f9b27d --- /dev/null +++ b/deploy/panel_installer/config.py @@ -0,0 +1,288 @@ +import os +import re +import ssl +import stat +import tomllib +from dataclasses import asdict, dataclass +from ipaddress import ip_address +from pathlib import Path +from platform import freedesktop_os_release + +PLATFORMS = { + ("ubuntu", "26.04"): ("8.5", True), + ("debian", "13"): ("8.4", True), + ("ubuntu", "24.04"): (None, False), +} +DNS_LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?") +FILE_PATH = re.compile(r"/[a-zA-Z0-9_./+-]+") +USERNAME = re.compile(r"[a-zA-Z0-9@.+_-]{1,150}") +EMAIL = re.compile(r"[^\s@]+@[^\s@]+\.[^\s@]+") + + +class InstallError(Exception): + pass + + +def keys(table, allowed, label): + if not isinstance(table, dict) or table.keys() - set(allowed): + raise InstallError(f"Check the fields in the {label} section.") + + +def hostname(value, label): + if isinstance(value, str): + try: + value = value.encode("idna").decode("ascii").lower().rstrip(".") + labels = value.split(".") + if ( + len(value) <= 253 + and len(labels) >= 2 + and all(DNS_LABEL.fullmatch(part) for part in labels) + ): + return value + except UnicodeError: + pass + raise InstallError(f"Enter a fully qualified {label} hostname.") + + +def address(value, label, *, private=False): + if not isinstance(value, str) or "%" in value: + raise InstallError(f"Enter a literal IP address for {label}.") + try: + ip = ip_address(value) + except ValueError: + raise InstallError( + f"Enter a literal IP address for {label}." + ) from None + if ( + ip.is_unspecified + or ip.is_multicast + or (private and (ip.is_global or not ip.is_private)) + ): + raise InstallError(f"Enter a usable address for {label}.") + return str(ip) + + +def port(value, label, default): + if value is None: + return default + if type(value) is not int or not 1 <= value <= 65535: + raise InstallError(f"Enter a port from 1 to 65535 for {label}.") + return value + + +def file_path(value, label): + if ( + not isinstance(value, str) + or not FILE_PATH.fullmatch(value) + or ".." in Path(value).parts + ): + raise InstallError(f"Enter an absolute file path for {label}.") + return value + + +def certificate(table, label): + chain = file_path(table.get("certificate"), f"the {label} certificate") + key = file_path(table.get("key"), f"the {label} certificate key") + try: + for value in (chain, key): + resolved = Path(value).resolve(strict=True) + if any( + resolved.is_relative_to(directory) + for directory in ("/root", "/home", "/run/user") + ): + raise InstallError( + f"Place the {label} TLS files outside home directories." + ) + ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER).load_cert_chain( + chain, key, password="" + ) + except (OSError, ValueError) as error: + raise InstallError( + f"Check the certificate and key for {label}." + ) from error + return chain, key + + +@dataclass(frozen=True) +class Role: + mode: str + host: str = "" + port: int = 22 + host_key: str = "" + certificate: str = "" + key: str = "" + + +def role(table, name): + if not isinstance(table, dict): + raise InstallError(f"Check the {name} section.") + mode = table.get("mode", "off") + if mode == "off" or (mode == "local" and name == "dns"): + keys(table, {"mode"}, name) + return Role(mode) + if mode == "local": + keys(table, {"mode", "host", "certificate", "key"}, name) + host = hostname(table.get("host"), "mail") + chain, key = certificate(table, "mail") + return Role(mode, host=host, certificate=chain, key=key) + if mode == "remote": + keys(table, {"mode", "host", "host_key", "port"}, name) + host = table.get("host") + try: + normalized = address(host, f"the {name} node") + except InstallError: + normalized = hostname(host, f"{name} node") + host_key = file_path(table.get("host_key"), f"the {name} SSH host key") + try: + with Path(host_key).open(encoding="ascii") as source: + key = source.read(16385) + if len(key) > 16384 or len(key.strip().splitlines()) != 1: + raise ValueError + if len(key.split()) < 2: + raise ValueError + except (OSError, ValueError): + raise InstallError( + f"Read the pinned {name} SSH public key." + ) from None + return Role( + mode, + host=normalized, + port=port(table.get("port"), f"the {name} node", 22), + host_key=host_key, + ) + raise InstallError(f"Choose off, local, or remote for {name}.") + + +@dataclass(frozen=True) +class Plan: + hostname: str + access: str + certificate: str + key: str + origin_ip: str + proxy_ip: str + origin_port: int + admin_username: str + admin_email: str + dns: Role + mail: Role + + def description(self): + return ( + f"https://{self.hostname}/ · {self.access} · " + f"DNS {self.dns.mode} · mail {self.mail.mode} · " + f"Administrator {self.admin_username}" + ) + + def record(self): + return asdict(self) + + +def parse_plan(data): + keys(data, {"panel", "admin", "dns", "mail"}, "installation") + panel = data.get("panel") + admin = data.get("admin") + keys(admin, {"username", "email", "password_file"}, "admin") + username = admin.get("username", "operator") + email = admin.get("email", "") + if not isinstance(username, str) or not USERNAME.fullmatch(username): + raise InstallError("Enter a valid administrator username.") + if ( + not isinstance(email, str) + or len(email) > 254 + or not EMAIL.fullmatch(email) + ): + raise InstallError("Enter a valid administrator email address.") + if not isinstance(panel, dict): + raise InstallError("Provide a panel section.") + host = hostname(panel.get("hostname"), "panel") + access = panel.get("access", "tls") + chain = key = origin = proxy = "" + origin_port = 8080 + if access == "tls": + keys(panel, {"hostname", "access", "certificate", "key"}, "panel") + chain, key = certificate(panel, "the panel") + elif access == "proxy": + keys( + panel, + {"hostname", "access", "origin_ip", "origin_port", "proxy_ip"}, + "panel", + ) + origin = address(panel.get("origin_ip"), "the origin", private=True) + proxy = address( + panel.get("proxy_ip"), "the reverse proxy", private=True + ) + origin_port = port(panel.get("origin_port"), "the origin", 8080) + if origin_port in {80, 443}: + raise InstallError( + "Use a separate origin port for the reverse proxy." + ) + else: + raise InstallError("Choose tls or proxy for panel access.") + return Plan( + host, + access, + chain, + key, + origin, + proxy, + origin_port, + username, + email, + role(data.get("dns", {}), "dns"), + role(data.get("mail", {}), "mail"), + ) + + +def read_plan(path): + try: + with Path(path).open("rb") as source: + raw = source.read(65537) + if len(raw) > 65536: + raise ValueError + return tomllib.loads(raw.decode("utf-8")) + except (OSError, ValueError) as error: + raise InstallError("Read a valid TOML installation file.") from error + + +def check_password(password): + if not isinstance(password, str) or not 12 <= len(password) <= 1024: + raise InstallError( + "Use an administrator password of 12 to 1024 characters." + ) + if not password.isprintable(): + raise InstallError("Use a single-line administrator password.") + return password + + +def read_password(path): + try: + fd = os.open( + file_path(path, "the administrator password file"), + os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, + ) + with os.fdopen(fd, "rb") as source: + info = os.fstat(source.fileno()) + if ( + not stat.S_ISREG(info.st_mode) + or info.st_uid != 0 + or stat.S_IMODE(info.st_mode) != 0o600 + or info.st_size > 4097 + ): + raise OSError + password = source.read(4098).decode("utf-8").removesuffix("\n") + except (OSError, ValueError): + raise InstallError( + "Use a root-owned administrator password file with mode 0600." + ) from None + return check_password(password) + + +def platform_settings(): + try: + system = freedesktop_os_release() + return PLATFORMS[system["ID"], system["VERSION_ID"]] + except (KeyError, OSError): + raise InstallError( + "Use Ubuntu 26.04, Ubuntu 24.04, or Debian 13." + ) from None diff --git a/deploy/panel_installer/engine.py b/deploy/panel_installer/engine.py new file mode 100644 index 0000000..f73b28e --- /dev/null +++ b/deploy/panel_installer/engine.py @@ -0,0 +1,690 @@ +import fcntl +import grp +import json +import os +import pwd +import secrets +import socket +import stat +import subprocess +import sys +import time +import tomllib +from contextlib import contextmanager +from pathlib import Path +from tempfile import TemporaryDirectory + +from . import roles +from .config import InstallError, platform_settings + +SOURCE = Path(__file__).resolve().parents[2] +ASSETS = SOURCE / "deploy" +VENV = Path("/opt/coulobre") +BINDIR = VENV / "bin" +ETC = Path("/etc/coulobre") +ENV_FILE = ETC / "panel.env" +STATE = Path("/var/lib/coulobre-installer") +SYSTEMD = Path("/etc/systemd/system") +STATIC = Path("/var/www/coulobre-panel-static") +PATH = "/usr/sbin:/usr/bin:/sbin:/bin" +PANEL_UNITS = ( + "coulobre-panel.service", + "coulobre-worker.service", + "coulobre-beat.service", +) +BASE_PACKAGES = ( + "apache2", + "mariadb-server", + "rabbitmq-server", + "python3-venv", + "python3-dev", + "build-essential", + "pkg-config", + "default-libmysqlclient-dev", + "ca-certificates", +) +ADMIN_SCRIPT = """import json +import sys +import django +django.setup() +from django.contrib.auth import get_user_model +from django.contrib.auth.password_validation import validate_password +from django.db import transaction + +data = json.load(sys.stdin) +users = get_user_model().objects +with transaction.atomic(): + previous = users.filter(username=data["username"]).first() + if previous is not None: + if not previous.is_superuser or previous.email != data["email"]: + sys.exit(1) + else: + validate_password(data["password"]) + users.create_superuser(**data) +""" + + +def run(*args, label, source=None, timeout=120, env=None): + try: + result = subprocess.run( + [os.fspath(value) for value in args], + input=source, + stdin=subprocess.DEVNULL if source is None else None, + capture_output=True, + env={"PATH": PATH, "LC_ALL": "C.UTF-8", **(env or {})}, + check=False, + timeout=timeout, + ) + except (OSError, subprocess.TimeoutExpired): + raise InstallError(f"{label} failed or timed out.") from None + if result.returncode: + raise InstallError(f"{label} failed. Check the service and retry.") + return result.stdout.decode("utf-8", errors="replace") + + +def root_directory(path, mode=0o755): + if not os.path.lexists(path): + path.mkdir(mode=mode) + info = path.lstat() + if ( + not stat.S_ISDIR(info.st_mode) + or info.st_uid != 0 + or info.st_mode & 0o022 + ): + raise InstallError(f"Expected a root-controlled directory at {path}.") + + +def root_file(path, mode): + info = path.lstat() + if ( + not stat.S_ISREG(info.st_mode) + or info.st_uid != 0 + or stat.S_IMODE(info.st_mode) != mode + ): + raise InstallError(f"Expected a root-owned {mode:04o} file at {path}.") + + +def put_file(path, content, *, mode=0o644, group=0, update=False): + root_directory(path.parent) + if os.path.lexists(path): + root_file(path, mode) + if path.stat().st_gid != group: + raise InstallError(f"Check the group ownership of {path}.") + if path.read_text(encoding="utf-8") == content: + return + if not update: + raise InstallError(f"Existing configuration differs at {path}.") + with TemporaryDirectory(dir=path.parent) as directory: + staged = Path(directory) / "new" + with staged.open("x", encoding="utf-8") as stream: + stream.write(content) + stream.flush() + os.fchown(stream.fileno(), 0, group) + os.fchmod(stream.fileno(), mode) + os.fsync(stream.fileno()) + if update: + staged.replace(path) + else: + os.link(staged, path) + directory_fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) + + +def group(name): + try: + return grp.getgrnam(name) + except KeyError: + run("groupadd", "--system", name, label=f"Create group {name}") + return grp.getgrnam(name) + + +def identity(name, home="/nonexistent"): + try: + account = pwd.getpwnam(name) + except KeyError: + run( + "useradd", + "--system", + "--user-group", + "--no-create-home", + "--home-dir", + home, + "--shell", + "/usr/sbin/nologin", + name, + label=f"Create service user {name}", + ) + account = pwd.getpwnam(name) + try: + primary_gid = grp.getgrnam(name).gr_gid + except KeyError: + raise InstallError(f"Create a private group for {name}.") from None + if ( + account.pw_uid == 0 + or account.pw_gid != primary_gid + or account.pw_dir != home + or account.pw_shell != "/usr/sbin/nologin" + or set(os.getgrouplist(name, account.pw_gid)) != {account.pw_gid} + ): + raise InstallError(f"Review the existing service account {name}.") + return account + + +def install_unit(unit): + source = ASSETS / "systemd" / unit + if "/" in unit: + root_directory((SYSTEMD / unit).parent) + put_file(SYSTEMD / unit, source.read_text(encoding="utf-8")) + + +def install_worker(group_name, user, socket_unit, worker_unit): + group(group_name) + identity(user) + for unit in ( + f"{socket_unit}.socket", + f"{socket_unit}@.service", + worker_unit, + ): + install_unit(unit) + return worker_unit + + +def systemctl(*args): + return run( + "systemctl", *args, label=f"systemctl {' '.join(args)}", timeout=180 + ) + + +def install_packages(packages, *, mail_host=""): + status = subprocess.run( + ["dpkg-query", "-W", "-f=${db:Status-Status} ${Package}\n", *packages], + stdin=subprocess.DEVNULL, + capture_output=True, + env={"PATH": PATH}, + timeout=30, + check=False, + ) + installed = { + line.split()[1] + for line in status.stdout.decode().splitlines() + if line.startswith("installed ") + } + if set(packages) - installed: + apt_env = {"DEBIAN_FRONTEND": "noninteractive"} + if mail_host and "postfix" not in installed: + answers = ( + "postfix postfix/main_mailer_type select Internet Site\n" + f"postfix postfix/mailname string {mail_host}\n" + ) + run( + "debconf-set-selections", + 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, + ) + + +def install_release(release): + root_directory(VENV.parent) + if os.path.lexists(VENV): + root_directory(VENV) + if not (BINDIR / "python").is_file(): + run( + sys.executable, + "-m", + "venv", + VENV, + label="Create the Coulobre virtual environment", + ) + root_directory(BINDIR) + script = ( + "from importlib.util import find_spec; " + "from importlib.metadata import distributions; " + "print(next((p.version for p in distributions() " + "if p.metadata['Name'] == 'coulobre-panel'), '')); " + "print(int(bool(find_spec('gunicorn') and find_spec('MySQLdb'))))" + ) + installed, ready = run( + BINDIR / "python", "-c", script, label="Check the Coulobre version" + ).splitlines() + if installed and installed != release: + raise InstallError("Use the source release matching /opt/coulobre.") + if installed and ready == "1": + return + with_extras = f"{SOURCE}[server,mariadb]" + pip_env = { + key: os.environ[key] + 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, + ) + + +@contextmanager +def install_lock(): + root_directory(STATE, mode=0o700) + if stat.S_IMODE(STATE.stat().st_mode) != 0o700: + raise InstallError(f"Set mode 0700 on {STATE}.") + lock = os.open( + STATE / "lock", os.O_CREAT | os.O_NOFOLLOW | os.O_RDWR, 0o600 + ) + try: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + raise InstallError( + "A Coulobre installation is already running." + ) from None + yield + finally: + os.close(lock) + + +class Installer: + def __init__(self, plan, password, progress): + self.plan = plan + self.password = password + self.progress = progress + 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"] + + def save_state(self): + put_file( + self.state_file, + json.dumps(self.state, indent=2) + "\n", + mode=0o600, + update=True, + ) + + def read_state(self): + expected = {"release": self.release, "plan": self.plan.record()} + if self.state_file.exists(): + root_file(self.state_file, 0o600) + self.state = json.loads( + self.state_file.read_text(encoding="utf-8") + ) + if {key: self.state.get(key) for key in expected} != expected: + raise InstallError( + "Resume with the same installation settings and release." + ) + else: + if os.path.lexists(ENV_FILE): + raise InstallError( + "The panel already has a configuration. " + "Use the upgrade guide." + ) + self.state = expected | { + "secret_key": secrets.token_urlsafe(48), + "database_password": secrets.token_urlsafe(36), + "broker_password": secrets.token_urlsafe(36), + } + self.save_state() + + def packages(self): + packages = list(BASE_PACKAGES) + if self.php: + packages.append(f"php{self.php}-fpm") + if self.plan.dns.mode == "local": + packages.extend(("bind9", "bind9-utils")) + if self.plan.mail.mode == "local": + packages.extend( + ("postfix", "dovecot-core", "dovecot-imapd", "dovecot-lmtpd") + ) + if "remote" in (self.plan.dns.mode, self.plan.mail.mode): + packages.extend(("openssh-client", "socat")) + return packages + + def configure_stores(self): + put_file( + Path("/etc/mysql/mariadb.conf.d/90-coulobre-loopback.cnf"), + "[mariadbd]\nbind-address=127.0.0.1\n", + ) + broker_config = Path("/etc/rabbitmq") + if any( + (broker_config / name).exists() + for name in ("rabbitmq.conf", "advanced.config") + ) or any((broker_config / "conf.d").glob("*.conf")): + raise InstallError("Review the existing RabbitMQ configuration.") + put_file( + Path("/etc/coulobre-rabbitmq.conf"), + "listeners.tcp.1 = 127.0.0.1:5672\n", + ) + drop_in = SYSTEMD / "rabbitmq-server.service.d" + root_directory(drop_in) + put_file( + drop_in / "coulobre.conf", + "[Service]\n" + "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") + + def mariadb(sql): + return run( + "mariadb", + "--batch", + "--skip-column-names", + "--protocol=socket", + source=sql.encode(), + label="Configure the local MariaDB database", + ).strip() + + if not self.state.get("stores_reserved"): + existing = mariadb( + "SELECT EXISTS(SELECT 1 FROM information_schema.schemata " + "WHERE schema_name='coulobre_panel') OR " + "EXISTS(SELECT 1 FROM mysql.user WHERE User='coulobre');" + ) + if existing != "0": + raise InstallError( + "A Coulobre MariaDB database or user already exists." + ) + for action in ("list_users", "list_vhosts"): + rows = run( + "rabbitmqctl", "--quiet", action, label="Inspect RabbitMQ" + ) + if "coulobre" in { + row.split()[0] for row in rows.splitlines() if row.split() + }: + raise InstallError( + "A Coulobre RabbitMQ user or virtual host exists." + ) + self.state["stores_reserved"] = True + self.save_state() + + mariadb( + "CREATE DATABASE IF NOT EXISTS coulobre_panel " + "CHARACTER SET utf8mb4;" + "CREATE USER IF NOT EXISTS 'coulobre'@'localhost' IDENTIFIED BY " + f"'{self.state['database_password']}';" + "GRANT ALL PRIVILEGES ON coulobre_panel.* " + "TO 'coulobre'@'localhost';" + ) + users = run( + "rabbitmqctl", + "--quiet", + "list_users", + label="Inspect RabbitMQ users", + ) + if "coulobre" not in { + row.split()[0] for row in users.splitlines() if row.split() + }: + run( + "rabbitmqctl", + "add_user", + "coulobre", + source=(self.state["broker_password"] + "\n").encode(), + label="Create the Coulobre RabbitMQ login", + ) + hosts = run( + "rabbitmqctl", + "--quiet", + "list_vhosts", + label="Inspect RabbitMQ virtual hosts", + ) + if "coulobre" not in {row.strip() for row in hosts.splitlines()}: + run( + "rabbitmqctl", + "add_vhost", + "coulobre", + label="Create the Coulobre RabbitMQ virtual host", + ) + run( + "rabbitmqctl", + "set_permissions", + "-p", + "coulobre", + "coulobre", + ".*", + ".*", + ".*", + label="Grant access to the Coulobre virtual host", + ) + + def environment(self): + options = { + "DJANGO_SETTINGS_MODULE": "coulobre.settings", + "COULOBRE_ALLOWED_HOSTS": self.plan.hostname, + "COULOBRE_HTTPS_PROXY": "1", + "COULOBRE_REQUIRE_PRIVILEGED_MFA": "1", + "COULOBRE_TRUST_APACHE_CLIENT_IP": "1", + "COULOBRE_STATIC_ROOT": str(STATIC), + "COULOBRE_SECRET_KEY": self.state["secret_key"], + "COULOBRE_DB_NAME": "coulobre_panel", + "COULOBRE_DB_USER": "coulobre", + "COULOBRE_DB_PASSWORD": self.state["database_password"], + "COULOBRE_DB_HOST": "/run/mysqld/mysqld.sock", + "COULOBRE_BROKER_URL": ( + f"amqp://coulobre:{self.state['broker_password']}@127.0.0.1:5672/coulobre" + ), + "COULOBRE_LOCAL_DATABASE_PROVISIONING": "1", + } + if self.php: + options["COULOBRE_LOCAL_WEB_ACTIVATION"] = "1" + if self.plan.dns.mode != "off": + options["COULOBRE_LOCAL_DNS_PUBLISHING"] = "1" + if self.plan.mail.mode != "off": + options["COULOBRE_LOCAL_MAILBOX_PROVISIONING"] = "1" + return "".join(f"{key}={value}\n" for key, value in options.items()) + + def prepare_panel(self): + panel = identity("coulobre-panel") + root_directory(ETC, mode=0o750) + if not os.path.lexists(STATIC): + STATIC.mkdir(mode=0o755) + os.chown(STATIC, panel.pw_uid, panel.pw_gid) + info = STATIC.lstat() + if not stat.S_ISDIR(info.st_mode) or (info.st_uid, info.st_gid) != ( + panel.pw_uid, + panel.pw_gid, + ): + raise InstallError( + f"Check the directory and ownership of {STATIC}." + ) + put_file(ENV_FILE, self.environment(), mode=0o600) + unit = ( + "systemd-run", + "--quiet", + "--wait", + "--pipe", + "--collect", + "--uid=coulobre-panel", + "--property=EnvironmentFile=/etc/coulobre/panel.env", + str(BINDIR / "python"), + ) + run( + *unit, + "-m", + "django", + "migrate", + "--noinput", + label="Apply panel migrations", + timeout=600, + ) + run( + *unit, + "-m", + "django", + "collectstatic", + "--noinput", + label="Install panel static files", + ) + info = { + "username": self.plan.admin_username, + "email": self.plan.admin_email, + "password": self.password, + } + run( + *unit, + "-c", + ADMIN_SCRIPT, + source=json.dumps(info).encode(), + label="Create the administrator account", + ) + + def apache(self): + modules = ["headers", "proxy", "proxy_http"] + if self.php: + modules.append("proxy_fcgi") + systemctl("enable", "--now", f"php{self.php}-fpm.service") + plan = self.plan + if plan.access == "tls": + modules.append("ssl") + config = (ASSETS / "apache/panel-tls.conf.example").read_text() + config = ( + config.replace("panel.example.net", plan.hostname) + .replace( + "/etc/ssl/coulobre-panel/fullchain.pem", plan.certificate + ) + .replace("/etc/ssl/coulobre-panel/privkey.pem", plan.key) + ) + else: + modules.append("remoteip") + local = ( + f"[{plan.origin_ip}]" + if ":" in plan.origin_ip + else plan.origin_ip + ) + config = (ASSETS / "apache/panel-origin.conf.example").read_text() + config = ( + config.replace("panel.example.net", plan.hostname) + .replace("192.168.10.20:8080", f"{local}:{plan.origin_port}") + .replace("192.168.10.10", plan.proxy_ip) + ) + put_file( + ETC / "panel-proxy.inc", + (ASSETS / "apache/panel-proxy.inc").read_text(), + ) + put_file( + Path("/etc/apache2/sites-available/coulobre-panel.conf"), config + ) + run("a2enmod", *modules, label="Enable the Apache modules") + run( + "a2ensite", "coulobre-panel", label="Enable the panel virtual host" + ) + run( + "apache2ctl", + "configtest", + label="Validate the Apache virtual host", + ) + + def verify_panel(self): + request = ( + f"GET /sign-in/ HTTP/1.0\r\nHost: {self.plan.hostname}\r\n" + "X-Forwarded-Proto: https\r\n\r\n" + ).encode() + for _ in range(20): + try: + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer: + peer.settimeout(2) + peer.connect("/run/coulobre-panel/panel.sock") + peer.sendall(request) + with peer.makefile("rb") as reply: + if reply.readline(256).split()[1:2] == [b"200"]: + return + except OSError: + pass + time.sleep(1) + raise InstallError( + "The panel did not respond. Check journalctl -u coulobre-panel." + ) + + def install(self): + if os.geteuid() != 0 or not Path("/run/systemd/system").is_dir(): + raise InstallError("Run the installer as root on a systemd host.") + with install_lock(): + self.read_state() + if self.state.get("complete"): + self.progress( + "Coulobre is already installed with these settings." + ) + self.verify_panel() + return + self.progress( + "Installing system packages and the Coulobre release." + ) + mail = self.plan.mail + install_packages( + self.packages(), + mail_host=mail.host if mail.mode == "local" else "", + ) + install_release(self.release) + self.progress("Preparing MariaDB and RabbitMQ on loopback.") + self.configure_stores() + self.progress( + "Configuring hosting service identities and provisioning." + ) + workers = [ + install_worker( + "coulobre-db-provisioning", + "coulobre-db-provisioner", + "coulobre-database-apply", + "coulobre-database-provisioner.service", + ) + ] + if self.php: + workers.append( + install_worker( + "coulobre-web-provisioning", + "coulobre-provisioner", + "coulobre-web-apply", + "coulobre-provisioner.service", + ) + ) + for name in ("dns", "mail"): + target = getattr(self.plan, name) + if target.mode != "off": + workers.append(roles.configure_role(self, name, target)) + self.progress( + "Applying panel migrations and creating the administrator." + ) + self.prepare_panel() + self.progress("Validating Apache and starting the panel services.") + self.apache() + for unit in PANEL_UNITS: + install_unit(unit) + systemctl("daemon-reload") + systemctl( + "enable", "--now", *PANEL_UNITS, *workers, "apache2.service" + ) + systemctl("reload", "apache2.service") + self.verify_panel() + for key in ("secret_key", "database_password", "broker_password"): + self.state.pop(key, None) + self.state["complete"] = True + self.save_state() + self.progress( + f"Installation complete. Sign in at https://{self.plan.hostname}/" + ) diff --git a/deploy/panel_installer/roles.py b/deploy/panel_installer/roles.py new file mode 100644 index 0000000..cd66347 --- /dev/null +++ b/deploy/panel_installer/roles.py @@ -0,0 +1,232 @@ +import hashlib +import os +from pathlib import Path + +from . import engine +from .config import InstallError + +WORKERS = { + "dns": ( + "coulobre-dns-provisioning", + "coulobre-dns-publisher", + "coulobre-dns-apply", + "coulobre-dns-publisher.service", + ), + "mail": ( + "coulobre-mail-provisioning", + "coulobre-mail-provisioner", + "coulobre-mail-apply", + "coulobre-mailbox-provisioner.service", + ), +} +BIND_CONFIG = """options { + directory "/var/cache/bind"; + recursion no; + allow-new-zones yes; + allow-query { any; }; + allow-transfer { none; }; + listen-on-v6 { any; }; +}; +""" +DOVECOT_23 = """protocols = imap lmtp +ssl = required +ssl_cert = <{certificate} +ssl_key = <{key} +mail_location = maildir:~/Maildir +first_valid_uid = {uid} +last_valid_uid = {uid} +auth_username_format = %Lu +auth_cache_size = 0 +passdb {{ + driver = passwd-file + args = /etc/dovecot/coulobre-users +}} +userdb {{ + driver = passwd-file + args = /etc/dovecot/coulobre-users +}} +service lmtp {{ + unix_listener /var/spool/postfix/private/dovecot-lmtp {{ + user = postfix + group = postfix + mode = 0600 + }} +}} +mail_plugins = $mail_plugins quota +protocol imap {{ + mail_plugins = $mail_plugins imap_quota +}} +plugin {{ + quota = count:User quota + quota_vsizes = yes + quota_grace = 0 +}} +""" + + +def replace_stock_config(path, package, content): + engine.root_file(path, 0o644) + current = path.read_bytes() + if current == content.encode(): + return + if package == "dovecot-core": + stock = Path("/usr/share/dovecot/dovecot.conf").read_bytes() + matches = current == stock + else: + manifest = engine.run( + "dpkg-query", + "-W", + "-f=${Conffiles}", + package, + label=f"Check the distribution configuration for {package}", + ) + hashes = { + parts[0]: parts[1] + for line in manifest.splitlines() + if len(parts := line.split()) >= 2 + } + matches = ( + hashes.get(str(path)) + == hashlib.md5(current, usedforsecurity=False).hexdigest() + ) + if not matches: + raise InstallError(f"Existing configuration differs at {path}.") + engine.put_file(path, content, group=path.stat().st_gid, update=True) + + +def ensure_table(path, *, mode, group=0): + if os.path.lexists(path): + engine.root_file(path, mode) + if path.stat().st_gid != group: + raise InstallError(f"Check the group ownership of {path}.") + else: + engine.put_file(path, "", mode=mode, group=group) + + +def configure_dns(): + engine.root_directory(Path("/etc/bind/coulobre")) + replace_stock_config(Path("/etc/bind/named.conf"), "bind9", BIND_CONFIG) + engine.run("named-checkconf", label="Validate the BIND9 configuration") + engine.systemctl("enable", "--now", "named.service") + engine.systemctl("restart", "named.service") + engine.run( + "rndc", + "-s", + "127.0.0.1", + "status", + label="Check BIND9's local RNDC connection", + ) + + +def configure_mail(target, modern): + vmail = engine.identity("coulobre-vmail", home="/srv/coulobre-mail") + dovecot = engine.group("dovecot") + ensure_table(Path("/etc/postfix/coulobre-domains"), mode=0o644) + ensure_table(Path("/etc/postfix/coulobre-mailboxes"), mode=0o644) + ensure_table( + Path("/etc/dovecot/coulobre-users"), mode=0o640, group=dovecot.gr_gid + ) + config = { + "myhostname": target.host, + "mydestination": "$myhostname, localhost", + "inet_interfaces": "all", + "virtual_mailbox_domains": ( + "proxy:texthash:/etc/postfix/coulobre-domains" + ), + "virtual_mailbox_maps": ( + "proxy:texthash:/etc/postfix/coulobre-mailboxes" + ), + "virtual_transport": "lmtp:unix:private/dovecot-lmtp", + "smtpd_reject_unlisted_recipient": "yes", + "smtpd_tls_security_level": "may", + "smtpd_tls_cert_file": target.certificate, + "smtpd_tls_key_file": target.key, + } + # Virtual mailbox routing may already belong to another service. + managed_maps = ( + "virtual_mailbox_domains", + "virtual_mailbox_maps", + "virtual_transport", + ) + for field in managed_maps: + default = engine.run( + "postconf", "-d", "-h", field, label="Inspect Postfix defaults" + ).strip() + current = engine.run( + "postconf", "-h", field, label="Inspect Postfix routing" + ).strip() + if current not in {default, config[field]}: + raise InstallError( + "Existing Postfix virtual mailbox routing differs." + ) + if modern: + template = ( + engine.ASSETS / "dovecot/coulobre-2.4.conf.example" + ).read_text() + dovecot_config = ( + template.replace( + "first_valid_uid = 103", f"first_valid_uid = {vmail.pw_uid}" + ) + .replace( + "last_valid_uid = 103", f"last_valid_uid = {vmail.pw_uid}" + ) + .replace( + "/etc/ssl/coulobre-mail/fullchain.pem", target.certificate + ) + .replace("/etc/ssl/coulobre-mail/privkey.pem", target.key) + ) + else: + dovecot_config = DOVECOT_23.format( + certificate=target.certificate, + key=target.key, + uid=vmail.pw_uid, + ) + replace_stock_config( + Path("/etc/dovecot/dovecot.conf"), "dovecot-core", dovecot_config + ) + engine.run("doveconf", "-n", label="Validate the Dovecot configuration") + engine.run( + "postconf", + "-e", + *(f"{key}={value}" for key, value in config.items()), + label="Configure Postfix mailbox delivery", + ) + engine.run("postfix", "check", label="Validate the Postfix configuration") + engine.systemctl("enable", "--now", "postfix.service", "dovecot.service") + engine.systemctl("restart", "postfix.service", "dovecot.service") + + +def configure_role(installer, name, target): + group, worker, receiver, unit = WORKERS[name] + if target.mode == "remote": + node_setup = engine.BINDIR / "coulobre-node-setup" + engine.run( + node_setup, + "prepare-panel", + name, + label=f"Prepare the panel's public key for the {name} node", + ) + installer.progress( + f"Checking the remote {name} node. Panel key: " + f"/etc/coulobre-remote/{name}/id_ed25519.pub" + ) + engine.run( + node_setup, + "--source", + engine.SOURCE, + "enrol-panel", + name, + target.host, + target.host_key, + "--port", + str(target.port), + label=f"Enrol the {name} node. Check its receiver and panel key", + ) + return unit + if os.path.lexists(engine.SYSTEMD / f"{receiver}@.service.d/remote.conf"): + raise InstallError(f"An existing relay already manages {name}.") + if name == "dns": + configure_dns() + else: + configure_mail(target, installer.modern_mail) + return engine.install_worker(group, worker, receiver, unit)