diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 7727899..1c55388 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -2,6 +2,7 @@ import argparse import json import sys from dataclasses import dataclass +from hashlib import sha256 from importlib.resources import files from pathlib import Path from string import Template @@ -68,15 +69,84 @@ class WebSite: "socket_path": f"/run/php/{service_user}.sock", } - def render(self, configuration, *, port=80, tls_settings=""): + def render( + self, configuration, *, port=80, tls_settings="", server_name=None + ): resource = files("coulobre.hosting").joinpath( "templates", "hosting", CONFIGURATIONS[configuration] ) + values = self.configuration() + if server_name is not None: + values["domain"] = canonical_domain(server_name) return Template(resource.read_text(encoding="utf-8")).substitute( - self.configuration(), port=port, tls_settings=tls_settings + values, port=port, tls_settings=tls_settings ) +@dataclass(frozen=True) +class WebAlias: + site: WebSite + domain: str + + def __post_init__(self): + if not isinstance(self.domain, str): + raise ValueError("Enter a valid website alias.") + domain = canonical_domain(self.domain) + if domain == self.site.domain: + raise ValueError("An alias must differ from the primary domain.") + object.__setattr__(self, "domain", domain) + + @property + def name(self): + suffix = sha256(self.domain.encode("ascii")).hexdigest()[:24] + return f"coulobre-{self.site.account_id}-alias-{suffix}" + + @classmethod + def from_manifest(cls, data): + if ( + not isinstance(data, dict) + or data.keys() != {"version", "site", "domain"} + or type(data["version"]) is not int + or data["version"] != MANIFEST_VERSION + ): + raise ValueError("Expected a website alias manifest.") + return cls(WebSite.from_manifest(data["site"]), data["domain"]) + + def manifest(self): + return { + "version": MANIFEST_VERSION, + "site": self.site.manifest(), + "domain": self.domain, + } + + def render(self, configuration, *, port=80, tls_settings=""): + return self.site.render( + configuration, + port=port, + tls_settings=tls_settings, + server_name=self.domain, + ) + + +@dataclass(frozen=True) +class WebAliasRequest: + alias: WebAlias + operation: str + + def __post_init__(self): + if self.operation not in ("apply_alias", "remove_alias"): + raise ValueError("Expected a website alias operation.") + + def manifest(self): + return {"operation": self.operation, "alias": self.alias.manifest()} + + +def parse_https_request(data): + if isinstance(data, dict) and "site" in data: + return WebAlias.from_manifest(data) + return WebSite.from_manifest(data) + + @dataclass(frozen=True) class WebStorageRequest: site: WebSite @@ -123,6 +193,10 @@ def parse_web_request(data): return WebQuotaRequest( WebSite.from_manifest(data["site"]), data["limit_mib"] ) + if isinstance(data, dict) and data.keys() == {"operation", "alias"}: + return WebAliasRequest( + WebAlias.from_manifest(data["alias"]), data["operation"] + ) return WebSite.from_manifest(data) @@ -138,6 +212,15 @@ def apply_web_request(request): apply_website_limit(request) return None + if isinstance(request, WebAliasRequest): + from .web_node_aliases import activate_alias, remove_alias + + if request.operation == "apply_alias": + activate_alias(request.alias) + else: + remove_alias(request.alias) + return None + from .web_node_apply import apply_site apply_site(request) @@ -244,7 +327,7 @@ def main(argv=None): from .web_node_tls import provision_https return serve_apply_request( - MANIFEST_VERSION, WebSite.from_manifest, provision_https + MANIFEST_VERSION, parse_https_request, provision_https ) if args.command == "sftp-keys-request": diff --git a/src/coulobre/web_node_aliases.py b/src/coulobre/web_node_aliases.py new file mode 100644 index 0000000..555ec1e --- /dev/null +++ b/src/coulobre/web_node_aliases.py @@ -0,0 +1,179 @@ +import fcntl +import json +import os +import re +from fnmatch import fnmatchcase +from pathlib import Path + +from . import web_node_apply as web +from .node_files import read_root_file, require_root_directory, write_new_file +from .web_node import WebAlias +from .web_node_tls import ( + check_https_prerequisites, + delete_alias_certificate, + ensure_certificate, + install_https_configuration, + render_https_configuration, +) + +APACHE_VHOST_NAME = re.compile( + r"^\s*(?:default server|port \d+ namevhost|\S+:\d+)\s+(\S+)\s+\(" +) +APACHE_VHOST_ALIAS = re.compile(r"^\s*(?:wild )?alias\s+(\S+)(?:\s|$)") + + +def alias_directory(): + return web.STATE_DIRECTORY / "aliases" + + +def alias_marker(alias): + return alias_directory() / f"{alias.name}.json" + + +def alias_paths(alias, *, https=False): + suffix = "-https" if https else "" + name = f"zz-{alias.name}{suffix}.conf" + return web.APACHE_AVAILABLE / name, web.APACHE_ENABLED / name + + +def read_alias(marker): + return WebAlias.from_manifest( + json.loads(read_root_file(marker, mode=0o600)) + ) + + +def check_alias_domain_available(domain, *, alias=None): + directory = alias_directory() + if not os.path.lexists(directory): + return + require_root_directory(directory) + for marker in directory.glob("*.json"): + current = read_alias(marker) + if current.domain == domain and current != alias: + raise ValueError( + "This domain is reserved as another website alias." + ) + + +def check_apache_hostname_available(domain): + configuration = web.run("/usr/sbin/apache2ctl", "-S") + for line in configuration.splitlines(): + match = APACHE_VHOST_NAME.match(line) or APACHE_VHOST_ALIAS.match(line) + if match and fnmatchcase(domain, match[1].rstrip(".").lower()): + raise ValueError("This hostname is already configured in Apache.") + + +def reserve_alias(alias): + for marker in web.STATE_DIRECTORY.glob("*.json"): + if json.loads(read_root_file(marker))["domain"] == alias.domain: + raise ValueError( + "This alias is already reserved as a primary domain." + ) + + require_root_directory(alias_directory(), create_mode=0o700) + check_alias_domain_available(alias.domain, alias=alias) + marker = alias_marker(alias) + if os.path.lexists(marker): + if read_alias(marker) != alias: + raise ValueError( + "The website alias reservation has a different identity." + ) + return + + if any( + os.path.lexists(path) + for paths in (alias_paths(alias), alias_paths(alias, https=True)) + for path in paths + ): + raise ValueError( + "The web node already has unmanaged files for this alias." + ) + check_apache_hostname_available(alias.domain) + write_new_file(marker, json.dumps(alias.manifest()) + "\n", mode=0o600) + + +def activate_alias(alias): + if os.geteuid() != 0: + raise ValueError("Apply the website alias as root on the web node.") + with web.locked_web_node(fcntl.LOCK_EX): + web.check_reservation(alias.site) + web.check_installation(alias.site, web.SitePaths.for_site(alias.site)) + reserve_alias(alias) + apache, enabled = alias_paths(alias) + with web.configuration_installation() as (created, reload_attempts): + web.install_configuration(apache, alias.render("apache"), created) + web.enable_apache_site(apache, enabled, created) + web.run("/usr/sbin/apache2ctl", "configtest") + reload_attempts.append("apache2") + web.run("/usr/sbin/service", "apache2", "reload") + + +def provision_alias_https(alias): + with web.locked_web_node(fcntl.LOCK_EX): + check_https_prerequisites( + alias.site, web.SitePaths.for_site(alias.site) + ) + require_root_directory(alias_directory()) + if read_alias(alias_marker(alias)) != alias: + raise ValueError( + "The website alias reservation has a different identity." + ) + apache, enabled = alias_paths(alias) + web.check_configuration(apache, alias.render("apache")) + web.check_site_link(enabled, Path("../sites-available") / apache.name) + ensure_certificate(alias) + install_https_configuration(alias, *alias_paths(alias, https=True)) + + +def remove_alias(alias): + if os.geteuid() != 0: + raise ValueError("Remove the website alias as root on the web node.") + with web.locked_web_node(fcntl.LOCK_EX): + web.check_reservation(alias.site) + for directory in (web.APACHE_AVAILABLE, web.APACHE_ENABLED): + require_root_directory(directory) + marker = alias_marker(alias) + paths = (alias_paths(alias), alias_paths(alias, https=True)) + if not os.path.lexists(marker): + if any(os.path.lexists(path) for pair in paths for path in pair): + raise ValueError( + "The web node has unmanaged files for this alias." + ) + return + require_root_directory(alias_directory()) + if read_alias(marker) != alias: + raise ValueError( + "The website alias reservation has a different identity." + ) + + expected = (alias.render("apache"), render_https_configuration(alias)) + links = [] + for (apache, enabled), contents in zip(paths, expected, strict=True): + if os.path.lexists(apache): + web.check_configuration(apache, contents) + if os.path.lexists(enabled): + target = Path("../sites-available") / apache.name + web.check_site_link(enabled, target) + links.append((enabled, target)) + + disable_alias_vhosts(links) + for apache, _ in paths: + apache.unlink(missing_ok=True) + delete_alias_certificate(alias) + marker.unlink() + + +def disable_alias_vhosts(links): + removed = [] + try: + for enabled, target in links: + enabled.unlink() + removed.append((enabled, target)) + web.run("/usr/sbin/apache2ctl", "configtest") + web.run("/usr/sbin/service", "apache2", "reload") + except (OSError, ValueError, KeyboardInterrupt): + for enabled, target in removed: + enabled.symlink_to(target) + if removed: + web.run("/usr/sbin/service", "apache2", "reload") + raise diff --git a/src/coulobre/web_node_apply.py b/src/coulobre/web_node_apply.py index 47eb507..b0020fc 100644 --- a/src/coulobre/web_node_apply.py +++ b/src/coulobre/web_node_apply.py @@ -196,6 +196,10 @@ def reserve_account(site, user, paths): "The primary domain is already reserved by another account." ) + from .web_node_aliases import check_alias_domain_available + + check_alias_domain_available(site.domain) + if os.path.lexists(marker): return if ( diff --git a/src/coulobre/web_node_tls.py b/src/coulobre/web_node_tls.py index 4ed0193..a2b6528 100644 --- a/src/coulobre/web_node_tls.py +++ b/src/coulobre/web_node_tls.py @@ -5,6 +5,7 @@ import subprocess from pathlib import Path from .node_files import check_root_file, require_root_directory +from .web_node import WebAlias from .web_node_apply import ( SitePaths, check_configuration, @@ -26,28 +27,38 @@ def provision_https(site): if os.geteuid() != 0: raise ValueError("Run https-request as root on the web node.") + if isinstance(site, WebAlias): + from .web_node_aliases import provision_alias_https + + provision_alias_https(site) + return + with locked_web_node(fcntl.LOCK_SH): check_https_prerequisites(site, SitePaths.for_site(site)) - if not os.path.lexists(certbot_lineage(site)): - try: - require_root_directory(CERTBOT_ROOT) - except FileNotFoundError: - raise ValueError( - "Register a Certbot account on the web node." - ) from None - challenge = ACME_WEBROOT / ".well-known" / "acme-challenge" - try: - require_root_directory(challenge) - except FileNotFoundError: - raise ValueError( - "Configure the Certbot HTTP-01 webroot on the web node." - ) from None - request_certificate(site) - + ensure_certificate(site) enable_https(site) +def ensure_certificate(site): + if os.path.lexists(certbot_lineage(site)): + return + try: + require_root_directory(CERTBOT_ROOT) + except FileNotFoundError: + raise ValueError( + "Register a Certbot account on the web node." + ) from None + challenge = ACME_WEBROOT / ".well-known" / "acme-challenge" + try: + require_root_directory(challenge) + except FileNotFoundError: + raise ValueError( + "Configure the Certbot HTTP-01 webroot on the web node." + ) from None + request_certificate(site) + + def request_certificate(site): command = ( "/usr/bin/certbot", @@ -93,13 +104,17 @@ def enable_https(site): apache, enabled = https_paths(paths) with locked_web_node(fcntl.LOCK_EX): check_https_prerequisites(site, paths) - config = https_configuration(site) - with configuration_installation() as (created, reload_attempts): - install_configuration(apache, config, created) - enable_apache_site(apache, enabled, created) - run("/usr/sbin/apache2ctl", "configtest") - reload_attempts.append("apache2") - run("/usr/sbin/service", "apache2", "reload") + install_https_configuration(site, apache, enabled) + + +def install_https_configuration(site, apache, enabled): + config = https_configuration(site) + with configuration_installation() as (created, reload_attempts): + install_configuration(apache, config, created) + enable_apache_site(apache, enabled, created) + run("/usr/sbin/apache2ctl", "configtest") + reload_attempts.append("apache2") + run("/usr/sbin/service", "apache2", "reload") def check_https_prerequisites(site, paths): @@ -138,7 +153,12 @@ def https_paths(paths): def certbot_lineage(site): - return CERTBOT_ROOT / "live" / f"coulobre-{site.account_id}" + name = ( + site.name + if isinstance(site, WebAlias) + else f"coulobre-{site.account_id}" + ) + return CERTBOT_ROOT / "live" / name def https_configuration(site): @@ -185,6 +205,13 @@ def https_configuration(site): str(chain_file), ) + return render_https_configuration(site) + + +def render_https_configuration(site): + lineage = certbot_lineage(site) + certificate = lineage / "fullchain.pem" + private_key = lineage / "privkey.pem" return site.render( "apache", port=443, @@ -196,3 +223,42 @@ def https_configuration(site): f' SSLCertificateKeyFile "{private_key}"\n' ), ) + + +def delete_alias_certificate(alias): + lineage = certbot_lineage(alias) + renewal = CERTBOT_ROOT / "renewal" / f"{lineage.name}.conf" + archive = CERTBOT_ROOT / "archive" / lineage.name + if not any(os.path.lexists(path) for path in (lineage, renewal, archive)): + return + for directory in (lineage, archive): + if os.path.lexists(directory): + require_root_directory(directory) + if os.path.lexists(renewal): + require_root_directory(renewal.parent) + check_root_file(renewal) + try: + subprocess.run( + ( + "/usr/bin/certbot", + "delete", + "--non-interactive", + "--cert-name", + lineage.name, + ), + check=True, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=90, + env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C"}, + ) + except ( + FileNotFoundError, + subprocess.TimeoutExpired, + subprocess.CalledProcessError, + ): + raise ValueError( + "Certbot could not remove the alias certificate. " + "Check the Certbot log." + ) from None