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}/" )